diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..c0d4e80 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,20 @@ +# Contributing to RynthSuite + +RynthCore is the hook layer: it injects into the client, reads the game, runs plugins and hosts their windows. RynthSuite is the plugins. RynthAi is one plugin among them, built on RynthCore the same way any other plugin is. + +## Where a change goes + +| It is... | It goes in | +|---|---| +| A hook into the client, game state, the plugin API, the window host, a service every plugin can use | **RynthCore** | +| A plugin's behaviour or its own screens | **That plugin** (`Plugins/RynthCore.Plugin.`), drawn by the plugin with the engine's ImGui | +| A feature for one game server | **That server's plugin**, in the **RynthServers** repository | + +A shared plugin (RynthAi, RynthOracle, RynthInventory, RynthNav, ...) never names a server. When a server plugin needs a place in one of them, add a generic hook the server plugin fills (the ServerPack hooks, the server tab host, the storage and chat feeds) and keep the server's own code in the server plugin. + +## Pull requests + +- One purpose per pull request. A change that touches several layers comes as one pull request per layer, the RynthCore hook first. +- Plugin API numbers and plugin versions are assigned when a change is merged. +- Add or update tests where the project has them (`Tools/`, each plugin's `*.Tests`). +- Say in the description what you tested in game and on which server. diff --git a/Plugins/RynthCore.Plugin.RynthAChard/RynthCore.Plugin.RynthAChard.csproj b/Plugins/RynthCore.Plugin.RynthAChard/RynthCore.Plugin.RynthAChard.csproj deleted file mode 100644 index 589c30a..0000000 --- a/Plugins/RynthCore.Plugin.RynthAChard/RynthCore.Plugin.RynthAChard.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - - RynthCore.Plugin.RynthAChard - 0.1.0 - achard - AChard - a-chard.ddns.net - AChard|A-Chard - AChard only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthAChard/ServerData.cs b/Plugins/RynthCore.Plugin.RynthAChard/ServerData.cs deleted file mode 100644 index d3ec8dd..0000000 --- a/Plugins/RynthCore.Plugin.RynthAChard/ServerData.cs +++ /dev/null @@ -1,23 +0,0 @@ -// ServerData.cs - What is known about AChard (RynthAChard). Identity (id, hosts, world names) is in the csproj. -namespace RynthCore.Plugin.ServerPack; - -internal static class ServerData -{ - public static ServerPackInfo Create() => - new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) - { - Port = 9000, - Emulator = "ACE", - Ruleset = "PvP", - Status = "Stable", - Summary = "ACE EOR PVP Server/Custom PK Content/PK Kill Rankings", - Facts = new[] - { - "PvP server: other players can attack you.", - "Custom PK content and PK kill rankings.", - }, - Discord = "https://discord.gg/gmHfqt2J2D", - Website = "http://a-chard.ddns.net/", - Source = "public AC server list (acresources/serverslist), checked 2026-10-13", - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthBoards.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthBoards.cs deleted file mode 100644 index a007686..0000000 --- a/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthBoards.cs +++ /dev/null @@ -1,277 +0,0 @@ -// Moved here from RynthOracle (Data/AelrynthBoards.cs) on 2026-10-20: Aelrynth-only features live in RynthAelrynth. -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; -using RynthCore.Plugin.ServerPack; - -namespace RynthCore.Plugin.RynthAelrynth; - -/// A row of a leaderboard. -internal sealed class BoardRow -{ - public int Rank; - public string Name = ""; - public string Value = ""; - public string Extra = ""; - public bool IsYou; -} - -/// A board in Aelrynth's /top overview. -internal sealed class AelrynthBoardSummary -{ - public string Key = "", Title = "", Leader = "", Value = ""; -} - -/// Your standing on one board ("/top me"). -internal sealed class AelrynthStanding -{ - public string Title = ""; - public int Rank; - public int Of; - public string Value = ""; -} - -/// A line of the "/trial" overview: a dungeon's record, yours and this week's best. -internal sealed class TrialDungeon -{ - public string Name = "", Landblock = "", Record = "", You = "", Week = ""; -} - -/// -/// Aelrynth's leaderboards, read from the replies of the server's own commands -/// (ACEPublic Mods: Aeshnidae.Leaderboard /top, Aeshnidae.Trials /trial; one Broadcast line -/// each, numbers with thousands separators). Formats (Commands.cs): -/// /top "Leaderboards - N characters, refreshed X. /top <board> ..." -/// then " key Title: Leader, value" (or ": nobody yet") -/// /top <board> "Title - top K of N[, counted since ...][, per account]:" -/// then " r. Name value[ extra][ <- you]", " ... you: #r with v", " nobody yet." -/// /top me "Name on the boards:" then " Title #r of N, value" or " Title -" -/// /trial a few intro lines, then " Dungeon (LLLL): records | you: ... | this week: ..." -/// /trial <dungeon> "Dungeon (LLLL) - top 10, best per character, any tier:" -/// then " r. m:ss Name (tier T, K kills, d MMM)" and " records per tier/you/this week" lines -/// Entry lines only count right after their header (within a few seconds), so ordinary chat -/// can't add rows. Conquest answers /top in a very different shape (RynthConquest's parser), which is -/// why each server plugin reads only its own server's replies. -/// -internal sealed class AelrynthBoards -{ - private const long BlockMs = 4000; - - private static readonly Regex OverviewHeader = new(@"^\s*Leaderboards - ([\d,]+) characters, refreshed (.+?)\.\s"); - private static readonly Regex OverviewEntry = new(@"^\s*(\S+)\s+(.+?): (?:(.+), ([\d,]+)|nobody yet)\s*$"); - private static readonly Regex BoardHeader = new(@"^\s*(.+?) - top (\d+) of (\d+)(.*):\s*$"); - private static readonly Regex BoardEntry = new(@"^\s*(\d+)\.\s+(.+?)\s+([\d,]+)(?:\s{2,}(?!<-)(.+?))?(\s{2,}<- you)?\s*$"); - private static readonly Regex BoardYouBelow = new(@"^\s*\.\.\.\s+you: #(\d+) with ([\d,]+)\s*$"); - private static readonly Regex MeHeader = new(@"^\s*(.+?) on the boards:\s*$"); - private static readonly Regex MeEntry = new(@"^\s*(.+?)\s+#(\d+) of (\d+), ([\d,]+)\s*$"); - private static readonly Regex MeNone = new(@"^\s*(.+?)\s+-\s*$"); - private static readonly Regex OneMe = new(@"^\s*(.+?): you are #(\d+) of (\d+) with ([\d,]+)"); - private static readonly Regex TopError = new(@"^\s*(?:No board called '|Leaderboards are unavailable|The boards are still being built)"); - private static readonly Regex TrialDungeonLine = new(@"^\s*(.+?) \(([0-9A-Fa-f]{4})\): (.+?) \| you: (.+?) \| this week: (.+?)\s*$"); - private static readonly Regex TrialBoardHeader = new(@"^\s*(.+?) \(([0-9A-Fa-f]{4})\) - top 10, best per character, any tier:\s*$"); - private static readonly Regex TrialEntry = new(@"^\s*(\d+)\.\s+(\d+:\d{2}(?::\d{2})?)\s+(.+?) \((.+)\)\s*$"); - private static readonly Regex TrialNote = new(@"^\s*(?:records per tier|you|this week \([^)]*\)):\s"); - private static readonly Regex TrialError = new(@"^\s*(?:No Trial matches '|The Trials are switched off|The Trials could not be read)"); - private static readonly Regex TrialIntro = new(@"^\s*Trials - a fresh personal copy of a listed dungeon"); - private static readonly Regex TrialExtra = new(@"^\s*(?:your next attempt here: in \d+ min|running now: .+|Trophy: the week's fastest clear .+)$"); - - private enum Block { None, Overview, Board, Me, TrialList, TrialBoard } - - public readonly List Overview = new(); - public string OverviewNote = ""; - public string BoardTitle = "", BoardNote = ""; - public readonly List BoardRows = new(); - public string BoardYou = ""; - public readonly List Standings = new(); - public readonly List Trials = new(); - public readonly List TrialLines = new(); - public string TrialBoardTitle = ""; - public readonly List TrialRows = new(); - public readonly List TrialNotes = new(); - public string LastError = ""; - public int Revision { get; private set; } - - private Block _block; - private long _blockMs; - private readonly ServerChatRequest _topReq = new(), _trialReq = new(); - - public void Clear() - { - Overview.Clear(); BoardRows.Clear(); Standings.Clear(); Trials.Clear(); TrialLines.Clear(); TrialRows.Clear(); TrialNotes.Clear(); - OverviewNote = BoardTitle = BoardNote = BoardYou = TrialBoardTitle = LastError = ""; - _block = Block.None; - Revision++; - } - - public string RequestTop(string arg, long now) - { - _topReq.Sent(now); - LastError = ""; - if (string.IsNullOrWhiteSpace(arg)) { BoardTitle = ""; BoardRows.Clear(); } - return string.IsNullOrWhiteSpace(arg) ? "/top" : "/top " + arg.Trim(); - } - - public string RequestTrial(string arg, long now) - { - _trialReq.Sent(now); - LastError = ""; - return string.IsNullOrWhiteSpace(arg) ? "/trial" : "/trial " + arg.Trim(); - } - - private bool InBlock(Block b, long now) => _block == b && now - _blockMs < BlockMs; - - private void Start(Block b, long now) { _block = b; _blockMs = now; } - - /// A chat line: true when it was a leaderboard reply; = it answers RynthAelrynth's request. - public bool OnChatLine(string text, long now, out bool ours) - { - ours = false; - Match m; - - if ((m = OverviewHeader.Match(text)).Success) - { - Overview.Clear(); - OverviewNote = $"{m.Groups[1].Value} characters, refreshed {m.Groups[2].Value}"; - Start(Block.Overview, now); - return Mine(_topReq, now, out ours); - } - if ((m = TrialBoardHeader.Match(text)).Success) - { - TrialBoardTitle = $"{m.Groups[1].Value} ({m.Groups[2].Value.ToUpperInvariant()})"; - TrialRows.Clear(); - TrialNotes.Clear(); - Start(Block.TrialBoard, now); - return Mine(_trialReq, now, out ours); - } - if ((m = BoardHeader.Match(text)).Success && !text.Contains(" on the boards", StringComparison.Ordinal)) - { - BoardTitle = m.Groups[1].Value.Trim(); - BoardNote = $"top {m.Groups[2].Value} of {m.Groups[3].Value}{m.Groups[4].Value}"; - BoardRows.Clear(); - BoardYou = ""; - Start(Block.Board, now); - return Mine(_topReq, now, out ours); - } - if ((m = MeHeader.Match(text)).Success) - { - Standings.Clear(); - Start(Block.Me, now); - return Mine(_topReq, now, out ours); - } - if ((m = OneMe.Match(text)).Success) - { - BoardYou = $"{m.Groups[1].Value}: #{m.Groups[2].Value} of {m.Groups[3].Value} with {m.Groups[4].Value}"; - return Mine(_topReq, now, out ours); - } - if (TopError.IsMatch(text)) - { - LastError = text.Trim(); - return Mine(_topReq, now, out ours); - } - if (TrialError.IsMatch(text)) - { - LastError = text.Trim(); - return Mine(_trialReq, now, out ours); - } - if ((m = TrialDungeonLine.Match(text)).Success) - { - if (!InBlock(Block.TrialList, now)) { Trials.Clear(); TrialLines.Clear(); } - Trials.Add(new TrialDungeon - { - Name = m.Groups[1].Value.Trim(), Landblock = m.Groups[2].Value.ToUpperInvariant(), - Record = m.Groups[3].Value.Trim(), You = m.Groups[4].Value.Trim(), Week = m.Groups[5].Value.Trim(), - }); - Start(Block.TrialList, now); - return Mine(_trialReq, now, out ours); - } - - if (InBlock(Block.Overview, now) && (m = OverviewEntry.Match(text)).Success) - { - Overview.Add(new AelrynthBoardSummary - { - Key = m.Groups[1].Value, Title = m.Groups[2].Value.Trim(), - Leader = m.Groups[3].Success ? m.Groups[3].Value.Trim() : "nobody yet", - Value = m.Groups[4].Success ? m.Groups[4].Value : "", - }); - _blockMs = now; - return Mine(_topReq, now, out ours); - } - if (InBlock(Block.Board, now)) - { - if ((m = BoardEntry.Match(text)).Success) - { - int.TryParse(m.Groups[1].Value, out int rank); - BoardRows.Add(new BoardRow - { - Rank = rank, Name = m.Groups[2].Value.Trim(), Value = m.Groups[3].Value, - Extra = m.Groups[4].Success ? m.Groups[4].Value.Trim() : "", IsYou = m.Groups[5].Success, - }); - _blockMs = now; - return Mine(_topReq, now, out ours); - } - if ((m = BoardYouBelow.Match(text)).Success) - { - BoardYou = $"you: #{m.Groups[1].Value} with {m.Groups[2].Value}"; - return Mine(_topReq, now, out ours); - } - if (text.Trim() == "nobody yet.") return Mine(_topReq, now, out ours); - } - if (InBlock(Block.Me, now)) - { - if ((m = MeEntry.Match(text)).Success) - { - int.TryParse(m.Groups[2].Value, out int r); - int.TryParse(m.Groups[3].Value, out int of); - Standings.Add(new AelrynthStanding { Title = m.Groups[1].Value.Trim(), Rank = r, Of = of, Value = m.Groups[4].Value }); - _blockMs = now; - return Mine(_topReq, now, out ours); - } - if ((m = MeNone.Match(text)).Success) - { - Standings.Add(new AelrynthStanding { Title = m.Groups[1].Value.Trim() }); - _blockMs = now; - return Mine(_topReq, now, out ours); - } - } - if (InBlock(Block.TrialBoard, now)) - { - if ((m = TrialEntry.Match(text)).Success) - { - int.TryParse(m.Groups[1].Value, out int rank); - TrialRows.Add(new BoardRow { Rank = rank, Value = m.Groups[2].Value, Name = m.Groups[3].Value.Trim(), Extra = m.Groups[4].Value.Trim() }); - _blockMs = now; - return Mine(_trialReq, now, out ours); - } - if (TrialNote.IsMatch(text) || text.Trim() == "no clear yet") - { - TrialNotes.Add(text.Trim()); - _blockMs = now; - return Mine(_trialReq, now, out ours); - } - } - // The rest of a /trial overview: the intro, "next attempt", "running now" and trophy lines. - if (TrialIntro.IsMatch(text)) - { - Trials.Clear(); - TrialLines.Clear(); - TrialLines.Add(text.Trim()); - Start(Block.TrialList, now); - return Mine(_trialReq, now, out ours); - } - if (InBlock(Block.TrialList, now) && TrialExtra.IsMatch(text)) - { - TrialLines.Add(text.Trim()); - _blockMs = now; - return Mine(_trialReq, now, out ours); - } - return false; - } - - private bool Mine(ServerChatRequest req, long now, out bool ours) - { - ours = req.Awaiting(now); - req.Extend(now); - Revision++; - return true; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthFeature.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthFeature.cs deleted file mode 100644 index bc236dd..0000000 --- a/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthFeature.cs +++ /dev/null @@ -1,106 +0,0 @@ -// AelrynthFeature.cs - What RynthAelrynth does on Aelrynth, without the host (AelrynthPlugin.cs wires it -// to the engine, AelrynthPages.cs draws it). Moved out of RynthOracle on 2026-10-20 so that only players -// who installed RynthAelrynth carry Aelrynth's features: -// * reads the replies of Aelrynth's own commands (AelrynthBoards: /top, /top me, /trial) and hides -// the replies to its own requests when HideOwnReplies is on; -// * reads the account vault (VaultFeed: /mule-data, moved here from RynthInventory, which asked every -// server for it) a few seconds after login and every ten minutes, and hands it to RynthInventory -// through the generic storage feed (Plugins/Shared/StorageFeed.cs), so it shows in Global Inventory. -// Settings: rynthaelrynth.json (ServerPackSettings); "hide own replies" is taken over once from -// rynthoracle.json (it was RynthOracle's hideOwnQuestReplies). -// Threads: everything here runs under Gate (chat and tick from the pump, the pages on the render thread). -// Pure: RynthServerPack.Tests covers it. -using System; -using RynthCore.Plugin.ServerPack; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthAelrynth; - -internal sealed class AelrynthFeature -{ - public const string SettingHideOwnReplies = "hideOwnReplies"; - /// Set once rynthoracle.json's setting was taken over (it's never read again). - public const string MigrationMarker = "migratedFromRynthOracle"; - - /// RynthAelrynth's pages (AelrynthPages draws them): id, label, tooltip. - public static readonly (string Id, string Label, string Tooltip)[] PageList = - { - ("boards", "Leaderboards", "Aelrynth's /top leaderboards and /trial dungeon records (RynthAelrynth)."), - }; - - /// Held for everything below (pump and render thread). - public readonly object Gate = new(); - public readonly AelrynthBoards Boards = new(); - - /// Hide the replies to RynthAelrynth's own requests (a command typed by hand always shows). - public bool HideOwnReplies = true; - - /// Sends a chat command as if typed (the vault's /mule-data); the plugin sets it (AelrynthPlugin). - public Func SendCommand = _ => false; - - /// The account vault reader. - public readonly VaultFeed Vault; - private long _nextVaultAskMs; - - /// What happened to the last vault read on its way to RynthInventory ("" before one). - public string VaultHandOff = string.Empty; - - public AelrynthFeature() => Vault = new VaultFeed(cmd => SendCommand(cmd)); - - /// Takes over RynthOracle's reply-hiding choice once (default: hidden, as it was there). - public static bool Migrate(ServerPackSettings settings, string oraclePath) => settings.MigrateOnce(MigrationMarker, s => - { - if (ServerPackSettings.ReadBoolFrom(oraclePath, "hideOwnQuestReplies") is bool hide) s.SetBool(SettingHideOwnReplies, hide); - }); - - public void LoadSettings(ServerPackSettings s) => HideOwnReplies = s.GetBool(SettingHideOwnReplies, true); - - public void SaveSettings(ServerPackSettings s) - { - if (s.SetBool(SettingHideOwnReplies, HideOwnReplies)) s.Save(); - } - - /// Login and logout: the boards and the vault are read fresh. - public void Reset() - { - Boards.Clear(); - Vault.Reset(); - _nextVaultAskMs = 0; - VaultHandOff = string.Empty; - } - - /// - /// An incoming chat line on Aelrynth: true when it should be hidden. The vault's data lines (and - /// the unknown-command reply to our own probe) always are; a leaderboard reply to our own request - /// is when HideOwnReplies is on. - /// - public bool OnChatLine(string text, int chatType, long nowMs) - { - if (Vault.ShouldEat(text, chatType)) return true; - return Boards.OnChatLine(text.TrimEnd('\r', '\n'), nowMs, out bool ours) && ours && HideOwnReplies; - } - - /// - /// The vault's timing (plugin tick, on Aelrynth): the first read - /// after login, then every unless the server has no vault. - /// Returns the record to hand to RynthInventory when a read just finished, else null. - /// - public StorageFeedRecord? VaultTick(long nowMs, string account) - { - if (_nextVaultAskMs == 0) _nextVaultAskMs = nowMs + VaultFeed.FirstAskMs; - else if (nowMs >= _nextVaultAskMs && Vault.Status != VaultFeed.State.Unsupported) - { - _nextVaultAskMs = nowMs + VaultFeed.RefreshMs; - Vault.Ask(nowMs); - } - Vault.Tick(nowMs, account); - return Vault.TakeChanged() ? Vault.Record : null; - } - - /// "/rserver vault": a read now (even on a server that said it has none); the next timed one in ten minutes. - public bool VaultAskNow(long nowMs) - { - _nextVaultAskMs = nowMs + VaultFeed.RefreshMs; - return Vault.Ask(nowMs, force: true); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthPages.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthPages.cs deleted file mode 100644 index 7745c0c..0000000 --- a/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/AelrynthPages.cs +++ /dev/null @@ -1,252 +0,0 @@ -// RynthOracle's Leaderboards tab, Aelrynth's half (Views/BoardsTab.cs), moved here on 2026-10-20 and -// redrawn with ImGui as RynthAelrynth's Leaderboards page: a sub-tab of the Mini Remote's Server -// section while on Aelrynth, and a tab of the /rserver window. -using System; -using System.Numerics; -using ImGuiNET; -using RynthCore.Plugin.ServerPack; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthAelrynth; - -/// -/// Aelrynth's /top boards (every board's leader, one board's top 10, your own standings) and the -/// /trial dungeon records. Render thread: draws holding the feature's lock, and queues what it sends. -/// -internal sealed class AelrynthPages -{ - private static readonly Vector4 Gold = new(1.00f, 0.84f, 0.30f, 1f); - private static readonly Vector4 Red = new(0.95f, 0.45f, 0.40f, 1f); - private static readonly Vector4 Selected = new(0.26f, 0.45f, 0.70f, 1f); - - private readonly AelrynthFeature _f; - private readonly Func _active; - private readonly Action _runOnTick; - private readonly Func _send; - private readonly Action _print; - private readonly Action _saveSettings; - private readonly ServerRefreshRow _refresh = new(); - - private int _view; // 0 boards, 1 me, 2 trials - private string _boardArg = ""; - private string _trialArg = ""; - - public AelrynthPages(AelrynthFeature feature, Func active, Action runOnTick, Func send, - Action print, Action saveSettings) - { - _f = feature; - _active = active; - _runOnTick = runOnTick; - _send = send; - _print = print; - _saveSettings = saveSettings; - } - - public ServerPage[] Pages() - { - var list = AelrynthFeature.PageList; - return new[] { new ServerPage(list[0].Id, list[0].Label, list[0].Tooltip, DrawBoards) }; - } - - /// Logout: the next character's status lines start empty. - public void Reset() => _refresh.Reset(); - - private void DrawBoards() - { - if (!_active()) - { - SafeImGui.TextWrapped("This page is for Aelrynth. RynthCore doesn't see this world as Aelrynth " - + "(check RynthCore Options > Diagnostics, or /rserver info)."); - return; - } - lock (_f.Gate) - { - AelrynthBoards a = _f.Boards; - if (Toggle("Boards##ab_v0", _view == 0)) _view = 0; - ImGui.SameLine(); - if (Toggle("Me##ab_v1", _view == 1)) _view = 1; - ImGui.SameLine(); - if (Toggle("Trials##ab_v2", _view == 2)) _view = 2; - _refresh.Draw("ab" + _view, BoardsHelp(), RefreshBoards); - ImGui.Separator(); - if (a.LastError.Length > 0) SafeImGui.TextColored(Red, a.LastError); - - if (_view == 1) DrawMe(a); - else if (_view == 2) DrawTrials(a); - else DrawOverview(a); - - ImGui.Spacing(); - bool hide = _f.HideOwnReplies; - if (ImGui.Checkbox("Hide the replies to RynthAelrynth's own requests##ab_hide", ref hide)) - { - _f.HideOwnReplies = hide; - _runOnTick(_saveSettings); - } - if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("/top and /trial when RynthAelrynth sends them. A command you type yourself always shows its reply."); - } - } - - private void DrawMe(AelrynthBoards a) - { - if (ImGui.BeginChild("##ab_me", new Vector2(0f, 300f), ImGuiChildFlags.Borders)) - { - foreach (AelrynthStanding s in a.Standings) - { - SafeImGui.Text(Cut(s.Title, 34)); - ImGui.SameLine(260f); - SafeImGui.Text(s.Rank > 0 ? $"#{s.Rank} of {s.Of}" : "-"); - if (s.Value.Length > 0) { ImGui.SameLine(380f); SafeImGui.Text(s.Value); } - } - if (a.Standings.Count == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh."); - } - ImGui.EndChild(); - } - - private void DrawTrials(AelrynthBoards a) - { - ImGui.SetNextItemWidth(220f); - ImGui.InputText("Dungeon##ab_trialarg", ref _trialArg, 48); - ImGui.SameLine(); - if (ImGui.SmallButton("Top 10##ab_trialtop") && _trialArg.Trim().Length > 0) Ask(a, isTrial: true, _trialArg); - if (ImGui.BeginChild("##ab_trials", new Vector2(0f, 300f), ImGuiChildFlags.Borders)) - { - int i = 0; - foreach (TrialDungeon d in a.Trials) - { - TrialDungeon row = d; - if (ImGui.Selectable($"{d.Name} ({d.Landblock})##ab_t{i++}")) - { - _trialArg = row.Name; - Ask(a, isTrial: true, row.Name); - } - if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("Click for this dungeon's top 10."); - ImGui.TextDisabled(" record:"); ImGui.SameLine(90f); SafeImGui.TextWrapped(d.Record); - ImGui.TextDisabled(" you:"); ImGui.SameLine(90f); SafeImGui.Text(d.You); - ImGui.TextDisabled(" this week:"); ImGui.SameLine(90f); SafeImGui.Text(d.Week); - } - foreach (string line in a.TrialLines) if (!line.StartsWith("Trials - ", StringComparison.Ordinal)) SafeImGui.TextWrapped(line); - if (a.TrialBoardTitle.Length > 0) - { - ImGui.SeparatorText(a.TrialBoardTitle); - foreach (BoardRow r in a.TrialRows) - { - SafeImGui.Text($"{r.Rank,2}. {r.Value}"); - ImGui.SameLine(90f); - SafeImGui.Text(Cut(r.Name, 28)); - ImGui.SameLine(300f); - SafeImGui.TextDisabled(Cut(r.Extra, 40)); - } - foreach (string n in a.TrialNotes) SafeImGui.TextWrapped(n); - } - if (a.Trials.Count == 0 && a.TrialBoardTitle.Length == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh."); - } - ImGui.EndChild(); - } - - private void DrawOverview(AelrynthBoards a) - { - if (ImGui.SmallButton("All boards##ab_all")) Ask(a, isTrial: false, ""); - if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("Sends /top: every board's leader."); - ImGui.SameLine(); - ImGui.SetNextItemWidth(160f); - ImGui.InputText("Board##ab_arg", ref _boardArg, 32); - ImGui.SameLine(); - if (ImGui.SmallButton("Top 10##ab_board") && _boardArg.Trim().Length > 0) Ask(a, isTrial: false, _boardArg); - if (a.OverviewNote.Length > 0) SafeImGui.TextDisabled(a.OverviewNote); - - if (a.BoardTitle.Length > 0) - { - ImGui.SeparatorText($"{a.BoardTitle} ({a.BoardNote})"); - if (a.BoardYou.Length > 0) SafeImGui.TextColored(Gold, a.BoardYou); - if (ImGui.BeginChild("##ab_rows", new Vector2(0f, 300f), ImGuiChildFlags.Borders)) - { - ImGui.TextDisabled("Rank"); ImGui.SameLine(60f); ImGui.TextDisabled("Name"); ImGui.SameLine(280f); ImGui.TextDisabled("Value"); - foreach (BoardRow r in a.BoardRows) - { - SafeImGui.Text(r.Rank.ToString()); - ImGui.SameLine(60f); - if (r.IsYou) SafeImGui.TextColored(Gold, Cut(r.Name, 30)); - else SafeImGui.Text(Cut(r.Name, 30)); - ImGui.SameLine(280f); - SafeImGui.Text(r.Value); - if (r.Extra.Length > 0) { ImGui.SameLine(420f); SafeImGui.TextDisabled(Cut(r.Extra, 40)); } - } - if (a.BoardRows.Count == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh."); - } - ImGui.EndChild(); - return; - } - if (ImGui.BeginChild("##ab_overview", new Vector2(0f, 300f), ImGuiChildFlags.Borders)) - { - int i = 0; - foreach (AelrynthBoardSummary s in a.Overview) - { - AelrynthBoardSummary row = s; - if (ImGui.Selectable(Cut(s.Title, 30) + "##ab_o" + i++, false, ImGuiSelectableFlags.None, new Vector2(230f, 0f))) - { - _boardArg = row.Key; - Ask(a, isTrial: false, row.Key); - } - if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"/top {s.Key}"); - ImGui.SameLine(240f); - SafeImGui.Text(Cut(s.Leader, 24)); - if (s.Value.Length > 0) { ImGui.SameLine(430f); SafeImGui.Text(s.Value); } - } - if (a.Overview.Count == 0) ImGui.TextDisabled("Nothing read yet. Press All boards."); - } - ImGui.EndChild(); - } - - // ── Refresh (RynthOracle's RefreshBar, Aelrynth's part) ───────────── - - private ServerRefreshResult RefreshBoards() - { - AelrynthBoards a = _f.Boards; - string key = _view switch { 1 => "top me", 2 => "trial", _ => "top " + _boardArg }; - if (_refresh.CoolingDown(key, Environment.TickCount64)) return new ServerRefreshResult(ServerRefreshRow.TooSoon); - int before = a.Revision; - string cmd = _view switch - { - 1 => Ask(a, isTrial: false, "me"), - 2 => Ask(a, isTrial: true, ""), - _ => Ask(a, isTrial: false, a.BoardTitle.Length > 0 ? _boardArg : ""), - }; - return new ServerRefreshResult($"Sent {cmd}.", () => a.Revision != before); - } - - private string BoardsHelp() => _view switch - { - 1 => "Sends /top me and reads the reply.", - 2 => "Sends /trial and reads the dungeon list.", - _ => "Sends /top (every board's leader), or asks again for the board that is open.", - }; - - /// - /// "/top [arg]" or "/trial [arg]" on the next tick, marked as RynthAelrynth's own (its reply can - /// be hidden); returns the command. - /// - private string Ask(AelrynthBoards a, bool isTrial, string arg) - { - string cmd = string.IsNullOrWhiteSpace(arg) ? (isTrial ? "/trial" : "/top") : (isTrial ? "/trial " : "/top ") + arg.Trim(); - _runOnTick(() => - { - lock (_f.Gate) - { - if (isTrial) a.RequestTrial(arg, Environment.TickCount64); - else a.RequestTop(arg, Environment.TickCount64); - } - if (!_send(cmd)) _print($"Couldn't send {cmd} (not in the world)."); - }); - return cmd; - } - - private static bool Toggle(string label, bool selected) - { - if (selected) ImGui.PushStyleColor(ImGuiCol.Button, Selected); - bool clicked = ImGui.SmallButton(label); - if (selected) ImGui.PopStyleColor(); - return clicked; - } - - private static string Cut(string s, int max) => s.Length <= max ? s : s.Substring(0, Math.Max(0, max - 3)) + "..."; -} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/VaultFeed.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/VaultFeed.cs deleted file mode 100644 index ea3732e..0000000 --- a/Plugins/RynthCore.Plugin.RynthAelrynth/Aelrynth/VaultFeed.cs +++ /dev/null @@ -1,239 +0,0 @@ -// Moved here from RynthInventory (Scanning/VaultFeed.cs) on 2026-10-20: RynthInventory asked every server -// for an Aelrynth vault; now only RynthAelrynth asks, on Aelrynth, and hands the vault to RynthInventory -// through the generic storage feed (Plugins/Shared/StorageFeed.cs). -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Globalization; -using System.Text.Json; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthAelrynth; - -/// -/// The Aelrynth account vault (the Aeshnidae.Mule mod): item storage the retail client is never -/// shown, so the only way to see inside is to ask. RynthAelrynth types /mule-data, exactly as a -/// player could, and the server answers one chat line a page: -/// -/// ~ael1 {"t":"mule","ready":true,"page":1,"pages":3,"count":57,"max":1000,"items":[{...}]} -/// -/// (the same "~ael1" lines the Aelrynth Companion reads; only lines whose "t" is "mule" are ours). -/// The pages are collected into one StorageFeedRecord, which RynthAelrynth sends to RynthInventory -/// (StorageFeed): it is kept with the character's storage, so the vault is searched, shown with -/// icons and merged across characters like any other storage; the newest copy wins, and a vault -/// belongs to the account, so every character sees the same one. -/// -/// A server without the command (Aelrynth without the mod, or a world wrongly taken for Aelrynth) -/// is asked once after login; its "Unknown command" reply is eaten and the feed stays quiet. A -/// vault the server says is not ready yet is asked again a few times, and is never recorded as empty. -/// -/// Threads: only queues; everything else runs on the plugin tick. -/// Pure: RynthServerPack.Tests covers it. -/// -internal sealed class VaultFeed -{ - public const string Command = "/mule-data"; - public const string Prefix = "~ael1 "; - public const string Label = "Account vault"; - public const string VaultName = "Aelrynth vault"; - /// After login, before the first /mule-data; then every . - public const long FirstAskMs = 8_000, RefreshMs = 10 * 60_000; - - public enum State { Idle, Asking, Unsupported, Waiting } - - private const long AnswerWindowMs = 15_000, RetryReadyMs = 3_000; - private const int MaxReadyRetries = 6, MaxPages = 80; - private const string UnknownMarker = "\u0001unknown"; - - private readonly Func _send; - private readonly ConcurrentQueue _lines = new(); - - private long _sentAtMs; - private volatile bool _expecting; - private int _readyTries; - private long _retryAtMs; - private readonly List _pages = new(); - private bool _changed; - - public VaultFeed(Func send) => _send = send; - - public State Status { get; private set; } = State.Idle; - /// The vault once a full read finished (null until then). - public StorageFeedRecord? Record { get; private set; } - public int Max { get; private set; } - - /// For /rserver info. - public string Describe() => Status switch - { - State.Unsupported => "no vault on this server", - State.Asking => "reading the vault...", - State.Waiting => "the vault is still loading on the server", - _ => Record == null ? "vault not read yet" : $"vault: {Record.Items.Count} item(s)" + (Max > 0 ? $" of {Max}" : ""), - }; - - /// True once after was replaced. - public bool TakeChanged() { bool c = _changed; _changed = false; return c; } - - /// Login and logout: a fresh read (the record from before is forgotten). - public void Reset() - { - Status = State.Idle; - _expecting = false; - _pages.Clear(); - _readyTries = 0; - Record = null; - _changed = false; - Max = 0; - while (_lines.TryDequeue(out _)) { } - } - - /// Starts a read from page 1, unless one is under way or the server has no vault ( asks anyway). - public bool Ask(long nowMs, bool force = false) - { - if (Status == State.Asking || Status == State.Waiting) return false; - if (Status == State.Unsupported && !force) return false; - _readyTries = 0; - _pages.Clear(); - return SendPage(nowMs, 1); - } - - private bool SendPage(long nowMs, int page) - { - _sentAtMs = nowMs; - Status = State.Asking; - _expecting = true; - if (_send(page <= 1 ? Command : Command + " " + page.ToString(CultureInfo.InvariantCulture))) return true; - _expecting = false; - Status = State.Idle; - return false; - } - - /// - /// True for a line this feed answers, so the caller keeps it out of the chat window. Cheap; any thread. - /// is the line's eChatTypes (-1 = not known). Server lines only: a line - /// in a player's chat type, or one that doesn't start with the marker (a player's copy has their - /// name in front), is left alone, so nobody can feed the vault view or hide chat by typing "~ael1". - /// - public bool ShouldEat(string? text, int chatType = -1) - { - if (string.IsNullOrEmpty(text) || ChatSource.IsPlayerAuthored(chatType)) return false; - int at = ChatSource.ContentStart(text); - if (ChatSource.StartsWithMarker(text, Prefix)) - { - // Only our own kind: another plugin's ~ael1 line (the Companion's) stays visible to it. - if (text.IndexOf("\"t\":\"mule\"", at, StringComparison.Ordinal) < 0) return false; - _lines.Enqueue(text.Substring(at + Prefix.Length)); - return true; - } - // The reply of a server that has no such command: swallowed only while we wait for one. - if (_expecting && IsUnknownCommandReply(text)) - { - _lines.Enqueue(UnknownMarker); - return true; - } - return false; - } - - /// ACE's "Unknown command: mule-data" (GameActionTalk names the bare command; a leading / or @ is allowed). - private static bool IsUnknownCommandReply(string text) - { - const string marker = "Unknown command:"; - if (!ChatSource.StartsWithMarker(text, marker, StringComparison.OrdinalIgnoreCase)) return false; - string named = text.Substring(ChatSource.ContentStart(text) + marker.Length).Trim().TrimStart('/', '@'); - return string.Equals(named, "mule-data", StringComparison.OrdinalIgnoreCase); - } - - /// Applies what arrived and decides what to send next. Plugin tick. - public void Tick(long nowMs, string account) - { - while (_lines.TryDequeue(out string? line)) Apply(line, nowMs, account); - - if (Status == State.Waiting && nowMs >= _retryAtMs) SendPage(nowMs, 1); - else if (Status == State.Asking && nowMs - _sentAtMs > AnswerWindowMs) - { - // Nothing came back: a server without the mod, or a lost line. The next refresh retries. - _expecting = false; - Status = State.Idle; - _pages.Clear(); - } - } - - private void Apply(string line, long nowMs, string account) - { - if (line == UnknownMarker) - { - if (Status == State.Asking) { _expecting = false; Status = State.Unsupported; _pages.Clear(); } - return; - } - if (Status != State.Asking) return; // a line we did not ask for (typed by hand, say) - _expecting = false; - - try - { - using JsonDocument doc = JsonDocument.Parse(line); - JsonElement root = doc.RootElement; - if (root.ValueKind != JsonValueKind.Object) { Status = State.Idle; return; } - - if (!(root.TryGetProperty("ready", out JsonElement ready) && ready.ValueKind == JsonValueKind.True)) - { - string why = Str(root, "why"); - if (why == "loading" && ++_readyTries <= MaxReadyRetries) { Status = State.Waiting; _retryAtMs = nowMs + RetryReadyMs; } - else Status = State.Idle; // closed / fault / error: try again at the next refresh - _pages.Clear(); - return; - } - - int page = Int(root, "page", 1), pages = Math.Min(Math.Max(Int(root, "pages", 1), 1), MaxPages); - Max = Int(root, "max", Max); - int count = Int(root, "count", 0); - if (page == 1) _pages.Clear(); - if (root.TryGetProperty("items", out JsonElement items) && items.ValueKind == JsonValueKind.Array) - foreach (JsonElement e in items.EnumerateArray()) - if (e.ValueKind == JsonValueKind.Object) _pages.Add(Item(e)); - - if (page < pages) { SendPage(nowMs, page + 1); return; } - - // Last page. A total that disagrees with what was read means the vault changed under - // the read (a deposit between pages): keep the old copy and read again shortly. - if (count != _pages.Count && _readyTries++ < MaxReadyRetries) - { - Status = State.Waiting; _retryAtMs = nowMs + RetryReadyMs; _pages.Clear(); return; - } - Record = new StorageFeedRecord(VaultId(account), VaultName, Label, new List(_pages)); - _pages.Clear(); - _changed = true; - Status = State.Idle; - } - catch (JsonException) - { - Status = State.Idle; - _pages.Clear(); - } - } - - private static StorageFeedItem Item(JsonElement e) => new( - UInt(e, "o"), UInt(e, "w"), Str(e, "n"), UInt(e, "i"), UInt(e, "u"), UInt(e, "v"), - Math.Max(1, Int(e, "s", 1)), Int(e, "m", 0), UInt(e, "y")); - - /// - /// A stand-in container id for the account's vault. Storage is merged by (server, id) with the - /// newest copy winning, so the same id on every character of the account shows ONE vault. It is - /// in the top of the id space, where no object the client has seen lives (StorageFeed.IsStandInId). - /// The same formula as RynthInventory used, so vaults saved before the move are replaced, not doubled. - /// - public static uint VaultId(string account) - { - uint h = 2166136261u; - foreach (char c in (account ?? "").Trim().ToLowerInvariant()) { h ^= c; h *= 16777619u; } - return 0xFF000000u | (h & 0x00FFFFFFu); - } - - private static int Int(JsonElement e, string name, int fallback) => - e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : fallback; - - private static uint UInt(JsonElement e, string name) => - e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetUInt32(out uint u) ? u : 0u; - - private static string Str(JsonElement e, string name) => - e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty; -} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/AelrynthPlugin.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/AelrynthPlugin.cs deleted file mode 100644 index 6f8447c..0000000 --- a/Plugins/RynthCore.Plugin.RynthAelrynth/AelrynthPlugin.cs +++ /dev/null @@ -1,127 +0,0 @@ -// AelrynthPlugin.cs - RynthAelrynth's own features, through the shared server plugin's hooks -// (Plugins/Shared/ServerPack/ServerPackPlugin.cs). Aelrynth-specific code that RynthOracle and -// RynthInventory used to carry lives here since 2026-10-20 (Aelrynth/AelrynthFeature.cs says what), -// so a player without RynthAelrynth gets none of it, and no other server is asked for a vault. -using System; -using System.IO; -using RynthCore.Plugin.RynthAelrynth; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.ServerPack; - -public sealed partial class ServerPackPlugin -{ - private readonly AelrynthFeature _aelrynth = new(); - private AelrynthPages? _aelrynthPages; - // The last vault read, until RynthInventory took it (it may load after the read). - private StorageFeedRecord? _vaultToHandOff; - private long _nextVaultHandOffMs; - private const long VaultHandOffRetryMs = 30_000; - - /// Where RynthOracle kept the reply-hiding choice before it moved here (read once). - internal static string OracleSettingsPath => Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthoracle.json"); - - partial void ServerPages(System.Collections.Generic.List pages) - { - _aelrynthPages = new AelrynthPages(_aelrynth, () => Active, RunOnTick, Send, - text => ChatLine($"[{RynthPluginInfo.Name}] {text}"), SaveAelrynthSettings); - pages.AddRange(_aelrynthPages.Pages()); - } - - partial void ServerCommandVerbs(System.Collections.Generic.List verbs) => verbs.Add("vault"); - - partial void ServerInitialize() - { - _aelrynth.SendCommand = Send; - if (AelrynthFeature.Migrate(Settings, OracleSettingsPath)) - LogTagged("Took over RynthOracle's reply-hiding choice from rynthoracle.json."); - lock (_aelrynth.Gate) _aelrynth.LoadSettings(Settings); - } - - private void SaveAelrynthSettings() - { - lock (_aelrynth.Gate) _aelrynth.SaveSettings(Settings); - } - - partial void ServerLoginComplete() - { - lock (_aelrynth.Gate) _aelrynth.Reset(); - _vaultToHandOff = null; - _aelrynthPages?.Reset(); - } - - partial void ServerLogout() - { - lock (_aelrynth.Gate) _aelrynth.Reset(); - _vaultToHandOff = null; - _aelrynthPages?.Reset(); - } - - partial void ServerShutdown() => SaveAelrynthSettings(); - - partial void ServerChatText(string text, int chatType, ref bool eat) - { - if (!Active) return; - bool hide; - lock (_aelrynth.Gate) hide = _aelrynth.OnChatLine(text, chatType, Environment.TickCount64); - if (hide) eat = true; - } - - partial void ServerTick(bool active) - { - if (!active || !Host.HasInvokeChatParser) return; - long now = Environment.TickCount64; - uint player = Host.HasGetPlayerId ? Host.GetPlayerId() : 0; - if (player == 0) return; // the vault belongs to the account; wait for the character - string account = Host.TryGetAccountName(out string a) && a.Trim().Length > 0 ? a.Trim() : "unknown"; - StorageFeedRecord? read; - lock (_aelrynth.Gate) read = _aelrynth.VaultTick(now, account); - if (read != null) { _vaultToHandOff = read; _nextVaultHandOffMs = 0; } - if (_vaultToHandOff != null && now >= _nextVaultHandOffMs) HandOffVault(now); - } - - /// - /// The vault to RynthInventory (StorageFeed), which files it with the character's storage. Kept and - /// offered again now and then while RynthInventory isn't there to take it. - /// - private void HandOffVault(long now) - { - StorageFeedRecord? vault = _vaultToHandOff; - if (vault == null) return; - bool taken = Host.HasSendPluginCommand - && Host.SendPluginCommand(StorageFeed.TargetPlugin, StorageFeed.Action, StorageFeed.ToJson(vault)); - string note = taken - ? $"{vault.Items.Count} item(s) handed to RynthInventory at {DateTime.Now:HH:mm}" - : "RynthInventory isn't loaded (or is too old), so the vault isn't in Global Inventory"; - lock (_aelrynth.Gate) _aelrynth.VaultHandOff = note; - if (taken) _vaultToHandOff = null; - else _nextVaultHandOffMs = now + VaultHandOffRetryMs; - } - - partial void ServerChatCommand(string[] parts, ref bool handled) - { - if (parts.Length < 2 || !parts[1].Equals("vault", StringComparison.OrdinalIgnoreCase)) return; - handled = true; - string tag = $"[{RynthPluginInfo.Name}] "; - if (!Active) { ChatLine(tag + "The account vault is Aelrynth's; RynthCore doesn't see this world as Aelrynth."); return; } - bool asked; - string state; - lock (_aelrynth.Gate) - { - asked = _aelrynth.VaultAskNow(Environment.TickCount64); - state = _aelrynth.Vault.Describe(); - } - ChatLine(tag + (asked ? "Reading the account vault (/mule-data)..." : "The vault is already being read: " + state)); - } - - partial void ServerInfoLines(Action line) - { - lock (_aelrynth.Gate) - { - string handOff = _aelrynth.VaultHandOff.Length > 0 ? "; " + _aelrynth.VaultHandOff : ""; - line("Account vault: " + _aelrynth.Vault.Describe() + handOff + " (/rserver vault reads it now)."); - line("Own replies (/top, /trial) " + (_aelrynth.HideOwnReplies ? "hidden" : "shown") + "."); - } - } -} diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/RynthCore.Plugin.RynthAelrynth.csproj b/Plugins/RynthCore.Plugin.RynthAelrynth/RynthCore.Plugin.RynthAelrynth.csproj deleted file mode 100644 index 389e70b..0000000 --- a/Plugins/RynthCore.Plugin.RynthAelrynth/RynthCore.Plugin.RynthAelrynth.csproj +++ /dev/null @@ -1,27 +0,0 @@ - - - - - RynthCore.Plugin.RynthAelrynth - 0.2.0 - aelrynth - Aelrynth - aelrynth.com - Aelrynth*|Aeshnidae* - Aelrynth only: the server card (its mods, links, account setup), Aelrynth's leaderboards and Trials records in the Mini Remote, and the account vault in Global Inventory. - - - - - - - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthAelrynth/ServerData.cs b/Plugins/RynthCore.Plugin.RynthAelrynth/ServerData.cs deleted file mode 100644 index ceda2cc..0000000 --- a/Plugins/RynthCore.Plugin.RynthAelrynth/ServerData.cs +++ /dev/null @@ -1,27 +0,0 @@ -// ServerData.cs - What is known about Aelrynth (RynthAelrynth). Identity (id, hosts, world names) is in the csproj. -// Aelrynth isn't in the public server list; this comes from RynthCore's own Aelrynth support -// (Compatibility/AelrynthWire.cs, Net/AelrynthVaultWire.cs) and RynthOracle's quest pack. -namespace RynthCore.Plugin.ServerPack; - -internal static class ServerData -{ - public static ServerPackInfo Create() => - new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) - { - Port = 9020, - Emulator = "ACE", - Ruleset = "PvE", - Summary = "Aelrynth (aelrynth.com), an ACE server with its own mods.", - Facts = new[] - { - "Bank mod: Radiance and Luminance banking (RynthCore reads its totals).", - "Skill Mastery mod (RynthCore shows mastery progress).", - "Account vault for mules (RynthCore reads its contents; RynthAelrynth puts it in Global Inventory, /rserver vault).", - "RynthOracle has an Aelrynth quest pack (quests.aelrynth.csv).", - "RynthAelrynth's Leaderboards page (Server section, or /rserver): the /top boards and /trial dungeon records.", - "The world was named Aeshnidae before; both names count.", - }, - Website = "https://aelrynth.com", - Source = "RynthCore's Aelrynth support and RynthOracle, 2026-10-13", - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index 27adb2b..eee4786 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -507,7 +507,7 @@ public partial class CombatManager : IDisposable private int _fightCastCount; // offensive casts fired this fight (for casts-to-kill learning) private bool _fightAppraiseRequested; // one appraisal attempt per fight to fill unknown HP private bool _fightHpEstimated; // _fightTargetMaxHp is tier 0's scaled by the tier, not measured - private AwakenedTier? _awakenedTier; // Aelrynth's difficulty tier where we stand (0 elsewhere) + private DifficultyTier? _difficultyTier; // the server plugin's difficulty tier where we stand (0 without one) // Predicted one-shots are swapped away BEFORE their own KillerNotification // arrives, so OnKillNotification (which keys off the CURRENT target) can't @@ -589,10 +589,10 @@ public partial class CombatManager : IDisposable _damageStore = damage; } - internal void SetAwakenedTier(AwakenedTier? tier) => _awakenedTier = tier; + internal void SetDifficultyTier(DifficultyTier? tier) => _difficultyTier = tier; - /// Aelrynth's difficulty tier where we stand; always 0 on other servers. - private int Difficulty => _awakenedTier?.Current ?? 0; + /// The difficulty tier where we stand, as the server plugin reports it; always 0 without one. + private int Difficulty => _difficultyTier?.Current ?? 0; public int RaycastBlockCount { get; private set; } public int RaycastCheckCount { get; private set; } @@ -2762,10 +2762,10 @@ public partial class CombatManager : IDisposable if (_fightTargetMaxHp > 0 && !_fightHpEstimated) return; - // Aelrynth's awakened worlds and scaled copies: the same wcid, +5% health a tier. - // 0 everywhere else, and then this is the old resolution exactly. + // A server's scaled worlds and copies: the same wcid, its health percent a tier (the server + // plugin's numbers, DifficultyTier). 0 everywhere else, and then this is the old resolution exactly. int difficulty = Difficulty; - double scale = AwakenedTier.HealthScale(difficulty); + double scale = _difficultyTier?.HealthScale(difficulty) ?? 1.0; // User-entered HP override (set in the Damage panel) is authoritative — // it's the manual fix for ACE's skill-gated appraisal reading low. diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/OffhandPlanner.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/OffhandPlanner.cs index 45a412b..b5c8b4c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/OffhandPlanner.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/OffhandPlanner.cs @@ -152,7 +152,9 @@ internal static class OffhandRules /// adds none). /// * An explicit item (the Damage tab's per-monster offhand, else the rule's old item pick): /// used when it is listed and allowed (a weapon needs the Dual Wield skill and the -/// slot-wield call), else the mode decides. +/// slot-wield call), else the mode decides. An explicit weapon that is the main weapon this +/// fight (picked for the monster's weakness) gives its place to the other listed one-handed +/// weapon, so the character keeps dual wielding. /// * Shield: the best listed shield. Weapon: a second listed one-handed melee weapon when /// the Dual Wield skill is trained, else the best shield. Auto: the best shield; a second /// listed one-handed weapon instead only when is on and @@ -180,12 +182,21 @@ internal static class OffhandPlanner else if (weapon == null || (c.InOffhand && !weapon.InOffhand)) weapon = c; } - if (explicitId != 0 && explicitId != mainId) + if (explicitId != 0) { foreach (var c in listed) { if (c.Id != explicitId) continue; - if (c.IsShield || dualOk) return new OffhandPlan(c.Id, explicitSource); + if (explicitId != mainId) + { + if (c.IsShield || dualOk) return new OffhandPlan(c.Id, explicitSource); + } + // The off-hand weapon picked is the main weapon this fight (chosen for the monster's + // weakness): the other listed one-handed weapon goes in the off hand, so the + // character still dual wields. It used to fall to the mode, and Auto with no shield + // listed left the off hand empty (Drakkon, 2026-10-21). + else if (!c.IsShield && dualOk && weapon != null) + return new OffhandPlan(weapon.Id, explicitSource + "; it is in the main hand, so the other weapon"); break; } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/AwakenedTier.cs b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/AwakenedTier.cs deleted file mode 100644 index cd94d52..0000000 --- a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/AwakenedTier.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.RynthAi.CreatureData; - -/// -/// Aelrynth's difficulty tier where the player stands, and which server this is (2026-10-03). -/// -/// Aelrynth's awakened worlds and scaled dungeon copies hold the same monsters as real Dereth - -/// same names, same wcids - with health, skills and damage scaled 5% a tier (resistances and -/// weaknesses are not). Every monster in one copy or world shares one tier. The server tells -/// the player's own client that tier as PropertyInt 9051 on the player (Aeshnidae.AwakenedRewards -/// TierFeed.cs): a private update on login, teleport and every change; 0 = real Dereth. -/// -/// The rule: on any server other than Aelrynth this is inert - is 0 and -/// false - so every store keyed by tier behaves exactly as before. On -/// Aelrynth it also stays inert until the property has been seen this login (an older server -/// build that does not send it changes nothing either). -/// -/// Server detection matches RynthOracle's (Data/ServerIdentity.cs) older-engine path: the world -/// name the server announced (Aelrynth's live world is still named "Aeshnidae"; both names, and -/// the staging world, count), else the Bank mod's player properties 9101-9103, which only -/// Aelrynth sends. Engine API v75 adds GetServerInfo (the engine's own verdict); when the SDK -/// this builds against has it, it should be asked first, as RynthOracle does. -/// -internal sealed class AwakenedTier -{ - /// PropertyInt 9051 on the player: the difficulty tier where they stand. - public const uint TierProperty = 9051; - - /// The server's scaling per tier (InstancesNoDat DifficultyPercentPerEnlightenment, 5.0). - public const double PercentPerTier = 5.0; - - private const uint QuadRadianceEarned = 9101, QuadLuminanceBanked = 9102, QuadLuminanceDrawn = 9103; - - private volatile bool _aelrynth; - private volatile bool _seen; - private volatile int _tier; - private string _serverKey = ""; - private long _nextRefreshMs; - - /// On Aelrynth (live or staging), by the world name or the Bank properties. - public bool OnAelrynth => _aelrynth; - - /// The tier property has been seen this login. - public bool Seen => _seen; - - /// The tier feature is in force: on Aelrynth and the property seen. Off everywhere else. - public bool Active => _aelrynth && _seen; - - /// The tier where the player stands; 0 whenever is false. - public int Current => Active ? _tier : 0; - - /// - /// The server's key for per-server data (creatures.json): "Aelrynth" for every Aelrynth - /// world name (live "Aeshnidae", "Aelrynth", "Aeshnidae Staging"), else the world name made - /// safe for a folder name; "" while unknown. - /// - public string ServerKey => _serverKey; - - /// The multiplier a tier puts on a monster's health: 1 + 5% per tier. - public static double HealthScale(int tier) => tier <= 0 ? 1.0 : 1.0 + PercentPerTier / 100.0 * tier; - - /// Logout: nothing carries to the next login (it may be another server). - public void Reset() - { - _aelrynth = false; - _seen = false; - _tier = 0; - _serverKey = ""; - _nextRefreshMs = 0; - } - - /// Re-reads the server and the tier, at most once a second. Pump thread. - public void Refresh(RynthCoreHost host, uint playerId, bool force = false) - { - long now = Environment.TickCount64; - if (!force && now < _nextRefreshMs) return; - _nextRefreshMs = now + 1000; - - try - { - string world = host.HasGetWorldName && host.TryGetWorldName(out string w) ? (w ?? "").Trim() : ""; - bool aelrynth = IsAelrynthWorld(world) - || (playerId != 0 && host.HasGetObjectQuadProperty - && (host.TryGetObjectQuadProperty(playerId, QuadRadianceEarned, out _) - || host.TryGetObjectQuadProperty(playerId, QuadLuminanceBanked, out _) - || host.TryGetObjectQuadProperty(playerId, QuadLuminanceDrawn, out _))); - _aelrynth = aelrynth; - _serverKey = aelrynth ? "Aelrynth" : SafeKey(world); - - if (aelrynth && playerId != 0 && host.HasGetObjectIntProperty - && host.TryGetObjectIntProperty(playerId, TierProperty, out int tier)) - { - _tier = Math.Max(0, tier); - _seen = true; - } - } - catch { } - } - - /// Aelrynth's world names: "Aelrynth...", or "Aeshnidae..." (its earlier name, still the live config's). - public static bool IsAelrynthWorld(string? world) - { - if (string.IsNullOrWhiteSpace(world)) return false; - string w = world.Trim(); - return w.StartsWith("Aelrynth", StringComparison.OrdinalIgnoreCase) - || w.StartsWith("Aeshnidae", StringComparison.OrdinalIgnoreCase); - } - - /// A world name as a folder name (the SettingsProfiles rule); "" for none. - public static string SafeKey(string? world) - { - if (string.IsNullOrWhiteSpace(world)) return ""; - var sb = new System.Text.StringBuilder(world.Length); - foreach (char c in world.Trim()) - sb.Append(char.IsLetterOrDigit(c) || c == '\'' || c == '-' ? c : '_'); - return sb.ToString(); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfile.cs b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfile.cs index 9ecc344..a9c94eb 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfile.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfile.cs @@ -17,13 +17,13 @@ public sealed class CreatureProfile public int CreatureType { get; set; } - /// Max health at Aelrynth difficulty tier 0 (real Dereth; every tier on other servers). + /// Max health at difficulty tier 0 (the unscaled world; every tier on servers without tiers). public uint MaxHealth { get; set; } /// - /// Max health at Aelrynth difficulty tiers above 0 (awakened worlds, scaled copies: +5% a - /// tier), tier -> highest seen. Null until one is seen, and then left out of the file - /// on every other server. Resists, armour, spells and type are the same at every tier. + /// Max health at difficulty tiers above 0 (a server plugin's tiers, DifficultyTier: scaled + /// worlds or copies), tier -> highest seen. Null until one is seen, and then left out of the + /// file on every server without tiers. Resists, armour, spells and type are the same at every tier. /// [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public Dictionary? TierMaxHealth { get; set; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfileStore.cs b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfileStore.cs index 4de994d..0cdc26f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfileStore.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/CreatureProfileStore.cs @@ -11,18 +11,19 @@ namespace RynthCore.Plugin.RynthAi.CreatureData; /// Keyed by composite "name|wcid" so tier variants don't collide. /// /// Per server (2026-10-03): wcids are only unique within one server's world database, and -/// custom content (Aelrynth's 3000001+, ConquestAC's own) reuses numbers, so each server keeps -/// its own file: +/// servers' custom content reuses numbers, so each server keeps its own file: /// C:\Games\RynthSuite\RynthAi\CreatureData\<server>\creatures.json -/// <server> is : "Aelrynth" for every Aelrynth world name, -/// else the world name the server announced, made safe for a folder (the SettingsProfiles rule). +/// <server> is : the folder that already holds this +/// server's data (by RynthCore's server id, its name or the world name), else the server's id, +/// else (no server known) the world name the server announced, made safe for a folder (the +/// SettingsProfiles rule). Folders made before 2026-10-21 are read where they are; nothing moves. /// The shared file from before, CreatureData\creatures.json, is the legacy store: COPIED (not /// moved) into a server's folder the first time that server is played, so every server starts /// from exactly what it had - the same precedent as the per-server SettingsProfiles /// (MigrateToServerFolder). It is only read and written while no server is known (before the /// first tick of a login, or a server that announces no name), as before. /// -/// Aelrynth difficulty tiers: appraised max health above tier 0 goes to +/// Difficulty tiers (a server plugin's, DifficultyTier): appraised max health above tier 0 goes to /// ; MaxHealth stays the tier-0 value. Everything /// else in a profile is the same at every tier. /// @@ -47,6 +48,27 @@ internal sealed class CreatureProfileStore /// The server whose file is loaded ("" = the legacy shared file). public string ServerKey { get { lock (_lock) return _serverKey; } } + /// + /// The name, as on disk, of the per-server folder matching (any case) + /// that holds a creatures.json; null when there is none. Never throws. + /// + public static string? ExistingServerFolder(string serverKey) + { + if (string.IsNullOrWhiteSpace(serverKey)) return null; + try + { + if (!Directory.Exists(Folder)) return null; + foreach (string dir in Directory.EnumerateDirectories(Folder)) + { + string name = Path.GetFileName(dir); + if (name.Equals(serverKey.Trim(), StringComparison.OrdinalIgnoreCase) && File.Exists(Path.Combine(dir, FileName))) + return name; + } + } + catch { } + return null; + } + /// /// Switch to 's file (saving the current one first). The first /// time a server is seen its file is a copy of the legacy shared file. "" or the same server @@ -198,8 +220,8 @@ internal sealed class CreatureProfileStore } /// - /// A profile's appraised max health at an Aelrynth difficulty tier (0 = real Dereth, and - /// every tier on other servers); 0 when that tier hasn't been seen. + /// A profile's appraised max health at a difficulty tier (0 = the unscaled world, and every + /// tier on servers without tiers); 0 when that tier hasn't been seen. /// public uint MaxHealthAt(CreatureProfile? profile, int difficulty) { @@ -212,7 +234,7 @@ internal sealed class CreatureProfileStore /// /// Merge a new observation into the store. Fields with value 0 / empty are /// ignored so partial samples don't clobber better data. - /// above 0 (an Aelrynth awakened world or scaled copy) files the max health under that tier + /// above 0 (a server's scaled world or copy, DifficultyTier) files the max health under that tier /// and leaves the tier-0 vitals alone; the rest merges as always. /// public void Upsert(CreatureProfile sample, int difficulty = 0) diff --git a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/DifficultyTier.cs b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/DifficultyTier.cs new file mode 100644 index 0000000..6e58f4b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/DifficultyTier.cs @@ -0,0 +1,169 @@ +using System; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi.CreatureData; + +/// +/// The difficulty tier where the player stands and the monster health a tier adds, as the active +/// server's plugin reports them, and which server this is for per-server data (2026-10-03 as one +/// server's AwakenedTier; server-neutral since 2026-10-21). +/// +/// Some servers hold the same monsters (same names, same wcids) at several difficulty tiers, with +/// health, skills and damage scaled per tier. A server plugin that knows its server's tiers says so +/// in its "RynthServer.Profile" values (Plugins/Shared/RynthServerProfileApi.cs): +/// "difficultyTier" the tier where the player stands (0 = the unscaled world); +/// "difficultyHealthPercent" the health one tier adds, in percent of tier 0's (absent: 0). +/// They are read from the plugin that owns RynthCore's active server (ServerStateClient, plugin API +/// v86), about once a second. RynthAi knows nothing else about the server. +/// +/// The rule: while no server plugin reports a tier this is inert - is 0, +/// false and every health scale 1 - so every store keyed by tier behaves +/// exactly as before. A reported tier 0 is Active (the Damage panel shows the picker) and still +/// changes nothing about the numbers. +/// +/// : the folder of the per-server creature data (CreatureProfileStore), see +/// . +/// +internal sealed class DifficultyTier +{ + /// The largest tier taken as reported (anything above is read as this). + public const int MaxTier = 10_000; + + /// The largest health percent per tier taken (anything else, or below 0, reads as 0). + public const double MaxHealthPercent = 1000; + + /// One reading of the server plugin's values: replaced whole (render and pump threads read it). + internal sealed record Reading(bool Active, int Tier, double HealthPercent, string Plugin) + { + public static readonly Reading None = new(false, 0, 0, string.Empty); + } + + private readonly ServerStateClient _server = new(); + private volatile Reading _reading = Reading.None; + private volatile string _serverKey = string.Empty; + private long _nextRefreshMs; + private int _appliedRevision = -1; + private string _appliedWorld = string.Empty; + + /// The active server's plugin reports a difficulty tier. False everywhere else. + public bool Active => _reading.Active; + + /// The tier where the player stands; 0 whenever is false. + public int Current => _reading.Active ? _reading.Tier : 0; + + /// The monster health one tier adds, in percent of tier 0's; 0 whenever is false. + public double HealthPercentPerTier => _reading.Active ? _reading.HealthPercent : 0; + + /// The plugin the tier comes from ("" while none reports one). + public string Source => _reading.Plugin; + + /// + /// The server's key for per-server data (creatures.json): see ; + /// "" while unknown. + /// + public string ServerKey => _serverKey; + + /// The multiplier this server's tier puts on a monster's health (1 without tiers). + public double HealthScale(int tier) => HealthScale(tier, HealthPercentPerTier); + + /// The multiplier a tier puts on a monster's health: 1 + % per tier. + public static double HealthScale(int tier, double percentPerTier) + => tier <= 0 || percentPerTier <= 0 ? 1.0 : 1.0 + percentPerTier / 100.0 * tier; + + /// Logout: nothing carries to the next login (it may be another server). + public void Reset() + { + _server.Clear(); + _reading = Reading.None; + _serverKey = string.Empty; + _nextRefreshMs = 0; + _appliedRevision = -1; + _appliedWorld = string.Empty; + } + + /// Re-reads the server and its tier, at most once a second (: now). Pump thread. + public void Refresh(RynthCoreHost host, bool force = false) + { + long now = Environment.TickCount64; + if (!force && now < _nextRefreshMs) return; + _nextRefreshMs = now + 1000; + try + { + _server.Poll(host, now, force: true); // throttled here, not by the client's own 2 s + string world = host.HasGetWorldName && host.TryGetWorldName(out string w) ? (w ?? string.Empty).Trim() : string.Empty; + if (_server.Revision == _appliedRevision && world == _appliedWorld) return; + _appliedRevision = _server.Revision; + _appliedWorld = world; + Apply(_server.State, _server.ProfileJson, _server.ProfilePlugin, world, CreatureProfileStore.ExistingServerFolder); + } + catch { } + } + + /// + /// What RynthCore's server list, the active server owner's profile JSON and the world name mean: + /// the tier reading and the creature data key. answers whether a + /// per-server creature data folder exists (its name as on disk, or null). Pure apart from it. + /// + internal void Apply(EngineServerState? state, string? profileJson, string? plugin, string? world, + Func existingFolder) + { + _reading = Read(profileJson, plugin); + _serverKey = ResolveServerKey(state, world, existingFolder); + } + + /// The tier values of a profile JSON; without a "difficultyTier". Pure. + internal static Reading Read(string? profileJson, string? plugin) + { + double tier = ServerProfileView.Value(profileJson, RynthServerProfile.ValueDifficultyTier, double.NaN); + if (double.IsNaN(tier)) return Reading.None; + double percent = ServerProfileView.Value(profileJson, RynthServerProfile.ValueDifficultyHealthPercent, 0); + if (!(percent >= 0 && percent <= MaxHealthPercent)) percent = 0; + return new Reading(true, (int)Math.Clamp(Math.Round(tier), 0, MaxTier), percent, plugin ?? string.Empty); + } + + /// + /// The folder name of this server's creature data. Pure apart from . + /// * RynthCore names the server (the active one, else one its detection found and this character + /// turned off): a folder that already holds data is kept, looked for under the server's id, then + /// its name, then the world name (RynthAi before 2026-10-21 used the world name, and "Aelrynth" + /// for that server's worlds, which its name finds); with none, the server's id. + /// * Otherwise (no server, an engine before v86): the world name, as before. + /// Every key is made safe for a folder name (the SettingsProfiles rule); "" while nothing is known. + /// + internal static string ResolveServerKey(EngineServerState? state, string? world, Func existingFolder) + { + string legacy = SafeKey(world); + EngineServer? server = ServerOf(state); + if (server == null) return legacy; + string id = SafeKey(server.Id); + foreach (string candidate in new[] { id, SafeKey(server.Name), legacy }) + { + if (candidate.Length == 0) continue; + string? found = existingFolder(candidate); + if (!string.IsNullOrEmpty(found)) return found; + } + return id.Length > 0 ? id : legacy; + } + + /// RynthCore's active server, else the first one its detection found (turned off by an override); null for none. + private static EngineServer? ServerOf(EngineServerState? state) + { + if (state == null) return null; + if (state.HasActive) + return state.Find(state.Active) ?? new EngineServer(state.Active, state.ActiveName, true, true, "auto", false, state.ActivePlugin, ""); + foreach (EngineServer s in state.Servers) + if (s.Detected) return s; + return null; + } + + /// A world or server name as a folder name (the SettingsProfiles rule); "" for none. + public static string SafeKey(string? name) + { + if (string.IsNullOrWhiteSpace(name)) return string.Empty; + var sb = new System.Text.StringBuilder(name.Length); + foreach (char c in name.Trim()) + sb.Append(char.IsLetterOrDigit(c) || c == '\'' || c == '-' ? c : '_'); + return sb.ToString(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/MonsterDamageStore.cs b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/MonsterDamageStore.cs index 4eb6dd5..649d519 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CreatureData/MonsterDamageStore.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CreatureData/MonsterDamageStore.cs @@ -32,13 +32,13 @@ namespace RynthCore.Plugin.RynthAi.CreatureData; /// D|<wcid>|<name>|<weaponId>|<element>|<tier>|<avgDamage>|<dmgSamples>|<avgCastsToKill>|<killSamples>|<critAvg>|<critSamples>|<nonCritAvg>|<nonCritSamples> /// (The loader also accepts the older 9/10-field name-less / crit-less D rows so existing data carries over.) /// -/// Aelrynth difficulty tiers (2026-10-03, ): Aelrynth's awakened worlds -/// and scaled copies hold the same monsters (same wcids) with health, skills and damage scaled 5% -/// a tier. What a tier changes is kept per (wcid, tier): the HP pool, casts-to-kill, hits and +/// Difficulty tiers (2026-10-03, : the active server plugin reports +/// them): a server's scaled worlds and copies hold the same monsters (same wcids) with health, +/// skills and damage scaled by the tier. What a tier changes is kept per (wcid, tier): the HP pool, casts-to-kill, hits and /// misses, seconds per kill (per weapon and per summon) and the damage the monster does to us. /// What it does not change stays shared: per-cast damage (resistances and armour don't scale) -/// and every rule (weapon, offhand, pet, manual HP). Tier 0 - real Dereth, and every other -/// server, where the tier is always 0 - is today's data in today's rows, untouched. Tiers above 0 +/// and every rule (weapon, offhand, pet, manual HP). Tier 0 - the unscaled world, and every +/// server without tiers, where the tier is always 0 - is today's data in today's rows, untouched. Tiers above 0 /// are extra rows an older loader skips: /// AH|<tier>|<wcid>|<name>|<hpToKill>|<samples> /// AD|<tier>|<wcid>|<name>|<weaponId>|<element>|<spellTier>|<avgCastsToKill>|<killSamples> @@ -115,7 +115,7 @@ internal sealed class MonsterDamageStore public int KillSamples; } - /// What one Aelrynth difficulty tier above 0 changes about one monster (see the class comment). + /// What one difficulty tier above 0 changes about one monster (see the class comment). private sealed class TierProfile { public double HpPool; @@ -134,9 +134,9 @@ internal sealed class MonsterDamageStore private volatile int _difficulty; /// - /// The Aelrynth difficulty tier new observations are recorded under, and the one the - /// tier-less readers answer for: the tier where the player stands (AwakenedTier.Current, - /// set every tick). Always 0 off Aelrynth. + /// The difficulty tier new observations are recorded under, and the one the tier-less + /// readers answer for: the tier where the player stands (DifficultyTier.Current, set every + /// tick). Always 0 on a server without tiers. /// public int Difficulty { @@ -425,7 +425,7 @@ internal sealed class MonsterDamageStore private void AppendTierRows(StringBuilder sb) { if (_byTier.Count == 0) return; - sb.Append("# Aelrynth difficulty tiers above 0 (awakened worlds, scaled copies); tier 0 is the rows above:\n"); + sb.Append("# Above tier 0: the server's difficulty tiers (scaled worlds, copies); tier 0 is the rows above:\n"); sb.Append("# AH|tier|wcid|name|hpToKill|samples\n"); sb.Append("# AD|tier|wcid|name|weaponId|element|spellTier|avgCastsToKill|killSamples\n"); sb.Append("# AU|tier|wcid|name|weaponId|hits|misses|secToKillAvg|secSamples\n"); @@ -764,7 +764,7 @@ internal sealed class MonsterDamageStore return tp; } - /// The difficulty tiers above 0 with anything learned, ascending (empty off Aelrynth). + /// The difficulty tiers above 0 with anything learned, ascending (empty on a server without tiers). public List KnownDifficulties() { var set = new SortedSet(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs index bf7aa3b..93451e7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs @@ -453,10 +453,10 @@ internal sealed class MiniRemoteHud { // The server plugin's Remote sections (RynthILT: Bank, Guardian answer) decide themselves whether // they show (their switches are the plugin's); nothing is drawn without one. - bool drawn = remote?.ServerHub.RenderSection(RynthIltHub.SectionRemoteBank) == true; + bool drawn = remote?.ServerHub.RenderSection(RynthServerHub.SectionRemoteBank) == true; if (s.MiniShowRebuff) RenderRebuff(); if (s.MiniShowTranslate && _hud.Translate is { } translate) translate.RenderHubSection(); - drawn |= remote?.ServerHub.RenderSection(RynthIltHub.SectionRemoteGuardian) == true; + drawn |= remote?.ServerHub.RenderSection(RynthServerHub.SectionRemoteGuardian) == true; _serverEconomyDrawn = drawn; } @@ -490,7 +490,7 @@ internal sealed class MiniRemoteHud if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"{v.LumPassUp:N0} this session.\n{PassUpTooltip}"); } Stat("Kills:", HudDraw.Compact(v.KillsPerHour) + "/h"); - remote?.ServerHub.RenderSection(RynthIltHub.SectionRemoteStats); + remote?.ServerHub.RenderSection(RynthServerHub.SectionRemoteStats); } /// @@ -660,7 +660,7 @@ internal sealed class MiniRemoteHud + $"({HudDraw.Compact(v.LumLast5Min)} last 5m)"; if (v.PassUpTracked) line += $", Pass-up {HudDraw.Compact(v.PassUpPerHour)}/h"; line += $", Kills {HudDraw.Compact(v.KillsPerHour)}/h ({v.Kills:N0})"; - line += _hud.Remote()?.ServerHub.Text(RynthIltHub.TextSessionReport) ?? string.Empty; // the server plugin's rates + line += _hud.Remote()?.ServerHub.Text(RynthServerHub.TextSessionReport) ?? string.Empty; // the server plugin's rates _hud.Chat(line); } @@ -832,7 +832,7 @@ internal sealed class MiniRemoteHud Flag("Rebuff", ref s.MiniShowRebuff); Flag("Translate", ref s.MiniShowTranslate); // The server plugin's Remote sections (RynthILT: Bank, Guardian answer): its own switches. - _hud.Remote()?.ServerHub.RenderSection(RynthIltHub.SectionRemoteOptions); + _hud.Remote()?.ServerHub.RenderSection(RynthServerHub.SectionRemoteOptions); ImGui.Separator(); Flag("Horizontal layout", ref s.MiniRemoteHorizontal); RenderSlotSizeSlider(s); @@ -937,13 +937,13 @@ internal sealed class MiniRemoteHud ServerMenuGroup[]? groups = ServerMenuModel.Groups; if (groups == null) { - remote?.ServerHub.RenderSection(RynthIltHub.SectionServerMenu); + remote?.ServerHub.RenderSection(RynthServerHub.SectionServerMenu); return; } if (groups.Length == 0) return; // no server plugin installed // The server the active server plugin's tabs and status belong to (RynthILT: "ilt"); "" without one. - string pluginServer = remote?.ServerHub.Text(RynthIltHub.TextServerId) ?? string.Empty; + string pluginServer = remote?.ServerHub.Text(RynthServerHub.TextServerId) ?? string.Empty; bool any = false; foreach (ServerMenuGroup g in groups) { @@ -969,7 +969,7 @@ internal sealed class MiniRemoteHud SafeImGui.SetTooltip(enabled ? item.Tooltip : item.Tooltip + "\nShows once the server reports this feature on."); } // The plugin's status under its server (RynthILT: why no ILT feature is on, Refresh). - if (ours) remote?.ServerHub.RenderSection(RynthIltHub.SectionIltStatus); + if (ours) remote?.ServerHub.RenderSection(RynthServerHub.SectionServerStatus); } if (any) return; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index 19f04a2..b04853e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -1101,7 +1101,7 @@ internal sealed partial class LegacyDashboardRenderer // ── Settings bridge (engine-side Avalonia SettingsPanel) ───────────────── /// - /// The active server plugin's mirrored settings (RynthILT.Hub GetSetting / SetSetting, through the + /// The active server plugin's mirrored settings (RynthServer.Hub GetSetting / SetSetting, through the /// Mini Remote's server client): the value, or -1 when none is offered. Set by RynthAiPlugin. /// public Func? ServerSettingGet { get; set; } @@ -1238,7 +1238,7 @@ internal sealed partial class LegacyDashboardRenderer CorpseApproachRangeMin = s.CorpseApproachRangeMin, // Navigation BoostNavPriority = s.BoostNavPriority, - EnableVaultedDungeons = ServerSettingBool(RynthCore.Plugin.Shared.RynthIltHub.SettingVaultedDungeons), // RynthILT's (null: the row hides) + EnableVaultedDungeons = ServerSettingBool(RynthCore.Plugin.Shared.RynthServerHub.SettingVaultedDungeons), // the server plugin's (null: the row hides) FollowNavMin = s.FollowNavMin, NavRingThickness = s.NavRingThickness, NavLineThickness = s.NavLineThickness, @@ -1499,7 +1499,7 @@ internal sealed partial class LegacyDashboardRenderer // Navigation s.BoostNavPriority = p.BoostNavPriority; if (p.EnableVaultedDungeons is bool vaulted) // absent = unchanged - ServerSettingSet?.Invoke(RynthCore.Plugin.Shared.RynthIltHub.SettingVaultedDungeons, vaulted ? 1 : 0); // RynthILT's switch + ServerSettingSet?.Invoke(RynthCore.Plugin.Shared.RynthServerHub.SettingVaultedDungeons, vaulted ? 1 : 0); // the server plugin's switch s.FollowNavMin = p.FollowNavMin; s.NavRingThickness = p.NavRingThickness; s.NavLineThickness = p.NavLineThickness; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs index 00739cc..516034a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs @@ -24,7 +24,7 @@ namespace RynthCore.Plugin.RynthAi; [JsonSerializable(typeof(RynthCore.Plugin.RynthAi.RynthLogConfig))] [JsonSerializable(typeof(RynthCore.Plugin.RynthAi.Huds.HudState))] [JsonSerializable(typeof(RynthCore.Plugin.RynthAi.MiniRemote.MiniRemoteState))] -[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.MiniRemote.LegacyIltHubFile))] +[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.MiniRemote.LegacyHubFile))] [JsonSerializable(typeof(RynthCore.Plugin.RynthAi.BuffProfile))] [JsonSourceGenerationOptions( WriteIndented = true, diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteController.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteController.cs index 78195df..2d9e284 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteController.cs @@ -78,7 +78,7 @@ internal sealed class MiniRemoteController public Func? MiniRemoteTabCommand { get; set; } /// True when the server plugin already says /myquests is off on its server (skip the login refresh). - public bool SkipLoginQuestRefresh => _ctx.ServerHub.ServerActive && _ctx.ServerHub.IsOff(RynthIltHub.FeatureQuests); + public bool SkipLoginQuestRefresh => _ctx.ServerHub.ServerActive && _ctx.ServerHub.IsOff(RynthServerHub.FeatureQuests); // ── Lifecycle ─────────────────────────────────────────────────────────── @@ -144,7 +144,7 @@ internal sealed class MiniRemoteController RynthLog.Trace(LogCat.Quests, "RefreshQuests()"); QuestTracker? t = _quests(); if (t == null) return "Quest tracker not ready."; - if (_ctx.ServerHub.IsOff(RynthIltHub.FeatureQuests) || t.Disabled) return "/myquests is disabled on this server."; + if (_ctx.ServerHub.IsOff(RynthServerHub.FeatureQuests) || t.Disabled) return "/myquests is disabled on this server."; long now = MiniRemoteContext.NowMs; if (now - _lastQuestRefreshAt < QuestRefreshCooldownMs) return $"Wait {(QuestRefreshCooldownMs - (now - _lastQuestRefreshAt)) / 1000}s (server allows one /myquests per minute)."; diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs index e301026..9d527d8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs @@ -155,17 +155,17 @@ public sealed class QuestsTabState } /// The parts of an old ilt-hub.json the universal tabs take over (first load only). -public sealed class LegacyIltHubFile +public sealed class LegacyHubFile { public PetTabState? Pet; /// The ILT Hub's IltCharacterState: its quest fields have QuestsTabState's names. public QuestsTabState? Character; - public LegacyIltGear? Gear; + public LegacyHubGear? Gear; /// The ILT Hub's Crafting tab (build-comp-10-11 hosted it in RynthAi): same field names. public CraftingTabState? Crafting; } -public sealed class LegacyIltGear +public sealed class LegacyHubGear { public string? LastUsdPath; } @@ -202,7 +202,7 @@ internal sealed class MiniRemoteStore string legacy = Path.Combine(_charFolder, LegacyFileName); if (_charFolder.Length > 0 && File.Exists(legacy)) { - var old = JsonSerializer.Deserialize(File.ReadAllText(legacy), RynthAiJsonContext.Default.LegacyIltHubFile); + var old = JsonSerializer.Deserialize(File.ReadAllText(legacy), RynthAiJsonContext.Default.LegacyHubFile); if (old != null) { var s = FromLegacy(old); @@ -216,7 +216,7 @@ internal sealed class MiniRemoteStore } /// The universal parts of an old ilt-hub.json as a fresh state. - internal static MiniRemoteState FromLegacy(LegacyIltHubFile old) + internal static MiniRemoteState FromLegacy(LegacyHubFile old) { var s = new MiniRemoteState { diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs index cee9f62..ef53730 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs @@ -676,7 +676,7 @@ internal sealed class PetsTab internal string? PendingSubTab => _selectSubTab; /// The sub-tabs the server plugin adds to this tab now (RynthILT's Breeding); empty without one. - public IReadOnlyList SubTabs() => _ctx.ServerHub.SubTabs(RynthIltHub.TabParentPets); + public IReadOnlyList SubTabs() => _ctx.ServerHub.SubTabs(RynthServerHub.TabParentPets); /// /// The shown sub-tab a "/ra hub open|tab <name>" names: its label ("Breeding"), its id, or its id @@ -699,7 +699,7 @@ internal sealed class PetsTab return null; } - private const string SubTabPrefix = RynthIltHub.TabParentPets + "-"; + private const string SubTabPrefix = RynthServerHub.TabParentPets + "-"; /// /// The Pets tab: the universal roster, and Roster | ... sub-tabs when the server plugin adds some @@ -770,11 +770,11 @@ internal sealed class PetsTab RenderRosterTable(); // The server plugin's own pet features (RynthILT: ACECustom's charms and siphon capture); // each draws its own separator, and nothing off its server. - _ctx.ServerHub.RenderSection(RynthIltHub.SectionPetCharms); - _ctx.ServerHub.RenderSection(RynthIltHub.SectionPetCapture); + _ctx.ServerHub.RenderSection(RynthServerHub.SectionPetCharms); + _ctx.ServerHub.RenderSection(RynthServerHub.SectionPetCapture); ImGui.Separator(); RenderHealing(); - _ctx.ServerHub.RenderSection(RynthIltHub.SectionPetLogs); + _ctx.ServerHub.RenderSection(RynthServerHub.SectionPetLogs); } /// Type / Sort combos, action buttons, the active-summon line and per-type options. diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/ServerHubClient.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/ServerHubClient.cs index 30e6842..f4fa058 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/ServerHubClient.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/ServerHubClient.cs @@ -1,12 +1,13 @@ -// ServerHubClient.cs - RynthAi's side of a server plugin's hub (the "RynthILT.Hub" table layout, -// Plugins/Shared/RynthIltHubApi.cs; was IltClient until 2026-10-20): the tabs, sub-tabs and sections +// ServerHubClient.cs - RynthAi's side of a server plugin's hub ("RynthServer.Hub", +// Plugins/Shared/RynthServerHubApi.cs; was IltClient until 2026-10-20): the tabs, sub-tabs and sections // the Mini Remote hosts for the server you're on, its feature bits (the Quests tab's /myquests bit), // its texts and settings, its "/ra" verbs, and its pet gate. RynthAi knows no server's content: it // shows what the plugin offers. // -// The plugin is found by the engine's server list first (the active server's owner plugin, under the -// neutral name "RynthServer.Hub"), then RynthILT under "RynthILT.Hub" (every RynthILT answers that; -// older ones only that). Without one (not installed, too old, not loaded yet: any retail-like world) +// The plugin is found through RynthCore's server list (plugin API v86, GetServerStateJson): the +// active server's owner plugin first, else the owners of the other servers it lists (a server plugin +// may follow its own world check or override), preferring one that says this world is its server. +// Without one (not installed, too old, not loaded yet, an engine before v86: any retail-like world) // every call answers "nothing": no tab, no section, unknown feature bits, no verbs. The table is // looked up on the pump thread (Tick) at most every RecheckMs and kept in a volatile field for the // render thread; the plugin never frees it (Version goes to 0 on its shutdown), so reading a stale @@ -32,7 +33,7 @@ internal sealed unsafe class ServerHubClient private IntPtr _table; // volatile reads/writes: the render thread uses what the pump found private long _checkedAt; private bool _checkedOnce; // false: look now (a sentinel time would overflow "now - _checkedAt") - private readonly IltTabV1[] _tabBuf = new IltTabV1[MaxTabs]; + private readonly ServerHubTabV1[] _tabBuf = new ServerHubTabV1[MaxTabs]; private readonly List _tabs = new(); private bool _pinned; // tests: a table handed in, never looked up @@ -52,39 +53,69 @@ internal sealed unsafe class ServerHubClient { if (_pinned) return; long now = Environment.TickCount64; - var t = (RynthIltHubApiV1*)System.Threading.Volatile.Read(ref _table); + var t = (RynthServerHubApiV1*)System.Threading.Volatile.Read(ref _table); if (!LookupDue(_checkedOnce, _checkedAt, now, haveTable: t != null, tableLive: t != null && t->Version >= 1)) return; _checkedOnce = true; _checkedAt = now; IntPtr found = IntPtr.Zero; if (_host.HasGetPluginInterface) { - // The active server's own plugin (the engine's server list), under the neutral name ... - string owner = ActiveServerPlugin(); - if (owner.Length > 0) found = Look(owner, RynthIltHubApiV1.NeutralInterfaceName); - // ... else RynthILT under its own name (every RynthILT; it also follows its own world check). - if (found == IntPtr.Zero) found = Look(RynthIltHub.PluginName, RynthIltHubApiV1.InterfaceName); + EngineServerState? st = EngineState(); + IReadOnlyList owners = OwnerOrder(st); + bool activeFirst = st != null && st.ActivePlugin.Length > 0; + IntPtr first = IntPtr.Zero; + for (int i = 0; i < owners.Count && found == IntPtr.Zero; i++) + { + IntPtr p = Look(owners[i]); + if (p == IntPtr.Zero) continue; + // The active server's own plugin is the one; another server's only when it claims this world. + var hub = (RynthServerHubApiV1*)p; + if ((i == 0 && activeFirst) || (hub->IsServerWorld != null && hub->IsServerWorld() != 0)) found = p; + else if (first == IntPtr.Zero) first = p; + } + // None claims this world: the first that serves a hub (its tabs say they're hidden). + if (found == IntPtr.Zero) found = first; } System.Threading.Volatile.Write(ref _table, found); } - /// A hub table serves as , or 0. - private IntPtr Look(string plugin, string iface) + /// A hub table serves, or 0. + private IntPtr Look(string plugin) { - var p = (RynthIltHubApiV1*)_host.GetPluginInterface(plugin, iface, RynthIltHubApiV1.InterfaceVersion); + var p = (RynthServerHubApiV1*)_host.GetPluginInterface(plugin, RynthServerHubApiV1.InterfaceName, RynthServerHubApiV1.InterfaceVersion); // Any table at least as big as the first release's: newer functions are checked with Has. - return p != null && p->Version >= 1 && p->StructSize >= RynthIltHubApiV1.BaseStructSize ? (IntPtr)p : IntPtr.Zero; + return p != null && p->Version >= 1 && p->StructSize >= RynthServerHubApiV1.BaseStructSize ? (IntPtr)p : IntPtr.Zero; } - /// The plugin that owns the engine's active server ("" when none, or the engine is pre-v86). Pump thread. - private string ActiveServerPlugin() + /// RynthCore's server list (null when none, or the engine is pre-v86). Pump thread. + private EngineServerState? EngineState() { try { - if (!_host.HasGetServerStateJson || !_host.TryGetServerStateJson(out string json)) return string.Empty; - return EngineServerState.Parse(json)?.ActivePlugin ?? string.Empty; + if (!_host.HasGetServerStateJson || !_host.TryGetServerStateJson(out string json)) return null; + return EngineServerState.Parse(json); } - catch { return string.Empty; } + catch { return null; } + } + + /// + /// The plugins to ask for a hub, in order: the active server's owner, then every other server's + /// owner RynthCore lists (each once). Empty without a server list. Pure. + /// + internal static IReadOnlyList OwnerOrder(EngineServerState? st) + { + var list = new List(); + if (st == null) return list; + if (st.ActivePlugin.Length > 0) list.Add(st.ActivePlugin); + foreach (EngineServer s in st.Servers) + { + if (s.Plugin.Length == 0) continue; + bool seen = false; + foreach (string p in list) + if (p.Equals(s.Plugin, StringComparison.OrdinalIgnoreCase)) { seen = true; break; } + if (!seen) list.Add(s.Plugin); + } + return list; } /// Forget the table (login, logout); the next Tick looks again. @@ -97,7 +128,7 @@ internal sealed unsafe class ServerHubClient /// /// Whether Tick looks the table up again. Pure. Always on the first call (and after Reset), at - /// once when the table RynthILT gave is shut down (Version 0), else every . + /// once when the table the plugin gave is shut down (Version 0), else every . /// internal static bool LookupDue(bool checkedOnce, long checkedAt, long now, bool haveTable, bool tableLive) { @@ -106,11 +137,11 @@ internal sealed unsafe class ServerHubClient return now - checkedAt >= RecheckMs; } - private RynthIltHubApiV1* T + private RynthServerHubApiV1* T { get { - var t = (RynthIltHubApiV1*)System.Threading.Volatile.Read(ref _table); + var t = (RynthServerHubApiV1*)System.Threading.Volatile.Read(ref _table); return t != null && t->Version >= 1 ? t : null; } } @@ -118,13 +149,13 @@ internal sealed unsafe class ServerHubClient /// A server plugin answers (any thread). public bool Loaded => T != null; - /// This world is the plugin's server (or forced there), as it sees it (RynthILT: Infinite Leaftide). Any thread. + /// This world is the plugin's server (or forced there), as it sees it. Any thread. public bool ServerActive { get { var t = T; - return t != null && t->IsIltWorld != null && t->IsIltWorld() != 0; + return t != null && t->IsServerWorld != null && t->IsServerWorld() != 0; } } @@ -144,13 +175,13 @@ internal sealed unsafe class ServerHubClient public bool IsOn(string key) => Feature(key) == 1; /// - /// A short text from the server plugin (RynthIltHub.Text*: the session report's tail, its server id); + /// A short text from the server plugin (RynthServerHub.Text*: the session report's tail, its server id); /// "" without one, from an older one, or for nothing. Any thread. /// public string Text(string id) { var t = T; - if (t == null || !RynthIltHubApiV1.Has(t, RynthIltHubApiV1.GetTextOffset) || t->GetText == null) return string.Empty; + if (t == null || !RynthServerHubApiV1.Has(t, RynthServerHubApiV1.GetTextOffset) || t->GetText == null) return string.Empty; byte* buf = stackalloc byte[256]; buf[0] = 0; int n; @@ -161,7 +192,7 @@ internal sealed unsafe class ServerHubClient } /// - /// This character forces the plugin's server (RynthILT: "Treat this world as ILT"; set there or in + /// This character forces the plugin's server (its own override; set there or in /// RynthCore's Options > Diagnostics, never by RynthAi). Any thread. /// public bool ServerForced @@ -169,7 +200,7 @@ internal sealed unsafe class ServerHubClient get { var t = T; - return t != null && t->GetForceIlt != null && t->GetForceIlt() != 0; + return t != null && t->GetForceServer != null && t->GetForceServer() != 0; } } @@ -180,22 +211,22 @@ internal sealed unsafe class ServerHubClient var t = T; if (t == null || t->GetTabs == null) return _tabs; int n; - fixed (IltTabV1* buf = _tabBuf) n = t->GetTabs(buf, MaxTabs); + fixed (ServerHubTabV1* buf = _tabBuf) n = t->GetTabs(buf, MaxTabs); n = Math.Min(n, MaxTabs); for (int i = 0; i < n; i++) { - ref IltTabV1 tab = ref _tabBuf[i]; + ref ServerHubTabV1 tab = ref _tabBuf[i]; string id, label; fixed (byte* pid = tab.Id) id = Marshal.PtrToStringUTF8((IntPtr)pid) ?? string.Empty; fixed (byte* plabel = tab.Label) label = Marshal.PtrToStringUTF8((IntPtr)plabel) ?? string.Empty; if (id.Length == 0) continue; _tabs.Add(new ServerTabInfo(id, label.Length > 0 ? label : id, tab.Width, tab.Height, - (tab.Flags & RynthIltHub.TabShown) != 0, (tab.Flags & RynthIltHub.TabAvailable) != 0)); + (tab.Flags & RynthServerHub.TabShown) != 0, (tab.Flags & RynthServerHub.TabAvailable) != 0)); } return _tabs; } - /// Render thread: one ILT tab's body into the current child window; false = nothing drawn. + /// Render thread: one of the plugin's tabs into the current child window; false = nothing drawn. public bool RenderTab(string id) { var t = T; @@ -204,7 +235,7 @@ internal sealed unsafe class ServerHubClient return t->RenderTab(s.P) != 0; } - /// Render thread: an ILT section (RynthIltHub.Section*); false = nothing drawn (not ILT, or no RynthILT). + /// Render thread: a server section (RynthServerHub.Section*); false = nothing drawn (not its server, or no plugin). public bool RenderSection(string id) { var t = T; @@ -213,7 +244,7 @@ internal sealed unsafe class ServerHubClient return t->RenderSection(s.P) != 0; } - /// An ILT "/ra" verb ("hub bank", "guardian handin", ...); false when RynthILT doesn't take it. + /// One of the plugin's "/ra" verbs ("hub bank", ...); false when it doesn't take it. public bool Command(string text) { var t = T; @@ -224,21 +255,21 @@ internal sealed unsafe class ServerHubClient /// /// The server plugin's answer to "may an EMPTY pet essence be summoned?" (the server refills it; - /// RynthILT: ACECustom's Summon Essence Refill charm). False without one, or from an older one + /// e.g. a refill charm). False without one, or from an older one /// that doesn't answer: an empty essence is then never used. Any thread. /// public bool AllowSummonOnEmpty() { var t = T; - return t != null && RynthIltHubApiV1.Has(t, RynthIltHubApiV1.AllowSummonOnEmptyOffset) + return t != null && RynthServerHubApiV1.Has(t, RynthServerHubApiV1.AllowSummonOnEmptyOffset) && t->AllowSummonOnEmpty != null && t->AllowSummonOnEmpty() != 0; } - /// One of the server plugin's mirrored settings (RynthIltHub.Setting*): its value, -1 when not offered. Any thread. + /// One of the server plugin's mirrored settings (RynthServerHub.Setting*): its value, -1 when not offered. Any thread. public int Setting(string key) { var t = T; - if (t == null || !RynthIltHubApiV1.Has(t, RynthIltHubApiV1.GetSettingOffset) || t->GetSetting == null) return -1; + if (t == null || !RynthServerHubApiV1.Has(t, RynthServerHubApiV1.GetSettingOffset) || t->GetSetting == null) return -1; using var k = new Utf8(key); return t->GetSetting(k.P); } @@ -247,7 +278,7 @@ internal sealed unsafe class ServerHubClient public bool SetSetting(string key, int value) { var t = T; - if (t == null || !RynthIltHubApiV1.Has(t, RynthIltHubApiV1.SetSettingOffset) || t->SetSetting == null) return false; + if (t == null || !RynthServerHubApiV1.Has(t, RynthServerHubApiV1.SetSettingOffset) || t->SetSetting == null) return false; using var k = new Utf8(key); return t->SetSetting(k.P, value) != 0; } @@ -256,15 +287,15 @@ internal sealed unsafe class ServerHubClient /// /// The sub-tabs the server plugin adds to one of the Mini Remote's tabs ( - /// "pets": RynthILT's Breeding). Each id is a RenderSection id. Empty without one. A new list each + /// "pets": e.g. a Breeding sub-tab). Each id is a RenderSection id. Empty without one. A new list each /// call (the render thread draws them, a command looks one up). Any thread. /// public IReadOnlyList SubTabs(string parent) { var t = T; - if (t == null || !RynthIltHubApiV1.Has(t, RynthIltHubApiV1.GetSubTabsOffset) || t->GetSubTabs == null) + if (t == null || !RynthServerHubApiV1.Has(t, RynthServerHubApiV1.GetSubTabsOffset) || t->GetSubTabs == null) return Array.Empty(); - IltTabV1* buf = stackalloc IltTabV1[MaxSubTabs]; + ServerHubTabV1* buf = stackalloc ServerHubTabV1[MaxSubTabs]; int n; using (var p = new Utf8(parent)) n = t->GetSubTabs(p.P, buf, MaxSubTabs); n = Math.Min(n, MaxSubTabs); @@ -272,14 +303,14 @@ internal sealed unsafe class ServerHubClient var list = new List(n); for (int i = 0; i < n; i++) { - IltTabV1* tab = &buf[i]; + ServerHubTabV1* tab = &buf[i]; tab->Id[23] = 0; // never read past a buffer the other side filled to the brim tab->Label[31] = 0; string id = Marshal.PtrToStringUTF8((IntPtr)tab->Id) ?? string.Empty; string label = Marshal.PtrToStringUTF8((IntPtr)tab->Label) ?? string.Empty; if (id.Length == 0) continue; list.Add(new ServerTabInfo(id, label.Length > 0 ? label : id, tab->Width, tab->Height, - (tab->Flags & RynthIltHub.TabShown) != 0, (tab->Flags & RynthIltHub.TabAvailable) != 0)); + (tab->Flags & RynthServerHub.TabShown) != 0, (tab->Flags & RynthServerHub.TabAvailable) != 0)); } return list; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs index 53af1b2..a4b9b62 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -481,20 +481,21 @@ public static unsafe class PluginExports } // Manual HP override from the Damage panel (hp <= 0 clears it). - private static IntPtr _awakenedTierJsonPtr = IntPtr.Zero; + private static IntPtr _difficultyTierJsonPtr = IntPtr.Zero; - // Aelrynth difficulty tiers (2026-10-03): the Damage panel's tier label and picker. - // {"show":false} off Aelrynth or until the server has sent a tier; else - // {"show":true,"current":N,"view":M,"following":bool,"percent":5,"tiers":[0,...]}. + // Difficulty tiers (2026-10-03; a server plugin's values since 2026-10-21, CreatureData/DifficultyTier.cs): + // the Damage panel's tier label and picker. {"show":false} while no server plugin reports a tier; else + // {"show":true,"current":N,"view":M,"following":bool,"percent":P,"tiers":[0,...]} (P: health % a tier). + // The export keeps the name the engine binds ("...AwakenedTierJson", its first server's word). // An engine without the picker never calls this; the damage JSON then shows the current tier. [UnmanagedCallersOnly(EntryPoint = "RynthPluginGetAwakenedTierJson", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetAwakenedTierJson() + public static IntPtr GetDifficultyTierJson() { try { - string json = Runtime.Plugin?.BuildAwakenedTierJson() ?? "{\"show\":false}"; + string json = Runtime.Plugin?.BuildDifficultyTierJson() ?? "{\"show\":false}"; IntPtr newPtr = Marshal.StringToHGlobalAnsi(json); - IntPtr oldPtr = Interlocked.Exchange(ref _awakenedTierJsonPtr, newPtr); + IntPtr oldPtr = Interlocked.Exchange(ref _difficultyTierJsonPtr, newPtr); if (oldPtr != IntPtr.Zero) Marshal.FreeHGlobal(oldPtr); return newPtr; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index 9fe7345..c02ec8d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -192,10 +192,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // Per-character learned combat damage (avg damage by wcid/element/tier + // learned HP-to-kill), used by CombatManager for kill-shot prediction. private CreatureData.MonsterDamageStore? _damageStore; - // Aelrynth's difficulty tier where the player stands (and which server this is): keys the - // tier-scaled learned numbers. Inert (tier 0) on every other server. - private readonly CreatureData.AwakenedTier _tier = new(); - internal CreatureData.AwakenedTier AwakenedTier => _tier; + // The difficulty tier where the player stands, as the active server's plugin reports it (and + // which server this is): keys the tier-scaled learned numbers. Inert (tier 0) on every server + // whose plugin reports none. + private readonly CreatureData.DifficultyTier _tier = new(); + internal CreatureData.DifficultyTier DifficultyTier => _tier; // The tier the Damage panel shows: -1 = the current one (the default). private volatile int _damageViewTier = -1; // wcids appraised this session (AutoId of nearby mobs). Surfaced as bare rows in the @@ -755,7 +756,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _combatManager.SetPlayerId(_playerId); _combatManager.SetDamageStores(_creatureStore, _damageStore); _combatManager.MobSeedLookup = LookupMobSeed; - _combatManager.SetAwakenedTier(_tier); + _combatManager.SetDifficultyTier(_tier); // The raycast init thread may already have finished (warm dats): hand it over now. WireRaycastIntoCombat(); _navigationEngine?.SetCombatManager(_combatManager); @@ -1534,7 +1535,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _objectCache?.Tick(); if (diag) Host.Log("[RynthAi] OnTick: after cache tick"); - if (_loginComplete) TickAwakenedTier(); + if (_loginComplete) TickDifficultyTier(); // A stop the action pacing held (nothing of ours moving, a server action unanswered) // goes out as soon as the server has answered: a stop is never dropped (2026-10-12). @@ -2585,7 +2586,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { var store = _damageStore; if (store == null) return "[]"; - // The Aelrynth difficulty tier shown (0 off Aelrynth): HP, kills, casts to kill, seconds + // The difficulty tier shown (0 without a server plugin's tiers): HP, kills, casts to kill, seconds // per kill and hit rate are that tier's; damage per cast and every rule are shared. int vt = DamageViewDifficulty; _jsonViewTier = vt; @@ -2961,17 +2962,18 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { if (_damageStore == null) return; // The Damage panel shows (and so edits) the HP of the difficulty tier it shows; the - // override is kept as the real-Dereth value, which every tier scales by 5% a tier. - // Off Aelrynth the tier is 0 and this is the value as typed, as before. + // override is kept as the real-Dereth value, which every tier scales by the server's + // percent a tier. Without a server plugin's tiers the tier is 0 and this is the value as + // typed, as before. int vt = DamageViewDifficulty; - double value = hp > 0 && vt > 0 ? hp / CreatureData.AwakenedTier.HealthScale(vt) : hp; + double value = hp > 0 && vt > 0 ? hp / _tier.HealthScale(vt) : hp; foreach (uint w in DamageGroupOf(wcid)) _damageStore.SetManualHp(w, value); // every kind of the row _damageStore.SaveIfDirty(); } /// - /// The Aelrynth difficulty tier the Damage panel shows: the one picked there, else the one - /// where the player stands. Always 0 off Aelrynth (or before the server has sent a tier). + /// The difficulty tier the Damage panel shows: the one picked there, else the one where the + /// player stands. Always 0 while no server plugin reports a tier. /// internal int DamageViewDifficulty { @@ -2987,10 +2989,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase public void SetDamageViewTier(int tier) => _damageViewTier = tier < 0 ? -1 : tier; /// - /// The tier picker's state for the Damage panel: {"show":false} off Aelrynth or until the - /// server has sent a tier this login - the panel then shows nothing of it. + /// The tier picker's state for the Damage panel (RynthPluginGetAwakenedTierJson): {"show":false} + /// while no server plugin reports a tier - the panel then shows nothing of it. /// - public string BuildAwakenedTierJson() + public string BuildDifficultyTierJson() { if (!_tier.Active) return "{\"show\":false}"; var tiers = new SortedSet { 0, _tier.Current }; @@ -3001,7 +3003,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase sb.Append("{\"show\":true,\"current\":").Append(_tier.Current) .Append(",\"view\":").Append(view) .Append(",\"following\":").Append(_damageViewTier < 0 ? "true" : "false") - .Append(",\"percent\":").Append(JsonNum(CreatureData.AwakenedTier.PercentPerTier)) + .Append(",\"percent\":").Append(JsonNum(_tier.HealthPercentPerTier)) .Append(",\"tiers\":[").Append(string.Join(",", tiers)).Append("]}"); return sb.ToString(); } @@ -3009,15 +3011,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase /// /// A monster's HP at a difficulty tier, for the Damage panel: the manual override (a /// real-Dereth value, scaled), else that tier's appraisal, else that tier's learned pool - /// (), else - above tier 0 only - tier 0's scaled by 5% a tier, + /// (), else - above tier 0 only - tier 0's scaled by the tier, /// flagged as an estimate. At tier 0 this is the panel's old order exactly. /// private (double Hp, bool Manual, bool Estimated, string Source) HpAt(uint wcid, int difficulty, bool learned = true) { var store = _damageStore; if (store == null || wcid == 0) return (0, false, false, ""); - double scale = CreatureData.AwakenedTier.HealthScale(difficulty); - double pct = difficulty * CreatureData.AwakenedTier.PercentPerTier; + double scale = _tier.HealthScale(difficulty); + double pct = difficulty * _tier.HealthPercentPerTier; double manual = store.GetManualHp(wcid); if (manual > 0) return (manual * scale, true, false, difficulty > 0 ? $"set by you (real Dereth {manual:0}, +{pct:0}%)" : "set by you"); @@ -3251,18 +3253,18 @@ public sealed partial class RynthAiPlugin : RynthPluginBase private const uint PROP_FLOAT_RESIST_ELECTRIC = 70; /// - /// Once a second (AwakenedTier throttles): which server, and Aelrynth's tier where the player - /// stands. The creature store follows the server; the damage store records under the tier. - /// Off Aelrynth the tier stays 0, so nothing below changes there. + /// Once a second (DifficultyTier throttles): which server, and the difficulty tier where the + /// player stands as the server's plugin reports it. The creature store follows the server; the + /// damage store records under the tier. Without a server plugin's tiers the tier stays 0, so + /// nothing below changes there. /// - private void TickAwakenedTier() + private void TickDifficultyTier() { try { - uint pid = _playerId != 0 ? _playerId : Host.GetPlayerId(); bool wasActive = _tier.Active; int was = _tier.Current; - _tier.Refresh(Host, pid); + _tier.Refresh(Host); if (_damageStore != null) _damageStore.Difficulty = _tier.Current; if (_creatureStore != null && _tier.ServerKey.Length > 0 @@ -3273,11 +3275,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase } if (_tier.Active && (!wasActive || was != _tier.Current)) - Log($"RynthAi: Aelrynth difficulty tier {_tier.Current} - learned HP, casts to kill, accuracy and fight times are kept for this tier."); + Log($"RynthAi: difficulty tier {_tier.Current} (+{_tier.HealthPercentPerTier:0.##}% monster health a tier, from {_tier.Source})" + + " - learned HP, casts to kill, accuracy and fight times are kept for this tier."); } catch (Exception ex) { - Host.Log($"[RynthAi] TickAwakenedTier: {ex.Message}"); + Host.Log($"[RynthAi] TickDifficultyTier: {ex.Message}"); } } @@ -3332,7 +3335,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase } } - TickAwakenedTier(); // the right server's file and tier before the first write (throttled) + TickDifficultyTier(); // the right server's file and tier before the first write (throttled) _creatureStore.Upsert(sample, _tier.Current); // Remember this monster type so the Damage table shows it (as a bare row with diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiServerCommand.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiServerCommand.cs index 5b3b154..5562d3f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiServerCommand.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiServerCommand.cs @@ -50,7 +50,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] Mini Remote server tabs: no server plugin hub connected (none loaded for this world)."); else { - string id = hub.Text(RynthIltHub.TextServerId); + string id = hub.Text(RynthServerHub.TextServerId); ChatLine($"[RynthAi] Mini Remote server tabs: connected{(id.Length > 0 ? " (server '" + id + "')" : string.Empty)}, " + (hub.ServerActive ? "its server is this world." : "its server is not this world (nothing shown).")); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj index 2eeaf02..2d9acaf 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj @@ -67,8 +67,8 @@ - - + + diff --git a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCompatCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCompatCommands.cs index 6522ee9..0ec1be9 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCompatCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltCompatCommands.cs @@ -140,11 +140,11 @@ public sealed partial class RynthAiPlugin UbNoEquivalent(cmd, "RynthSort reads its rules itself"); return true; - // ── A server's own commands (ub-IT's ACECustom verbs): the server plugin's (RynthILT) ── + // ── A server's own commands (ub-IT's server verbs): the active server plugin's, if it takes them ── case "qblist": case "augs": if (!TryForwardToServerPlugin(new[] { "/ra", "ub", cmd })) - UbNoEquivalent(cmd, "it is a server plugin's command (Infinite Leaftide: RynthILT), and none is loaded"); + UbNoEquivalent(cmd, "it is a server plugin's command, and no loaded server plugin takes it"); return true; // ── RynthCore's window placement ──────────────────────────────────── diff --git a/Plugins/RynthCore.Plugin.RynthColdeve/RynthCore.Plugin.RynthColdeve.csproj b/Plugins/RynthCore.Plugin.RynthColdeve/RynthCore.Plugin.RynthColdeve.csproj deleted file mode 100644 index 551ffc8..0000000 --- a/Plugins/RynthCore.Plugin.RynthColdeve/RynthCore.Plugin.RynthColdeve.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - - RynthCore.Plugin.RynthColdeve - 0.1.0 - coldeve - Coldeve - play.coldeve.ac - Coldeve - Coldeve only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthColdeve/ServerData.cs b/Plugins/RynthCore.Plugin.RynthColdeve/ServerData.cs deleted file mode 100644 index ba07823..0000000 --- a/Plugins/RynthCore.Plugin.RynthColdeve/ServerData.cs +++ /dev/null @@ -1,18 +0,0 @@ -// ServerData.cs - What is known about Coldeve (RynthColdeve). Identity (id, hosts, world names) is in the csproj. -namespace RynthCore.Plugin.ServerPack; - -internal static class ServerData -{ - public static ServerPackInfo Create() => - new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) - { - Port = 9000, - Emulator = "ACE", - Ruleset = "PvE", - Status = "Stable", - Summary = "A PVE AC Server evolving to provide a end of retail experience running ACEmulator.", - Facts = new[] { "End-of-retail experience on ACEmulator." }, - Discord = "https://discord.gg/nUR4PHe", - Source = "public AC server list (acresources/serverslist), checked 2026-10-13", - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestData.cs b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestData.cs deleted file mode 100644 index deaf617..0000000 --- a/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestData.cs +++ /dev/null @@ -1,428 +0,0 @@ -// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md. -// Moved here from RynthOracle (Data/Conquest.cs) on 2026-10-20: Conquest-only features live in RynthConquest. -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text.RegularExpressions; -using RynthCore.Plugin.ServerPack; - -namespace RynthCore.Plugin.RynthConquest; - -/// A labelled value from a server reply ("Pyreals" = "1,039,678,533 (4,158 MMDs)"). -internal sealed class NamedValue -{ - public string Name = ""; - public string Value = ""; -} - -/// One of ConquestAC's advanced augmentations (counts from "/augs"). -internal sealed class ConquestAug -{ - public readonly string Name; - public readonly int CoinCost; - public readonly double LumBase, LumPercent; - public int Count; - - public ConquestAug(string name, int coinCost, double lumBase, double lumPercent) - { - Name = name; CoinCost = coinCost; LumBase = lumBase; LumPercent = lumPercent; - } - - /// The next purchase's luminance (Conquest-ACE's tiered cost, as upstream mirrors it). - public long NextLuminanceCost() - { - long idx = Count; - (double tierBase, long pos) = idx >= 65 ? (LumBase * 30.0, idx - 65) - : idx >= 60 ? (LumBase * 12.0, idx - 60) - : idx >= 30 ? (LumBase * 4.8, idx - 30) - : idx >= 15 ? (LumBase * 2.4, idx - 15) - : (LumBase, idx); - // The server truncates to long; the epsilon keeps 6,229,499.9999 (binary floating point) at the - // confirmed in-game 6,229,500 (Creature at 25). - return (long)(tierBase * (1.0 + pos * LumPercent) + 1e-6); - } - - public string NextCostText() => - $"{CoinCost} coins, {(NextLuminanceCost() / 1_000_000.0).ToString("0.##", CultureInfo.InvariantCulture)}M lum"; - - private double ResistPercent() - { - const double MaxBonus = 0.32, LinearRate = 0.003, Tuning = 0.0034597; - const int LinearCap = 10; - if (Count <= 0) return 0.0; - double bonus = Count <= LinearCap - ? Count * LinearRate - : LinearCap * LinearRate + (MaxBonus - LinearCap * LinearRate) * (1.0 - Math.Pow(1.0 - Tuning, Count - LinearCap)); - return Math.Min(bonus, MaxBonus) * 100.0; - } - - /// The effect at the current count (upstream's reading of the Conquest-ACE source). - public string Effect() => Name switch - { - "Creature" => $"+{Count} to creature buffs, -{Count} to debuffs", - "Item" => $"+{Count}% attack/melee, +{Count * 0.5:0.#} blood/spirit, +{Count} AL", - "Life" => $"+{ResistPercent():0.##}% prot, +{ResistPercent():0.##}% vuln, +{Count * 0.10:0.##} regen, +{Count / 10} surge rating", - "War" => $"+{Count * 2}% war magic potency", - "Void" => $"+{Count * 1.5:0.##}% void magic potency", - "Melee" => $"+{Count} melee damage, +{Count * 1.5:0.#}% crit damage", - "Missile" => $"+{Count} missile damage, +{Count * 1.5:0.#}% crit damage", - "Duration" => $"+{Count * 5}% spell duration", - "Specialization" => $"+{Count} skill spec cap (now {70 + Count})", - _ => "", - }; -} - -/// A fellowship from "/fship list". -internal sealed class ConquestFellowship -{ - public string Name = "", Leader = "", Members = "", Location = ""; - - public int MemberCount - { - get - { - int slash = Members.IndexOf('/'); - return int.TryParse(slash >= 0 ? Members[..slash] : Members, out int n) ? n : 0; - } - } -} - -/// A row of a leaderboard. -internal sealed class BoardRow -{ - public int Rank; - public string Name = ""; - public string Value = ""; - public string Extra = ""; - public bool IsYou; -} - -/// One of ConquestAC's /top boards. -internal sealed class ConquestBoard -{ - public readonly string Key, Label, Header; - public readonly List Rows = new(); - public BoardRow? You; - public DateTime UpdatedUtc = DateTime.MinValue; - - public ConquestBoard(string key, string label, string header) { Key = key; Label = label; Header = header; } - - public string Command => "/top " + Key; -} - -/// -/// Everything Conquest-only: bank balances and bank commands ("/b", "/bank"), -/// advanced augmentations ("/augs"), enlightenment augmentations ("/enl augs"), the XP bonus -/// breakdown ("/bonus"), fellowships looking for members ("/fship list"), the /top boards, and -/// the void damage-over-time duration scaling. RynthConquest only feeds it chat while the server is -/// Conquest (and only loads there); every reply regex is anchored at the start of the line (after -/// an optional chat timestamp), as upstream does, so a pasted copy in a chat channel can't -/// overwrite your values. -/// -internal sealed class ConquestData -{ - private const string Ts = @"^\s*(?:\[[^\]]*\][\s:]*)?"; - - // /b balances - private static readonly Regex BankLine = new(Ts + @"\[BANK\]\s+(.+?):\s*(.*\S)\s*$"); - private static readonly Regex BankChrome = new(Ts + @"\[BANK\]\s+[^:]*:\s*$"); - private static readonly Regex EventToken = new(@"Event Tokens \[(.+?)\]"); - private static readonly Regex DepositReply = new(Ts + @"(?:No .+? (?:found|available) to deposit|Deposited\b.*)\s*$", RegexOptions.IgnoreCase); - // /augs - private static readonly Regex AugLine = new(Ts + @"(Creature|Item|Life|War|Void|Duration|Specialization|Melee|Missile):\s*([\d,]+)\b"); - private static readonly Regex AugChrome = new(Ts + @"(?:-{3,}|Advanced Augmentation Levels:|Use /aug info for per-level effect details\.)\s*$", RegexOptions.IgnoreCase); - // /enl augs - private static readonly Regex EnlLine = new(Ts + @"([A-Za-z][A-Za-z '\-]*?):\s*(([\d,]+)\s*\(\s*[\d,]+\s+max\s*\))\s*$"); - private static readonly Regex EnlChrome = new(Ts + @"Enlightenment Augmentations:\s*$"); - // /bonus - private static readonly Regex BonusLine = new(Ts + @"(Quest|Enlightenment|PK Dungeon|Augmentation|Equipment|Total) Bonus(?:\s*\(([^)]+)\))?:\s*(.+\S)\s*$"); - private static readonly Regex BonusChrome = new(Ts + @"={2,}\s*XP Bonuses\s*={2,}\s*$"); - // /fship list - private static readonly Regex FshipHeader = new(Ts + @"Fellowships looking for members"); - private static readonly Regex FshipLine = new(Ts + @"-\s+(.+?)\s+\(Leader:\s+(.+?)\)\s+\[(\d+/\d+)\](?:\s+@\s+(.+?))?\s*$"); - // /top - private static readonly Regex TopHeader = new(Ts + @"Top\s+(\d+)\s+Players?\s+by\s+(.+?):\s*$"); - private static readonly Regex TopEntry = new(Ts + @"(\d+):\s+([\d,]+)\s+-\s+(.+?)\s*$"); - private static readonly Regex TopSeparator = new(Ts + @"\.\.\.\s*$"); - - private static readonly string[] EnlOrder = - { - "Damage", "Damage Reduction", "Crit Damage", "Crit Damage Reduction", "Imbue", "Salvage", "Skill Credits", - "Stamina Benediction", "Mana Benediction", "Cleave", "Arrow Split", "Spell Chain", "Aetheria Surge", "Void Contagion", - }; - private static readonly Dictionary EnlCosts = new(StringComparer.OrdinalIgnoreCase) - { - ["Cleave"] = "1 Pristine Token", ["Arrow Split"] = "1 Pristine Token", ["Spell Chain"] = "1 Pristine Token", - ["Aetheria Surge"] = "1 Pristine Token", ["Void Contagion"] = "1 Pristine Token", - ["Damage"] = "2 Tokens", ["Damage Reduction"] = "2 Tokens", ["Crit Damage"] = "2 Tokens", - ["Crit Damage Reduction"] = "2 Tokens", ["Imbue"] = "2 Tokens", ["Salvage"] = "2 Tokens", - ["Skill Credits"] = "4 Tokens", ["Stamina Benediction"] = "4 Tokens", ["Mana Benediction"] = "4 Tokens", - }; - - public const int PyrealsPerMmd = 250_000; - - public readonly List Bank = new(); - public readonly List Augs = new() - { - new("Creature", 25, 2_500_000, 0.003825), new("Item", 100, 3_000_000, 0.006825), new("Life", 75, 2_500_000, 0.0095), - new("War", 50, 1_750_000, 0.00425), new("Void", 50, 1_800_000, 0.00425), new("Duration", 30, 1_400_000, 0.00625), - new("Specialization", 125, 3_000_000, 0.02), new("Melee", 50, 1_750_000, 0.00425), new("Missile", 50, 1_750_000, 0.00425), - }; - public List EnlAugs { get; private set; } = new(); - public readonly List Bonuses = new() - { - new() { Name = "Quest" }, new() { Name = "Enlightenment" }, new() { Name = "PK Dungeon" }, new() { Name = "Augmentation" }, - new() { Name = "Equipment" }, new() { Name = "Total (Kills)" }, new() { Name = "Total (Quest/Lum)" }, - }; - public readonly List Fellowships = new(); - public readonly List Boards = new() - { - new("augs", "Augs", "Total Augmentations"), new("deaths", "Deaths", "Deaths"), new("enl", "Enlightens", "Enlightenment"), - new("level", "Levels", "Level"), new("lum", "Luminance", "Banked Luminance"), new("bank", "Pyreals", "Banked Pyreals"), - new("qb", "QB", "Quest Bonus"), new("titles", "Titles", "Titles"), - }; - - public DateTime BankUtc = DateTime.MinValue, AugsUtc = DateTime.MinValue, EnlUtc = DateTime.MinValue, - BonusUtc = DateTime.MinValue, FshipUtc = DateTime.MinValue; - public int Revision { get; private set; } - - private readonly ServerChatRequest _bankReq = new(), _augReq = new(), _enlReq = new(), _bonusReq = new(), _fshipReq = new(), - _topReq = new(), _depositReq = new(); - private ConquestBoard? _collecting; - private long _collectingMs; - private int _collectingExpected = int.MaxValue; - private bool _collectingCleared; - - public static string EnlCost(string name) => EnlCosts.TryGetValue(name, out string? c) ? c : ""; - - public int AugTotal => Augs.Sum(a => a.Count); - public int DurationAugs => Augs.First(a => a.Name == "Duration").Count; - - public void Clear() - { - Bank.Clear(); - foreach (ConquestAug a in Augs) a.Count = 0; - EnlAugs = new List(); - foreach (NamedValue b in Bonuses) b.Value = ""; - Fellowships.Clear(); - foreach (ConquestBoard b in Boards) { b.Rows.Clear(); b.You = null; b.UpdatedUtc = DateTime.MinValue; } - BankUtc = AugsUtc = EnlUtc = BonusUtc = FshipUtc = DateTime.MinValue; - _collecting = null; - Revision++; - } - - // ── Requests (the plugin sends the command; each returns the command text) ── - - public string RequestBank(long now) { _bankReq.Sent(now); return "/b"; } - public string RequestAugs(long now) { _augReq.Sent(now); return "/augs"; } - public string RequestEnl(long now) { _enlReq.Sent(now); return "/enl augs"; } - public string RequestBonus(long now) { _bonusReq.Sent(now); return "/bonus"; } - public string RequestFships(long now) { _fshipReq.Sent(now); Fellowships.Clear(); Revision++; return "/fship list"; } - - public string RequestBoard(ConquestBoard board, long now) - { - _topReq.Sent(now); - Open(board, now); - return "/top " + board.Key; - } - - /// An automatic deposit: its reply is ours to hide. - public string AutoDeposit(long now) { _depositReq.Sent(now); return "/bank deposit"; } - - /// - /// A chat line: true when it was a reply this module reads; = it - /// answers a request RynthConquest sent (eligible to be hidden). - /// - public bool OnChatLine(string text, long now, out bool ours) - { - ours = false; - Match m; - - if (_depositReq.Awaiting(now) && DepositReply.IsMatch(text)) { ours = true; _depositReq.Extend(now); return true; } - - if ((m = BankLine.Match(text)).Success) - { - string name = EventToken.Replace(m.Groups[1].Value.Trim(), "$1"); - string value = m.Groups[2].Value.Trim(); - if (name == "Pyreals" && long.TryParse(value.Replace(",", ""), out long py)) - value += $" ({(py / PyrealsPerMmd).ToString("N0", CultureInfo.InvariantCulture)} MMDs)"; - NamedValue? e = Bank.FirstOrDefault(b => b.Name == name); - if (e != null) e.Value = value; else Bank.Add(new NamedValue { Name = name, Value = value }); - BankUtc = DateTime.UtcNow; - return Done(_bankReq, now, out ours); - } - if (_bankReq.Awaiting(now) && BankChrome.IsMatch(text)) return Done(_bankReq, now, out ours); - - if ((m = AugLine.Match(text)).Success) - { - ConquestAug? a = Augs.FirstOrDefault(x => x.Name == m.Groups[1].Value); - if (a != null && int.TryParse(m.Groups[2].Value.Replace(",", ""), out int c)) a.Count = c; - AugsUtc = DateTime.UtcNow; - return Done(_augReq, now, out ours); - } - if (_augReq.Awaiting(now) && AugChrome.IsMatch(text)) return Done(_augReq, now, out ours); - - if (EnlChrome.IsMatch(text)) - { - EnlAugs = new List(); - return Done(_enlReq, now, out ours); - } - if ((m = EnlLine.Match(text)).Success) - { - // "Label: N (M max)" is specific to the "/enl augs" reply (its header starts a fresh list). - string name = m.Groups[1].Value.Trim(); - var list = new List(EnlAugs.Where(x => x.Name != name)) { new() { Name = name, Value = m.Groups[2].Value.Trim() } }; - list.Sort((x, y) => Rank(x.Name).CompareTo(Rank(y.Name))); - EnlAugs = list; - EnlUtc = DateTime.UtcNow; - return Done(_enlReq, now, out ours); - } - - if ((m = BonusLine.Match(text)).Success) - { - string q = m.Groups[2].Value.Trim(); - string name = q.Length > 0 ? $"{m.Groups[1].Value} ({q})" : m.Groups[1].Value; - NamedValue? b = Bonuses.FirstOrDefault(x => x.Name == name); - if (b != null) b.Value = m.Groups[3].Value.Trim(); - BonusUtc = DateTime.UtcNow; - return Done(_bonusReq, now, out ours); - } - if (_bonusReq.Awaiting(now) && BonusChrome.IsMatch(text)) return Done(_bonusReq, now, out ours); - - if (FshipHeader.IsMatch(text)) - { - if (!_fshipReq.Awaiting(now)) Fellowships.Clear(); - FshipUtc = DateTime.UtcNow; - return Done(_fshipReq, now, out ours); - } - if ((m = FshipLine.Match(text)).Success) - { - Fellowships.Add(new ConquestFellowship - { - Name = m.Groups[1].Value.Trim(), Leader = m.Groups[2].Value.Trim(), Members = m.Groups[3].Value.Trim(), - Location = m.Groups[4].Success ? m.Groups[4].Value.Trim() : "", - }); - FshipUtc = DateTime.UtcNow; - return Done(_fshipReq, now, out ours); - } - - if ((m = TopHeader.Match(text)).Success) - { - ConquestBoard? board = Active(now) ?? Boards.FirstOrDefault(b => b.Header.Equals(m.Groups[2].Value.Trim(), StringComparison.OrdinalIgnoreCase)); - if (board == null) return false; - Open(board, now); - ClearOnce(); - _collectingExpected = int.TryParse(m.Groups[1].Value, out int n) ? n : int.MaxValue; - return Done(_topReq, now, out ours); - } - if ((m = TopEntry.Match(text)).Success && Active(now) is ConquestBoard cb) - { - ClearOnce(); - int.TryParse(m.Groups[1].Value, out int rank); - string name = m.Groups[3].Value.Trim(); - var row = new BoardRow { Rank = rank, Value = m.Groups[2].Value.Trim(), Name = name }; - if (name.EndsWith("(You)", StringComparison.OrdinalIgnoreCase)) - { - row.IsYou = true; - row.Name = name[..^5].Trim(); - cb.You = row; - } - if (rank <= _collectingExpected && cb.Rows.All(r => r.Rank != rank)) cb.Rows.Add(row); - cb.Rows.Sort((x, y) => x.Rank.CompareTo(y.Rank)); - cb.UpdatedUtc = DateTime.UtcNow; - _collectingMs = now; - return Done(_topReq, now, out ours); - } - if (Active(now) != null && TopSeparator.IsMatch(text)) return Done(_topReq, now, out ours); - - return false; - } - - private bool Done(ServerChatRequest req, long now, out bool ours) - { - ours = req.Awaiting(now); - req.Extend(now); - Revision++; - return true; - } - - private static int Rank(string name) - { - int i = Array.FindIndex(EnlOrder, n => n.Equals(name, StringComparison.OrdinalIgnoreCase)); - return i < 0 ? EnlOrder.Length : i; - } - - private void Open(ConquestBoard board, long now) - { - if (_collecting == board && now - _collectingMs < 15_000) return; - _collecting = board; - _collectingMs = now; - _collectingExpected = int.MaxValue; - _collectingCleared = false; - } - - private ConquestBoard? Active(long now) => _collecting != null && now - _collectingMs < 15_000 ? _collecting : null; - - private void ClearOnce() - { - if (_collectingCleared || _collecting == null) return; - _collecting.Rows.Clear(); - _collecting.You = null; - _collectingCleared = true; - } - - // ── Bank commands (Conquest-ACE's /bank; tokens are its one-letter currency codes) ── - - public sealed record Currency(string Label, string Token, long Multiplier = 1, long Max = long.MaxValue); - - public static readonly Currency[] Withdrawable = - { - new("Conquest Coins", "c"), new("Event Tokens", "e"), new("Legendary Keys", "k"), new("Pyreals", "p"), - new("Soul Fragments", "s"), new("MMD Notes (250k)", "n"), new("MM Notes (200k)", "n MM"), new("M Notes (100k)", "n M"), - new("D Notes (50k)", "n D"), new("C Notes (10k)", "n C"), new("L Notes (5k)", "n L"), new("X Notes (1k)", "n X"), - new("V Notes (500)", "n V"), new("I Notes (100)", "n I"), - }; - public const int DefaultWithdraw = 5; // MMD notes - - public static readonly Currency[] Transferable = - { - new("Legendary Keys", "k"), new("Luminance", "l"), new("MMD Notes (250k)", "p", 250_000, 1_000), new("Pyreals", "p"), - }; - public const int DefaultTransfer = 1; // Luminance - - /// "/bank withdraw <token> <n>", or null when the amount isn't a whole number above 0. - public static string? WithdrawCommand(Currency c, string amount) => - long.TryParse((amount ?? "").Replace(",", "").Trim(), out long n) && n > 0 ? $"/bank withdraw {c.Token} {n}" : null; - - /// "/bank transfer <token> <n> "name"", or null when the amount or name isn't usable. - public static string? TransferCommand(Currency c, string amount, string target) - { - target = (target ?? "").Trim().Replace("\"", ""); - if (target.Length == 0 || !long.TryParse((amount ?? "").Replace(",", "").Trim(), out long n) || n <= 0 || n > c.Max) return null; - try { return $"/bank transfer {c.Token} {checked(n * c.Multiplier)} \"{target}\""; } - catch (OverflowException) { return null; } - } - - // ── Levels and enlightenment (ConquestAC's levels 276-300, upstream's table) ── - - private static readonly long[] Levels276To300 = - { - 194665023377, 198152685223, 201689992550, 205277652043, 208916380445, - 212606904701, 216349962105, 220146300445, 223996678153, 227901864460, - 231862639544, 235879794689, 239954132442, 244086466776, 248277623248, - 252528439169, 256839763767, 261212458359, 265647396522, 270145464270, - 274707560226, 279334595807, 284027495403, 288787196561, 293614650176, - }; - public const int MaxLevel = 300; - - /// Total XP to reach a level 276-300 (0 otherwise). - public static long XpForLevel(int level) => level >= 276 && level <= 300 ? Levels276To300[level - 276] : 0; - - private static double EnlMultiplier(int target) => target >= 75 ? 7.5 : target >= 50 ? 5.0 : target >= 25 ? 2.5 : 1.0; - public static long EnlCoinCost(int target) => (long)(target * 100 * EnlMultiplier(target)); - public static long EnlLuminanceCost(int target) => (long)(target * 1_000_000L * EnlMultiplier(target)); - - /// Void DoT duration on ConquestAC: × (1 + Archmage's Endurance × 0.2 + Duration augs × 0.05). - public double VoidDurationMultiplier(int archmagesEndurance) => 1.0 + archmagesEndurance * 0.2 + DurationAugs * 0.05; -} diff --git a/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestFeature.cs b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestFeature.cs deleted file mode 100644 index c631271..0000000 --- a/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestFeature.cs +++ /dev/null @@ -1,143 +0,0 @@ -// ConquestFeature.cs - What RynthConquest does on Conquest, without the host (ConquestPlugin.cs wires it -// to the engine, ConquestPages.cs draws it). Moved out of RynthOracle on 2026-10-20 so that only players -// who installed RynthConquest get Conquest's features, and the automatic /bank deposit with them: -// * reads the replies of Conquest's own commands (ConquestData: /b, /augs, /enl augs, /bonus, -// /fship list, /top) and the quest flags (/myquests, for the custom quest worklist), and hides -// the replies to its own requests when HideOwnReplies is on; -// * reads the advanced augmentations once after login (the Void DoT rule needs the Duration augs); -// * deposits everything at each ten-minute mark when AutoDeposit is on (off unless the player -// turned it on, in RynthOracle before or here); -// * works out the Void DoT duration rule for this character, which RynthOracle's Void timers read -// from the server profile ("voidDotDurationScale") instead of knowing about Conquest. -// Settings: rynthconquest.json (ServerPackSettings), taken over once from rynthoracle.json. -// Threads: everything here runs under Gate. Chat and tick come from the pump, the pages draw on the -// render thread holding it too; nothing in here calls the host. -// Pure: RynthServerPack.Tests covers it. -using System; -using RynthCore.Plugin.RynthOracle.Data; -using RynthCore.Plugin.ServerPack; - -namespace RynthCore.Plugin.RynthConquest; - -internal sealed class ConquestFeature -{ - public const string SettingAutoDeposit = "autoDeposit"; - public const string SettingHideOwnReplies = "hideOwnReplies"; - /// Set once rynthoracle.json's Conquest settings were taken over (they're never read again). - public const string MigrationMarker = "migratedFromRynthOracle"; - /// The profile value RynthOracle's Void timers apply ("RynthServer.Profile" values). - public const string VoidScaleKey = "voidDotDurationScale"; - /// After login, before the hidden /augs (RynthOracle's old timing: its quest read plus 4 s). - public const long AugsReadDelayMs = 10_000; - /// The character's level, XP and augmentation are read this often. - public const long CharacterReadMs = 1000; - - /// RynthConquest's pages (ConquestPages draws them): id, label, tooltip. - public static readonly (string Id, string Label, string Tooltip)[] PageList = - { - ("main", "Conquest", "Conquest: bank and auto-deposit, augmentations, levels past 275, fellowships and custom quests (RynthConquest)."), - ("boards", "Leaderboards", "Conquest's /top boards (RynthConquest)."), - }; - - /// Held for everything below (pump and render thread). - public readonly object Gate = new(); - public readonly ConquestData Data = new(); - public readonly QuestFlagStore Flags = new(); - - /// "/bank deposit" at every ten-minute mark (upstream's auto-deposit). Off by default. - public bool AutoDeposit; - /// Hide the replies to RynthConquest's own requests (a command typed by hand always shows). - public bool HideOwnReplies = true; - - // The character (ConquestPlugin reads them every CharacterReadMs). - public bool CharacterKnown; - public int Level, Enlightenment, ArchmagesEndurance; - public long TotalXp; - - private long _loginMs; - private bool _augsAsked; - private long _lastDepositBlock = -1; - - /// - /// Takes over the settings RynthOracle had for Conquest (rynthoracle.json at ), - /// once per settings file; a value that isn't there keeps this plugin's default (auto-deposit off, - /// hiding on, as they were in RynthOracle). True when it ran now. - /// - public static bool Migrate(ServerPackSettings settings, string oraclePath) => settings.MigrateOnce(MigrationMarker, s => - { - if (ServerPackSettings.ReadBoolFrom(oraclePath, "conquestAutoDeposit") is bool deposit) s.SetBool(SettingAutoDeposit, deposit); - if (ServerPackSettings.ReadBoolFrom(oraclePath, "hideOwnQuestReplies") is bool hide) s.SetBool(SettingHideOwnReplies, hide); - }); - - public void LoadSettings(ServerPackSettings s) - { - AutoDeposit = s.GetBool(SettingAutoDeposit, false); - HideOwnReplies = s.GetBool(SettingHideOwnReplies, true); - } - - public void SaveSettings(ServerPackSettings s) - { - bool changed = s.SetBool(SettingAutoDeposit, AutoDeposit); - changed |= s.SetBool(SettingHideOwnReplies, HideOwnReplies); - if (changed) s.Save(); - } - - /// A character logged in (or the plugin loaded in game): everything is read fresh. - public void Login(long nowMs) - { - _loginMs = nowMs; - _augsAsked = false; - Data.Clear(); - Flags.Clear(); - CharacterKnown = false; - Level = Enlightenment = ArchmagesEndurance = 0; - TotalXp = 0; - } - - public void Logout() - { - Data.Clear(); - Flags.Clear(); - CharacterKnown = false; - } - - /// - /// An incoming chat line on Conquest. True when it should be hidden: a reply to one of - /// RynthConquest's own requests, with HideOwnReplies on. - /// - public bool OnChatLine(string text, long nowMs) - { - string line = text.TrimEnd('\r', '\n'); - MyQuestsLine kind = Flags.OnChatLine(line, nowMs); - if (kind != MyQuestsLine.None) - return Flags.AwaitingOurs && HideOwnReplies && kind is MyQuestsLine.Quest or MyQuestsLine.Empty; - return Data.OnChatLine(line, nowMs, out bool ours) && ours && HideOwnReplies; - } - - /// The once-after-login /augs: the command to send now, or null. - public string? LoginAugsDue(long nowMs) - { - if (_augsAsked || nowMs - _loginMs <= AugsReadDelayMs) return null; - _augsAsked = true; - return Data.RequestAugs(nowMs); - } - - /// The automatic deposit: "/bank deposit" when one is due now, else null. - public string? AutoDepositDue(DateTime local, long nowMs) - => AutoDeposit && DepositDue(local, ref _lastDepositBlock) ? Data.AutoDeposit(nowMs) : null; - - /// - /// True once in each ten-minute block, at its first minute (:00, :10, :20 ... local time), as - /// upstream does; remembers the block already done. - /// - public static bool DepositDue(DateTime local, ref long lastBlock) - { - long block = local.Ticks / TimeSpan.TicksPerMinute / 10; - if (local.Minute % 10 != 0 || block == lastBlock) return false; - lastBlock = block; - return true; - } - - /// This character's Void DoT duration multiplier on Conquest (Archmage's Endurance and the Duration augs). - public double VoidScale => Data.VoidDurationMultiplier(ArchmagesEndurance); -} diff --git a/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestPages.cs b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestPages.cs deleted file mode 100644 index 27e3fae..0000000 --- a/Plugins/RynthCore.Plugin.RynthConquest/Conquest/ConquestPages.cs +++ /dev/null @@ -1,417 +0,0 @@ -// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md. -// RynthOracle's Conquest tab (Views/ConquestTab.cs) and the Conquest half of its Leaderboards tab -// (Views/BoardsTab.cs), moved here on 2026-10-20 and redrawn with ImGui as RynthConquest's pages: -// sub-tabs of the Mini Remote's Server section while on Conquest, and tabs of the /rserver window. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; -using ImGuiNET; -using RynthCore.Plugin.RynthOracle.Data; -using RynthCore.Plugin.ServerPack; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthConquest; - -/// -/// The Conquest page (bank balances and bank commands, advanced and enlightenment augmentations, -/// levels past 275 and the XP bonus breakdown, fellowships looking for members, the custom quest -/// worklist: upstream's Bank, Conquest Augs, Conquest XP, Fship and Custom tabs) and the -/// Leaderboards page (Conquest's /top boards: upstream's Top Players tab). -/// Render thread: each page draws holding the feature's lock, and queues what it sends for the tick. -/// -internal sealed class ConquestPages -{ - private static readonly Vector4 Gold = new(1.00f, 0.84f, 0.30f, 1f); - private static readonly Vector4 Green = new(0.45f, 0.85f, 0.45f, 1f); - private static readonly Vector4 Grey = new(0.55f, 0.57f, 0.60f, 1f); - private static readonly Vector4 Selected = new(0.26f, 0.45f, 0.70f, 1f); - - private static readonly string[] Views = { "Bank", "Augs", "Enlightenment", "Experience", "Fellowships", "Custom quests" }; - private static readonly string[] FshipSorts = { "Name", "Leader", "Most members", "Location" }; - - private readonly ConquestFeature _f; - private readonly Func _active; - private readonly Action _runOnTick; - private readonly Func _send; - private readonly Action _print; - private readonly Action _saveSettings; - private readonly ServerRefreshRow _refresh = new(); - - private int _view; - private int _withdrawIndex = ConquestData.DefaultWithdraw, _transferIndex = ConquestData.DefaultTransfer; - private string _withdrawAmount = "", _transferAmount = "", _transferTarget = ""; - private int _fshipSort; - private int _board; - - /// RynthConquest's server is this world. - /// Queues work for the plugin tick (ServerPackPlugin.RunOnTick). - /// Sends a chat command as if typed (pump thread). - /// A line in the chat window (pump thread). - /// Writes the feature's settings (pump thread). - public ConquestPages(ConquestFeature feature, Func active, Action runOnTick, Func send, - Action print, Action saveSettings) - { - _f = feature; - _active = active; - _runOnTick = runOnTick; - _send = send; - _print = print; - _saveSettings = saveSettings; - } - - public ServerPage[] Pages() - { - var list = ConquestFeature.PageList; - return new[] - { - new ServerPage(list[0].Id, list[0].Label, list[0].Tooltip, DrawConquest), - new ServerPage(list[1].Id, list[1].Label, list[1].Tooltip, DrawBoards), - }; - } - - /// Logout: the next character's status lines start empty. - public void Reset() => _refresh.Reset(); - - // ── Conquest page ─────────────────────────────────────────────────── - - private void DrawConquest() - { - if (!Ready()) return; - lock (_f.Gate) - { - for (int i = 0; i < Views.Length; i++) - { - if (i > 0) ImGui.SameLine(); - if (Toggle(Views[i] + "##cq_v" + i, i == _view)) _view = i; - } - _refresh.Draw("cq" + _view, ConquestHelp(), RefreshConquest); - ImGui.Separator(); - switch (_view) - { - case 0: DrawBank(); break; - case 1: DrawAugs(); break; - case 2: DrawEnl(); break; - case 3: DrawXp(); break; - case 4: DrawFships(); break; - default: DrawCustom(); break; - } - ImGui.Spacing(); - bool hide = _f.HideOwnReplies; - if (ImGui.Checkbox("Hide the replies to RynthConquest's own requests##cq_hide", ref hide)) - { - _f.HideOwnReplies = hide; - _runOnTick(_saveSettings); - } - Tooltip("/b, /augs, /top, /myquests and the like when RynthConquest sends them. A command you type yourself always shows its reply."); - } - } - - /// True when the page has something to show; otherwise says why. - private bool Ready() - { - if (_active()) return true; - SafeImGui.TextWrapped("These pages are for Conquest. RynthCore doesn't see this world as Conquest " - + "(check RynthCore Options > Diagnostics, or /rserver info)."); - return false; - } - - private static string ReadAt(DateTime utc) => utc == DateTime.MinValue ? "not read yet" : $"read at {utc.ToLocalTime():HH:mm}"; - - private void DrawBank() - { - ConquestData cq = _f.Data; - SafeImGui.TextDisabled(ReadAt(cq.BankUtc)); - foreach (NamedValue b in cq.Bank.OrderBy(b => b.Name, StringComparer.OrdinalIgnoreCase)) - { - SafeImGui.TextDisabled(Cut(b.Name, 34)); - ImGui.SameLine(260f); - SafeImGui.Text(b.Value); - } - if (cq.Bank.Count == 0) SafeImGui.TextDisabled("No balances read yet."); - - ImGui.SeparatorText("Deposit"); - if (ImGui.Button("Deposit everything##cq_dep")) Queue("/bank deposit"); - Tooltip("Sends /bank deposit."); - bool auto = _f.AutoDeposit; - if (ImGui.Checkbox("Deposit by itself every ten minutes##cq_auto", ref auto)) - { - _f.AutoDeposit = auto; - _runOnTick(_saveSettings); - } - Tooltip("At :00, :10, :20 ... while you're logged in on Conquest. Its reply is hidden."); - - ImGui.SeparatorText("Withdraw"); - string[] wl = ConquestData.Withdrawable.Select(c => c.Label).ToArray(); - ImGui.SetNextItemWidth(200f); - if (ImGui.Combo("Currency##cq_wcur", ref _withdrawIndex, wl, wl.Length)) _withdrawIndex = Math.Clamp(_withdrawIndex, 0, wl.Length - 1); - ImGui.SetNextItemWidth(200f); - ImGui.InputText("Amount##cq_wamt", ref _withdrawAmount, 16); - if (ImGui.Button("Withdraw##cq_withdraw")) - { - string? cmd = ConquestData.WithdrawCommand(ConquestData.Withdrawable[_withdrawIndex], _withdrawAmount); - if (cmd == null) Print("Withdraw: type a whole number above 0."); - else Queue(cmd); - } - - ImGui.SeparatorText("Transfer to a character"); - string[] tl = ConquestData.Transferable.Select(c => c.Label).ToArray(); - ImGui.SetNextItemWidth(200f); - if (ImGui.Combo("Currency##cq_tcur", ref _transferIndex, tl, tl.Length)) _transferIndex = Math.Clamp(_transferIndex, 0, tl.Length - 1); - ImGui.SetNextItemWidth(200f); - ImGui.InputText("Amount##cq_tamt", ref _transferAmount, 16); - ImGui.SetNextItemWidth(200f); - ImGui.InputText("Character##cq_tgt", ref _transferTarget, 40); - if (ImGui.Button("Transfer##cq_transfer")) - { - string? cmd = ConquestData.TransferCommand(ConquestData.Transferable[_transferIndex], _transferAmount, _transferTarget); - if (cmd == null) Print("Transfer: type a whole number above 0 (MMD notes: at most 1,000) and a character name."); - else Queue(cmd); - } - } - - private void DrawAugs() - { - ConquestData cq = _f.Data; - SafeImGui.TextDisabled($"{ReadAt(cq.AugsUtc)}, {cq.AugTotal} in total"); - ImGui.TextDisabled("Aug"); ImGui.SameLine(120f); ImGui.TextDisabled("Have"); ImGui.SameLine(170f); - ImGui.TextDisabled("Next costs"); ImGui.SameLine(330f); ImGui.TextDisabled("Effect now"); - foreach (ConquestAug a in cq.Augs) - { - SafeImGui.Text(a.Name); - ImGui.SameLine(120f); - SafeImGui.Text(a.Count.ToString()); - ImGui.SameLine(170f); - SafeImGui.Text(a.NextCostText()); - ImGui.SameLine(330f); - SafeImGui.TextDisabled(Cut(a.Effect(), 48)); - Tooltip(a.Effect()); - } - } - - private void DrawEnl() - { - ConquestData cq = _f.Data; - SafeImGui.TextDisabled(ReadAt(cq.EnlUtc)); - foreach (NamedValue a in cq.EnlAugs) - { - SafeImGui.Text(Cut(a.Name, 26)); - ImGui.SameLine(200f); - SafeImGui.Text(a.Value); - ImGui.SameLine(360f); - SafeImGui.TextDisabled(ConquestData.EnlCost(a.Name)); - } - if (cq.EnlAugs.Count == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh."); - } - - private void DrawXp() - { - ConquestData cq = _f.Data; - int level = _f.Level; - if (!_f.CharacterKnown) ImGui.TextDisabled("Reading your character..."); - ImGui.SeparatorText($"Level {level}"); - if (level >= ConquestData.MaxLevel) ImGui.TextUnformatted("Maximum level."); - else if (level < 275) - { - // Retail levels: RynthOracle's Character tab has the progress to the next one. - SafeImGui.TextDisabled($"Conquest's own levels start at 276. {Number(Math.Max(0, ConquestData.XpForLevel(276) - _f.TotalXp))} XP to level 276."); - } - else - { - long start = level >= 276 ? ConquestData.XpForLevel(level) : 0; - long next = ConquestData.XpForLevel(level + 1); - long toNext = Math.Max(0, next - _f.TotalXp); - long begin = level == 275 ? 191_226_310_247 : start; - float frac = next > begin ? (float)Math.Clamp((double)(_f.TotalXp - begin) / (next - begin), 0, 1) : 1f; - ImGui.ProgressBar(frac, new Vector2(-1f, 0f), $"{Number(toNext)} to level {level + 1}"); - long toMax = Math.Max(0, ConquestData.XpForLevel(ConquestData.MaxLevel) - _f.TotalXp); - SafeImGui.TextDisabled($"{Number(toMax)} to level {ConquestData.MaxLevel}"); - } - int target = _f.Enlightenment + 1; - ImGui.SeparatorText($"Enlightenment {_f.Enlightenment}"); - SafeImGui.Text($"Next costs {Number(ConquestData.EnlCoinCost(target))} coins and {(ConquestData.EnlLuminanceCost(target) / 1_000_000.0):0.##}M luminance"); - - ImGui.SeparatorText("Experience bonuses"); - SafeImGui.TextDisabled(ReadAt(cq.BonusUtc)); - foreach (NamedValue b in cq.Bonuses) - { - SafeImGui.TextDisabled(b.Name); - ImGui.SameLine(200f); - SafeImGui.Text(b.Value.Length > 0 ? b.Value : "-"); - } - } - - private void DrawFships() - { - ConquestData cq = _f.Data; - SafeImGui.TextDisabled($"{ReadAt(cq.FshipUtc)}, {cq.Fellowships.Count} looking for members"); - ImGui.SetNextItemWidth(160f); - ImGui.Combo("Sort##cq_fsort", ref _fshipSort, FshipSorts, FshipSorts.Length); - IEnumerable list = _fshipSort switch - { - 1 => cq.Fellowships.OrderBy(f => f.Leader, StringComparer.OrdinalIgnoreCase), - 2 => cq.Fellowships.OrderByDescending(f => f.MemberCount), - 3 => cq.Fellowships.OrderBy(f => f.Location, StringComparer.OrdinalIgnoreCase), - _ => cq.Fellowships.OrderBy(f => f.Name, StringComparer.OrdinalIgnoreCase), - }; - if (ImGui.BeginChild("##cq_fships", new Vector2(0f, 220f), ImGuiChildFlags.Borders)) - { - foreach (ConquestFellowship f in list) - { - SafeImGui.Text(Cut(f.Name, 26)); - ImGui.SameLine(200f); - SafeImGui.Text(Cut(f.Leader, 20)); - ImGui.SameLine(350f); - SafeImGui.Text(f.Members); - if (f.Location.Length > 0) { ImGui.SameLine(410f); SafeImGui.TextDisabled(Cut(f.Location, 26)); } - } - if (cq.Fellowships.Count == 0) ImGui.TextDisabled("None read yet. Press Refresh."); - } - ImGui.EndChild(); - } - - private void DrawCustom() - { - DateTime now = DateTime.UtcNow; - int i = 0; - foreach (CustomQuest q in CustomQuestList.All) - { - bool done = q.IsComplete(_f.Flags, now); - SafeImGui.TextColored(done ? Green : Grey, done ? "done" : "--"); - ImGui.SameLine(50f); - string status = q.Status(_f.Flags, now); - CustomQuest row = q; - if (ImGui.Selectable(Cut(q.Name, 34) + "##cq_cust" + i++, false, ImGuiSelectableFlags.None, new Vector2(280f, 0f))) - PrintEntry(row.Name, row.Flag, status, row.Hint, row.Url); - Tooltip("Click: the quest's hint in chat."); - ImGui.SameLine(340f); - SafeImGui.Text(status); - } - if (CustomQuestList.All.Count == 0) ImGui.TextDisabled("No custom quests listed."); - if (_f.Flags.LastReadUtc == DateTime.MinValue) ImGui.TextDisabled("Press Refresh to read your quest flags (/myquests) for their status."); - } - - /// An entry's name, status, hint and link in chat (upstream "thinks" them). - private void PrintEntry(string name, string flag, string status, string details, string url) - { - Print(flag.Length > 0 ? $"{name} ({flag}){(status.Length > 0 ? " - " + status : "")}" : name); - if (details.Length > 0) Print(details); - if (url.Length > 0) Print(url); - } - - // ── Leaderboards page ─────────────────────────────────────────────── - - private void DrawBoards() - { - if (!Ready()) return; - lock (_f.Gate) - { - ConquestData cq = _f.Data; - _board = Math.Clamp(_board, 0, cq.Boards.Count - 1); - for (int i = 0; i < cq.Boards.Count; i++) - { - if (i > 0) ImGui.SameLine(); - if (Toggle(cq.Boards[i].Label + "##cb_tab" + i, i == _board)) _board = i; - } - ConquestBoard b = cq.Boards[_board]; - _refresh.Draw("board" + b.Key, $"Sends {b.Command} and reads the reply.", () => Ask("board" + b.Key, () => b.UpdatedUtc.Ticks, b.Command, - now => cq.RequestBoard(b, now))); - ImGui.Separator(); - SafeImGui.TextDisabled(b.UpdatedUtc == DateTime.MinValue ? "not read yet" : $"read at {b.UpdatedUtc.ToLocalTime():HH:mm}"); - if (b.You != null) SafeImGui.Text($"You: #{b.You.Rank} with {b.You.Value}"); - if (ImGui.BeginChild("##cb_rows", Vector2.Zero, ImGuiChildFlags.Borders)) - { - ImGui.TextDisabled("Rank"); ImGui.SameLine(60f); ImGui.TextDisabled("Name"); ImGui.SameLine(280f); ImGui.TextDisabled("Value"); - foreach (BoardRow r in b.Rows) - { - SafeImGui.Text(r.Rank.ToString()); - ImGui.SameLine(60f); - if (r.IsYou) SafeImGui.TextColored(Gold, Cut(r.Name, 30)); - else SafeImGui.Text(Cut(r.Name, 30)); - ImGui.SameLine(280f); - SafeImGui.Text(r.Value); - if (r.Extra.Length > 0) { ImGui.SameLine(420f); SafeImGui.TextDisabled(Cut(r.Extra, 40)); } - } - if (b.Rows.Count == 0) ImGui.TextDisabled("Nothing read yet. Press Refresh."); - } - ImGui.EndChild(); - } - } - - // ── Refresh (RynthOracle's RefreshBar, Conquest's part) ────────────── - - private ServerRefreshResult RefreshConquest() - { - ConquestData cq = _f.Data; - switch (_view) - { - case 0: return Ask("bank", () => cq.BankUtc.Ticks, "/b", now => cq.RequestBank(now)); - case 1: return Ask("augs", () => cq.AugsUtc.Ticks, "/augs", now => cq.RequestAugs(now)); - case 2: return Ask("enl", () => cq.EnlUtc.Ticks, "/enl augs", now => cq.RequestEnl(now)); - case 3: return Ask("bonus", () => cq.BonusUtc.Ticks, "/bonus", now => cq.RequestBonus(now)); - case 4: return Ask("fship", () => cq.FshipUtc.Ticks, "/fship list", now => cq.RequestFships(now)); - default: - if (_refresh.CoolingDown("quests", Environment.TickCount64)) return new ServerRefreshResult(ServerRefreshRow.TooSoon); - QuestFlagStore flags = _f.Flags; - int rev = flags.Revision; - int wait = flags.ThrottleSecondsLeft(Environment.TickCount64); - if (wait > 0) return new ServerRefreshResult($"The server answers one /myquests a minute; try again in {wait}s (the flags shown are kept)."); - _runOnTick(() => - { - lock (_f.Gate) flags.Request(_send, Environment.TickCount64); - }); - return new ServerRefreshResult("Asked the server for your quest flags (/myquests).", () => flags.Revision != rev); - } - } - - private string ConquestHelp() => _view switch - { - 0 => "Sends /b and reads your balances.", - 1 => "Sends /augs and reads your advanced augmentations.", - 2 => "Sends /enl augs and reads your enlightenment augmentations.", - 3 => "Sends /bonus for the experience bonuses (your level is read from the game).", - 4 => "Sends /fship list and reads the fellowships looking for members.", - _ => "Sends /myquests: the custom quests' status comes from your quest flags.", - }; - - /// - /// Sends one of the page's own commands on the next tick (marking it as RynthConquest's, so its - /// reply can be hidden) and waits for to change. - /// - private ServerRefreshResult Ask(string key, Func state, string command, Action markSent) - { - if (_refresh.CoolingDown(key, Environment.TickCount64)) return new ServerRefreshResult(ServerRefreshRow.TooSoon); - long before = state(); - _runOnTick(() => - { - lock (_f.Gate) markSent(Environment.TickCount64); - if (!_send(command)) _print($"Couldn't send {command} (not in the world)."); - }); - return new ServerRefreshResult($"Sent {command}.", () => state() != before); - } - - // ── Helpers ───────────────────────────────────────────────────────── - - /// A command from a button, sent on the next tick. - private void Queue(string command) => _runOnTick(() => _send(command)); - - /// A line in chat, written on the next tick. - private void Print(string text) => _runOnTick(() => _print(text)); - - private static bool Toggle(string label, bool selected) - { - if (selected) ImGui.PushStyleColor(ImGuiCol.Button, Selected); - bool clicked = ImGui.SmallButton(label); - if (selected) ImGui.PopStyleColor(); - return clicked; - } - - private static void Tooltip(string text) - { - if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(text); - } - - private static string Cut(string s, int max) => s.Length <= max ? s : s.Substring(0, Math.Max(0, max - 3)) + "..."; - - private static string Number(long n) => TimeText.Number(n); -} diff --git a/Plugins/RynthCore.Plugin.RynthConquest/Conquest/CustomQuests.cs b/Plugins/RynthCore.Plugin.RynthConquest/Conquest/CustomQuests.cs deleted file mode 100644 index 6d0e033..0000000 --- a/Plugins/RynthCore.Plugin.RynthConquest/Conquest/CustomQuests.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Ported from Oracle of Dereth by Advis Eveldan (advis61), MIT. See THIRD_PARTY_NOTICES.md. -// Moved here from RynthOracle (Data/CustomQuests.cs) on 2026-10-20, with Resources\customquests.csv. -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using System.Text; -using RynthCore.Plugin.RynthOracle.Data; - -namespace RynthCore.Plugin.RynthConquest; - -/// -/// Conquest's custom quest worklist (customquests.csv: Server, Name, QuestFlag, Url, Hint; every row -/// is Conquest's), upstream's Custom tab. The status comes from the character's quest flags -/// (/myquests, read with RynthOracle's parser, linked source). A repeatable counts as done only -/// while on cooldown (upstream's rule). -/// -internal sealed class CustomQuest -{ - public string Server = "", Name = "", Flag = "", Url = "", Hint = ""; - - public bool IsComplete(QuestFlagStore flags, DateTime utcNow) - { - if (!flags.TryGet(Flag, out QuestFlag q)) return false; - if (q.RepeatTime == TimeSpan.Zero) return q.Solves > 0; - return !q.Ready(utcNow); - } - - public string Status(QuestFlagStore flags, DateTime utcNow) - { - if (!flags.TryGet(Flag, out QuestFlag q)) return "ready"; - if (q.RepeatTime == TimeSpan.Zero) return q.Solves > 0 ? "completed" : "ready"; - return q.NextAvailable(utcNow); - } -} - -internal static class CustomQuestList -{ - /// The embedded list's logical name (RynthCore.Plugin.RynthConquest.csproj). - public const string ResourceName = "RynthConquest.customquests.csv"; - - public static List All { get; } = Load(); - - private static List Load() - { - var list = new List(); - Stream? stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(ResourceName); - if (stream == null) return list; - using var r = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true); - r.ReadLine(); // Server,Name,QuestFlag,Url,Hint - while (r.ReadLine() is string line) - { - if (string.IsNullOrWhiteSpace(line)) continue; - string[] f = Csv.ParseLine(line); - list.Add(new CustomQuest - { - Server = Csv.Field(f, 0), Name = Csv.Field(f, 1), Flag = Csv.Field(f, 2).ToLowerInvariant(), - Url = Csv.Field(f, 3), Hint = Csv.Field(f, 4), - }); - } - return list; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthConquest/ConquestPlugin.cs b/Plugins/RynthCore.Plugin.RynthConquest/ConquestPlugin.cs deleted file mode 100644 index 906ca89..0000000 --- a/Plugins/RynthCore.Plugin.RynthConquest/ConquestPlugin.cs +++ /dev/null @@ -1,118 +0,0 @@ -// ConquestPlugin.cs - RynthConquest's own features, through the shared server plugin's hooks -// (Plugins/Shared/ServerPack/ServerPackPlugin.cs). Everything Conquest-specific that RynthOracle used to -// carry lives here since 2026-10-20 (Conquest/ConquestFeature.cs says what), so a player without -// RynthConquest gets none of it, the automatic /bank deposit included. -using System; -using System.IO; -using RynthCore.Plugin.RynthConquest; - -namespace RynthCore.Plugin.ServerPack; - -public sealed partial class ServerPackPlugin -{ - private readonly ConquestFeature _conquest = new(); - private ConquestPages? _conquestPages; - private long _nextConquestCharacterMs; - - /// Where RynthOracle kept the Conquest settings before they moved here (read once). - internal static string OracleSettingsPath => Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthoracle.json"); - - partial void ServerPages(System.Collections.Generic.List pages) - { - _conquestPages = new ConquestPages(_conquest, () => Active, RunOnTick, Send, - text => ChatLine($"[{RynthPluginInfo.Name}] {text}"), SaveConquestSettings); - pages.AddRange(_conquestPages.Pages()); - } - - partial void ServerInitialize() - { - if (ConquestFeature.Migrate(Settings, OracleSettingsPath)) - LogTagged("Took over RynthOracle's Conquest settings (auto-deposit, hiding own replies) from rynthoracle.json."); - lock (_conquest.Gate) _conquest.LoadSettings(Settings); - } - - private void SaveConquestSettings() - { - lock (_conquest.Gate) _conquest.SaveSettings(Settings); - } - - partial void ServerLoginComplete() - { - lock (_conquest.Gate) _conquest.Login(Environment.TickCount64); - _nextConquestCharacterMs = 0; - _conquestPages?.Reset(); - } - - partial void ServerLogout() - { - lock (_conquest.Gate) _conquest.Logout(); - _conquestPages?.Reset(); - } - - partial void ServerShutdown() => SaveConquestSettings(); - - partial void ServerChatText(string text, int chatType, ref bool eat) - { - if (!Active) return; - bool hide; - lock (_conquest.Gate) hide = _conquest.OnChatLine(text, Environment.TickCount64); - if (hide) eat = true; - } - - partial void ServerChatBar(string text) - { - // The player's own /myquests: its reply shows (QuestFlagStore tells it from RynthConquest's). - if (text.Equals("/myquests", StringComparison.OrdinalIgnoreCase)) _conquest.Flags.NoteTypedCommand(); - } - - partial void ServerTick(bool active) - { - if (!active) return; - long now = Environment.TickCount64; - string? augs, deposit; - lock (_conquest.Gate) - { - _conquest.Flags.Tick(now); - augs = _conquest.LoginAugsDue(now); - deposit = _conquest.AutoDepositDue(DateTime.Now, now); - } - if (augs != null) Send(augs); - if (deposit != null && Send(deposit)) ChatLine($"[{RynthPluginInfo.Name}] Auto-deposited to the bank."); - - if (now < _nextConquestCharacterMs) return; - _nextConquestCharacterMs = now + ConquestFeature.CharacterReadMs; - ReadConquestCharacter(); - } - - /// Level, XP, enlightenment and Archmage's Endurance (the Void DoT rule), then the rule for RynthOracle. - private void ReadConquestCharacter() - { - uint player = Host.HasGetPlayerId ? Host.GetPlayerId() : 0; - if (player == 0) return; - int level = Host.TryGetObjectIntProperty(player, 25, out int l) ? l : 0; // PropertyInt Level - int enl = Host.TryGetObjectIntProperty(player, 390, out int e) ? e : 0; // Enlightenment - int archmage = Host.TryGetObjectIntProperty(player, 238, out int a) ? a : 0; // AugmentationIncreasedSpellDuration - long xp = Host.HasGetObjectQuadProperty && Host.TryGetObjectQuadProperty(player, 1, out long x) ? x : 0; // TotalExperience - double scale; - lock (_conquest.Gate) - { - _conquest.Level = level; - _conquest.Enlightenment = enl; - _conquest.ArchmagesEndurance = archmage; - _conquest.TotalXp = xp; - _conquest.CharacterKnown = level > 0; - scale = _conquest.VoidScale; - } - SetProfileValue(ConquestFeature.VoidScaleKey, scale); - } - - partial void ServerInfoLines(Action line) - { - lock (_conquest.Gate) - { - line($"Auto-deposit {(_conquest.AutoDeposit ? "on" : "off")}; own replies {(_conquest.HideOwnReplies ? "hidden" : "shown")}" - + $"; Void DoT duration x{_conquest.VoidScale:0.##} ({_conquest.Data.DurationAugs} Duration augs)."); - } - } -} diff --git a/Plugins/RynthCore.Plugin.RynthConquest/Resources/customquests.csv b/Plugins/RynthCore.Plugin.RynthConquest/Resources/customquests.csv deleted file mode 100644 index f935527..0000000 --- a/Plugins/RynthCore.Plugin.RynthConquest/Resources/customquests.csv +++ /dev/null @@ -1,7 +0,0 @@ -Server,Name,QuestFlag,Url,Hint -Conquest,Darshmaul the Brutal,assaultonaimaru,,Shoushi - Portal to Fort 33.6S 74.9E - Kill Darshmaul the Brutal 34.3S 80.7E - Loot Finger - Shoushi - Give to Vovran 33.4S 72.8E -Conquest,Forgotten One,GhostDenCompleted,,Desolution Beach - Helsing 82.5N 43.5W - Den of Ghosts 82.4N 41.3W - Head North and hug left. Don't go downstairs - Defeat The Forgotten One and Loot Head - Back to Helsing -Conquest,Ice Giants,icegiantkilltask,,No hint available -Conquest,Thorsten's Tears,cragstonetearspickup,,No hint available -Conquest,Uber Bobo,uberpawlooted,,No hint available -Conquest,Uber Curator,uberrtwreward,,No hint available \ No newline at end of file diff --git a/Plugins/RynthCore.Plugin.RynthConquest/RynthCore.Plugin.RynthConquest.csproj b/Plugins/RynthCore.Plugin.RynthConquest/RynthCore.Plugin.RynthConquest.csproj deleted file mode 100644 index da0377e..0000000 --- a/Plugins/RynthCore.Plugin.RynthConquest/RynthCore.Plugin.RynthConquest.csproj +++ /dev/null @@ -1,37 +0,0 @@ - - - - - RynthCore.Plugin.RynthConquest - 0.2.0 - conquest - Conquest - acconquest.ddns.net - Conquest|ConquestAC - Conquest only: the server card, and Conquest's bank (with auto-deposit), augmentations, levels past 275, fellowships, custom quests and leaderboards in the Mini Remote. - - - - - - - - - - - - - - - - - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthConquest/ServerData.cs b/Plugins/RynthCore.Plugin.RynthConquest/ServerData.cs deleted file mode 100644 index b830bde..0000000 --- a/Plugins/RynthCore.Plugin.RynthConquest/ServerData.cs +++ /dev/null @@ -1,25 +0,0 @@ -// ServerData.cs - What is known about Conquest (RynthConquest). Identity (id, hosts, world names) is in the csproj. -namespace RynthCore.Plugin.ServerPack; - -internal static class ServerData -{ - public static ServerPackInfo Create() => - new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) - { - Port = 9000, - Emulator = "ACE", - Ruleset = "PvE", - Status = "Development", - Summary = "Custom PvE server with live events, deep crafting, active development, and PK system.", - Facts = new[] - { - "Live events and deep crafting.", - "Has a PK system on a PvE server.", - "RynthOracle has a Conquest quest pack (quests.conquest.csv).", - "RynthConquest's pages (Server section, or /rserver): bank and auto-deposit, augmentations, levels past 275, fellowships, custom quests, leaderboards.", - }, - Discord = "https://discord.gg/Gsadhhv72S", - Website = "https://dsc.gg/conquerac", - Source = "public AC server list (acresources/serverslist), checked 2026-10-13", - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthConquest/THIRD_PARTY_NOTICES.md b/Plugins/RynthCore.Plugin.RynthConquest/THIRD_PARTY_NOTICES.md deleted file mode 100644 index ceba802..0000000 --- a/Plugins/RynthCore.Plugin.RynthConquest/THIRD_PARTY_NOTICES.md +++ /dev/null @@ -1,42 +0,0 @@ -# Third-party notices: RynthConquest - -RynthConquest's Conquest features (the bank, advanced and enlightenment augmentations, XP bonuses -and levels past 275, the fellowship list, the /top boards, the custom quest worklist, the -auto-deposit and the Void damage-over-time duration rule) are ported from **Oracle of Dereth**, a -Decal plugin for Asheron's Call by **Advis Eveldan** (GitHub: -[advis61](https://github.com/advis61/OracleOfDereth)). They were part of RynthOracle until -2026-10-20 and moved here so that only Conquest players carry them. Thank you, Advis! - -- Upstream: https://github.com/advis61/OracleOfDereth -- Ported from commit `ee618c6847b98b656a47ca87cc347441d206c547` (2026-10-01, version 2.3.0). -- Licence: MIT. The upstream README states "License: MIT". The repository has no separate - LICENSE file and names no copyright line, so the standard MIT text is reproduced below - with the author and the years of the repository's history. - -What came from upstream: `Resources\customquests.csv` (copied unchanged), and the logic of the -features above, rewritten for RynthCore. Ported files say so in their header. RynthOracle's quest -flag parser (`QuestFlags.cs`, also ported from upstream) is compiled in as shared source. - ---- - -MIT License - -Copyright (c) 2024-2026 Advis Eveldan (GitHub: advis61) and contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/Plugins/RynthCore.Plugin.RynthDerptide/RynthCore.Plugin.RynthDerptide.csproj b/Plugins/RynthCore.Plugin.RynthDerptide/RynthCore.Plugin.RynthDerptide.csproj deleted file mode 100644 index b1e82e5..0000000 --- a/Plugins/RynthCore.Plugin.RynthDerptide/RynthCore.Plugin.RynthDerptide.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - - RynthCore.Plugin.RynthDerptide - 0.1.0 - derptide - Derptide - ac.derptide.net - Derptide - Derptide only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthDerptide/ServerData.cs b/Plugins/RynthCore.Plugin.RynthDerptide/ServerData.cs deleted file mode 100644 index 6ef4066..0000000 --- a/Plugins/RynthCore.Plugin.RynthDerptide/ServerData.cs +++ /dev/null @@ -1,25 +0,0 @@ -// ServerData.cs - What is known about Derptide (RynthDerptide). Identity (id, hosts, world names) is in the csproj. -namespace RynthCore.Plugin.ServerPack; - -internal static class ServerData -{ - public static ServerPackInfo Create() => - new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) - { - Port = 9000, - Emulator = "ACE", - Ruleset = "PvE", - Status = "Stable", - Summary = "EOR server that pushes custom content and Qol changes, All quest weapons have been upgraded to be useful, " + - "and usable. No quest item will EVER be better than lootgen, Live events, Ongoing story arcs. and TONS of tailoring options.", - Facts = new[] - { - "Quest weapons are upgraded to be useful, but never better than loot-generated items.", - "Live events and ongoing story arcs.", - "Many tailoring options.", - }, - Discord = "https://discord.gg/3gDTBVtfAg", - Website = "https://derptide.net", - Source = "public AC server list (acresources/serverslist), checked 2026-10-13", - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj deleted file mode 100644 index 8b1faa3..0000000 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - - RynthCore.Plugin.RynthDreamWeave - 0.1.0 - dreamweave - DreamWeave - play.acdreamweave.com - DreamWeave|Dream Weave - DreamWeave only: the server card (rules, server features, player commands, links, account setup) in the Mini Remote. - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs deleted file mode 100644 index e17a30b..0000000 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs +++ /dev/null @@ -1,76 +0,0 @@ -// ServerData.cs - What is known about DreamWeave (RynthDreamWeave). Identity (id, hosts, world names) is in the csproj. -// The features and commands come from the server's public source (ACE-DreamWeave: its README and the -// player-level chat commands under Source/ACE.Server/Command/Handlers). Stock ACE commands and the -// stage-test-shard grants (/myxp, /mylum, ...) are left out. -namespace RynthCore.Plugin.ServerPack; - -internal static class ServerData -{ - public static ServerPackInfo Create() => - new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) - { - Port = 9000, - Emulator = "ACE", - Ruleset = "PvE", - Status = "Development", - Summary = "PvE server pushing unmodified end-of-retail ToD to the limit. Lore driven, new class abilities, " + - "new crafting system, tons of QOL, up-to-date wiki.", - Facts = new[] - { - "Lore driven, built on end-of-retail Throne of Destiny.", - "New class abilities and a new crafting system.", - "Its wiki is kept up to date.", - "Class abilities: trainers sell ability tokens for class ability points (/abilities, /cavoucher).", - "Equipment and weapon mods on armor, clothing and jewelry (/mods).", - "Facets: several builds per character, including a PK facet (/facet).", - "In-game bank for pyreals, luminance, legendary keys, promissory and trade notes (/bank).", - "Account vault (mule) with its own vendor, shared with characters you choose (/mule).", - "Player market: browse, list and buy items (/market).", - "Realms and ephemeral instances (/realm, /exitinst).", - "Drift Network: a hall of linked drift-doors, recalled to with /dn (/tn for the retail Town Network).", - "Threads dungeons (/dd) and treasure-map dig sites (/digsite, /rrtm).", - "PvP arenas (1v1, 2v2, Tugak Brawl free-for-all) and battlegrounds on templates, with ratings (/arena).", - "Leaderboards for DPS, defense, waves, speed, level, bank, stamps, threads and PvP (/top).", - "XP, luminance and custom augmentations (/aug).", - "Experience bonuses: gear, augmentations, alt-character catch-up and offline (/bonus).", - "Fast tick opt-in: faster spell release, fast-chug and melee stick-to-target (/fasttick).", - "Web character sheet you can publish (/charsheet).", - }, - Commands = new[] - { - new ServerCommand("/bank", "deposit, withdraw, transfer and check banked currency (/b d deposits everything)"), - new ServerCommand("/mule", "summon your account vault's vendor, or manage who can use it"), - new ServerCommand("/market", "browse, list and buy items on the market"), - new ServerCommand("/abilities", "manage your class abilities"), - new ServerCommand("/cavoucher", "buy a class ability token for ability points, or refund an unused one"), - new ServerCommand("/facet", "show your facets; /facet switches build, /facet pk the PK facet"), - new ServerCommand("/mods", "summarize the equipment mods on what you wear"), - new ServerCommand("/aug", "augmentation list: /aug xp, /aug lum or /aug custom"), - new ServerCommand("/dn", "recall to the Drift Network (moving too far interrupts it)"), - new ServerCommand("/tn", "recall to the retail Town Network"), - new ServerCommand("/realm", "which realm and instance you are in"), - new ServerCommand("/exitinst", "leave the current ephemeral instance"), - new ServerCommand("/dd", "Threads dungeon status"), - new ServerCommand("/digsite", "status of the dig site you are at; /digsite bail ends one you dug"), - new ServerCommand("/rrtm", "reroll a treasure map's dig site to the one nearest you"), - new ServerCommand("/arena", "PvP arena: /arena join 1v1|2v2|tugak|bg, templates, status, rating, top"), - new ServerCommand("/top", "leaderboards: dps, defense, wave, speed, level, bank, stamp, thread, 1v1, 2v2, tugak, bg"), - new ServerCommand("/xp", "your experience progress"), - new ServerCommand("/quests", "your quest stamp progress"), - new ServerCommand("/bonus", "every experience bonus you have and the total (/altbonus, /offlinebonus)"), - new ServerCommand("/lph", "luminance per hour since login, or since /lph start"), - new ServerCommand("/pickupspeed", "your pick-up speed bonus, including permanent quest bonuses"), - new ServerCommand("/fasttick", "fast tick on, off, default or status"), - new ServerCommand("/dotdamage", "show or hide your damage-over-time tick messages"), - new ServerCommand("/summondamage", "show or hide a chat line for each hit your pets land"), - new ServerCommand("/summonattackontarget", "pets switch to the monster you last hit (on or off)"), - new ServerCommand("/relaria", "Aun Relaria repeat-kill aura visual: /relaria aura on|off"), - new ServerCommand("/charsheet", "publish a web character sheet (off, rotate)"), - new ServerCommand("/fi", "resend nearby monsters and NPCs (invisible creatures), once a minute"), - }, - Discord = "https://discord.gg/p2h3yca4BD", - Wiki = "https://wiki.acdreamweave.com", - Source = "public AC server list (acresources/serverslist), checked 2026-10-13; features and commands from " + - "github.com/Awful-Waffle-Rofl/ACE-DreamWeave (4aa7de6), checked 2026-10-14", - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthEversong/RynthCore.Plugin.RynthEversong.csproj b/Plugins/RynthCore.Plugin.RynthEversong/RynthCore.Plugin.RynthEversong.csproj deleted file mode 100644 index b972d60..0000000 --- a/Plugins/RynthCore.Plugin.RynthEversong/RynthCore.Plugin.RynthEversong.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - - RynthCore.Plugin.RynthEversong - 0.1.0 - eversong - Eversong - eversong.abrdns.com - Eversong - Eversong only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthEversong/ServerData.cs b/Plugins/RynthCore.Plugin.RynthEversong/ServerData.cs deleted file mode 100644 index 916e5d6..0000000 --- a/Plugins/RynthCore.Plugin.RynthEversong/ServerData.cs +++ /dev/null @@ -1,24 +0,0 @@ -// ServerData.cs - What is known about Eversong (RynthEversong). Identity (id, hosts, world names) is in the csproj. -namespace RynthCore.Plugin.ServerPack; - -internal static class ServerData -{ - public static ServerPackInfo Create() => - new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) - { - Port = 9000, - Emulator = "ACE", - Ruleset = "PvE", - Status = "Stable", - Summary = "Five difficulty worlds, quest bonuses, enlightenment & milestones, banking & lockboxes, invasions, optional classes.", - Facts = new[] - { - "Five difficulty worlds.", - "Quest bonuses, enlightenment and milestones.", - "Banking and lockboxes.", - "Invasions and optional classes.", - }, - Discord = "https://discord.gg/9eHxTb7p2J", - Source = "public AC server list (acresources/serverslist), checked 2026-10-13", - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthFrostACE/RynthCore.Plugin.RynthFrostACE.csproj b/Plugins/RynthCore.Plugin.RynthFrostACE/RynthCore.Plugin.RynthFrostACE.csproj deleted file mode 100644 index 4baa0d6..0000000 --- a/Plugins/RynthCore.Plugin.RynthFrostACE/RynthCore.Plugin.RynthFrostACE.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - - RynthCore.Plugin.RynthFrostACE - 0.1.0 - frostace - FrostACE - 172.111.230.127 - FrostACE|FrostfACE - FrostACE only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthFrostACE/ServerData.cs b/Plugins/RynthCore.Plugin.RynthFrostACE/ServerData.cs deleted file mode 100644 index d103925..0000000 --- a/Plugins/RynthCore.Plugin.RynthFrostACE/ServerData.cs +++ /dev/null @@ -1,22 +0,0 @@ -// ServerData.cs - What is known about FrostACE (RynthFrostACE). Identity (id, hosts, world names) is in the csproj. -namespace RynthCore.Plugin.ServerPack; - -internal static class ServerData -{ - public static ServerPackInfo Create() => - new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) - { - Port = 9000, - Emulator = "ACE", - Ruleset = "PvE", - Status = "Development", - Summary = "New accounts include lvl 275 starter characters. Retail character restoration also supported.", - Facts = new[] - { - "New accounts get level 275 starter characters.", - "Retail character restoration is supported.", - "Listed as \"FrostfACE\" in the public server list; it connects by IP address.", - }, - Source = "public AC server list (acresources/serverslist), checked 2026-10-13", - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthFrostcull/RynthCore.Plugin.RynthFrostcull.csproj b/Plugins/RynthCore.Plugin.RynthFrostcull/RynthCore.Plugin.RynthFrostcull.csproj deleted file mode 100644 index 04f81e2..0000000 --- a/Plugins/RynthCore.Plugin.RynthFrostcull/RynthCore.Plugin.RynthFrostcull.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - - RynthCore.Plugin.RynthFrostcull - 0.1.0 - frostcull - Frostcull - frostcull.ddns.net - Frostcull - Frostcull only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthFrostcull/ServerData.cs b/Plugins/RynthCore.Plugin.RynthFrostcull/ServerData.cs deleted file mode 100644 index d0e8e87..0000000 --- a/Plugins/RynthCore.Plugin.RynthFrostcull/ServerData.cs +++ /dev/null @@ -1,24 +0,0 @@ -// ServerData.cs - What is known about Frostcull (RynthFrostcull). Identity (id, hosts, world names) is in the csproj. -namespace RynthCore.Plugin.ServerPack; - -internal static class ServerData -{ - public static ServerPackInfo Create() => - new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) - { - Port = 9000, - Emulator = "ACE", - Ruleset = "PvE", - Status = "Stable", - Summary = "NO LEVEL/ATTRIBUTE CAP! 10x XP/Luminance, 25x Drop Rate, Quest Timers Reduced By 90%!", - Facts = new[] - { - "No level or attribute cap.", - "10x experience and luminance.", - "25x drop rate.", - "Quest timers 90% shorter.", - }, - Discord = "https://discord.gg/RQF7HgEZn4", - Source = "public AC server list (acresources/serverslist), checked 2026-10-13", - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyParse.cs b/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyParse.cs deleted file mode 100644 index 984839f..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyParse.cs +++ /dev/null @@ -1,229 +0,0 @@ -// BountyParse.cs - Parses ACECustom's bounty output (BountyManager / BountyCommands). -// -// The progress itself (PropertyString BountyProgress) is server-only, so the tracker reads -// what the server prints. All lines are ChatMessageType.Broadcast: -// /bounty list "Bounties:" header, then one line per reward of every active area: -// " {where}: {amount} {item} every {N kill(s)}[ (at most every {wait})] - you: {status}." -// footer "Bounty: type /bounty to see the bounties where you stand." -// or "Bounty: there are no bounties anywhere right now." -// /bounty "Bounty[ (all zones)| ({region})]: {amount} {item} - {status}." -// or "Bounty: there is no bounty here." -// status "{k} of {n} kills" | "unlocks in {wait}, then {N kill(s)} required" | "needs {qb} QB (you have {n})" -// events "Bounty unlocked: {item} - {N kill(s)} required." "Bounty complete! +{n} {item} gained." -// "Next bounty unlocks in {wait} - {N kill(s)} required." "Next bounty requires {N kill(s)}." -// held rewards: "Bounty: +{n} ..." / "Bounty: Your inventory is full. ..." -// wait "45 sec", "5 min", "2 min 30 sec", "1 hr 15 sec" (FormatWait); numbers use N0 grouping. -// A server without the bounty system answers "Unknown command: bounty". -using System; -using System.Text.RegularExpressions; - -namespace RynthCore.Plugin.RynthILT.Bounty; - -/// Where the player stands on one bounty reward. -internal enum BountyStatus -{ - /// Kills are counting: Kills of KillsRequired. - Counting = 0, - /// The cooldown after the last award runs; kills do not count until UnlockAtUtc. - Cooldown = 1, - /// The player's QB is below the reward's minimum; kills do not count. - NeedsQb = 2, -} - -/// One parsed status phrase. -internal readonly record struct BountyStatusInfo(BountyStatus Status, int Kills, int KillsRequired, - int WaitSeconds, long QbRequired, long QbHave); - -/// One "/bounty list" line. -internal readonly record struct BountyListLine(string Where, long Amount, string Item, int KillsRequired, - int CooldownSeconds, BountyStatusInfo Status); - -/// One "/bounty" (where you stand) line. Scope is "" (this dungeon/zone), "all zones" or a region name. -internal readonly record struct BountyHereLine(string Scope, long Amount, string Item, BountyStatusInfo Status); - -/// Kind of a bounty chat event. -internal enum BountyEventKind { Unlocked, Complete, NextCooldown, NextReady, Held } - -internal static class BountyParse -{ - private const RegexOptions Opt = RegexOptions.Compiled | RegexOptions.CultureInvariant; - private const string Num = @"\d[\d,]*"; - - // Status alternatives are spelled out inside the line patterns so backtracking can place the - // " - " separator correctly when an item name itself contains " - ". - private const string StatusPattern = - @"(?" + Num + @" of " + Num + @" kills?|unlocks in .+?, then " + Num + @" kills? required|needs " - + Num + @" QB \(you have " + Num + @"\))"; - - /// "/bounty list" reward line (leading indentation already trimmed). - private static readonly Regex ListLine = new( - @"^(?.+?): (?" + Num + @") (?.+?) every (?" + Num + @") kills?" - + @"(?: \(at most every (?[^)]+)\))? - you: " + StatusPattern + @"\.$", Opt); - - /// "/bounty" reward line. - private static readonly Regex HereLine = new( - @"^Bounty(?: \((?[^)]+)\))?: (?" + Num + @") (?.+?) - " + StatusPattern + @"\.$", Opt); - - private static readonly Regex Counting = new(@"^(?" + Num + @") of (?" + Num + @") kills?$", Opt); - private static readonly Regex Cooldown = new(@"^unlocks in (?.+?), then (?" + Num + @") kills? required$", Opt); - private static readonly Regex Qb = new(@"^needs (?" + Num + @") QB \(you have (?" + Num + @")\)$", Opt); - private static readonly Regex WaitPart = new(@"(?\d+)\s*(?hr|min|sec)\b", Opt); - - private static readonly Regex EvUnlocked = new(@"^Bounty unlocked: (?.+) - (?" + Num + @") kills? required\.$", Opt); - private static readonly Regex EvComplete = new(@"^Bounty complete! \+(?" + Num + @") (?.+) gained\.$", Opt); - private static readonly Regex EvNextWait = new(@"^Next bounty unlocks in (?.+?) - (?" + Num + @") kills? required\.$", Opt); - private static readonly Regex EvNextReady = new(@"^Next bounty requires (?" + Num + @") kills?\.$", Opt); - - /// "/bounty list" header line. - public const string ListHeader = "Bounties:"; - - /// True for the line that ends a "/bounty list" reply (footer or "no bounties anywhere"). - public static bool IsListTerminator(string text) - => text.StartsWith("Bounty: type /bounty", StringComparison.OrdinalIgnoreCase) - || text.StartsWith("Bounty: there are no bounties anywhere", StringComparison.OrdinalIgnoreCase); - - /// True when the terminator says no bounty is active anywhere. - public static bool IsNoBountiesAnywhere(string text) - => text.StartsWith("Bounty: there are no bounties anywhere", StringComparison.OrdinalIgnoreCase); - - /// ACE's reply to a command the server doesn't register. - public static bool IsUnknownCommand(string text) - => text.StartsWith("Unknown command: bounty", StringComparison.OrdinalIgnoreCase); - - /// Parses a "/bounty list" reward line. - public static bool TryParseListLine(string text, out BountyListLine line) - { - line = default; - var m = ListLine.Match((text ?? string.Empty).Trim()); - if (!m.Success || !TryParseStatus(m.Groups["status"].Value, out var status)) return false; - int required = ToInt(m.Groups["kills"].Value); - int cooldown = m.Groups["cd"].Success ? ParseWaitSeconds(m.Groups["cd"].Value) : 0; - line = new BountyListLine(m.Groups["where"].Value.Trim(), ParseLong(m.Groups["amount"].Value), - m.Groups["item"].Value.Trim(), required, cooldown, status); - return true; - } - - /// Parses a "/bounty" (where you stand) reward line. - public static bool TryParseHereLine(string text, out BountyHereLine line) - { - line = default; - var m = HereLine.Match((text ?? string.Empty).Trim()); - if (!m.Success || !TryParseStatus(m.Groups["status"].Value, out var status)) return false; - line = new BountyHereLine(m.Groups["scope"].Success ? m.Groups["scope"].Value.Trim() : string.Empty, - ParseLong(m.Groups["amount"].Value), m.Groups["item"].Value.Trim(), status); - return true; - } - - /// Parses one status phrase (without the trailing period). - public static bool TryParseStatus(string text, out BountyStatusInfo status) - { - status = default; - string t = (text ?? string.Empty).Trim().TrimEnd('.'); - var m = Counting.Match(t); - if (m.Success) - { - status = new BountyStatusInfo(BountyStatus.Counting, ToInt(m.Groups["k"].Value), ToInt(m.Groups["n"].Value), 0, 0, 0); - return true; - } - m = Cooldown.Match(t); - if (m.Success) - { - status = new BountyStatusInfo(BountyStatus.Cooldown, 0, ToInt(m.Groups["n"].Value), - ParseWaitSeconds(m.Groups["wait"].Value), 0, 0); - return true; - } - m = Qb.Match(t); - if (m.Success) - { - status = new BountyStatusInfo(BountyStatus.NeedsQb, 0, 0, 0, - ParseLong(m.Groups["qb"].Value), ParseLong(m.Groups["have"].Value)); - return true; - } - return false; - } - - /// "2 min 30 sec" → 150, "1 hr 15 sec" → 3615. 0 when nothing parses. - public static int ParseWaitSeconds(string text) - { - long total = 0; - foreach (Match m in WaitPart.Matches(text ?? string.Empty)) - { - long v = ParseLong(m.Groups["v"].Value); - total += m.Groups["u"].Value switch { "hr" => v * 3600, "min" => v * 60, _ => v }; - } - return (int)Math.Min(total, int.MaxValue); - } - - /// - /// Recognises a bounty chat event (award, unlock, next cooldown, held reward). Item and - /// KillsRequired are filled when the line names them; WaitSeconds for "Next bounty unlocks in". - /// - public static bool TryParseEvent(string text, out BountyEventKind kind, out string item, out int killsRequired, out int waitSeconds) - { - kind = BountyEventKind.Held; - item = string.Empty; - killsRequired = 0; - waitSeconds = 0; - string t = (text ?? string.Empty).Trim(); - if (t.Length == 0) return false; - - Match m; - if ((m = EvUnlocked.Match(t)).Success) - { - kind = BountyEventKind.Unlocked; - item = m.Groups["item"].Value.Trim(); - killsRequired = ToInt(m.Groups["n"].Value); - return true; - } - if ((m = EvComplete.Match(t)).Success) - { - kind = BountyEventKind.Complete; - item = m.Groups["item"].Value.Trim(); - return true; - } - if ((m = EvNextWait.Match(t)).Success) - { - kind = BountyEventKind.NextCooldown; - waitSeconds = ParseWaitSeconds(m.Groups["wait"].Value); - killsRequired = ToInt(m.Groups["n"].Value); - return true; - } - if ((m = EvNextReady.Match(t)).Success) - { - kind = BountyEventKind.NextReady; - killsRequired = ToInt(m.Groups["n"].Value); - return true; - } - // Held-reward notices; the "/bounty" and "/bounty list" status lines also start with "Bounty: ". - if (t.StartsWith("Bounty: +", StringComparison.Ordinal) - || t.StartsWith("Bounty: Your inventory is full", StringComparison.OrdinalIgnoreCase)) - { - kind = BountyEventKind.Held; - return true; - } - return false; - } - - /// Key that identifies one reward of one area across refreshes. - public static string Key(string where, long amount, string item, int killsRequired) - => $"{where}|{amount}|{item}|{killsRequired}".ToLowerInvariant(); - - /// "1 hr 5 min", "45 sec", "2 days 3 hr". Negative spans read as 0 sec. - public static string Duration(TimeSpan span) - { - long s = Math.Max(0, (long)span.TotalSeconds); - if (s >= 86400) return $"{s / 86400} day{(s / 86400 == 1 ? "" : "s")}" + (s % 86400 >= 3600 ? $" {s % 86400 / 3600} hr" : ""); - if (s >= 3600) return $"{s / 3600} hr" + (s % 3600 >= 60 ? $" {s % 3600 / 60} min" : ""); - if (s >= 60) return $"{s / 60} min" + (s % 60 > 0 ? $" {s % 60} sec" : ""); - return $"{s} sec"; - } - - /// Digits with "," grouping removed; 0 when nothing parses. - internal static long ParseLong(string text) - { - string digits = (text ?? string.Empty).Replace(",", string.Empty).Trim(); - return long.TryParse(digits, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out long v) ? v : 0; - } - - private static int ToInt(string text) => (int)Math.Min(ParseLong(text), int.MaxValue); -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyTracker.cs b/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyTracker.cs deleted file mode 100644 index 8880ef2..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Bounty/BountyTracker.cs +++ /dev/null @@ -1,714 +0,0 @@ -// BountyTracker.cs - Every ACECustom bounty and this character's progress, for the engine's Bounties window. -// -// The server keeps the counts (PropertyString BountyProgress is server-only), so the tracker reads -// "/bounty list", which reports every active bounty on the server - wherever the player stands - -// with the player's kills, cooldown or QB requirement for each. The read is a quiet capture (the -// reply is eaten from chat) and runs only while the engine's Bounties window polls the export: -// * when the window opens (and the list is old or kills happened while it was closed), -// * a moment after each of this character's kills, -// * after a bounty chat event ("Bounty complete!", "Bounty unlocked:", "Next bounty ..."), -// * every PeriodicRefreshMinutes as a backstop, and on Refresh / "/ilt bounty refresh". -// Every read, whatever asked for it, waits for MinRefreshSeconds (at least 5 s) since the last -// one, and none is sent while the window is closed (RynthILT review, 2026-10-09). -// Lines the player prints themselves ("/bounty list", "/bounty") update the list too, and are -// never eaten: a /bounty the player types (NoteTypedCommand) turns the capture it overlaps into -// a shown one, and a typed "/bounty list" stands in for the tracker's next read. -// Cooldowns count down locally from the read time; when one ends the bounty shows 0 of N kills, -// which is what the server says too (an award resets the count before the cooldown starts). -// -// Everything runs on the plugin's game thread: OnTick, chat, kills and the engine's export polls. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace RynthCore.Plugin.RynthILT.Bounty; - -/// Persisted per character (bounties.json): the window's options and the last list read. -internal sealed class BountyState -{ - public bool RefreshOnKills = true; - public int MinRefreshSeconds = 10; - public int PeriodicRefreshMinutes = 5; - public bool HideQbLocked; - public bool SortByProgress; - public List Entries = new(); - public DateTime ListedUtc; - public bool NoneAnywhere; - public string LastEvent = string.Empty; - public DateTime LastEventUtc; -} - -/// One reward of one bounty area and where this character stands on it. -internal sealed class BountyEntry -{ - public string Where = string.Empty; - public long Amount; - public string Item = string.Empty; - public int KillsRequired; - public int CooldownSeconds; - /// A value. - public int Status; - public int Kills; - public DateTime UnlockAtUtc; - public long QbRequired; - public long QbHave; - /// Last time the kills went up or an award reset them (row highlight). - public DateTime ChangedUtc; -} - -/// -/// RynthPluginGetBountiesJson payload. Mirrored by RynthCore.Engine UI/Data/BountiesSnapshotJson.cs; -/// either side may add fields (unknown ones are skipped, missing ones keep their defaults). -/// -internal sealed class BountyBridgePayload -{ - [JsonPropertyName("unsupported")] public bool Unsupported; - [JsonPropertyName("reading")] public bool Reading; - [JsonPropertyName("status")] public string Status = string.Empty; - /// Seconds since the last list read; -1 = never. - [JsonPropertyName("listedAgoSec")] public int ListedAgoSec = -1; - [JsonPropertyName("noneAnywhere")] public bool NoneAnywhere; - [JsonPropertyName("lastEvent")] public string LastEvent = string.Empty; - [JsonPropertyName("lastEventAgoSec")] public int LastEventAgoSec = -1; - [JsonPropertyName("refreshOnKills")] public bool RefreshOnKills; - [JsonPropertyName("minRefreshSeconds")] public int MinRefreshSeconds; - [JsonPropertyName("periodicRefreshMinutes")] public int PeriodicRefreshMinutes; - [JsonPropertyName("hideQbLocked")] public bool HideQbLocked; - [JsonPropertyName("sortByProgress")] public bool SortByProgress; - /// Rows not shown because of HideQbLocked. - [JsonPropertyName("hiddenCount")] public int HiddenCount; - [JsonPropertyName("rows")] public List Rows = new(); -} - -/// One row of , with the status as of the poll. -internal sealed class BountyRow -{ - [JsonPropertyName("where")] public string Where = string.Empty; - [JsonPropertyName("amount")] public long Amount; - [JsonPropertyName("item")] public string Item = string.Empty; - [JsonPropertyName("killsRequired")] public int KillsRequired; - [JsonPropertyName("cooldownSeconds")] public int CooldownSeconds; - /// A value; an ended cooldown is already Counting. - [JsonPropertyName("status")] public int Status; - [JsonPropertyName("kills")] public int Kills; - [JsonPropertyName("unlockInSec")] public int UnlockInSec; - [JsonPropertyName("qbRequired")] public long QbRequired; - [JsonPropertyName("qbHave")] public long QbHave; - /// Kills went up (or an award reset them) in the last 15 seconds. - [JsonPropertyName("changed")] public bool Changed; -} - -internal sealed class BountyTracker -{ - /// The capture command; "/bounty all" is the same list. - public const string ListCommand = "/bounty list"; - /// Lowest allowed MinRefreshSeconds (the server is asked at most this often after kills). - public const int MinRefreshFloorSeconds = 5; - public const int MinRefreshCeilingSeconds = 300; - public const int PeriodicCeilingMinutes = 60; - public const string FileName = "bounties.json"; - - /// Wait after a kill so a burst of kills (and the server's own award lines) lands in one read. - private const long KillDebounceMs = 2000; - /// Wait after a bounty chat event before re-reading. - private const long EventDebounceMs = 1500; - /// The window counts as open while the engine polled the export this recently (it polls every second). - private const long WindowPollWindowMs = 3000; - /// A capture with no reply line by then is abandoned. - private const long FirstLineTimeoutMs = 10000; - /// A capture whose footer never came ends this long after its last line. - private const long IdleEndMs = 1500; - /// The engine may pass our own /bounty list back through the chat bar hook this soon after sending it. - private const long OwnEchoMs = 2000; - /// Longer chat lines are never parsed (no bounty line is near this; bounds the regex work). - private const int MaxLineLength = 512; - private const long SaveDebounceMs = 5000; - /// A list older than this is re-read when the window opens. - private static readonly TimeSpan OpenRefreshAge = TimeSpan.FromSeconds(30); - /// How long a row stays highlighted after its kills went up. - private static readonly TimeSpan ChangedHighlight = TimeSpan.FromSeconds(15); - - private readonly Action _send; - private readonly Action _chat; - private readonly Action _log; - private readonly string _filePath; - private readonly Func _clock; - private BountyState _s; - - // Scheduling. - private long _dueAtMs; // 0 = no read scheduled - private long _lastSentMs; // 0 = never this session - private long _lastPollMs; // last engine poll of the export; 0 = never - private bool _wasOpen; - private bool _stale; // kills or bounty events happened while the window was closed - - // The quiet "/bounty list" capture. - private bool _capActive; - private bool _capShown; // the player asked too (NoteTypedCommand): parse, never eat - private bool _expectEcho; // our /bounty list may come back through the chat bar hook - private long _capSentMs; - private long _capLastLineMs; // 0 = no reply line yet - private readonly List _capLines = new(); - - private bool _unsupported; - private string _status = string.Empty; - private bool _dirty; - private long _lastSaveMs; - - /// Sends a chat command to the server (Host.InvokeChatParser). - /// Prints a line to the player's chat window. - /// Writes to the RynthCore log. - /// bounties.json in the character folder; empty = not persisted. - /// Milliseconds clock; Environment.TickCount64 unless a test supplies one. - public BountyTracker(Action send, Action chat, Action log, string filePath, Func? clock = null) - { - _send = send; - _chat = chat; - _log = log; - _filePath = filePath ?? string.Empty; - _clock = clock ?? (() => Environment.TickCount64); - _s = Load(); - } - - private long NowMs => _clock(); - - /// The persisted state (host tests). - internal BountyState State => _s; - - /// True once the server answered "Unknown command: bounty" (no bounty system on this server). - public bool Unsupported => _unsupported; - - /// True while a "/bounty list" reply is being captured. - public bool Reading => _capActive; - - /// True while the engine's Bounties window is polling the export. - public bool WindowOpen => _lastPollMs != 0 && NowMs - _lastPollMs < WindowPollWindowMs; - - // ── Scheduling ────────────────────────────────────────────────────────── - - /// - /// Schedules a "/bounty list" read; the earliest pending request wins. Every read waits for - /// MinRefreshSeconds since the last one; false (a manual - /// refresh) waits only for the MinRefreshFloorSeconds floor. - /// - private void Schedule(long nowMs, long delayMs, bool respectMinInterval) - { - long due = nowMs + delayMs; - if (_lastSentMs != 0) - due = Math.Max(due, _lastSentMs + (respectMinInterval ? _s.MinRefreshSeconds : MinRefreshFloorSeconds) * 1000L); - if (_dueAtMs == 0 || due < _dueAtMs) _dueAtMs = due; - } - - /// - /// Manual refresh (window button, "/ilt bounty refresh"): retries an unsupported server and - /// reads as soon as the 5 s floor since the last read allows. Never sends with the window - /// closed: the next open reads instead. - /// - public string RequestRefresh() - { - _unsupported = false; - if (!WindowOpen) - { - _stale = true; - return "The list is read while the Bounties window is open (the ILT button, or /rc bounties)."; - } - long now = NowMs; - Schedule(now, 0, respectMinInterval: false); - return "Reading /bounty list..."; - } - - /// One of this character's kills (RynthILTPlugin.OnKillNotification). - public void OnKill() - { - if (!_s.RefreshOnKills || _unsupported) return; - if (WindowOpen) Schedule(NowMs, KillDebounceMs, respectMinInterval: true); - else _stale = true; - } - - private void Send(long nowMs) - { - if (_capActive) { _dueAtMs = 0; return; } - // The invariants, whatever scheduled this: the window is open, and the last read was at - // least MinRefreshFloorSeconds ago (else the read waits until then). - if (!WindowOpen) { _dueAtMs = 0; return; } - if (_lastSentMs != 0 && nowMs - _lastSentMs < MinRefreshFloorSeconds * 1000L) - { - _dueAtMs = _lastSentMs + MinRefreshFloorSeconds * 1000L; - return; - } - _dueAtMs = 0; - _lastSentMs = nowMs; - StartCapture(nowMs, shown: false); - _expectEcho = true; - try { _send(ListCommand); } - catch (Exception ex) - { - _capActive = false; - _expectEcho = false; - _status = "could not send /bounty list"; - _log($"[RynthILT] Bounties: sending {ListCommand} failed: {ex.Message}"); - } - } - - private void StartCapture(long nowMs, bool shown) - { - _capActive = true; - _capShown = shown; - _capSentMs = nowMs; - _capLastLineMs = 0; - _capLines.Clear(); - } - - /// - /// A "/bounty ..." the player typed (the plugin's OnChatBarEnter, passed on on the pump). - /// Its reply is never eaten: an overlapping capture of ours becomes a shown one, and a typed - /// "/bounty list" (or "/bounty all") starts a shown capture that counts as the next read, so - /// the tracker doesn't send its own on top. Our own command coming back through the chat - /// bar hook right after we sent it is recognised and ignored. - /// - public void NoteTypedCommand(string text) - { - string t = (text ?? string.Empty).Trim(); - long now = NowMs; - if (_expectEcho && now - _capSentMs <= OwnEchoMs && string.Equals(t, ListCommand, StringComparison.OrdinalIgnoreCase)) - { - _expectEcho = false; - return; - } - _expectEcho = false; - if (_capActive) { _capShown = true; return; } - if (!IsListCommand(t)) return; - _lastSentMs = now; - _dueAtMs = 0; - StartCapture(now, shown: true); - } - - /// "/bounty list" or "/bounty all" (or with ACE's '@' command prefix). - internal static bool IsListCommand(string text) - { - string[] parts = (text ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); - return parts.Length == 2 - && (parts[0].Equals("/bounty", StringComparison.OrdinalIgnoreCase) || parts[0].Equals("@bounty", StringComparison.OrdinalIgnoreCase)) - && (parts[1].Equals("list", StringComparison.OrdinalIgnoreCase) || parts[1].Equals("all", StringComparison.OrdinalIgnoreCase)); - } - - /// True for a chat-bar line that is a /bounty command (what the plugin passes to NoteTypedCommand). - public static bool IsBountyCommand(string? text) - { - string t = (text ?? string.Empty).TrimStart(); - if (!t.StartsWith("/bounty", StringComparison.OrdinalIgnoreCase) && !t.StartsWith("@bounty", StringComparison.OrdinalIgnoreCase)) - return false; - return t.Length == 7 || t[7] == ' '; // "/bounty" or "/bounty ...", not "/bountyhunter" - } - - public void Tick() - { - long now = NowMs; - if (_capActive) - { - if (_capLastLineMs == 0 && now - _capSentMs >= FirstLineTimeoutMs) - { - _capActive = false; - _expectEcho = false; - if (!_capShown) _status = "no reply to /bounty list"; - } - else if (_capLastLineMs != 0 && now - _capLastLineMs >= IdleEndMs) - { - FinishCapture(terminator: null); - } - } - - if (_dirty && now - _lastSaveMs >= SaveDebounceMs) Save(); - - bool open = WindowOpen; - if (!open) { _wasOpen = false; _dueAtMs = 0; return; } - - if (!_wasOpen) - { - _wasOpen = true; - if (_stale || _lastSentMs == 0 || DateTime.UtcNow - _s.ListedUtc > OpenRefreshAge) - Schedule(now, 0, respectMinInterval: true); - _stale = false; - } - - if (_s.PeriodicRefreshMinutes > 0 && _lastSentMs != 0 && now - _lastSentMs >= _s.PeriodicRefreshMinutes * 60_000L) - Schedule(now, 0, respectMinInterval: true); - - if (_dueAtMs != 0 && now >= _dueAtMs && !_unsupported) Send(now); - } - - private void FinishCapture(string? terminator) - { - _capActive = false; - _expectEcho = false; - bool complete = terminator != null; - bool none = complete && BountyParse.IsNoBountiesAnywhere(terminator!); - ApplyList(_capLines, complete, none, DateTime.UtcNow); - _status = complete ? string.Empty : "partial reply"; - _capLines.Clear(); - } - - // ── Chat ──────────────────────────────────────────────────────────────── - - /// - /// One chat line. Returns true when it belongs to our own "/bounty list" read and should be - /// eaten; everything else (the player's own bounty output, award lines) stays in chat. - /// - public bool OnChat(string text) - { - string t = (text ?? string.Empty).Trim(); - if (t.Length == 0 || t.Length > MaxLineLength) return false; - long now = NowMs; - - if (_capActive) - { - // A shown capture (the player asked too) parses the same lines but eats none. - bool eat = !_capShown; - if (BountyParse.IsUnknownCommand(t)) - { - _capActive = false; - _expectEcho = false; - _capLines.Clear(); - _unsupported = true; - _status = "this server has no /bounty command"; - _log("[RynthILT] Bounties: server has no /bounty command; automatic reads stopped."); - return eat; - } - if (t == BountyParse.ListHeader) { _capLastLineMs = now; return eat; } - if (BountyParse.TryParseListLine(t, out var captured)) { _capLines.Add(captured); _capLastLineMs = now; return eat; } - if (BountyParse.IsListTerminator(t)) { FinishCapture(t); return eat; } - } - - if (BountyParse.TryParseListLine(t, out var listLine)) - { - ApplyList(new[] { listLine }, complete: false, noneAnywhere: false, DateTime.UtcNow); - return false; - } - if (BountyParse.TryParseHereLine(t, out var here)) - { - ApplyHere(here, DateTime.UtcNow); - return false; - } - - if (BountyParse.TryParseEvent(t, out var kind, out _, out _, out _)) - { - _s.LastEvent = t; - _s.LastEventUtc = DateTime.UtcNow; - _dirty = true; - if (kind != BountyEventKind.Held) - { - // Awards can come every kill (a 1-kill bounty with no cooldown): the interval holds. - if (WindowOpen) Schedule(now, EventDebounceMs, respectMinInterval: true); - else _stale = true; - } - } - return false; - } - - // ── Applying server output (internal for the host tests) ──────────────── - - /// - /// Applies parsed "/bounty list" lines. A complete reply (footer seen) replaces the list in - /// server order; a partial one only updates or appends the rewards it names. - /// - internal void ApplyList(IReadOnlyList lines, bool complete, bool noneAnywhere, DateTime nowUtc) - { - var old = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (var e in _s.Entries) - old[BountyParse.Key(e.Where, e.Amount, e.Item, e.KillsRequired)] = e; - - var fresh = new List(lines.Count); - foreach (var l in lines) - { - old.TryGetValue(BountyParse.Key(l.Where, l.Amount, l.Item, l.KillsRequired), out var prev); - var e = new BountyEntry - { - Where = l.Where, - Amount = l.Amount, - Item = l.Item, - KillsRequired = l.KillsRequired, - CooldownSeconds = l.CooldownSeconds, - ChangedUtc = prev?.ChangedUtc ?? default, - }; - ApplyStatus(e, l.Status, prev, nowUtc); - fresh.Add(e); - } - - if (complete) - { - _s.Entries = fresh; - } - else - { - foreach (var e in fresh) - { - string key = BountyParse.Key(e.Where, e.Amount, e.Item, e.KillsRequired); - int i = _s.Entries.FindIndex(x => string.Equals(BountyParse.Key(x.Where, x.Amount, x.Item, x.KillsRequired), - key, StringComparison.OrdinalIgnoreCase)); - if (i >= 0) _s.Entries[i] = e; else _s.Entries.Add(e); - } - } - if (complete || lines.Count > 0) _s.ListedUtc = nowUtc; - if (complete) _s.NoneAnywhere = noneAnywhere; - _dirty = true; - } - - /// - /// Applies a "/bounty" (where you stand) line to the one listed reward it can only mean. - /// Returns false when no reward or more than one matches. - /// - internal bool ApplyHere(BountyHereLine h, DateTime nowUtc) - { - BountyEntry? match = null; - foreach (var e in _s.Entries) - { - if (e.Amount != h.Amount || !string.Equals(e.Item, h.Item, StringComparison.OrdinalIgnoreCase)) continue; - if (h.Status.KillsRequired > 0 && e.KillsRequired != h.Status.KillsRequired) continue; - bool allZones = string.Equals(e.Where, "All zones", StringComparison.OrdinalIgnoreCase); - bool scopeOk = h.Scope.Length == 0 ? !allZones - : h.Scope.Equals("all zones", StringComparison.OrdinalIgnoreCase) ? allZones - : string.Equals(e.Where, h.Scope, StringComparison.OrdinalIgnoreCase); - if (!scopeOk) continue; - if (match != null) return false; // ambiguous: two areas pay the same reward - match = e; - } - if (match == null) return false; - - var prev = new BountyEntry { Status = match.Status, Kills = match.Kills }; - ApplyStatus(match, h.Status, prev, nowUtc); - _dirty = true; - return true; - } - - /// Copies a parsed status onto and stamps ChangedUtc when kills went up or an award reset them. - private static void ApplyStatus(BountyEntry e, BountyStatusInfo st, BountyEntry? prev, DateTime nowUtc) - { - e.Status = (int)st.Status; - e.Kills = st.Status == BountyStatus.Counting ? st.Kills : 0; - e.UnlockAtUtc = st.Status == BountyStatus.Cooldown ? nowUtc.AddSeconds(st.WaitSeconds) : default; - e.QbRequired = st.QbRequired; - e.QbHave = st.QbHave; - if (prev == null) return; - bool wasCounting = prev.Status == (int)BountyStatus.Counting; - bool gained = wasCounting && st.Status == BountyStatus.Counting && st.Kills > prev.Kills; - bool awarded = wasCounting && prev.Kills > 0 - && (st.Status == BountyStatus.Cooldown || (st.Status == BountyStatus.Counting && st.Kills < prev.Kills)); - if (gained || awarded) e.ChangedUtc = nowUtc; - } - - /// The status to show now: a cooldown that has ended is "0 of N kills". - internal static (BountyStatus Status, int Kills) Effective(BountyEntry e, DateTime nowUtc) - { - var st = (BountyStatus)e.Status; - if (st == BountyStatus.Cooldown && nowUtc >= e.UnlockAtUtc) return (BountyStatus.Counting, 0); - return (st, st == BountyStatus.Counting ? e.Kills : 0); - } - - /// "Closest first" order: counting by fraction left, then cooldowns by time left, then QB-locked. - private static double SortKey(BountyEntry e, DateTime now) - { - var (st, kills) = Effective(e, now); - return st switch - { - BountyStatus.Counting => e.KillsRequired > 0 ? 1.0 - kills / (double)e.KillsRequired : 1.0, - BountyStatus.Cooldown => 2.0 + Math.Min((e.UnlockAtUtc - now).TotalSeconds, 1e9) / 1e9, - _ => 4.0, - }; - } - - // ── Engine bridge ─────────────────────────────────────────────────────── - - /// RynthPluginGetBountiesJson. Each call also marks the window open for the read schedule. - public string BuildJson() - { - _lastPollMs = NowMs; - var now = DateTime.UtcNow; - var p = new BountyBridgePayload - { - Unsupported = _unsupported, - Reading = _capActive, - Status = _status, - ListedAgoSec = _s.ListedUtc == default ? -1 : AgoSeconds(now - _s.ListedUtc), - NoneAnywhere = _s.NoneAnywhere, - LastEvent = _s.LastEvent, - LastEventAgoSec = _s.LastEventUtc == default ? -1 : AgoSeconds(now - _s.LastEventUtc), - RefreshOnKills = _s.RefreshOnKills, - MinRefreshSeconds = _s.MinRefreshSeconds, - PeriodicRefreshMinutes = _s.PeriodicRefreshMinutes, - HideQbLocked = _s.HideQbLocked, - SortByProgress = _s.SortByProgress, - }; - - IEnumerable shown = _s.Entries; - if (_s.HideQbLocked) - { - p.HiddenCount = _s.Entries.Count(e => e.Status == (int)BountyStatus.NeedsQb); - shown = shown.Where(e => e.Status != (int)BountyStatus.NeedsQb); - } - if (_s.SortByProgress) shown = shown.OrderBy(e => SortKey(e, now)); - foreach (var e in shown) - { - var (st, kills) = Effective(e, now); - p.Rows.Add(new BountyRow - { - Where = e.Where, - Amount = e.Amount, - Item = e.Item, - KillsRequired = e.KillsRequired, - CooldownSeconds = e.CooldownSeconds, - Status = (int)st, - Kills = kills, - UnlockInSec = st == BountyStatus.Cooldown ? AgoSeconds(e.UnlockAtUtc - now) : 0, - QbRequired = e.QbRequired, - QbHave = e.QbHave, - Changed = e.ChangedUtc != default && now - e.ChangedUtc < ChangedHighlight, - }); - } - return JsonSerializer.Serialize(p, RynthILTJsonContext.Default.BountyBridgePayload); - } - - private static int AgoSeconds(TimeSpan span) => (int)Math.Clamp(span.TotalSeconds, 0, int.MaxValue); - - /// - /// RynthPluginBountyCommand: "refresh", or "set {option} {value}" with option one of - /// refreshonkills, minrefreshseconds, periodicminutes, hideqblocked, sortbyprogress. - /// - public string Command(string text) - { - string[] parts = (text ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries); - if (parts.Length == 0) return string.Empty; - switch (parts[0].ToLowerInvariant()) - { - case "refresh": - case "read": - return RequestRefresh(); - case "set" when parts.Length >= 3: - return SetOption(parts[1], parts[2]); - default: - return $"unknown bounty command '{text}'"; - } - } - - private string SetOption(string name, string value) - { - bool on = value is "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase) - || value.Equals("on", StringComparison.OrdinalIgnoreCase); - int.TryParse(value, out int n); - switch (name.ToLowerInvariant()) - { - case "refreshonkills": _s.RefreshOnKills = on; break; - case "minrefreshseconds": _s.MinRefreshSeconds = Math.Clamp(n, MinRefreshFloorSeconds, MinRefreshCeilingSeconds); break; - case "periodicminutes": _s.PeriodicRefreshMinutes = Math.Clamp(n, 0, PeriodicCeilingMinutes); break; - case "hideqblocked": _s.HideQbLocked = on; break; - case "sortbyprogress": _s.SortByProgress = on; break; - default: return $"unknown bounty option '{name}'"; - } - _dirty = true; - return string.Empty; - } - - // ── Chat command ──────────────────────────────────────────────────────── - - /// "/ilt bounty [refresh|list]". - public void HandleChatCommand(string[] parts) - { - string verb = parts.Length >= 3 ? parts[2].ToLowerInvariant() : "list"; - switch (verb) - { - case "refresh": - case "read": - _chat("[Bounties] " + RequestRefresh()); - break; - case "list": - case "print": - case "show": - PrintList(); - _chat("[Bounties] The Bounties window: the ILT button on the RynthCore bar, or /rc bounties."); - break; - default: - _chat("[Bounties] /ilt bounty [list|refresh] - list the tracked bounties, or re-read /bounty list (while the window is open)."); - break; - } - } - - /// One-line chat text for an entry. - internal static string Describe(BountyEntry e, DateTime nowUtc) - { - var (st, kills) = Effective(e, nowUtc); - string reward = $"{e.Amount:N0} {e.Item}"; - return st switch - { - BountyStatus.Counting => $"{e.Where}: {kills:N0}/{e.KillsRequired:N0} kills -> {reward}", - BountyStatus.Cooldown => $"{e.Where}: unlocks in {BountyParse.Duration(e.UnlockAtUtc - nowUtc)}, then {e.KillsRequired:N0} kills -> {reward}", - _ => $"{e.Where}: needs {e.QbRequired:N0} QB (you have {e.QbHave:N0}) -> {reward}", - }; - } - - /// "/ilt bounty list": the tracked bounties in chat. - public void PrintList() - { - if (_unsupported) { _chat("[Bounties] This server has no /bounty command."); return; } - if (_s.Entries.Count == 0) - { - _chat(_s.NoneAnywhere ? "[Bounties] No bounties are active anywhere right now." - : "[Bounties] Nothing read yet. Open the Bounties window (the ILT button, or /rc bounties)."); - return; - } - var now = DateTime.UtcNow; - string age = _s.ListedUtc == default ? "never" : BountyParse.Duration(now - _s.ListedUtc) + " ago"; - _chat($"[Bounties] {_s.Entries.Count} bounty reward(s), read {age}:"); - foreach (var e in _s.Entries) _chat("[Bounties] " + Describe(e, now)); - } - - // ── Persistence ───────────────────────────────────────────────────────── - - private BountyState Load() - { - var s = new BountyState(); - try - { - if (_filePath.Length > 0 && File.Exists(_filePath)) - s = JsonSerializer.Deserialize(File.ReadAllText(_filePath), RynthILTJsonContext.Default.BountyState) ?? new BountyState(); - } - catch (Exception ex) - { - _log($"[RynthILT] Bounties: {_filePath} unreadable, starting empty: {ex.Message}"); - s = new BountyState(); - } - s.Entries ??= new List(); - s.Entries.RemoveAll(e => e == null); - s.LastEvent ??= string.Empty; - s.MinRefreshSeconds = Math.Clamp(s.MinRefreshSeconds, MinRefreshFloorSeconds, MinRefreshCeilingSeconds); - s.PeriodicRefreshMinutes = Math.Clamp(s.PeriodicRefreshMinutes, 0, PeriodicCeilingMinutes); - return s; - } - - /// Writes bounties.json when something changed (also called at logout). - public void Save() - { - _lastSaveMs = NowMs; - if (!_dirty || _filePath.Length == 0) { _dirty = false; return; } - _dirty = false; - string json; - try { json = JsonSerializer.Serialize(_s, RynthILTJsonContext.Default.BountyState); } - catch (Exception ex) - { - _log($"[RynthILT] Bounties: saving {_filePath} failed: {ex.Message}"); - return; - } - // A failed write is said in chat once per folder (on ILT) and logged; it stays dirty so the - // next debounced save tries again. - if (!RynthCore.Plugin.Shared.DataWriteGuard.TrySave("the bounty list", _filePath, () => - { - string? dir = Path.GetDirectoryName(_filePath); - if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); - string tmp = _filePath + ".tmp"; - File.WriteAllText(tmp, json); - File.Move(tmp, _filePath, overwrite: true); - })) - _dirty = true; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/DataInterface.cs b/Plugins/RynthCore.Plugin.RynthILT/DataInterface.cs deleted file mode 100644 index a892bf8..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/DataInterface.cs +++ /dev/null @@ -1,172 +0,0 @@ -// DataInterface.cs - RynthILT's side of the "RynthILT.Data" interface (Plugins/Shared/RynthIltDataApi.cs): -// the charms list and the bank balances (every character RynthILT has seen on this server) the -// Mini Remote's Charms and Banking tabs show, for other plugins to draw, with the charm Toggle and -// the bank verbs they send back; since version 2 also the pet breeding tracker's JSON and verbs; -// since version 3 the Temple guardians' JSON and verbs (RynthOracle's Quests tab). -// -// The table is allocated once per loaded copy of RynthILT and never freed (a plugin DLL is never -// unloaded); after Release() it reports Version 0 and every function answers 0. Before login there -// is no controller: the JSON getters answer 0 (nothing to report) and the actions are refused. -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT; - -internal static unsafe class DataInterface -{ - /// Longest bank / breeding verb line taken (a transfer with a long character name fits easily). - private const int MaxVerbBytes = 256; - - private static RynthIltDataApiV1* _table; - private static volatile bool _released; - - /// The table for (, ), or 0 when it isn't ours. - public static IntPtr Query(string iface, uint version) - { - if (iface != RynthIltDataApiV1.InterfaceName || version < 1 || version > RynthIltDataApiV1.InterfaceVersion || _released) - return IntPtr.Zero; - if (_table == null) - { - var t = (RynthIltDataApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthIltDataApiV1)); - t->StructSize = (uint)sizeof(RynthIltDataApiV1); - t->GetCharmsJson = &GetCharmsJson; - t->GetBankJson = &GetBankJson; - t->ToggleCharm = &ToggleCharm; - t->BankCommand = &BankCommand; - t->GetPetBreedingJson = &GetPetBreedingJson; - t->PetBreedingCommand = &PetBreedingCommand; - t->GetGuardianJson = &GetGuardianJson; - t->GuardianCommand = &GuardianCommand; - t->Version = RynthIltDataApiV1.InterfaceVersion; - _table = t; - } - return (IntPtr)_table; - } - - /// Plugin shutdown: readers see Version 0 and re-query; every function answers 0. - public static void Release() - { - _released = true; - if (_table != null) _table->Version = 0; - } - - private static IltHubController? Hub => _released ? null : PluginExports.Runtime.Plugin?.Hub; - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GetCharmsJson(byte* buffer, int capacity) - { - try - { - string? json = Hub?.CharmsJson; - return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity); - } - catch { return 0; } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GetBankJson(byte* buffer, int capacity) - { - try - { - string? json = Hub?.BankJson; - return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity); - } - catch { return 0; } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int ToggleCharm(uint objectId) - { - try - { - IltHubController? hub = Hub; - if (hub == null || objectId == 0) return 0; - hub.RequestCharmToggle(objectId); - return 1; - } - catch { return 0; } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int BankCommand(byte* utf8) - { - try - { - IltHubController? hub = Hub; - if (hub == null) return 0; - string? line = ReadVerb(utf8); - if (line == null) return 0; - hub.RequestBankVerb(line); - return 1; - } - catch { return 0; } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GetPetBreedingJson(byte* buffer, int capacity) - { - try - { - string? json = Hub?.PetBreedingJson; - return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity); - } - catch { return 0; } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int PetBreedingCommand(byte* utf8) - { - try - { - IltHubController? hub = Hub; - if (hub == null) return 0; - string? line = ReadVerb(utf8); - if (line == null) return 0; - hub.RequestBreedingVerb(line); - return 1; - } - catch { return 0; } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GetGuardianJson(byte* buffer, int capacity) - { - try - { - string? json = Hub?.GuardianJson; - return string.IsNullOrEmpty(json) ? 0 : ProfileInterface.Write(json, buffer, capacity); - } - catch { return 0; } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GuardianCommand(byte* utf8) - { - try - { - IltHubController? hub = Hub; - if (hub == null) return 0; - string? line = ReadVerb(utf8); - if (line == null) return 0; - hub.RequestGuardianVerb(line); - return 1; - } - catch { return 0; } - } - - /// A reader's verb line, or null when it is empty, too long or not plain ASCII (no control characters reach a chat command). - private static string? ReadVerb(byte* utf8) - { - if (utf8 == null) return null; - int len = 0; - while (len < MaxVerbBytes && utf8[len] != 0) len++; - if (len == 0 || len >= MaxVerbBytes) return null; - string line = System.Text.Encoding.UTF8.GetString(utf8, len); - foreach (char c in line) - if (c < 0x20 || c > 0x7E) return null; - return line; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltAttributeRaiser.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltAttributeRaiser.cs deleted file mode 100644 index 23ac250..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltAttributeRaiser.cs +++ /dev/null @@ -1,638 +0,0 @@ -// IltAttributeRaiser.cs — Infinite attributes: spend unassigned XP with the server's /attr. -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// -// ACECustom (Infinite Leaftide) lets attributes and vitals go past the retail cap, so the -// client's XP tables stop applying. The server is the only source of truth: -// "/xp all" → "[XP] Your XP cost for next 1 Strength level is: 1,234" per stat -// "/attr " → "[ATTR] Strength attribute raised by 1, costing 1,234!" -// (Same commands UB's Leaftide XP Calculator drives; it raises one level at a time and -// re-reads the costs after each confirmation, which is what this does too.) -// -// Raise now / auto-raise run one loop: read costs → pick a stat → /attr 1 → wait for -// the [ATTR] reply → read costs again → ... until nothing ticked is affordable, a reply is -// not a success, or MaxRaisesPerRun. Only the ticked stats are ever spent on, never below -// the reserve (AttrKeepXp). Which stat comes next depends on the raise mode: -// Priority the first ticked stat in the order that is affordable (fills the top stat) -// RoundRobin one level per ticked stat in order, then around again -// Cheapest the ticked stat with the lowest next-level cost -// Manual +1 / +10 buttons send "/attr N" straight to the server (its reply shows in chat) -// once the known (+1) or projected (+10, 7.7% per level as in UB) cost fits the unassigned XP. -// -// Gated on ServerFeatureGate (via IltServerOptions.IsIltLikeWorld) and on the server not -// reporting /xp off. Everything here runs on the plugin pump thread. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal sealed class IltAttributeRaiser -{ - /// Raise modes (IltCharacterState.AttrRaiseMode). - public enum Mode { Priority = 0, RoundRobin = 1, Cheapest = 2 } - - /// /attr abbreviation, display name, vital? - public sealed record Stat(string Abbr, string Name, bool Vital); - - public static readonly Stat[] Stats = - { - new("str", "Strength", false), new("end", "Endurance", false), new("coo", "Coordination", false), - new("qui", "Quickness", false), new("foc", "Focus", false), new("sel", "Self", false), - new("hea", "Health", true), new("sta", "Stamina", true), new("man", "Mana", true), - }; - - /// UB's default priority (Coordination, Quickness, Strength, Endurance, Focus, Self, vitals). - public static readonly string[] DefaultOrder = { "coo", "qui", "str", "end", "foc", "sel", "hea", "sta", "man" }; - - public const int MaxRaisesPerRun = 200; - - /// - /// Per-level growth for projecting several levels from the one cost "/xp all" reports (UB's - /// Leaftide XP tab uses the same 7.7%). The server prices each level itself; this only labels - /// the +10 button and gates it on the XP you have. - /// - public const double ProjectedLevelGrowth = 0.077; - - private const long FirstAutoDelayMs = 30_000; // after login / arming, before the first auto run - private const int ReplyTimeoutMs = 8000; - /// A run with no reply/step for this long is ended (a lost callback must not wedge it). - private const long StallMs = 45_000; - - /// "Your base Strength is now 250!" / "Your base Maximum Health is now 900!" (older servers / UB wording). - private static readonly Regex BaseNow = new(@"Your base (?:Maximum )?(\w+) is now (\d+)!", RegexOptions.Compiled | RegexOptions.CultureInvariant); - - private readonly IltHubContext _ctx; - // Last known costs (display, and the passive chat reader). A run decides only from _runCosts: - // the costs in the "/xp all" reply read right before that step, never an older value. - private readonly Dictionary _cost = new(StringComparer.OrdinalIgnoreCase); - private Dictionary _runCosts = new(StringComparer.OrdinalIgnoreCase); - private readonly Dictionary _base = new(StringComparer.OrdinalIgnoreCase); - private long _costsAtMs; - private DateTime _costsAtLocal; - // Opening the Progression tab reads the costs once per login, like UB's XP tab does on load. - private bool _autoCostsTried; - - // Run state. _runId guards against a capture that completes after Stop / a newer run. - private enum Phase { Idle, ReadingCosts, Raising } - private Phase _phase; - private int _runId; - private bool _runAuto; - private int _runRaised; - private long _runSpent; - private readonly Dictionary _runGains = new(StringComparer.OrdinalIgnoreCase); - private int _rrNext; - private string _raisingAbbr = string.Empty; - private long _raisingCost; - - private long _lastProgressMs; - private long _nextAutoAtMs; - private volatile string _status = "Idle."; - private volatile string _lastRun = string.Empty; - - public IltAttributeRaiser(IltHubContext ctx) => _ctx = ctx; - - /// - /// True while another XP spender runs (IltProgression's spend-before-/enl loop sends /attr - /// outside the capture queue). Nothing here starts, by hand or on the timer, while it is. - /// - public Func? HoldOff { get; set; } - - private bool HeldOff - { - get { try { return HoldOff?.Invoke() == true; } catch { return false; } } - } - - private IltCharacterState C => _ctx.State.Character; - - public bool Running => _phase != Phase.Idle; - - // ── Order / selection helpers (also used by IltHubStore.Normalize) ───────── - - public static Stat? Find(string keyOrName) - { - if (string.IsNullOrWhiteSpace(keyOrName)) return null; - string k = keyOrName.Trim(); - foreach (var s in Stats) - if (s.Abbr.Equals(k, StringComparison.OrdinalIgnoreCase) || s.Name.Equals(k, StringComparison.OrdinalIgnoreCase)) - return s; - // Cost lines may say "MaxHealth" / "Maximum Health"; the reply may abbreviate. - string lower = k.ToLowerInvariant().Replace(" ", ""); - if (lower.StartsWith("maximum")) lower = lower.Substring(7); - else if (lower.StartsWith("max")) lower = lower.Substring(3); - foreach (var s in Stats) - if (s.Name.Equals(lower, StringComparison.OrdinalIgnoreCase) || lower.StartsWith(s.Abbr, StringComparison.Ordinal)) - return s; - return null; - } - - /// All nine abbreviations exactly once: saved order first, missing ones appended, junk dropped. - public static List RepairOrder(List? order) - { - var result = new List(); - foreach (string k in order ?? new List()) - { - Stat? s = Find(k); - if (s != null && !result.Contains(s.Abbr)) result.Add(s.Abbr); - } - foreach (string k in DefaultOrder) - if (!result.Contains(k)) result.Add(k); - return result; - } - - public static List RepairSelection(List? selection) - { - var result = new List(); - foreach (string k in selection ?? new List()) - { - Stat? s = Find(k); - if (s != null && !result.Contains(s.Abbr)) result.Add(s.Abbr); - } - return result; - } - - /// - /// Picks the next stat to raise. Pure (unit-testable): is the - /// priority order, the stats allowed, the - /// known next-level costs, what may be spent. Round robin starts at - /// and returns the index after the pick there. - /// - public static string? Pick(Mode mode, IReadOnlyList order, ICollection ticked, - IReadOnlyDictionary cost, long budget, ref int rrNext) - { - if (budget <= 0 || order.Count == 0) return null; - bool Affordable(string k) => ticked.Contains(k) && cost.TryGetValue(k, out long c) && c > 0 && c <= budget; - - switch (mode) - { - case Mode.RoundRobin: - for (int step = 0; step < order.Count; step++) - { - int i = ((rrNext % order.Count) + step) % order.Count; - if (!Affordable(order[i])) continue; - rrNext = i + 1; - return order[i]; - } - return null; - case Mode.Cheapest: - string? best = null; - long bestCost = long.MaxValue; - foreach (string k in order) // ties go to the higher-priority stat - { - if (!Affordable(k)) continue; - long c = cost[k]; - if (c < bestCost) { best = k; bestCost = c; } - } - return best; - default: - foreach (string k in order) - if (Affordable(k)) return k; - return null; - } - } - - // ── Gate ────────────────────────────────────────────────────────────────── - - /// Why the raiser can't run here, or null when it can. - public string? Blocker() - { - if (!_ctx.Options.IsIltLikeWorld) - return "Server features are off for this world (Settings > Misc > Server Features)."; - if (_ctx.Options.IsOff(IltFeature.Xp)) return "This server reports /xp as unavailable."; - if (!_ctx.Host.HasInvokeChatParser) return "This engine build can't send chat commands."; - return null; - } - - // ── Pump-thread lifecycle ───────────────────────────────────────────────── - - /// Tick. : another XP spender (auto-enlighten's loop) is running. - public void Tick(long nowMs, bool holdOff) - { - if (Running && nowMs - _lastProgressMs > StallMs) { Finish($"Stopped: no reply for {StallMs / 1000} s."); return; } - if (!C.AttrAutoRaise || Running || holdOff || HeldOff) return; - if (_nextAutoAtMs == 0) { _nextAutoAtMs = nowMs + FirstAutoDelayMs; return; } - if (nowMs < _nextAutoAtMs) return; - _nextAutoAtMs = nowMs + Math.Clamp(C.AttrAutoRaiseMinutes, 1, 1440) * 60_000L; - if (Blocker() != null || C.AttrRaiseStats.Count == 0) return; - if (_ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp) <= Math.Max(0, C.AttrKeepXp)) return; - Start(auto: true); - } - - /// Passive: keeps costs / base values current when the player runs the commands by hand. - public void OnChat(string text) - { - var cost = IltParse.XpCost.Match(text); - if (cost.Success) - { - Stat? s = Find(cost.Groups[1].Value); - if (s != null) { _cost[s.Abbr] = IltParse.ParseLeadingLong(cost.Groups[2].Value); MarkCostsRead(); } - return; - } - var now = BaseNow.Match(text); - if (now.Success) - { - Stat? s = Find(now.Groups[1].Value); - if (s != null && int.TryParse(now.Groups[2].Value, out int v)) _base[s.Abbr] = v; - } - } - - public void OnLogout() - { - _runId++; - _phase = Phase.Idle; - _cost.Clear(); - _runCosts.Clear(); - _base.Clear(); - _costsAtMs = 0; - _autoCostsTried = false; - _nextAutoAtMs = 0; - _status = "Idle."; - } - - // ── Runs ────────────────────────────────────────────────────────────────── - - /// Starts a spend run (manual "Raise now" or the auto timer). - public void Start(bool auto) - { - if (Running) return; - string? blocked = Blocker(); - if (blocked != null) { _status = blocked; return; } - if (HeldOff) { _status = "Auto-enlighten is spending XP right now; try again when it finishes."; return; } - if (C.AttrRaiseStats.Count == 0) { _status = "Tick at least one attribute or vital to raise."; return; } - - _runId++; - _runAuto = auto; - _runRaised = 0; - _runSpent = 0; - _runGains.Clear(); - _rrNext = 0; - _runCosts = new Dictionary(StringComparer.OrdinalIgnoreCase); - _lastProgressMs = IltHubContext.NowMs; - RynthLog.Trace(LogCat.IltProgression, $"attr raise run {_runId} start (auto={auto}, mode={(Mode)C.AttrRaiseMode}, keep={C.AttrKeepXp}, stats={string.Join(",", C.AttrRaiseStats)})"); - ReadCosts(_runId, thenStep: true); - } - - public void Stop(string why = "Stopped.") - { - if (!Running) return; - Finish(why); - } - - /// Re-reads the costs only (the panel's Refresh button). - public void RefreshCosts() - { - if (Running || Blocker() != null) return; - ReadCosts(_runId, thenStep: false); - } - - /// Reads the costs once per login when the Progression tab is first shown. Pump thread. - public void EnsureCosts() - { - if (_autoCostsTried || _costsAtMs != 0 || Running || Blocker() != null) return; - _autoCostsTried = true; - ReadCosts(_runId, thenStep: false); - } - - /// - /// XP for raises when the next one costs , - /// each level dearer than the last. Saturates at long.MaxValue. - /// - public static long ProjectCost(long nextCost, int levels) - { - if (nextCost <= 0 || levels <= 0) return 0; - double total = 0, step = nextCost; - for (int i = 0; i < levels; i++) - { - total += step; - step *= 1 + ProjectedLevelGrowth; - } - return total >= long.MaxValue ? long.MaxValue : (long)total; - } - - private void MarkCostsRead() - { - _costsAtMs = IltHubContext.NowMs; - _costsAtLocal = DateTime.Now; - } - - /// - /// "+N" button: sends "/attr abbr N"; the server's reply shows in chat. Refused up front when - /// the known (or, for N > 1, projected) cost is more than the unassigned XP, like UB's XP tab. - /// - public void RaiseManual(string key, int levels) - { - Stat? s = Find(key); - if (s == null || levels <= 0) return; - if (Running) { _status = "Wait for the current raise run to finish (or Stop it)."; return; } - string? blocked = Blocker(); - if (blocked != null) { _status = blocked; return; } - if (HeldOff) { _status = "Auto-enlighten is spending XP right now; try again when it finishes."; return; } - levels = Math.Min(levels, 1000); - if (_cost.TryGetValue(s.Abbr, out long next) && next > 0) - { - long need = ProjectCost(next, levels); - long have = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp); - if (need > have) - { - _status = $"Not enough unassigned XP for {s.Name} +{levels}: need {(levels > 1 ? "~" : "")}{IltParse.Compact(need)}, have {IltParse.Compact(have)}."; - return; - } - } - RynthLog.Trace(LogCat.IltProgression, $"attr manual raise {s.Abbr} +{levels}"); - int run = _runId; - _ctx.Capture.Enqueue(new IltChatRequest - { - Command = $"/attr {s.Abbr} {levels}", - IsResponseLine = IsAttrReply, - IsTerminator = IsAttrReply, - IdleEndMs = 600, - FirstLineTimeoutMs = ReplyTimeoutMs, - Eat = false, - OnComplete = r => - { - string reply = r.TerminatorLine ?? r.Lines.FirstOrDefault() ?? (r.TimedOut ? "no reply" : ""); - _status = $"{s.Name} +{levels}: {reply}"; - if (run == _runId && !Running) ReadCosts(_runId, thenStep: false); - }, - }); - _status = $"Sent /attr {s.Abbr} {levels}..."; - } - - private static bool IsAttrReply(string t) - => t.StartsWith("[ATTR]", StringComparison.OrdinalIgnoreCase) || t.StartsWith("Your base", StringComparison.OrdinalIgnoreCase); - - private void ReadCosts(int run, bool thenStep) - { - // A plain refresh doesn't stack on one already queued; a run always gets its own reply. - if (!thenStep && _ctx.Capture.IsPending("/xp all")) return; - if (thenStep) - { - _phase = Phase.ReadingCosts; - if (_runRaised == 0) _status = "Reading XP costs (/xp all)..."; - } - _ctx.Capture.Enqueue(new IltChatRequest - { - Command = "/xp all", - IsResponseLine = t => t.StartsWith("[XP]", StringComparison.OrdinalIgnoreCase), - IdleEndMs = 900, - FirstLineTimeoutMs = ReplyTimeoutMs, - Eat = true, - OnComplete = r => Guard(run, () => - { - if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Xp, IltTri.Off); if (run == _runId && thenStep) Finish("This server has no /xp command."); return; } - var fresh = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (string line in r.Lines) - { - var m = IltParse.XpCost.Match(line); - if (!m.Success) continue; - Stat? s = Find(m.Groups[1].Value); - if (s == null) continue; - fresh[s.Abbr] = IltParse.ParseLeadingLong(m.Groups[2].Value); - } - foreach (var kv in fresh) _cost[kv.Key] = kv.Value; - if (fresh.Count > 0) MarkCostsRead(); - RynthLog.Trace(LogCat.IltProgression, $"attr costs: {fresh.Count} line(s) (timedOut={r.TimedOut})"); - if (!thenStep || run != _runId || !Running) return; - if (fresh.Count == 0) { Finish(r.TimedOut ? "No reply to /xp all." : "No cost lines in the /xp all reply."); return; } - _runCosts = fresh; // a stat missing from this reply is not raised this step - _lastProgressMs = IltHubContext.NowMs; - Step(run); - }), - }); - } - - private void Step(int run) - { - if (run != _runId || !Running) return; - // The world can leave Server Features (or /xp go off) mid-run, and auto-enlighten can start. - if (Blocker() is string blocked) { Finish("Stopped: " + blocked); return; } - if (HeldOff) { Finish("Stopped: auto-enlighten started spending XP."); return; } - if (_runRaised >= MaxRaisesPerRun) { Finish($"Stopped after {MaxRaisesPerRun} raises (runs again later)."); return; } - - long have = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp); - long budget = have - Math.Max(0, C.AttrKeepXp); - var ticked = new HashSet(C.AttrRaiseStats, StringComparer.OrdinalIgnoreCase); - string? pick = Pick((Mode)Math.Clamp(C.AttrRaiseMode, 0, 2), C.AttrOrder, ticked, _runCosts, budget, ref _rrNext); - if (pick == null) - { - Finish(_runRaised == 0 - ? (budget <= 0 ? "Nothing to spend (unassigned XP is at or below the reserve)." - : "Nothing affordable among the ticked stats.") - : string.Empty); - return; - } - - Stat s = Find(pick)!; - _phase = Phase.Raising; - _raisingAbbr = s.Abbr; - _raisingCost = _runCosts.TryGetValue(s.Abbr, out long c) ? c : 0; - _status = $"Raising {s.Name} +1 (cost {IltParse.Compact(_raisingCost)})..."; - _ctx.Capture.Enqueue(new IltChatRequest - { - Command = $"/attr {s.Abbr} 1", - IsResponseLine = IsAttrReply, - IsTerminator = IsAttrReply, - IdleEndMs = 600, - FirstLineTimeoutMs = ReplyTimeoutMs, - Eat = true, - OnComplete = r => Guard(run, () => OnRaiseReply(run, s, r)), - }); - } - - private void OnRaiseReply(int run, Stat s, IltChatResult r) - { - if (run != _runId || !Running) return; - string reply = r.TerminatorLine ?? r.Lines.FirstOrDefault() ?? string.Empty; - var ok = IltParse.AttrRaised.Match(reply); - var baseNow = BaseNow.Match(reply); - // The reply must be about the stat we raised (another /attr sender could answer first). - if (ok.Success && Find(ok.Groups[1].Value) != s) ok = Match.Empty; - if (baseNow.Success && Find(baseNow.Groups[1].Value) != s) baseNow = Match.Empty; - if (!ok.Success && !baseNow.Success) - { - RynthLog.Trace(LogCat.IltProgression, $"attr raise {s.Abbr}: not a success ('{reply}', timedOut={r.TimedOut}, unknown={r.UnknownCommand})"); - Finish(r.UnknownCommand ? "This server has no /attr command." - : reply.Length > 0 ? $"Server: {reply}" : "No reply to /attr."); - return; - } - - long spent = ok.Success ? IltParse.ParseLeadingLong(ok.Groups[3].Value) : _raisingCost; - int levels = ok.Success && int.TryParse(ok.Groups[2].Value, out int n) ? n : 1; - if (baseNow.Success && int.TryParse(baseNow.Groups[2].Value, out int v)) _base[s.Abbr] = v; - else if (_base.TryGetValue(s.Abbr, out int b)) _base[s.Abbr] = b + levels; - _runGains[s.Abbr] = (_runGains.TryGetValue(s.Abbr, out int g) ? g : 0) + levels; - _runRaised += levels; - _runSpent += spent; - _cost.Remove(s.Abbr); // its next level costs more; re-read before deciding again - _runCosts.Clear(); - _lastProgressMs = IltHubContext.NowMs; - _status = $"Raised {s.Name} (+{_runRaised} this run, {IltParse.Compact(_runSpent)} XP)..."; - ReadCosts(run, thenStep: true); - } - - /// Runs a capture callback; an exception ends the run instead of leaving it Running. - private void Guard(int run, Action body) - { - try { body(); } - catch (Exception ex) - { - RynthLog.Exception(LogCat.IltProgression, ex, "attr raise callback"); - if (run == _runId && Running) Finish("Stopped: internal error (see the RynthAi log)."); - } - } - - private void Finish(string reason) - { - _phase = Phase.Idle; - _runId++; // late callbacks from this run are ignored - string summary = _runRaised > 0 - ? "Raised " + string.Join(", ", C.AttrOrder.Where(_runGains.ContainsKey).Select(k => $"{Find(k)!.Name} +{_runGains[k]}")) - + $" ({IltParse.Compact(_runSpent)} XP)." - : string.Empty; - string text = (summary + (reason.Length > 0 ? (summary.Length > 0 ? " " : "") + reason : "")).Trim(); - if (text.Length == 0) text = "Done."; - _status = text; - _lastRun = $"{DateTime.Now:t} {(_runAuto ? "auto" : "manual")}: {text}"; - RynthLog.Trace(LogCat.IltProgression, $"attr raise run finished: {text}"); - if (_runRaised > 0) _ctx.Chat($"[Mini Remote] Attribute raise ({(_runAuto ? "auto" : "manual")}): {text}"); - } - - // ── Engine Skills panel bridge ──────────────────────────────────────────── - - /// Appends "attr":{...} for the Progression tab. - public void AppendJson(StringBuilder sb) - { - string? blocked = Blocker(); - long have = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp); - long budget = have - Math.Max(0, C.AttrKeepXp); - long now = IltHubContext.NowMs; - - sb.Append("\"attr\":{\"off\":").Append(blocked != null ? "true" : "false"); - Str(sb, "reason", blocked ?? string.Empty); - sb.Append(",\"auto\":").Append(C.AttrAutoRaise ? "true" : "false") - .Append(",\"every\":").Append(Math.Clamp(C.AttrAutoRaiseMinutes, 1, 1440)) - .Append(",\"mode\":").Append(Math.Clamp(C.AttrRaiseMode, 0, 2)) - .Append(",\"running\":").Append(Running ? "true" : "false"); - Str(sb, "keep", C.AttrKeepXp > 0 ? IltParse.Compact(C.AttrKeepXp) : "0"); - // The reserve box edits the exact number (the compact form above is lossy). - Str(sb, "keepFull", IltParse.N0(Math.Max(0, C.AttrKeepXp))); - Str(sb, "status", _status); - Str(sb, "lastRun", _lastRun); - Str(sb, "unassigned", $"Unassigned XP {IltParse.Compact(have)}" - + (C.AttrKeepXp > 0 ? $" (spendable {IltParse.Compact(Math.Max(0, budget))})" : "")); - string next = !C.AttrAutoRaise ? string.Empty - : Running ? "running" - : _nextAutoAtMs <= 0 ? "soon" - : IltParse.Duration(TimeSpan.FromMilliseconds(Math.Max(0, _nextAutoAtMs - now))); - Str(sb, "next", next); - Str(sb, "costsAge", _costsAtMs == 0 ? "costs not read yet" : $"costs read {Ago(now - _costsAtMs)} ago"); - Str(sb, "updated", _costsAtMs == 0 ? "-" : _costsAtLocal.ToString("HH:mm:ss")); - int level = _ctx.Inventory.PlayerInt(IltInventory.IntLevel); - long totalXp = _ctx.Inventory.PlayerQuad(IltInventory.QuadTotalXp); - Str(sb, "xpHeader", $"Level {(level > 0 ? level.ToString() : "?")} Total XP {(totalXp > 0 ? IltParse.Compact(totalXp) : "?")} Unassigned {IltParse.Compact(have)}"); - - var ticked = new HashSet(C.AttrRaiseStats, StringComparer.OrdinalIgnoreCase); - sb.Append(",\"rows\":["); - bool first = true; - foreach (string k in C.AttrOrder) - { - Stat? s = Find(k); - if (s == null) continue; - if (!first) sb.Append(','); - first = false; - bool known = _cost.TryGetValue(s.Abbr, out long c) && c > 0; - sb.Append('{'); - Str(sb, "key", s.Abbr, first: true); - Str(sb, "label", s.Name); - sb.Append(",\"vital\":").Append(s.Vital ? "true" : "false") - .Append(",\"on\":").Append(ticked.Contains(s.Abbr) ? "true" : "false") - .Append(",\"base\":").Append(_base.TryGetValue(s.Abbr, out int b) ? b : -1) - .Append(",\"afford\":").Append(known && c <= budget ? "true" : "false"); - Str(sb, "cost", known ? IltParse.Compact(c) : "?"); - // By hand (+1 / +10) only the unassigned XP limits, not the raiser's reserve. - long ten = known ? ProjectCost(c, 10) : 0; - sb.Append(",\"known\":").Append(known ? "true" : "false") - .Append(",\"afford1\":").Append(known && c <= have ? "true" : "false") - .Append(",\"afford10\":").Append(known && ten <= have ? "true" : "false"); - Str(sb, "cost10", known ? "~" + IltParse.Compact(ten) : "?"); - Str(sb, "costFull", known ? IltParse.N0(c) : ""); - Str(sb, "cost10Full", known ? IltParse.N0(ten) : ""); - sb.Append('}'); - } - sb.Append("]}"); - } - - private static string Ago(long ms) - { - long sec = Math.Max(0, ms / 1000); - return sec < 60 ? $"{sec}s" : sec < 3600 ? $"{sec / 60}m" : $"{sec / 3600}h {sec % 3600 / 60}m"; - } - - private static void Str(StringBuilder sb, string name, string value, bool first = false) - { - if (!first) sb.Append(','); - sb.Append('"').Append(name).Append("\":\"").Append(IltStyle.JsonEscape(value ?? string.Empty)).Append('"'); - } - - /// "prog attr…" commands from the Skills panel. Returns false when the verb isn't ours. - public bool HandleRemote(string verb, string[] a) - { - string arg1 = a.Length > 1 ? a[1] : string.Empty; - string arg2 = a.Length > 2 ? a[2] : string.Empty; - switch (verb) - { - case "attrauto": - C.AttrAutoRaise = arg1.Equals("on", StringComparison.OrdinalIgnoreCase); - _nextAutoAtMs = C.AttrAutoRaise ? IltHubContext.NowMs + FirstAutoDelayMs : 0; - if (!C.AttrAutoRaise && Running && _runAuto) Stop("Auto-raise turned off."); - return true; - case "attrevery": - if (int.TryParse(arg1, out int min)) - { - C.AttrAutoRaiseMinutes = Math.Clamp(min, 1, 1440); - if (C.AttrAutoRaise) _nextAutoAtMs = IltHubContext.NowMs + C.AttrAutoRaiseMinutes * 60_000L; - } - return true; - case "attrmode": - if (int.TryParse(arg1, out int mode)) C.AttrRaiseMode = Math.Clamp(mode, 0, 2); - return true; - case "attrkeep": - if (arg1.Length == 0 || arg1 == "0") C.AttrKeepXp = 0; - else if (IltParse.TryParseAmount(arg1, out long keep)) C.AttrKeepXp = Math.Max(0, keep); - return true; - case "attron": - { - Stat? s = Find(arg1); - if (s == null) return true; - bool on = arg2.Equals("on", StringComparison.OrdinalIgnoreCase); - C.AttrRaiseStats.RemoveAll(x => x.Equals(s.Abbr, StringComparison.OrdinalIgnoreCase)); - if (on) C.AttrRaiseStats.Add(s.Abbr); - return true; - } - case "attrmove": - { - Stat? s = Find(arg1); - if (s == null) return true; - int i = C.AttrOrder.FindIndex(x => x.Equals(s.Abbr, StringComparison.OrdinalIgnoreCase)); - int j = arg2.Equals("up", StringComparison.OrdinalIgnoreCase) ? i - 1 - : arg2.Equals("top", StringComparison.OrdinalIgnoreCase) ? 0 : i + 1; - if (i < 0 || j < 0 || j >= C.AttrOrder.Count || i == j) return true; - string item = C.AttrOrder[i]; - C.AttrOrder.RemoveAt(i); - C.AttrOrder.Insert(j, item); - return true; - } - case "attrorderreset": - C.AttrOrder = new List(DefaultOrder); - return true; - case "attrraise": - if (int.TryParse(arg2, out int levels)) RaiseManual(arg1, levels); - return true; - case "attrrun": Start(auto: false); return true; - case "attrstop": Stop(); return true; - case "attrcosts": RefreshCosts(); return true; - } - return false; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltAugCosts.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltAugCosts.cs deleted file mode 100644 index ae28ac6..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltAugCosts.cs +++ /dev/null @@ -1,228 +0,0 @@ -// IltAugCosts.cs — luminance augmentation cost rules, per server (world name). -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// -// Defaults are UB's Leaftide Augs tab (correct for InfiniteLeaftide): -// level i (1-based) costs (Base + (i-1) * Base * LinearPercent/100) * multiplier(i) -// multiplier(i) = M0 below S1, M1 from S1, M2 from S2, M3 from S3, M4 from S4 -// (UB: 1 / 4 / 8 / 16 / 24; a tier starts AT its S level). -// Another server can change the multipliers and every aug's base, growth, S1..S4, target cap -// and coins per level from the Progression tab; those edits are saved for that world only in -// one shared file, so every character on the world prices augs the same way. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text.Json; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// The saved file: one cost profile per world that was changed from the defaults. -public sealed class IltAugCostFile -{ - public Dictionary Servers = new(StringComparer.OrdinalIgnoreCase); -} - -/// A world's cost rules: the five tier multipliers and one row per aug. -public sealed class IltAugCostProfile -{ - public double[] Multipliers = (double[])IltAugCosts.DefaultMultipliers.Clone(); - public List Augs = new(); -} - -/// One aug's cost rule. Thresholds are 1-based levels; Cap 0 = no target limit. -public sealed class IltAugCostRow -{ - public string Key = string.Empty; - public long Base; - public double LinearPercent; - public int CoinsPerLevel; - public int S1, S2, S3, S4; - public int Cap; - - public IltAugCostRow Clone() => (IltAugCostRow)MemberwiseClone(); -} - -internal sealed class IltAugCosts -{ - /// UB's tier multipliers: below S1, from S1, from S2, from S3, from S4. - public static readonly double[] DefaultMultipliers = { 1, 4, 8, 16, 24 }; - - /// Highest target the planner accepts when an aug has no cap (keeps the plan sane). - public const int NoCapLimit = 100_000; - - /// Display order and labels; also the only keys a profile may hold. - public static readonly (string Key, string Label)[] Labels = - { - ("creature", "Creature"), ("item", "Item"), ("life", "Life"), ("war", "War"), ("void", "Void"), - ("duration", "Duration"), ("melee", "Melee"), ("missile", "Missile"), - ("specialization", "Specialization"), ("summon", "Summon"), - }; - - /// UB Augs.cs (ILT): cost models, coins per level and soft caps S1..S4; no target cap. - public static IltAugCostRow[] DefaultRows() => new[] - { - Row("creature", 750_000, 130, 3, 2750, 4000, 4750, 5250), - Row("item", 1_000_000, 165, 18, 1250, 2000, 3000, 3500), - Row("life", 975_000, 195, 12, 1000, 2000, 3000, 3750), - Row("war", 750_000, 140, 5, 1750, 2500, 3000, 3750), - Row("void", 800_000, 160, 5, 1750, 2500, 3000, 3750), - Row("duration", 400_000, 120, 5, 1000, 2000, 2500, 3000), - Row("melee", 750_000, 140, 5, 1750, 2500, 3000, 3750), - Row("missile", 750_000, 140, 5, 1750, 2500, 3000, 3750), - Row("specialization", 3_000_000, 200, 50, 1750, 2500, 3000, 3750), - Row("summon", 500_000, 125, 36, 1750, 2500, 3000, 3750), - }; - - private static IltAugCostRow Row(string key, long b, double lp, int coins, int s1, int s2, int s3, int s4) - => new() { Key = key, Base = b, LinearPercent = lp, CoinsPerLevel = coins, S1 = s1, S2 = s2, S3 = s3, S4 = s4, Cap = 0 }; - - /// The shared settings file. Tests point it at a scratch folder before first use. - public static string FilePath { get; set; } = Path.Combine(IltHubStore.SharedRoot, "ilt-aug-costs.json"); - - private IltAugCostFile? _file; - private string _lastJson = string.Empty; - private static readonly IltAugCostProfile Defaults = NewDefaultProfile(); - - public static string Label(string key) - { - foreach (var l in Labels) if (l.Key.Equals(key, StringComparison.OrdinalIgnoreCase)) return l.Label; - return key; - } - - private static IltAugCostProfile NewDefaultProfile() - => new() { Multipliers = (double[])DefaultMultipliers.Clone(), Augs = DefaultRows().ToList() }; - - private IltAugCostFile File_ - { - get - { - if (_file != null) return _file; - _file = new IltAugCostFile(); - try - { - if (File.Exists(FilePath)) - { - string json = File.ReadAllText(FilePath); - _file = JsonSerializer.Deserialize(json, IltHubJsonContext.Default.IltAugCostFile) ?? new IltAugCostFile(); - _lastJson = json; - } - } - catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"load {FilePath}"); _file = new IltAugCostFile(); } - var fixedUp = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (var kv in _file.Servers ?? new()) - if (kv.Value != null) fixedUp[kv.Key ?? string.Empty] = Normalize(kv.Value); - _file.Servers = fixedUp; - return _file; - } - } - - /// - /// Repairs a loaded or edited profile: five multipliers, exactly one row per known aug (missing - /// ones from the defaults, unknown ones dropped), non-negative values and S1 <= S2 <= S3 <= S4. - /// - public static IltAugCostProfile Normalize(IltAugCostProfile p) - { - var m = new double[5]; - for (int i = 0; i < 5; i++) - { - double v = p.Multipliers != null && i < p.Multipliers.Length ? p.Multipliers[i] : DefaultMultipliers[i]; - m[i] = double.IsFinite(v) ? Math.Clamp(v, 0, 1000) : DefaultMultipliers[i]; - } - p.Multipliers = m; - - var byKey = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (var r in p.Augs ?? new()) if (r != null && !string.IsNullOrEmpty(r.Key)) byKey[r.Key] = r; - var rows = new List(Labels.Length); - foreach (var def in DefaultRows()) - { - var r = byKey.TryGetValue(def.Key, out var have) ? have : def; - r.Key = def.Key; - r.Base = Math.Max(0, r.Base); - r.LinearPercent = double.IsFinite(r.LinearPercent) ? Math.Clamp(r.LinearPercent, 0, 100_000) : def.LinearPercent; - r.CoinsPerLevel = Math.Max(0, r.CoinsPerLevel); - r.S1 = Math.Max(0, r.S1); - r.S2 = Math.Max(r.S1, r.S2); - r.S3 = Math.Max(r.S2, r.S3); - r.S4 = Math.Max(r.S3, r.S4); - r.Cap = Math.Max(0, r.Cap); - rows.Add(r); - } - p.Augs = rows; - return p; - } - - /// The rules for : its saved profile, or the UB defaults. - public IltAugCostProfile For(string world) - => File_.Servers.TryGetValue(world ?? string.Empty, out var p) ? p : Defaults; - - /// True when has its own saved rules. - public bool IsCustom(string world) => File_.Servers.ContainsKey(world ?? string.Empty); - - /// Applies an edit to 's rules (copying the defaults first) and saves. - public void Edit(string world, Action change) - { - string key = world ?? string.Empty; - if (!File_.Servers.TryGetValue(key, out var p)) - { - p = NewDefaultProfile(); - File_.Servers[key] = p; - } - change(p); - Normalize(p); - Save(); - } - - /// Drops 's saved rules: it goes back to the UB defaults. - public void Reset(string world) - { - if (File_.Servers.Remove(world ?? string.Empty)) Save(); - } - - private void Save() - { - try - { - string json = JsonSerializer.Serialize(File_, IltHubJsonContext.Default.IltAugCostFile); - if (json == _lastJson) return; - if (RynthCore.Plugin.Shared.DataWriteGuard.TrySave("the aug cost table", FilePath, () => - { - Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!); - string tmp = FilePath + ".tmp"; - File.WriteAllText(tmp, json); - File.Move(tmp, FilePath, overwrite: true); - })) - _lastJson = json; - } - catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"save {FilePath}"); } - } - - /// Highest target the planner allows for at current level . - public static int Ceiling(IltAugCostRow r, int cur) => Math.Max(cur, r.Cap > 0 ? r.Cap : NoCapLimit); - - /// - /// Luminance for levels cur+1 .. tgt. Same result as UB's per-level loop, summed per tier in - /// closed form: within a tier the per-level base grows linearly, so each tier is an arithmetic series. - /// - public static decimal LumCost(IltAugCostRow r, double[] mult, int cur, int tgt) - { - int first = Math.Max(1, cur + 1); - if (tgt < first) return 0; - decimal b = r.Base; - decimal step = b * (decimal)r.LinearPercent / 100m; - // Tier t covers levels [lo[t], hi[t]) (1-based); the last tier has no end. - long[] lo = { 1, r.S1, r.S2, r.S3, r.S4 }; - long[] hi = { r.S1, r.S2, r.S3, r.S4, long.MaxValue }; - decimal total = 0; - for (int t = 0; t < 5; t++) - { - long a = Math.Max(first, lo[t]); - long z = Math.Min(tgt, hi[t] - 1); - if (z < a) continue; - decimal n = z - a + 1; - // sum over i=a..z of (b + (i-1)*step) = n*b + step * sum(i-1) = n*b + step * n*(a-1 + z-1)/2 - decimal levels = n * b + step * (n * ((a - 1) + (z - 1)) / 2m); - total += levels * (decimal)mult[t]; - } - return total; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankCommands.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankCommands.cs deleted file mode 100644 index e4782e2..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankCommands.cs +++ /dev/null @@ -1,188 +0,0 @@ -// IltBankCommands.cs — The /bank commands the Banking tab sends, and the reply lines it collects. -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// -// Server contract (ACECustom PlayerCommands.HandleBank / Player_Bank, upstream 976606695): -// /b d [code] deposit everything (no code) or one kind; "Deposited N ", -// "No found to deposit", "Deposited all !". -// /b lum bank luminance tokens: "Starting Banked Lum", one "Deposited N x " -// a kind, "Ending Banked Lum"; "No luminance tokens found to deposit". -// /b w withdraw: "Withdrew ...", "You don't have enough ...", "Failed to create ...". -// /b w n [n] trade notes by denomination (i v x l c d m md mm mmd). -// /b t transfer; "Transferred {N0} {Currency} to {Name}[ (offline)]". -// /b t n trade notes' pyreal value, then "(Equivalent to Nx DENOM notes)". -// The recipient is one argument: a name with a space has to be in "quotes". -// Prestige Coins are bound to the character: "[BANK] Prestige Coins are bound to you and -// cannot be transferred." Pyreal peas and luminance tokens are deposit only. -// Items is the one table of what the server allows; the deposit, withdraw and transfer lists -// are built from it. Deposit, withdraw and transfer share one server throttle -// (bank_command_limit); a plain /bank balance doesn't touch it. Pure: no host calls, so the -// host tests cover it. -using System; -using System.Linq; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal static class IltBankCommands -{ - /// - /// One bank item: label, server code, and what the server allows for it. For trade notes - /// ("n") a withdrawal or transfer is by denomination and note count. - /// - internal sealed record BankItem(string Label, string Code, bool Deposit, bool Withdraw, bool Transfer); - - /// The trade-notes code: withdrawn and transferred by denomination. - public const string NotesCode = "n"; - - /// The luminance-tokens deposit: its own command, "/b lum". - public const string LuminanceTokensCode = "lum"; - - /// Everything the bank holds, in the server's order, with what it allows. - public static readonly BankItem[] Items = - { - new("Pyreals", "p", Deposit: true, Withdraw: true, Transfer: true), - new("Pyreal peas", "ps", Deposit: true, Withdraw: false, Transfer: false), - new("Luminance", "l", Deposit: true, Withdraw: true, Transfer: true), - new("Luminance tokens", LuminanceTokensCode, Deposit: true, Withdraw: false, Transfer: false), - new("Legendary keys", "k", Deposit: true, Withdraw: true, Transfer: true), - new("Mythical keys", "mk", Deposit: true, Withdraw: true, Transfer: true), - new("Enlightened coins", "e", Deposit: true, Withdraw: true, Transfer: true), - new("Weakly enlightened coins", "we", Deposit: true, Withdraw: true, Transfer: true), - new("Prestige coins", "pc", Deposit: true, Withdraw: true, Transfer: false), - new("Trade notes", NotesCode, Deposit: true, Withdraw: true, Transfer: true), - }; - - /// A deposit choice: label, and the command's argument after "/b d" ("" = all). - public static readonly (string Label, string Args)[] Deposits = - new[] { ("Everything", string.Empty) } - .Concat(Items.Where(i => i.Deposit).Select(i => (i.Label, i.Code))) - .ToArray(); - - /// A withdraw choice: label and the server code; "n" is trade notes (by denomination). - public static readonly (string Label, string Code)[] Withdrawals = - Items.Where(i => i.Withdraw).Select(i => (i.Label, i.Code)).ToArray(); - - /// A transfer choice: label and the server code; "n" moves trade notes' pyreal value. - public static readonly (string Label, string Code)[] Transfers = - Items.Where(i => i.Transfer).Select(i => (i.Label, i.Code)).ToArray(); - - /// Trade note denominations: label and code, in the server's order. - public static readonly (string Label, string Code, long Value)[] NoteDenominations = - { - ("I (100)", "i", 100), ("V (500)", "v", 500), ("X (1K)", "x", 1_000), ("L (5K)", "l", 5_000), - ("C (10K)", "c", 10_000), ("D (50K)", "d", 50_000), ("M (100K)", "m", 100_000), - ("MD (150K)", "md", 150_000), ("MM (200K)", "mm", 200_000), ("MMD (250K)", "mmd", 250_000), - }; - - /// The server refuses a trade-note withdrawal of more than this many notes; transfers use the same cap. - public const int MaxNoteCount = 50_000; - - /// "/b d", "/b d p", or "/b lum" for the luminance tokens; empty for an unknown index. - public static string Deposit(int index) - { - if (index < 0 || index >= Deposits.Length) return string.Empty; - string args = Deposits[index].Args; - if (args.Length == 0) return "/b d"; - return args == LuminanceTokensCode ? "/b lum" : "/b d " + args; - } - - /// - /// "/b w p 1000000", or "/b w n mmd 5" for trade notes ( is then the - /// note count). Empty (with ) when the input can't be sent. - /// - public static string Withdraw(int index, long amount, int denomination, out string error) - { - error = string.Empty; - if (index < 0 || index >= Withdrawals.Length) { error = "Pick what to withdraw."; return string.Empty; } - if (amount <= 0) { error = "Amount must be positive."; return string.Empty; } - string code = Withdrawals[index].Code; - if (code != NotesCode) return $"/b w {code} {amount}"; - if (!TryNote(denomination, amount, out string denom, out error)) return string.Empty; - return $"/b w n {denom} {amount}"; - } - - /// - /// "/bank t p 250000 Bob", "/bank t n mmd 4 \"Some Name\"" for trade notes ( - /// is then the note count). must already be a checked character name - /// (IltParse.CharacterName); a name with a space is quoted, as the server reads one argument. - /// Empty (with ) when the input can't be sent. - /// - public static string Transfer(int index, long amount, int denomination, string target, out string error) - { - error = string.Empty; - if (index < 0 || index >= Transfers.Length) { error = "Pick a currency."; return string.Empty; } - if (amount <= 0) { error = "Amount must be positive."; return string.Empty; } - target = (target ?? string.Empty).Trim(); - if (target.Length == 0) { error = "Enter a recipient."; return string.Empty; } - if (target.IndexOf('"') >= 0) { error = "Recipient must be a character name."; return string.Empty; } - string who = target.IndexOf(' ') >= 0 ? "\"" + target + "\"" : target; - string code = Transfers[index].Code; - if (code != NotesCode) return $"/bank t {code} {amount} {who}"; - if (!TryNote(denomination, amount, out string denom, out error)) return string.Empty; - return $"/bank t n {denom} {amount} {who}"; - } - - /// True when is the trade-notes transfer (denomination and count). - public static bool IsNoteTransfer(int index) => index >= 0 && index < Transfers.Length && Transfers[index].Code == NotesCode; - - /// The pyreal value of notes of (0 if unknown). - public static long NoteValue(int denomination, long count) => - denomination >= 0 && denomination < NoteDenominations.Length && count > 0 ? NoteDenominations[denomination].Value * count : 0; - - private static bool TryNote(int denomination, long count, out string code, out string error) - { - code = string.Empty; - error = string.Empty; - if (denomination < 0 || denomination >= NoteDenominations.Length) { error = "Pick a note denomination."; return false; } - if (count > MaxNoteCount) { error = $"At most {MaxNoteCount:N0} notes at a time."; return false; } - code = NoteDenominations[denomination].Code; - return true; - } - - /// - /// True for a line the server sends in reply to a deposit or withdrawal (so the tab can show - /// it as the result). Only lines the bank code writes; never "[BANK]" balance lines. - /// - public static bool IsActionReply(string line) - { - if (string.IsNullOrEmpty(line)) return false; - return line.StartsWith("Deposited ", StringComparison.Ordinal) - || line.StartsWith("Withdrew ", StringComparison.Ordinal) - || (line.StartsWith("No ", StringComparison.Ordinal) && line.EndsWith("to deposit", StringComparison.Ordinal)) - || line.StartsWith("Starting Banked Lum", StringComparison.Ordinal) - || line.StartsWith("Ending Banked Lum", StringComparison.Ordinal) - || line.StartsWith("Not deposited", StringComparison.Ordinal) - || line.StartsWith("You don't have enough", StringComparison.Ordinal) - || line.StartsWith("You cannot hold any more", StringComparison.Ordinal) - || line.StartsWith("You have not been luminance flagged", StringComparison.Ordinal) - || line.StartsWith("Failed to ", StringComparison.Ordinal) - || line.StartsWith("Warning: Requested", StringComparison.Ordinal) - || line.StartsWith("Amount must be", StringComparison.Ordinal) - || line.StartsWith("Cannot deposit while", StringComparison.Ordinal) - || line.StartsWith("[Deposit]", StringComparison.Ordinal) - || line.StartsWith("[Withdraw]", StringComparison.Ordinal) - || line.StartsWith("Invalid amount", StringComparison.Ordinal) - || line.StartsWith("Invalid denomination", StringComparison.Ordinal) - || line.StartsWith("Count must be", StringComparison.Ordinal) - || line.StartsWith("Count cannot exceed", StringComparison.Ordinal) - || line.StartsWith("You are not permitted to use bank commands", StringComparison.Ordinal); - } - - /// - /// True for a line the server sends in reply to a transfer: the result, the trade-note - /// equivalent, the throttle, or a refusal (unknown player, bound prestige coins, bad input). - /// - public static bool IsTransferReply(string line) - { - if (string.IsNullOrEmpty(line)) return false; - return line.StartsWith("Transferred ", StringComparison.Ordinal) - || line.StartsWith("(Equivalent to ", StringComparison.Ordinal) - || line.StartsWith("Character '", StringComparison.Ordinal) - || line.StartsWith("You cannot transfer", StringComparison.Ordinal) - || line.StartsWith("You don't have enough", StringComparison.Ordinal) - || line.StartsWith("[Transfer]", StringComparison.Ordinal) - || line.StartsWith("[BANK] Too many parameters", StringComparison.Ordinal) - || line.StartsWith("[BANK] Prestige Coins are bound", StringComparison.Ordinal) - || line.StartsWith("Invalid count", StringComparison.Ordinal) - || line.StartsWith("Invalid denomination", StringComparison.Ordinal); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankExport.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankExport.cs deleted file mode 100644 index 65b3949..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBankExport.cs +++ /dev/null @@ -1,151 +0,0 @@ -// IltBankExport.cs - The bank JSON of "RynthILT.Data" (Plugins/Shared/RynthIltDataApi.cs): the -// Banking tab's balances, form choices and log for another plugin's view (every character here). -// -// Every character RynthILT has run on this server keeps its balances in its own hub.json -// (\\\hub.json, IltHubStore); the export lists them all, the -// logged-in character from its live state and the rest from their saved files (read on the pump -// at most every SiblingReadMs, so a reader polling every couple of seconds costs one directory -// listing now and then). Plus the form choices (IltBankCommands), the last action's reply and -// the recent transfers. Build is pure: the tests feed it rows. -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Text; -using System.Text.Json; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal static class IltBankExport -{ - /// How many recent transfers the JSON carries (newest first). - public const int MaxTransactions = 50; - - /// One character's balances as exported. - internal sealed record Row(string Name, bool Current, IltBankState Bank); - - /// - /// The bank JSON. : 1 the server has /bank, 0 not, -1 not known yet. - /// Rows are listed current character first, then by name. Plain ASCII. - /// - public static string Build(bool available, int enabled, string world, string character, IReadOnlyList rows, - string result, IReadOnlyList transactions) - { - var sb = new StringBuilder(4096); - sb.Append("{\"available\":").Append(available ? "true" : "false"); - sb.Append(",\"enabled\":").Append(Math.Clamp(enabled, -1, 1).ToString(CultureInfo.InvariantCulture)); - sb.Append(",\"world\":\"").Append(IltStyle.JsonEscape(world ?? string.Empty)).Append('"'); - sb.Append(",\"character\":\"").Append(IltStyle.JsonEscape(character ?? string.Empty)).Append('"'); - - var ordered = new List(rows); - ordered.Sort((a, b) => a.Current != b.Current ? (a.Current ? -1 : 1) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); - sb.Append(",\"characters\":["); - for (int i = 0; i < ordered.Count; i++) - { - Row r = ordered[i]; - IltBankState b = r.Bank; - if (i > 0) sb.Append(','); - sb.Append("{\"name\":\"").Append(IltStyle.JsonEscape(r.Name)).Append('"'); - sb.Append(",\"current\":").Append(r.Current ? "true" : "false"); - Num(sb, "pyreals", b.Pyreals); - Num(sb, "luminance", b.Luminance); - Num(sb, "legendaryKeys", b.LegendaryKeys); - Num(sb, "mythicalKeys", b.MythicalKeys); - Num(sb, "enlightenedCoins", b.EnlightenedCoins); - Num(sb, "weaklyEnlightenedCoins", b.WeaklyEnlightenedCoins); - Num(sb, "prestigeCoins", b.PrestigeCoins); - sb.Append(",\"updated\":\"").Append(Utc(b.LastUpdated)).Append("\"}"); - } - sb.Append(']'); - - sb.Append(",\"deposits\":["); - for (int i = 0; i < IltBankCommands.Deposits.Length; i++) - { - if (i > 0) sb.Append(','); - sb.Append('"').Append(IltStyle.JsonEscape(IltBankCommands.Deposits[i].Label)).Append('"'); - } - sb.Append(']'); - Choices(sb, "withdrawals", IltBankCommands.Withdrawals, w => w.Code == IltBankCommands.NotesCode); - Choices(sb, "transfers", IltBankCommands.Transfers, t => t.Code == IltBankCommands.NotesCode); - sb.Append(",\"notes\":["); - for (int i = 0; i < IltBankCommands.NoteDenominations.Length; i++) - { - var n = IltBankCommands.NoteDenominations[i]; - if (i > 0) sb.Append(','); - sb.Append("{\"label\":\"").Append(IltStyle.JsonEscape(n.Label)).Append('"'); - Num(sb, "value", n.Value); - sb.Append('}'); - } - sb.Append(']'); - - sb.Append(",\"result\":\"").Append(IltStyle.JsonEscape(result ?? string.Empty)).Append('"'); - sb.Append(",\"transactions\":["); - int written = 0; - for (int i = transactions.Count - 1; i >= 0 && written < MaxTransactions; i--, written++) - { - IltBankTransaction t = transactions[i]; - if (written > 0) sb.Append(','); - sb.Append("{\"when\":\"").Append(t.Timestamp == default ? "" : t.Timestamp.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture)).Append('"'); - sb.Append(",\"type\":\"").Append(IltStyle.JsonEscape(t.Type)).Append('"'); - Num(sb, "amount", t.Amount); - sb.Append(",\"currency\":\"").Append(IltStyle.JsonEscape(t.Currency)).Append('"'); - sb.Append(",\"player\":\"").Append(IltStyle.JsonEscape(t.OtherPlayer)).Append("\"}"); - } - sb.Append("]}"); - return sb.ToString(); - } - - private static void Num(StringBuilder sb, string name, long value) - => sb.Append(",\"").Append(name).Append("\":").Append(value.ToString(CultureInfo.InvariantCulture)); - - private static void Choices(StringBuilder sb, string name, (string Label, string Code)[] items, Func<(string Label, string Code), bool> notes) - { - sb.Append(",\"").Append(name).Append("\":["); - for (int i = 0; i < items.Length; i++) - { - if (i > 0) sb.Append(','); - sb.Append("{\"label\":\"").Append(IltStyle.JsonEscape(items[i].Label)).Append("\",\"notes\":") - .Append(notes(items[i]) ? "true" : "false").Append('}'); - } - sb.Append(']'); - } - - /// A local DateTime as ISO UTC ("" = never). - private static string Utc(DateTime local) => local == DateTime.MinValue || local == default - ? "" - : local.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture); - - /// - /// The other characters' saved balances: every <world folder>\*\hub.json except - /// . A file that can't be read is skipped (its character just - /// isn't listed). Characters never banked (no LastUpdated) are left out. - /// - public static List ReadSiblings(string currentFolder) - { - var rows = new List(); - if (string.IsNullOrEmpty(currentFolder)) return rows; - string? worldDir = Path.GetDirectoryName(currentFolder.TrimEnd('\\', '/')); - if (string.IsNullOrEmpty(worldDir) || !Directory.Exists(worldDir)) return rows; - string self = Path.GetFullPath(currentFolder).TrimEnd('\\', '/'); - foreach (string dir in Directory.EnumerateDirectories(worldDir)) - { - if (string.Equals(Path.GetFullPath(dir).TrimEnd('\\', '/'), self, StringComparison.OrdinalIgnoreCase)) continue; - string file = Path.Combine(dir, IltHubStore.StateFile); - if (!File.Exists(file)) continue; - try - { - using var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); - var state = JsonSerializer.Deserialize(fs, IltHubJsonContext.Default.IltHubState); - IltBankState? bank = state?.Bank; - if (bank == null || bank.LastUpdated == DateTime.MinValue) continue; - rows.Add(new Row(Path.GetFileName(dir), false, bank)); - } - catch (Exception ex) - { - RynthLog.Trace(LogCat.IltBanking, $"bank export: skipped {file} ({ex.Message})"); - } - } - return rows; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBanking.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBanking.cs deleted file mode 100644 index 1275f5e..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBanking.cs +++ /dev/null @@ -1,676 +0,0 @@ -// IltBanking.cs — ILT banking: /bank balances, deposits, withdrawals, confirmed transfers, -// transaction log. Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// Render is the Mini Remote's "Banking" tab. The balances and log are also exported to other -// plugins through "RynthILT.Data" (IltBankExport; their verbs come back through RunVerb). -// -// Server contract (ACECustom PlayerCommands bank handler, upstream 2026-10-11): -// /bank → "[BANK] Your balances are:" then "[BANK] Pyreals: N", "Luminance:", -// "Legendary Keys:", "Mythical Keys:", "Enlightened Coins:", -// "Weakly Enlightened Coins:", "Prestige Coins: N (bound to you ...)". -// /b d, /b lum, /b w → deposits and withdrawals (IltBankCommands has the commands and replies). -// /bank t → "Transferred {N0} {Currency} to {Name}[ (offline)]" or an error; -// the recipient sees "Received {N0} {currency} from {Name}". -// /bank t n → trade notes' pyreal value, then "(Equivalent to ...)". -// What each item allows is IltBankCommands.Items (the server's table): Prestige Coins (pc) -// are bound (deposit and withdraw only); pyreal peas and luminance tokens deposit only. -// Deposit, withdraw and transfer share the server's bank_command_limit throttle; a balance -// refresh doesn't, so it has its own (client-side) spacing. -// Balance lines are parsed whenever they appear (player-typed /bank too) but only EATEN -// when the Hub asked. Transfers always need a confirmation (UB had none). -// Backstop (SilentKelpie's PR 12, narrowed): the capture queue eats a quiet refresh's reply, but if -// it misses, balance-dump lines arriving within QuietBalanceWindowMs of a quiet refresh are eaten -// here. Only the dump itself (header and "Label: N" lines): other [BANK] lines (errors, bound-coin -// notes), Transferred / Received lines, and balance reads nobody here asked for (a macro's or another -// plugin's /bank, outside the window) are left alone. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; -using ImGuiNET; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal sealed class IltBanking : IIltFeature -{ - /// Transfer currencies: display name, /bank t code (IltBankCommands.Transfers). - public static readonly (string Name, string Code)[] Currencies = IltBankCommands.Transfers; - private static readonly string[] CurrencyNames = Currencies.Select(c => c.Name).ToArray(); - private static readonly string[] DepositNames = IltBankCommands.Deposits.Select(d => d.Label).ToArray(); - private static readonly string[] WithdrawNames = IltBankCommands.Withdrawals.Select(w => w.Label).ToArray(); - private static readonly string[] NoteNames = IltBankCommands.NoteDenominations.Select(n => n.Label).ToArray(); - - /// Server throttle for deposit / withdraw / transfer (bank_command_limit). - private const long BankCommandSpacingMs = 5000; - /// Client spacing for balance refreshes (the server doesn't throttle a plain /bank). - private const long BalanceSpacingMs = 5000; - /// After a deposit or withdrawal, the balances are re-read this long after the reply. - private const long RefreshAfterActionMs = 1500; - - 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 _lastBalanceAt; - private long _lastAutoRefreshAt; - /// When a quiet balance refresh is due after an action (0 = none). Pump thread. - private long _refreshDueAt; - /// Until then, money is moving between pack and bank (MovingMoney). Pump thread. - private long _moveUntil; - /// How long after a deposit / withdrawal reply the moved amounts are not income (covers the balance re-read). - private const long MoveWindowMs = 12_000; - /// Until this tick, a balance dump that reaches chat is the reply to a quiet Hub refresh (0 = no quiet refresh out). - private long _quietBalanceUntil; - /// How long after a quiet refresh is queued its leaked dump lines are still eaten here. - internal const long QuietBalanceWindowMs = 15_000; - - // Render-thread form state. - private string _amountText = string.Empty; - private string _withdrawText = string.Empty; - private string _txFilter = string.Empty; - private string _lastResult = string.Empty; - private volatile string _actionResult = string.Empty; - /// The newest action reply or error (deposit, withdrawal or transfer), for the bank export. - private volatile string _latestResult = string.Empty; - - /// - /// Another plugin is showing the balances (a "RynthILT.Data" reader): - /// the periodic quiet refresh runs as it does while the Mini Remote is open. Pump thread. - /// - public bool ReaderWatching; - - /// The newest action reply or error (any thread). - public string LatestResult => _latestResult; - - /// The transaction log as last published (any thread; oldest first). - public IReadOnlyList Transactions => _txSnapshot; - - /// The bank state (pump thread). - public IltBankState State => Bank; - - /// 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); - - /// - /// True while a deposit or withdrawal is moving money between the pack and the bank (sent from - /// this tab or typed): session rates then re-baseline instead of counting it as income. Pump thread. - /// - public bool MovingMoney => IltHubContext.NowMs < _moveUntil; - - /// 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 - _lastBalanceAt < BalanceSpacingMs) return; - _lastBalanceAt = now; - _quietBalanceUntil = quiet ? now + QuietBalanceWindowMs : 0; - _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. For trade notes - /// is the note count of . Pump thread. - /// Returns an error message, or empty when the command was queued. - /// - public string SendTransfer(int currencyIndex, long amount, string target, int denomination = -1) - { - RynthLog.Trace(LogCat.IltBanking, $"SendTransfer(currency={currencyIndex}, amount={amount}, denom={denomination}, target='{target}')"); - if (!Enabled) return "Bank is not available on this server."; - target = (target ?? string.Empty).Trim(); - // The recipient is spliced into a chat command, so only character-name characters are - // allowed: no '/', quotes, control characters or line breaks that could start a second command. - if (target.Length > 0 && !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."; - string cmd = IltBankCommands.Transfer(currencyIndex, amount, denomination, target, out string error); - if (cmd.Length == 0) return error; - long now = IltHubContext.NowMs; - if (now - _lastBankCommandAt < BankCommandSpacingMs) return "Bank commands are limited to one every 5 seconds."; - _lastBankCommandAt = now; - - _ctx.Capture.Enqueue(new IltChatRequest - { - Command = cmd, - IsResponseLine = IltBankCommands.IsTransferReply, - IdleEndMs = 500, - FirstLineTimeoutMs = 8000, - Eat = false, - OnComplete = r => - { - _lastResult = r.Lines.Count > 0 ? r.Lines[^1] : (r.TimedOut ? "No reply from server." : string.Empty); - _latestResult = _lastResult; - // Balances changed: read them again shortly. - _refreshDueAt = IltHubContext.NowMs + RefreshAfterActionMs; - }, - }); - return string.Empty; - } - - /// - /// Sends a deposit ( index). Pump thread. Returns an - /// error message, or empty when the command was queued; the reply lands in the tab. - /// - public string SendDeposit(int index) - { - string cmd = IltBankCommands.Deposit(index); - if (cmd.Length == 0) return "Pick what to deposit."; - return SendAction(cmd, "Deposit"); - } - - /// - /// Sends a withdrawal ( index; for trade notes - /// is the note count). Pump thread; same result as SendDeposit. - /// - public string SendWithdraw(int index, long amount, int denomination) - { - string cmd = IltBankCommands.Withdraw(index, amount, denomination, out string error); - if (cmd.Length == 0) return error; - return SendAction(cmd, "Withdraw"); - } - - /// A deposit or withdrawal through the capture queue (shown, not eaten), then a quiet balance read. - private string SendAction(string cmd, string what) - { - RynthLog.Trace(LogCat.IltBanking, $"{what}: '{cmd}'"); - if (!Enabled) return "Bank is not available on this server."; - long now = IltHubContext.NowMs; - if (now - _lastBankCommandAt < BankCommandSpacingMs) return "Bank commands are limited to one every 5 seconds."; - _lastBankCommandAt = now; - _moveUntil = now + MoveWindowMs; - _actionResult = what + " sent..."; - _ctx.Capture.Enqueue(new IltChatRequest - { - Command = cmd, - IsResponseLine = IltBankCommands.IsActionReply, - IdleEndMs = 800, - FirstLineTimeoutMs = 8000, - Eat = false, - OnComplete = r => - { - _actionResult = r.Lines.Count > 0 ? string.Join("\n", r.Lines.TakeLast(6)) - : r.TimedOut ? "No reply from the server." : string.Empty; - _latestResult = _actionResult; - _refreshDueAt = IltHubContext.NowMs + RefreshAfterActionMs; - }, - }); - return string.Empty; - } - - /// - /// A bank verb line from "RynthILT.Data" BankCommand (Plugins/Shared/RynthIltDataApi.cs): - /// "refresh", "deposit i", "withdraw i amount note", "transfer i amount note name". The reader - /// has already confirmed a transfer with the player. Pump thread. Returns an error, or empty - /// when it was queued; either way the outcome shows in . - /// - public string RunVerb(string line) - { - string[] p = (line ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); - string err; - if (p.Length == 0) err = "Empty bank command."; - else if (p[0] == "refresh" && p.Length == 1) { RequestRefresh(quiet: true); return string.Empty; } - else if (p[0] == "deposit" && p.Length == 2 && int.TryParse(p[1], out int d)) err = SendDeposit(d); - else if (p[0] == "withdraw" && p.Length == 4 && int.TryParse(p[1], out int w) && long.TryParse(p[2], out long wa) - && int.TryParse(p[3], out int wn)) - err = SendWithdraw(w, wa, wn); - else if (p[0] == "transfer" && p.Length >= 5 && int.TryParse(p[1], out int c) && long.TryParse(p[2], out long ta) - && int.TryParse(p[3], out int tn)) - { - // The name may hold spaces; SendTransfer checks it is a character name. - string who = string.Join(' ', p, 4, p.Length - 4); - err = SendTransfer(c, ta, who, IltBankCommands.IsNoteTransfer(c) ? tn : -1); - if (err.Length == 0) _latestResult = "Transfer sent..."; - } - else err = "Unknown bank command."; - if (err.Length > 0) _latestResult = err; - RynthLog.Trace(LogCat.IltBanking, $"reader verb '{line}' -> {(err.Length > 0 ? err : "queued")}"); - return err; - } - - // ── IIltFeature ───────────────────────────────────────────────────────── - - public void Tick(long nowMs) - { - // Periodic quiet refresh only while the balances are on screen (the Hub, or a reader's - // Banking tab) and the server has /bank. - int every = Bank.AutoRefreshSeconds; - if (Enabled && (_ctx.WindowOpen || ReaderWatching) && every > 0 && nowMs - _lastAutoRefreshAt >= every * 1000L - && nowMs - _lastBalanceAt >= BalanceSpacingMs) - { - _lastAutoRefreshAt = nowMs; - RequestRefresh(quiet: true); - } - // The balance read a deposit, withdrawal or transfer asked for (retried until the spacing allows). - if (_refreshDueAt != 0 && nowMs >= _refreshDueAt && Enabled && nowMs - _lastBalanceAt >= BalanceSpacingMs) - { - _refreshDueAt = 0; - _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)) - { - bool dump = ParseBalanceLine(text); - // Eating is decided by the capture queue; this only backs it up for a quiet refresh's dump. - return EatLeakedDump(dump, IltHubContext.NowMs, _quietBalanceUntil); - } - // A deposit or withdrawal reply (ours or a typed /b): the next balance and pack changes are moves. - if (text.StartsWith("Deposited ", StringComparison.Ordinal) || text.StartsWith("Withdrew ", StringComparison.Ordinal)) - _moveUntil = Math.Max(_moveUntil, IltHubContext.NowMs + MoveWindowMs); - TryLogTransaction(text); - return false; - } - - public void OnLogout() - { - lock (_txLock) _ctx.Store.SaveTransactionsIfDirty(_transactions); - } - - // ── Parsing ───────────────────────────────────────────────────────────── - - /// - /// True when a quiet refresh's dump line that reached chat should be eaten here: it is a balance - /// line (see ) and a quiet refresh was queued within the window. - /// - internal static bool EatLeakedDump(bool isBalanceLine, long nowMs, long quietUntilMs) - => isBalanceLine && quietUntilMs != 0 && nowMs < quietUntilMs; - - /// The balance key a dump label belongs to ("Weakly Enlightened Coins" -> WeaklyEnlightenedCoins), or null. - internal static string? BalanceKeyFor(string label) - { - // Order matters: "Weakly Enlightened Coins" also contains "Enlightened Coins". - if (label.Contains("Prestige", StringComparison.OrdinalIgnoreCase)) return "PrestigeCoins"; - if (label.Contains("Weakly", StringComparison.OrdinalIgnoreCase)) return "WeaklyEnlightenedCoins"; - if (label.Contains("Enlightened", StringComparison.OrdinalIgnoreCase)) return "EnlightenedCoins"; - if (label.Contains("Mythical", StringComparison.OrdinalIgnoreCase)) return "MythicalKeys"; - if (label.Contains("Legendary", StringComparison.OrdinalIgnoreCase)) return "LegendaryKeys"; - if (label.Contains("Luminance", StringComparison.OrdinalIgnoreCase)) return "Luminance"; - if (label.Contains("Pyreal", StringComparison.OrdinalIgnoreCase)) return "Pyreals"; - return null; - } - - /// - /// True when a "[BANK] ..." line is part of the /bank balance dump: the "Your balances are:" header - /// or a "Label: N" line for a known currency. Errors, the bound-coin note and the like are not. - /// - internal static bool IsBalanceDumpLine(string text) - { - if (!text.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase)) return false; - string body = text.Substring("[BANK]".Length).Trim(); - if (body.StartsWith("Your balances", StringComparison.OrdinalIgnoreCase)) return true; - int colon = body.IndexOf(':'); - if (colon <= 0) return false; - if (body.Substring(colon + 1).Trim().Length == 0) return true; // a header ending in a colon - return BalanceKeyFor(body.Substring(0, colon).Trim()) != null; - } - - /// Reads a "[BANK] ..." line into the balances. Returns . - private bool ParseBalanceLine(string text) - { - if (!IsBalanceDumpLine(text)) return false; - string body = text.Substring("[BANK]".Length).Trim(); - int colon = body.IndexOf(':'); - if (colon <= 0 || body.Substring(colon + 1).Trim().Length == 0) return true; // a header: nothing to read - string label = body.Substring(0, colon).Trim(); - long value = IltParse.ParseLeadingLong(body.Substring(colon + 1)); - - switch (BalanceKeyFor(label)) - { - case "PrestigeCoins": Apply("PrestigeCoins", ref Bank.PrestigeCoins, value); break; - case "WeaklyEnlightenedCoins": Apply("WeaklyEnlightenedCoins", ref Bank.WeaklyEnlightenedCoins, value); break; - case "EnlightenedCoins": Apply("EnlightenedCoins", ref Bank.EnlightenedCoins, value); break; - case "MythicalKeys": Apply("MythicalKeys", ref Bank.MythicalKeys, value); break; - case "LegendaryKeys": Apply("LegendaryKeys", ref Bank.LegendaryKeys, value); break; - case "Luminance": Apply("Luminance", ref Bank.Luminance, value); break; - case "Pyreals": Apply("Pyreals", ref Bank.Pyreals, value); break; - default: return false; - } - - Bank.LastUpdated = DateTime.Now; - _ctx.Options.Set(IltFeature.Bank, IltTri.On); - return true; - } - - private void Apply(string key, ref long field, long value) - { - 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(); - SafeImGui.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); - Row("Prestige Coins", Bank.PrestigeCoins); - if (ImGui.IsItemHovered()) ImGui.SetTooltip("Bound to you: deposit and withdraw only, never transferred."); - 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(); - RenderDepositWithdraw(); - 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)})"); - } - - /// Deposit (one kind or everything, luminance tokens included) and withdraw (an amount, or trade notes). - private void RenderDepositWithdraw() - { - ImGui.TextColored(IltStyle.ColTeal, "Deposit"); - int dep = Math.Clamp(Bank.DepositIndex, 0, DepositNames.Length - 1); - ImGui.SetNextItemWidth(200); - if (ImGui.Combo("##bankdep", ref dep, DepositNames, DepositNames.Length)) Bank.DepositIndex = dep; - ImGui.SameLine(); - if (ImGui.Button("Deposit##bankdep")) - { - int index = dep; - _ctx.Post(() => { string err = SendDeposit(index); if (err.Length > 0) _actionResult = err; }); - } - if (ImGui.IsItemHovered()) - SafeImGui.SetTooltip(IltBankCommands.Deposit(dep) + "\nEverything banks all currencies, notes and luminance tokens." - + "\nThe server refuses while you are busy or moving."); - - ImGui.TextColored(IltStyle.ColTeal, "Withdraw"); - int wd = Math.Clamp(Bank.WithdrawIndex, 0, WithdrawNames.Length - 1); - ImGui.SetNextItemWidth(200); - if (ImGui.Combo("##bankwd", ref wd, WithdrawNames, WithdrawNames.Length)) Bank.WithdrawIndex = wd; - bool notes = IltBankCommands.Withdrawals[wd].Code == "n"; - int denom = Math.Clamp(Bank.WithdrawNoteIndex, 0, NoteNames.Length - 1); - if (notes) - { - ImGui.SameLine(); - ImGui.SetNextItemWidth(110); - if (ImGui.Combo("##bankwdnote", ref denom, NoteNames, NoteNames.Length)) Bank.WithdrawNoteIndex = denom; - } - ImGui.SetNextItemWidth(200); - ImGui.InputTextWithHint("##bankwdamt", notes ? "how many notes" : "amount, e.g. 250000, 1.5m", ref _withdrawText, 32u); - bool ok = IltParse.TryParseAmount(_withdrawText, out long amount); - ImGui.SameLine(); - ImGui.BeginDisabled(!ok); - if (ImGui.Button("Withdraw##bankwd")) - { - int index = wd, note = denom; - long amt = amount; - _ctx.Post(() => { string err = SendWithdraw(index, amt, note); if (err.Length > 0) _actionResult = err; }); - } - ImGui.EndDisabled(); - if (_withdrawText.Length > 0) - { - ImGui.SameLine(); - if (!ok) ImGui.TextColored(IltStyle.ColHp, "invalid amount"); - else if (notes) SafeImGui.TextDisabled("= " + IltParse.N0(amount * IltBankCommands.NoteDenominations[denom].Value) + " pyreals"); - else SafeImGui.TextDisabled("= " + IltParse.N0(amount)); - } - - string result = _actionResult; - if (result.Length > 0) SafeImGui.TextWrapped(result); - } - - private void RenderTransferForm() - { - ImGui.TextColored(IltStyle.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; - bool notes = IltBankCommands.IsNoteTransfer(idx); - int denom = Math.Clamp(Bank.TransferNoteIndex, 0, NoteNames.Length - 1); - if (notes) - { - ImGui.SetNextItemWidth(200); - if (ImGui.Combo("Denomination##xfer", ref denom, NoteNames, NoteNames.Length)) Bank.TransferNoteIndex = denom; - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("The server moves the notes' pyreal value from your bank (/b t n )."); - } - - ImGui.SetNextItemWidth(200); - ImGui.InputTextWithHint("Amount##xfer", notes ? "how many notes" : "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.TextColored(IltStyle.ColHp, "invalid amount"); - else if (notes) SafeImGui.TextDisabled("= " + IltParse.N0(IltBankCommands.NoteValue(denom, amount)) + " pyreals"); - else SafeImGui.TextDisabled("= " + IltParse.N0(amount)); - } - - ImGui.BeginDisabled(!amountOk || string.IsNullOrWhiteSpace(Bank.TransferTarget)); - if (ImGui.Button("Send transfer...")) - { - int cur = idx, note = notes ? denom : -1; - long amt = amount; - string who = Bank.TransferTarget.Trim(); - string what = notes - ? $"{IltParse.N0(amt)} {IltBankCommands.NoteDenominations[denom].Label} trade notes ({IltParse.N0(IltBankCommands.NoteValue(denom, amt))} pyreals)" - : $"{IltParse.N0(amt)} {Currencies[cur].Name}"; - _ctx.Confirm("Confirm bank transfer", - $"Send {what} to {who}?\n\nThis cannot be undone.", - () => - { - string err = SendTransfer(cur, amt, who, note); - _lastResult = err.Length > 0 ? err : "Transfer sent..."; - }, - "Send"); - } - ImGui.EndDisabled(); - if (_lastResult.Length > 0) SafeImGui.TextWrapped(_lastResult); - } - - private void RenderTransactionLog() - { - var snap = _txSnapshot; - SafeImGui.TextColored(IltStyle.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(); - SafeImGui.TextColored(t.Type == "Sent" ? IltStyle.ColAmber : IltStyle.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)} | " - + $"P Coins: {IltParse.N0(Bank.PrestigeCoins)} | " - + $"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.RynthILT/Hub/IltBreedingEssence.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingEssence.cs deleted file mode 100644 index a708eb3..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingEssence.cs +++ /dev/null @@ -1,316 +0,0 @@ -// IltBreedingEssence.cs - One carried combat pet essence, as the breeding tracker sees it. -// -// The facts come from the essence's appraisal (ACECustom [AssessmentProperty] qualities: bond 9053, -// male charges 9057, next breeding time float 9056, incense float 9058, neutered bool 9051, the -// male override 50053, juvenile 50054, Chromatic Catalyst 50055, the guardian's Offering 50056, -// maturity kills 9077, the mutation lines 9070..9075) and its LongDesc breeding block ("Sex: ...", -// "Growth: ...", "(shiny - cannot breed)"). Evaluate turns them into what the player needs to know: -// stud or dam, every breeding gate that fails, when it clears, growth, and the boosters applied. -// The gates are ACE PetDevice_Breeding's, with the thresholds from IltBreedingRules. -// -// Pure: no host calls (IltPetBreeding reads the host), so RynthILT.Tests checks it offline. -using System; -using System.Collections.Generic; -using System.Globalization; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// A gate's outcome for one essence. -internal enum BreedGate { Ready, Resting, NoCharges, Growing, Neutered, Shiny, LowBond, LowTier, NeedsId } - -/// What was read for one essence (host values; pump thread fills it). -internal sealed class BreedEssenceFacts -{ - public int Id; - public string Name = string.Empty; - public uint Wcid; - public bool HasId; - /// The essence's level requirement (a tier fallback for WCIDs outside the table). - public int UseLevel; - public int Bond; - /// The server's explicit sex (Tailoring Kit), or null to derive it from the object id. - public bool? MaleOverride; - public bool Neutered; - public bool JuvenileFlag; - /// PetMaturityKills: -1 when absent (the essence was never bred). - public int MaturityKills = -1; - /// PetMaleBreedingCharges: -1 when absent (a full stud). - public int MaleCharges = -1; - public double MaleRefreshUnix; - public double NextBreedUnix; - public double Incense; - public bool Catalyst; - public bool Offering; - public double MaturityXpMult; - public int MutDamage, MutDamageResist, MutCrit, MutVitality, MutPotency, MutationCount; - public int PotencyStored; - public bool Attuned; - public string LongDesc = string.Empty; -} - -/// One essence evaluated for breeding. Immutable; the UI and the reader JSON read it. -internal sealed record BreedEssence( - int Id, string Name, uint Wcid, bool HasId, int Tier, int Bond, bool Male, BreedGate Gate, string Status, - IReadOnlyList Problems, double ReadyAtUnix, int Charges, int ChargesMax, double RefillAtUnix, - bool Bred, bool Juvenile, int Stage, int Stages, string StageName, int Kills, int KillsRequired, int KillsToNext, - double Incense, bool Catalyst, bool Offering, bool Draught, IReadOnlyList Boosters, - int MutD, int MutDR, int MutC, int MutV, int MutP, bool Shiny, bool Unbound, int Potency) -{ - /// Every gate passes now. - public bool Ready => Gate == BreedGate.Ready; - /// The stat mutation lines (damage, damage resist, crit, vitality) summed. - public int StatMutations => MutD + MutDR + MutC + MutV; - /// "Stud" or "Dam". - public string Role => Male ? "Stud" : "Dam"; -} - -internal static class IltBreedingEssence -{ - /// Essence tiers, in the order of each family row below (ACE PetDeviceWcids petLevelIndexes). - public static readonly int[] Tiers = { 50, 80, 100, 125, 150, 180, 200, 250, 300 }; - - // ACECustom PetDeviceWcids: one row per combat pet family, tiers 50 .. 300 in order. "a-b" is a - // run of consecutive WCIDs. Rows copied from Source/ACE.Server/Factories/Tables/Wcids/PetDeviceWcids.cs. - private static readonly string[] FamilyRows = - { - "48942,48944,48945,48946,48947,48948,48956,787801001,787801037", - "49213-49219,787801002,787801038", - "49220-49226,787801003,787801039", - "49227-49232,49212,787801004,787801040", - "48972,49234-49239,787801005,787801041", - "49240-49246,787801006,787801042", - "49247-49253,787801007,787801043", - "49254-49259,49233,787801008,787801044", - "49421-49427,787801009,787801045", - "49428-49434,787801010,787801046", - "49435-49441,787801011,787801047", - "49442-49448,787801012,787801048", - "48959,48961,48963,48965,48967,48969,48957,787801013,787801049", - "49261-49267,787801014,787801050", - "49268-49274,787801015,787801051", - "49275-49280,49260,787801016,787801052", - "49282-49287,49281,787801017,787801053", - "49289-49294,49288,787801018,787801054", - "49296-49301,49295,787801019,787801055", - "49303-49308,49302,787801020,787801056", - "49310-49316,787801021,787801057", - "49317-49323,787801022,787801058", - "49324-49330,787801023,787801059", - "49331-49336,49309,787801024,787801060", - "49338-49344,787801025,787801061", - "49345-49351,787801026,787801062", - "49352-49358,787801027,787801063", - "49359-49364,49337,787801028,787801064", - "49366-49372,787801029,787801065", - "49373-49379,787801030,787801066", - "49380-49386,787801031,787801067", - "49387-49392,49365,787801032,787801068", - "49524-49530,787801033,787801069", - "49531-49537,787801034,787801070", - "49538-49544,787801035,787801071", - "49545-49551,787801036,787801072", - }; - - /// Each family row expanded (tests check every row has one WCID per tier). - internal static readonly uint[][] Families = Array.ConvertAll(FamilyRows, ExpandRow); - - private static readonly Dictionary TierByWcid = BuildTiers(); - - private static uint[] ExpandRow(string row) - { - var list = new List(9); - foreach (string token in row.Split(',')) - { - int dash = token.IndexOf('-'); - if (dash < 0) { list.Add(uint.Parse(token, CultureInfo.InvariantCulture)); continue; } - uint a = uint.Parse(token.AsSpan(0, dash), NumberStyles.Integer, CultureInfo.InvariantCulture); - uint b = uint.Parse(token.AsSpan(dash + 1), NumberStyles.Integer, CultureInfo.InvariantCulture); - for (uint w = a; w <= b; w++) list.Add(w); - } - return list.ToArray(); - } - - private static Dictionary BuildTiers() - { - var d = new Dictionary(); - foreach (uint[] row in Families) - for (int i = 0; i < row.Length && i < Tiers.Length; i++) - d[row[i]] = Tiers[i]; - return d; - } - - /// True for a combat pet essence WCID (the only kind that breeds). - public static bool IsCombatEssence(uint wcid) => TierByWcid.ContainsKey(wcid); - - /// The essence tier for a WCID, else the level requirement when it is a tier, else 0. - public static int TierOf(uint wcid, int useLevel = 0) - { - if (TierByWcid.TryGetValue(wcid, out int t)) return t; - return Array.IndexOf(Tiers, useLevel) >= 0 ? useLevel : 0; - } - - /// ACE PetDevice.IsMale without an override: murmur3 fmix32 on the object id, even = male. - public 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; - } - - /// "3h 05m", "42m", "20s" (0 or less = "now"). - public static string Duration(double seconds) - { - if (seconds <= 0) return "now"; - long s = (long)Math.Ceiling(seconds); - if (s >= 3600) return $"{s / 3600}h {s % 3600 / 60:00}m"; - if (s >= 60) return $"{s / 60}m"; - return $"{s}s"; - } - - /// - /// Evaluates one essence: role, every failing gate (the first is the headline), the ready time, - /// growth and boosters. is unix seconds. - /// - public static BreedEssence Evaluate(BreedEssenceFacts f, IltBreedingRules r, double nowUnix) - { - string desc = f.LongDesc ?? string.Empty; - bool male = f.MaleOverride ?? DeriveIsMale(f.Id); - int tier = TierOf(f.Wcid, f.UseLevel); - int bond = Math.Max(1, f.Bond); - bool shiny = desc.Contains("(shiny - cannot breed)", StringComparison.OrdinalIgnoreCase); - bool bred = f.MaturityKills >= 0; - bool juvenile = f.JuvenileFlag || desc.Contains("cannot breed yet", StringComparison.OrdinalIgnoreCase); - - // Stud charges refill lazily on the server: full again once the refill time has passed. - int max = Math.Max(0, r.GetInt(IltBreedingRules.MaleCharges)); - int charges = f.MaleCharges < 0 ? max : Math.Min(f.MaleCharges, max); - double refillAt = 0; - double refillH = r.Get(IltBreedingRules.MaleRefillHours); - if (male && f.MaleRefreshUnix > 0 && refillH > 0) - { - refillAt = f.MaleRefreshUnix + refillH * 3600.0; - if (nowUnix >= refillAt) { charges = max; refillAt = 0; } - } - if (male && charges >= max) refillAt = 0; - - // Growth (bred essences only): stage from credited kills, as ACE PetDevice_Maturity. - int required = Math.Max(1, r.GetInt(IltBreedingRules.MaturityKills)); - int stages = Math.Max(1, r.GetInt(IltBreedingRules.MaturityStages)); - int kills = Math.Max(0, f.MaturityKills); - int perStage = Math.Max(1, (int)Math.Ceiling(required / (double)stages)); - int stage = juvenile ? Math.Min(stages, kills / perStage + 1) : stages + 1; - int toNext = juvenile ? Math.Max(0, Math.Min(required, stage * perStage) - kills) : 0; - string stageName = juvenile ? r.StageName(stage) : bred ? "Adult" : string.Empty; - if (juvenile && IltBreedingRules.TryParseGrowth(desc, out string seenName, out int seenStage, out _, out int seenNext, out _, out int seenAdult)) - { - // The appraisal line is the server's own math: prefer it when it is there. - stage = seenStage; - stageName = seenName; - toNext = seenNext; - kills = Math.Max(kills, required - seenAdult); - } - - // Every failing gate, in the order the server checks them. - var problems = new List(); - BreedGate gate = BreedGate.Ready; - void Fail(BreedGate g, string text) - { - if (gate == BreedGate.Ready) gate = g; - problems.Add(text); - } - double readyAt = 0; - if (!f.HasId) Fail(BreedGate.NeedsId, "not appraised yet"); - if (f.Neutered) Fail(BreedGate.Neutered, "neutered (permanent)"); - if (shiny) Fail(BreedGate.Shiny, "shiny essences can't breed"); - if (juvenile) Fail(BreedGate.Growing, $"still growing: {stageName} ({Math.Max(0, required - kills)} kills to Adult)"); - int minTier = r.GetInt(IltBreedingRules.MinTier); - if (tier > 0 && tier < minTier) Fail(BreedGate.LowTier, $"tier {tier} (needs {minTier}+)"); - int minBond = r.GetInt(IltBreedingRules.MinBond); - if (f.HasId && bond < minBond) Fail(BreedGate.LowBond, $"bond {bond}/{minBond}"); - if (male && charges <= 0) - { - Fail(BreedGate.NoCharges, refillAt > 0 ? $"no charges (refill in {Duration(refillAt - nowUnix)})" : "no charges left"); - readyAt = Math.Max(readyAt, refillAt); - } - if (!male && f.NextBreedUnix > nowUnix) - { - Fail(BreedGate.Resting, $"resting ({Duration(f.NextBreedUnix - nowUnix)})"); - readyAt = Math.Max(readyAt, f.NextBreedUnix); - } - - string status = gate switch - { - BreedGate.Ready => male ? $"Ready ({charges}/{max})" : "Ready", - BreedGate.Resting => "Rest " + Duration(f.NextBreedUnix - nowUnix), - BreedGate.NoCharges => refillAt > 0 ? "0/" + max + " refill " + Duration(refillAt - nowUnix) : "0/" + max, - BreedGate.Growing => $"{stageName} {Math.Min(stage, stages)}/{stages}", - BreedGate.Neutered => "Neutered", - BreedGate.Shiny => "Shiny", - BreedGate.LowBond => $"Bond {bond}/{minBond}", - BreedGate.LowTier => $"Tier {tier}", - _ => "ID needed", - }; - - bool draught = f.MaturityXpMult > 1.0001; - var boosters = new List(4); - if (f.Incense > 0) boosters.Add(IltBreedingSupplies.IncenseName(f.Incense)); - if (f.Catalyst) boosters.Add("Chromatic Catalyst"); - if (f.Offering) boosters.Add("Offering of Subjugation"); - if (draught) boosters.Add("Nurturing Draught x" + f.MaturityXpMult.ToString("0.#", CultureInfo.InvariantCulture)); - - return new BreedEssence( - f.Id, f.Name, f.Wcid, f.HasId, tier, bond, male, gate, status, problems, readyAt, - male ? charges : 0, male ? max : 0, male ? refillAt : 0, - bred, juvenile, juvenile ? stage : 0, stages, stageName, kills, required, toNext, - Math.Max(0, f.Incense), f.Catalyst, f.Offering, draught, boosters, - Math.Max(0, f.MutDamage), Math.Max(0, f.MutDamageResist), Math.Max(0, f.MutCrit), Math.Max(0, f.MutVitality), - Math.Max(0, f.MutPotency), shiny, bred && !f.Attuned && desc.Contains("Bond: Unbound", StringComparison.OrdinalIgnoreCase), - Math.Max(0, f.PotencyStored)); - } -} - -/// What a stud + dam pairing would do: the gates both must pass, and the baby's odds. -internal sealed record BreedPairPlan(bool CanBreed, IReadOnlyList Blockers, double Incense, double ChanceBest, double ChanceWorst, - double PotencyChance, int InheritMin, int InheritMax, IReadOnlyList Notes); - -internal static class IltBreedingPlanner -{ - /// - /// Plans one pairing. Each stat line comes from one parent, so the baby inherits between the - /// sum of the lower lines and the sum of the higher lines; more inherited mutations lower the - /// stat mutation chance (the decay), so the best case is the fewest. - /// - public static BreedPairPlan Plan(BreedEssence stud, BreedEssence dam, IltBreedingRules r) - { - var blockers = new List(); - if (!stud.Male) blockers.Add($"{stud.Name} is female: the stud must be male."); - if (dam.Male) blockers.Add($"{dam.Name} is male: the dam must be female."); - if (stud.Id == dam.Id) blockers.Add("Pick two different essences."); - foreach (string p in stud.Problems) blockers.Add($"{stud.Name}: {p}"); - foreach (string p in dam.Problems) blockers.Add($"{dam.Name}: {p}"); - - int lo = Math.Min(stud.MutD, dam.MutD) + Math.Min(stud.MutDR, dam.MutDR) + Math.Min(stud.MutC, dam.MutC) + Math.Min(stud.MutV, dam.MutV); - int hi = Math.Max(stud.MutD, dam.MutD) + Math.Max(stud.MutDR, dam.MutDR) + Math.Max(stud.MutC, dam.MutC) + Math.Max(stud.MutV, dam.MutV); - double incense = r.CombinedIncense(stud.Incense, dam.Incense); - - var notes = new List - { - "The baby goes to the dam's owner: they need a free main-pack slot and burden room.", - $"Both pets in the same room of the breeding area ({r.RoomText()}); both owners *dance* within {r.Get(IltBreedingRules.DanceWindow):0.#}s.", - }; - if (stud.Catalyst || dam.Catalyst) notes.Add("Chromatic Catalyst: the baby rolls a fresh colour."); - if (r.Get(IltBreedingRules.GuardianEnabled) >= 0.5) - notes.Add(stud.Offering || dam.Offering - ? "Offering of Subjugation applied: the mating guardian comes weakened." - : $"A mating guardian rises: kill it within {r.Get(IltBreedingRules.GuardianSeconds):0}s for an Awakened Blessing mutation."); - if (incense > 0) notes.Add($"Incense +{incense * 100:0.#}% is used up by this breed."); - - return new BreedPairPlan(blockers.Count == 0, blockers, incense, - r.StatMutationChance(lo, incense), r.StatMutationChance(hi, incense), - Math.Clamp(r.Get(IltBreedingRules.PotencyMutation), 0, 1), lo, hi, notes); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingRules.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingRules.cs deleted file mode 100644 index 6ed05f8..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingRules.cs +++ /dev/null @@ -1,445 +0,0 @@ -// IltBreedingRules.cs - Infinite Leaftide's pet breeding rules as RynthILT knows them. -// -// ACECustom's breeding (Source/ACE.Server/WorldObjects/PetDevice_Breeding.cs, docs/PET_BREEDING_*.md) -// is driven by ServerConfig values the client is never sent. Each rule here therefore has three -// possible sources, best last: -// * ACE default - the ServerConfig default in ACECustom; -// * ILT profile - what Infinite Leaftide runs (deploy/PROD_DEPLOY_PLAN.md: decay 0.1, the -// mating guardian on, pet bond on, the Seedy Motel room); -// * seen on server - read back from this server's own text: the appraisal breeding block -// ("Sex: Male (9/10 breeding charges today) - refills in 3h 10m", "Growth: ..."), -// "@breed-debug" ("Allowed Target: whole landblock 0x106, Variant=2"), and -// breeding chat ("spent a breeding charge: 9/10 left today", "They have 90s ..."). -// A value seen on the server is saved with the character (IltPetState.Breeding) and wins from then on. -// -// Pure: no host calls, so RynthILT.Tests checks every parser offline. -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// Where a breeding rule's value came from (later = more trusted). -internal enum BreedRuleSource { AceDefault = 0, IltProfile = 1, Server = 2 } - -/// One rule: stable key, label, unit, the ACE default and the ILT profile value (null = same as ACE). -internal sealed record BreedRuleDef(string Key, string Label, string Unit, double AceDefault, double? IltProfile, string Help); - -/// A rule's effective value and where it came from. -internal readonly record struct BreedRuleValue(BreedRuleDef Def, double Value, BreedRuleSource Source, DateTime SeenUtc); - -/// A value this server showed, saved with the character. -public sealed class IltLearnedRule -{ - public string Key = string.Empty; - public double Value; - public DateTime SeenUtc; -} - -/// One breeding event from chat (ritual, birth, growth, ...), newest last. -public sealed class IltBreedingEvent -{ - public DateTime Utc; - /// ritual, charge, birth, mutation, guardian, growth, adult, imprint, dance, debug. - public string Kind = string.Empty; - public string Text = string.Empty; -} - -/// The breeding tracker's saved part (IltPetState.Breeding). -public sealed class IltBreedingState -{ - /// Rules read back from this server (see IltBreedingRules). - public List Rules = new(); - /// Growth stage names this server uses, by stage (index 0 = stage 1); "" = not seen yet. - public List StageNames = new(); - /// Recent breeding events (capped at IltBreedingRules.MaxEvents). - public List Log = new(); - /// The last "@breed-debug" reply's lines and when it came. - public List LastDebug = new(); - public DateTime LastDebugUtc; -} - -/// What one "@breed-debug" reply said. -internal sealed record BreedDebugInfo(bool? Enabled, string Location, uint AllowedLandblock, int AllowedVariant, string AllowedKind, - bool? LocationOk, string ActivePet, string PetSex, int Partners); - -internal sealed class IltBreedingRules -{ - // ── Rule keys ─────────────────────────────────────────────────────────── - public const string Landblock = "landblock"; - public const string Variant = "variant"; - public const string DanceWindow = "dance_window_s"; - public const string MinTier = "min_tier"; - public const string MinBond = "min_bond"; - public const string MaleCharges = "male_charges"; - public const string MaleRefillHours = "male_refill_h"; - public const string FemaleRestHours = "female_rest_h"; - public const string BaseMutation = "base_mutation"; - public const string MutationDecay = "mutation_decay"; - public const string MutationFloor = "mutation_floor"; - public const string PotencyMutation = "potency_mutation"; - public const string IncenseCap = "incense_cap"; - public const string Inheritance = "inheritance"; - public const string GuardianEnabled = "guardian_enabled"; - public const string GuardianSeconds = "guardian_s"; - public const string MaturityKills = "maturity_kills"; - public const string MaturityStages = "maturity_stages"; - public const string MaturityShare = "maturity_share"; - - /// Breeding events kept with the character. - public const int MaxEvents = 60; - - /// ACECustom's default growth stage names (pet_maturity_stage_names). - public static readonly string[] DefaultStageNames = { "Newborn", "Whelp", "Juvenile", "Adolescent", "Young Adult" }; - - /// Every rule shown, in display order. Values copied from ACECustom ServerConfig and the ILT deploy plan. - public static readonly BreedRuleDef[] Defs = - { - new(Landblock, "Breeding room landblock", "hex", 0x0106, null, - "pet_breeding_allowed_landblock: the Seedy Motel (Ruggan's Annex, portal by Prof. Ruggan in Lin 54.7S 73.5E)."), - new(Variant, "Breeding room variant", "", 2, null, "pet_breeding_allowed_variant: the landblock variant the room is in."), - new(DanceWindow, "Dance window", "s", 5, null, "Both owners must *dance* (or @dance) within this many seconds."), - new(MinTier, "Minimum essence tier", "", 100, null, "Both parents must be at least this tier (50, 80, 100, ... 300)."), - new(MinBond, "Minimum bond", "", 100, null, "Both parents need this bond level (bond grows from kills; pet_bond must be on)."), - new(MaleCharges, "Stud charges", "", 10, null, "pet_breeding_male_max_charges: breeds a male can sire per refill."), - new(MaleRefillHours, "Stud refill", "h", 24, null, "pet_breeding_male_charge_reset_hours: charges refill this long after the last refill."), - new(FemaleRestHours, "Dam rest", "h", 4, null, "A female rests this long after each breed before she can breed again."), - new(BaseMutation, "Stat mutation chance", "%", 0.05, null, "pet_breeding_mutation_chance: the base chance of a stat mutation."), - new(MutationDecay, "Mutation decay", "", 0.0, 0.1, - "pet_breeding_mutation_decay: each stat mutation the baby inherits divides the chance by (1 + decay x mutations)."), - new(MutationFloor, "Mutation floor", "%", 0.02, null, "The stat mutation chance never drops below this."), - new(PotencyMutation, "Potency mutation chance", "%", 0.03, null, "An independent roll for a potency mutation."), - new(IncenseCap, "Incense cap", "%", 0.50, null, "Both parents' incense together adds at most this much."), - new(Inheritance, "Dominant line weight", "%", 0.55, null, "Each stat line comes from one parent, 55 / 45."), - new(GuardianEnabled, "Mating guardian", "on/off", 0, 1, - "pet_breeding_guardian_enabled: a spirit rises after the ritual; killing it in time grants an Awakened Blessing mutation."), - new(GuardianSeconds, "Guardian timer", "s", 90, null, "How long the two parents have to kill the guardian."), - new(MaturityKills, "Kills to adulthood", "", 300, null, "pet_maturity_kills_required: a bred baby grows up with this many credited kills."), - new(MaturityStages, "Growth stages", "", 5, null, "pet_maturity_stages: the growth stages before Adult."), - new(MaturityShare, "Kill credit share", "%", 0.10, null, - "A kill counts when the pet dealt this share of the victim's health and the victim's level is at least the essence tier."), - }; - - private static readonly Dictionary DefByKey = BuildIndex(); - - private static Dictionary BuildIndex() - { - var d = new Dictionary(StringComparer.Ordinal); - foreach (BreedRuleDef def in Defs) d[def.Key] = def; - return d; - } - - private readonly IltBreedingState _state; - - /// The saved breeding state; learned values are read from and written to it. - public IltBreedingRules(IltBreedingState state) => _state = state; - - /// The saved state these rules read and update. - public IltBreedingState State => _state; - - /// A copy that never changes (the render thread reads it while the pump learns). - public IltBreedingRules Frozen() - { - var copy = new IltBreedingState { StageNames = new List(_state.StageNames) }; - foreach (IltLearnedRule l in _state.Rules) - copy.Rules.Add(new IltLearnedRule { Key = l.Key, Value = l.Value, SeenUtc = l.SeenUtc }); - return new IltBreedingRules(copy); - } - - /// The effective value of rule (0 for an unknown key). - public double Get(string key) => Value(key).Value; - - /// A whole-number rule (charges, kills, tiers). - public int GetInt(string key) => (int)Math.Round(Get(key)); - - /// The effective value and its source. - public BreedRuleValue Value(string key) - { - if (!DefByKey.TryGetValue(key, out BreedRuleDef? def)) - return new BreedRuleValue(new BreedRuleDef(key, key, "", 0, null, ""), 0, BreedRuleSource.AceDefault, default); - foreach (IltLearnedRule l in _state.Rules) - if (l.Key == key) return new BreedRuleValue(def, l.Value, BreedRuleSource.Server, l.SeenUtc); - return def.IltProfile.HasValue - ? new BreedRuleValue(def, def.IltProfile.Value, BreedRuleSource.IltProfile, default) - : new BreedRuleValue(def, def.AceDefault, BreedRuleSource.AceDefault, default); - } - - /// Every rule's effective value, in display order. - public List All() - { - var list = new List(Defs.Length); - foreach (BreedRuleDef d in Defs) list.Add(Value(d.Key)); - return list; - } - - /// Records a value the server showed. True when it changed what RynthILT knew. - public bool Learn(string key, double value, DateTime utc) - { - if (!DefByKey.ContainsKey(key) || double.IsNaN(value) || double.IsInfinity(value)) return false; - foreach (IltLearnedRule l in _state.Rules) - { - if (l.Key != key) continue; - bool changed = Math.Abs(l.Value - value) > 1e-9; - l.Value = value; - l.SeenUtc = utc; - return changed; - } - _state.Rules.Add(new IltLearnedRule { Key = key, Value = value, SeenUtc = utc }); - return true; - } - - /// Applies every (key, value) an observer returned. True when anything changed. - public bool LearnAll(IEnumerable<(string Key, double Value)> seen, DateTime utc) - { - bool changed = false; - foreach ((string k, double v) in seen) changed |= Learn(k, v, utc); - return changed; - } - - /// Records a growth stage's name (1-based) as the server spelled it. - public bool LearnStageName(int stage, string name) - { - name = (name ?? string.Empty).Trim(); - if (stage < 1 || stage > 50 || name.Length == 0 || name.Length > 40) return false; - while (_state.StageNames.Count < stage) _state.StageNames.Add(string.Empty); - if (_state.StageNames[stage - 1] == name) return false; - _state.StageNames[stage - 1] = name; - return true; - } - - /// The name of growth stage (1-based): seen on the server, else ACE's default, else "Stage N". - public string StageName(int stage) - { - if (stage >= 1 && stage <= _state.StageNames.Count && _state.StageNames[stage - 1].Length > 0) - return _state.StageNames[stage - 1]; - if (stage >= 1 && stage <= DefaultStageNames.Length && GetInt(MaturityStages) == DefaultStageNames.Length) - return DefaultStageNames[stage - 1]; - return "Stage " + stage.ToString(CultureInfo.InvariantCulture); - } - - /// Appends an event, dropping the oldest past . - public void AddEvent(string kind, string text, DateTime utc) - { - _state.Log.Add(new IltBreedingEvent { Utc = utc, Kind = kind, Text = text }); - if (_state.Log.Count > MaxEvents) _state.Log.RemoveRange(0, _state.Log.Count - MaxEvents); - } - - // ── Mutation odds (ACE PetDevice_Breeding) ────────────────────────────── - - /// - /// The chance of a stat mutation for a baby that inherits - /// stat mutations, with from both parents (already capped): - /// clamp(max(floor, (base + incense) / (1 + decay x mutations)), 0, 1). - /// - public double StatMutationChance(int babyStatMutations, double incense) - { - double decay = Math.Max(0, Get(MutationDecay)); - double raw = (Get(BaseMutation) + Math.Max(0, incense)) / (1.0 + decay * Math.Max(0, babyStatMutations)); - return Math.Clamp(Math.Max(Get(MutationFloor), raw), 0.0, 1.0); - } - - /// Both parents' incense together, capped at the incense cap. - public double CombinedIncense(double a, double b) => Math.Clamp(Math.Max(0, a) + Math.Max(0, b), 0.0, Math.Max(0, Get(IncenseCap))); - - // ── Observers: what the server's own text says about its rules ────────── - - private const RegexOptions Rx = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase; - - private static readonly Regex MaleLine = new(@"Sex:\s*Male\s*\((\d+)\s*/\s*(\d+) breeding charges today\)(?:\s*-\s*refills in (?:(\d+)h\s*)?(?:(\d+)m)?)?", Rx); - private static readonly Regex GrowthLine = new(@"Growth:\s*(.+?)\s+(\d+)\s*/\s*(\d+)\s*-\s*(\d+) kills to (.+?)(?:,\s*(\d+) to Adult)?\s*$", Rx | RegexOptions.Multiline); - private static readonly Regex ChargeSpent = new(@"spent a breeding charge:\s*(\d+)\s*/\s*(\d+) left today", Rx); - private static readonly Regex GuardianRise = new(@"They have (\d+)s to bring it down together", Rx); - private static readonly Regex GrownInto = new(@"has grown into an? (.+?)!.*\((\d+)\s*/\s*(\d+)\)", Rx); - private static readonly Regex DanceWindowLine = new(@"\*dance\* within (\d+(?:\.\d+)?) seconds", Rx); - private static readonly Regex DebugEnabled = new(@"Breeding System Enabled:\s*(True|False)", Rx); - private static readonly Regex DebugLocation = new(@"Your Location:\s*(.+)$", Rx); - private static readonly Regex DebugAllowed = new(@"Allowed Target:\s*(anywhere|whole landblock|exact cell)\s*0x([0-9A-F]+),\s*Variant=(-?\d+)\s*=>\s*Location Match:\s*(VALID|INVALID)", Rx); - private static readonly Regex DebugPet = new(@"Your Active Pet:\s*(.+)$", Rx); - private static readonly Regex DebugSex = new(@"^\s*Sex:\s*(.+)$", Rx); - private static readonly Regex DebugPartners = new(@"(?:Eligible breeding partners nearby|Valid Partner Candidates within 30m):\s*(\d+)", Rx); - - /// - /// What an essence's appraisal text says: the stud's charge max and refill window (from the - /// "refills in" countdown against the essence's last refill time), and the growth stage count. - /// - /// The appraisal LongDesc (string 16). - /// The essence's PetMaleChargesRefreshTime (0 = not sent). - /// Now, unix seconds. - public static List<(string Key, double Value)> FromAppraisal(string longDesc, double maleRefreshUnix, double nowUnix) - { - var seen = new List<(string, double)>(); - if (string.IsNullOrEmpty(longDesc)) return seen; - - Match m = MaleLine.Match(longDesc); - if (m.Success) - { - if (int.TryParse(m.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int max) && max > 0 && max < 1000) - seen.Add((MaleCharges, max)); - if ((m.Groups[3].Success || m.Groups[4].Success) && maleRefreshUnix > 0) - { - int h = m.Groups[3].Success ? int.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture) : 0; - int min = m.Groups[4].Success ? int.Parse(m.Groups[4].Value, CultureInfo.InvariantCulture) : 0; - double refillAt = nowUnix + h * 3600.0 + min * 60.0; - double hours = Math.Round((refillAt - maleRefreshUnix) / 3600.0); - // The countdown is minute-rounded; only a whole-hour window that makes sense is taken. - if (hours >= 1 && hours <= 24 * 14) seen.Add((MaleRefillHours, hours)); - } - } - - Match g = GrowthLine.Match(longDesc); - if (g.Success && int.TryParse(g.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int stages) && stages >= 1 && stages <= 50) - seen.Add((MaturityStages, stages)); - return seen; - } - - /// - /// The growth line of an appraisal: current stage name, stage, stages, kills to the next stage - /// and to adulthood (-1 when the line has no "to Adult" part, i.e. the last stage). - /// - public static bool TryParseGrowth(string longDesc, out string stageName, out int stage, out int stages, out int toNext, out string nextName, out int toAdult) - { - stageName = nextName = string.Empty; - stage = stages = toNext = toAdult = 0; - if (string.IsNullOrEmpty(longDesc)) return false; - Match g = GrowthLine.Match(longDesc); - if (!g.Success) return false; - stageName = g.Groups[1].Value.Trim(); - int.TryParse(g.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out stage); - int.TryParse(g.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out stages); - int.TryParse(g.Groups[4].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out toNext); - nextName = g.Groups[5].Value.Trim(); - if (g.Groups[6].Success) int.TryParse(g.Groups[6].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out toAdult); - else { toAdult = toNext; nextName = "Adult"; } - return true; - } - - /// What one chat line says about the rules (a line can say nothing). - public static List<(string Key, double Value)> FromChat(string line) - { - var seen = new List<(string, double)>(); - if (string.IsNullOrEmpty(line)) return seen; - - Match m = ChargeSpent.Match(line); - if (m.Success && int.TryParse(m.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int max) && max > 0 && max < 1000) - seen.Add((MaleCharges, max)); - - m = GuardianRise.Match(line); - if (m.Success) - { - seen.Add((GuardianEnabled, 1)); - if (int.TryParse(m.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int s) && s > 0 && s < 3600) - seen.Add((GuardianSeconds, s)); - } - else if (line.Contains("The union stirs something", StringComparison.OrdinalIgnoreCase)) - seen.Add((GuardianEnabled, 1)); - - m = GrownInto.Match(line); - if (m.Success && int.TryParse(m.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int stages) && stages >= 1 && stages <= 50) - seen.Add((MaturityStages, stages)); - - m = DanceWindowLine.Match(line); - if (m.Success && double.TryParse(m.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out double w) && w > 0 && w < 600) - seen.Add((DanceWindow, w)); - - foreach (string part in line.Split('\n')) - { - m = DebugAllowed.Match(part); - if (!m.Success) continue; - if (uint.TryParse(m.Groups[2].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint lb)) - seen.Add((Landblock, lb)); - if (int.TryParse(m.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v)) - seen.Add((Variant, v)); - } - return seen; - } - - /// The stage name a "has grown into a Whelp! ... (2/5)" line gives, with its stage number; false for any other line. - public static bool TryParseGrownInto(string line, out int stage, out string name) - { - stage = 0; - name = string.Empty; - Match m = GrownInto.Match(line ?? string.Empty); - if (!m.Success || !int.TryParse(m.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out stage)) return false; - name = m.Groups[1].Value.Trim(); - return name.Length > 0; - } - - /// True for any line of an "@breed-debug" reply (one multi-line message, or its lines one by one). - public static bool IsDebugLine(string text) - { - if (string.IsNullOrEmpty(text)) return false; - return text.Contains("PET BREEDING DIAGNOSTICS", StringComparison.OrdinalIgnoreCase) - || DebugEnabled.IsMatch(text) || DebugLocation.IsMatch(text) || DebugAllowed.IsMatch(text) - || DebugPet.IsMatch(text) || DebugPartners.IsMatch(text) - || text.TrimStart().StartsWith("Sex:", StringComparison.OrdinalIgnoreCase) - || text.Contains("Ensure your partner has their pet summoned", StringComparison.OrdinalIgnoreCase) - || IsDebugEnd(text); - } - - /// The reply's closing rule of '=' (alone, or ending the whole message). - public static bool IsDebugEnd(string text) - => !string.IsNullOrEmpty(text) && text.TrimEnd().EndsWith("================================", StringComparison.Ordinal); - - /// Parses an "@breed-debug" reply (any mix of whole messages and single lines). - public static BreedDebugInfo ParseDebug(IEnumerable lines) - { - bool? enabled = null, ok = null; - string location = string.Empty, kind = string.Empty, pet = string.Empty, sex = string.Empty; - uint lb = 0; - int variant = -1, partners = -1; - foreach (string text in lines) - { - foreach (string raw in (text ?? string.Empty).Split('\n')) - { - string l = raw.TrimEnd('\r'); - Match m; - if ((m = DebugEnabled.Match(l)).Success) enabled = m.Groups[1].Value.Equals("True", StringComparison.OrdinalIgnoreCase); - else if ((m = DebugAllowed.Match(l)).Success) - { - kind = m.Groups[1].Value.ToLowerInvariant(); - uint.TryParse(m.Groups[2].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lb); - int.TryParse(m.Groups[3].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out variant); - ok = m.Groups[4].Value.Equals("VALID", StringComparison.OrdinalIgnoreCase); - } - else if ((m = DebugLocation.Match(l)).Success) location = m.Groups[1].Value.Trim(); - else if ((m = DebugPet.Match(l)).Success) pet = m.Groups[1].Value.Trim(); - else if ((m = DebugPartners.Match(l)).Success) int.TryParse(m.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out partners); - else if ((m = DebugSex.Match(l)).Success) sex = m.Groups[1].Value.Trim(); - } - } - return new BreedDebugInfo(enabled, location, lb, variant, kind, ok, pet, sex, partners); - } - - /// "0x0106 variant 2" (or "anywhere") for the rules list. - public string RoomText() - { - uint lb = (uint)Math.Max(0, Get(Landblock)); - int variant = GetInt(Variant); - if (lb == 0) return "anywhere"; - string place = lb > 0xFFFF ? "cell 0x" + lb.ToString("X8", CultureInfo.InvariantCulture) : "landblock 0x" + lb.ToString("X4", CultureInfo.InvariantCulture); - return variant >= 0 ? place + " variant " + variant.ToString(CultureInfo.InvariantCulture) : place; - } - - /// A rule value for display: "5%", "24h", "0x0106", "on", "10". - public static string Format(BreedRuleValue v) - { - switch (v.Def.Unit) - { - case "%": return (v.Value * 100.0).ToString("0.##", CultureInfo.InvariantCulture) + "%"; - case "h": return v.Value.ToString("0.#", CultureInfo.InvariantCulture) + "h"; - case "s": return v.Value.ToString("0.#", CultureInfo.InvariantCulture) + "s"; - case "hex": return "0x" + ((uint)Math.Max(0, v.Value)).ToString("X4", CultureInfo.InvariantCulture); - case "on/off": return v.Value >= 0.5 ? "on" : "off"; - default: return v.Value.ToString("0.##", CultureInfo.InvariantCulture); - } - } - - /// "ACE default", "ILT profile" or "seen on server". - public static string SourceText(BreedRuleSource s) => s switch - { - BreedRuleSource.Server => "seen on server", - BreedRuleSource.IltProfile => "ILT profile", - _ => "ACE default", - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingSupplies.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingSupplies.cs deleted file mode 100644 index 33381d0..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBreedingSupplies.cs +++ /dev/null @@ -1,112 +0,0 @@ -// IltBreedingSupplies.cs - Ivo's breeding supplies (ACECustom, Seedy Motel vendor) and when each can -// be used on an essence. -// -// WCIDs, prices and refusals copied from ACECustom (Player_Use.cs HandleActionUseOnTarget, the -// PetDevice.BreedingMath incense constants, docs/PET_BREEDING_PLAYER_GUIDE.md). RynthILT applies -// only the breeding boosters (incense, Nurturing Draught, Chromatic Catalyst, Offering of -// Subjugation), and only after the player confirms; the Neutering Kit is permanent and the kits, -// serum and tinctures are cosmetic, so those are counted, never used from here. -// -// Pure: RynthILT.Tests checks the refusals offline. -using System; -using System.Globalization; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// One supply: key, WCID, name, what it does, Ivo's price, and whether the tracker can apply it. -internal sealed record BreedSupplyDef(string Key, uint Wcid, string Name, string Effect, long Price, bool Apply); - -internal static class IltBreedingSupplies -{ - public const string LesserIncense = "incense1"; - public const string RefinedIncense = "incense2"; - public const string ExquisiteIncense = "incense3"; - public const string Draught = "draught"; - public const string Catalyst = "catalyst"; - public const string Offering = "offering"; - public const string NeuteringKit = "neuter"; - public const string TailoringKit = "tailor"; - public const string FilledTailoringKit = "tailor_filled"; - public const string Serum = "serum"; - public const string Solidifying = "solidify"; - public const string Fading = "fade"; - - /// Every supply, boosters first. - public static readonly BreedSupplyDef[] All = - { - new(LesserIncense, 78780250, "Lesser Courtship Incense", "+2.5% stat mutation chance on the next breed.", 1_250_000, true), - new(RefinedIncense, 78780251, "Refined Courtship Incense", "+5% stat mutation chance on the next breed.", 2_500_000, true), - new(ExquisiteIncense, 78780252, "Exquisite Courtship Incense", "+10% stat mutation chance on the next breed.", 5_000_000, true), - new(Draught, 78780253, "Nurturing Draught", "A juvenile earns 2x maturity kill credit until adulthood.", 2_500_000, true), - new(Catalyst, 78780254, "Chromatic Catalyst", "The next baby rolls a fresh colour.", 2_500_000, true), - new(Offering, 78780255, "Offering of Subjugation", "The next mating guardian comes weakened.", 2_500_000, true), - new(NeuteringKit, 78780258, "Neutering Kit", "Permanently stops an essence from breeding.", 2_500_000, false), - new(TailoringKit, 78780259, "Tailoring Kit", "Extracts an essence's appearance.", 125_000_000, false), - new(FilledTailoringKit, 78780260, "Filled Tailoring Kit", "Applies an extracted appearance.", 0, false), - new(Serum, 78780257, "Mutagenic Serum", "Re-rolls an essence's colour.", 25_000_000, false), - new(Solidifying, 78780262, "Solidifying Tincture", "Makes the summoned pet less translucent.", 12_500_000, false), - new(Fading, 78780263, "Fading Tincture", "Makes the summoned pet more translucent.", 12_500_000, false), - }; - - /// The supply with this key, or null. - public static BreedSupplyDef? Find(string key) => Array.Find(All, s => s.Key == key); - - /// The incense bonus a supply gives (0 for anything else). - public static double IncenseBonus(string key) => key switch - { - LesserIncense => 0.025, - RefinedIncense => 0.05, - ExquisiteIncense => 0.10, - _ => 0, - }; - - /// "Refined incense +5%" for an applied bonus. - public static string IncenseName(double bonus) - { - string grade = bonus >= 0.0999 ? "Exquisite" : bonus >= 0.0499 ? "Refined" : "Lesser"; - return $"{grade} incense +{(bonus * 100).ToString("0.#", CultureInfo.InvariantCulture)}%"; - } - - /// - /// Why the server would refuse on (the server's own - /// checks, so nothing is spent on a refusal), or null when it would take it. - /// - public static string? RefuseReason(BreedSupplyDef s, BreedEssence e, IltBreedingRules r) - { - if (!s.Apply) return "Not applied from here."; - double incense = IncenseBonus(s.Key); - if (incense > 0) - { - if (e.Gate == BreedGate.Neutered) return "A neutered essence can't take incense."; - if (e.Incense >= incense - 1e-6) return $"Already primed with equal or stronger incense (+{e.Incense * 100:0.#}%)."; - return null; - } - return s.Key switch - { - Draught when !e.Juvenile => "Only a juvenile (still growing) can take a Nurturing Draught.", - Draught when e.Draught => "Already under a Nurturing Draught.", - Catalyst when e.Catalyst => "Already infused with a Chromatic Catalyst.", - Offering when r.Get(IltBreedingRules.GuardianEnabled) < 0.5 => "Mating guardians are off on this server.", - Offering when e.Offering => "Already under an Offering of Subjugation.", - _ => null, - }; - } - - /// A warning to show in the confirmation (a weaker incense being replaced), or "". - public static string Warning(BreedSupplyDef s, BreedEssence e) - { - double incense = IncenseBonus(s.Key); - if (incense > 0 && e.Incense > 0 && e.Incense < incense) - return $" It replaces the +{e.Incense * 100:0.#}% incense already on it (that one is lost)."; - return string.Empty; - } - - /// "1.25M", "125M", "-" for a price. - public static string PriceText(long price) - { - if (price <= 0) return "-"; - if (price >= 1_000_000) return (price / 1_000_000.0).ToString("0.##", CultureInfo.InvariantCulture) + "M"; - if (price >= 1_000) return (price / 1_000.0).ToString("0.#", CultureInfo.InvariantCulture) + "k"; - return price.ToString(CultureInfo.InvariantCulture); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBuffKeepers.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBuffKeepers.cs deleted file mode 100644 index 8380011..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltBuffKeepers.cs +++ /dev/null @@ -1,256 +0,0 @@ -// IltBuffKeepers.cs — Rune-of-Dispel auto-dispel and Surging Strength keeper (Gear tab). -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// -// Both read the player's enchantment list once a second (one shared read). -// Dispel: classifies active spells by NAME (RynthAi's SpellDatabase, through RynthAi.Hub; it 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.Shared; - -namespace RynthCore.Plugin.RynthILT.Hub; - -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]); - // Spell names are RynthAi's spell table (RynthAi.Hub SpellName); without RynthAi nothing is classified. - string name = _ctx.Ai.SpellName(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(IltStyle.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); - SafeImGui.TextDisabled("Status: " + _dispelStatus); - var harm = _harmfulNow; - if (harm.Length > 0) SafeImGui.TextColored(IltStyle.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(IltStyle.ColTeal, "Surging Strength"); - bool ss = G.SurgingStrength; - if (ImGui.Checkbox("Keep Surging Strength up (Empowered Volcanic Ember)", ref ss)) G.SurgingStrength = ss; - SafeImGui.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++) - { - SafeImGui.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.RynthILT/Hub/IltCharmTracker.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharmTracker.cs deleted file mode 100644 index 4581c2a..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharmTracker.cs +++ /dev/null @@ -1,144 +0,0 @@ -// IltCharmTracker.cs — Every ACECustom registry charm's state: the Mini Remote's Charms tab -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// (IltCharms) and RynthPluginGetCharmsJson (an older engine's Settings "Charms Tracking" tab). -// -// 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.RynthILT.Hub; - -internal sealed class IltCharmTracker -{ - private readonly IltHubContext _ctx; - - public IltCharmTracker(IltHubContext ctx) => _ctx = ctx; - - /// - /// One charm's tracked state. is the carried copy a toggle uses - /// (the active one when one is on), 0 when none is carried. - /// - internal readonly record struct CharmState( - IltCharmDef Def, string Acquired, int Count, int Tier, int MaxTier, - IltTri Active, IltTri Server, DateTime LastSeenUtc, int ToggleId = 0); - - /// 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, toggleId = 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; - toggleId = items![0].Id; - 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; toggleId = wo.Id; } - 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, toggleId)); - } - 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(IltStyle.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(IltStyle.JsonEscape(r.Def.Name)).Append('"'); - sb.Append(",\"effect\":\"").Append(IltStyle.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('"'); - // The carried copy a reader's Toggle uses ("RynthILT.Data" ToggleCharm); 0 = none carried. - sb.Append(",\"toggleId\":").Append(unchecked((uint)r.ToggleId)).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.RynthILT/Hub/IltCharms.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharms.cs deleted file mode 100644 index fe85b08..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltCharms.cs +++ /dev/null @@ -1,266 +0,0 @@ -// IltCharms.cs — The Mini Remote's "Charms" ILT tab: every ACECustom registry charm and the -// Guardian Hand, with their toggles. Other plugins read the same list and toggle through -// "RynthILT.Data" (BuildReaderJson / ToggleFromReader). -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// -// Per charm (IltCharmTracker): acquired ("carried" now, "stored" = carried before and remembered -// per character, or no), status ON / OFF from the charm's appraisal or the player's ability flag, -// best tier, and the server's switch when the client has learned it. A carried charm has a -// Toggle (using a charm flips it). The Guardian Hand isn't a registry charm (no published WCID), -// so it is matched by name or a configured WCID and listed under the table with its own Toggle. -// This was the engine Settings panel's "Charms Tracking" tab plus the Gear tab's charm strip. -// Scans run on the pump thread every 3 s while the Mini Remote is on screen; Render reads the -// published arrays only. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; -using ImGuiNET; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal sealed class IltCharms : IIltFeature -{ - private const long ScanIntervalMs = 3000; - - private readonly IltHubContext _ctx; - private readonly IltCharmTracker _tracker; - - /// A Guardian Hand carried now (name or WCID match). - private sealed record HandRow(int Id, string Name, IltTri Status, bool ServerDisabled); - - private volatile IltCharmTracker.CharmState[] _rows = Array.Empty(); - private volatile HandRow[] _hands = Array.Empty(); - private long _lastScan; - - public IltCharms(IltHubContext ctx, IltCharmTracker tracker) - { - _ctx = ctx; - _tracker = tracker; - } - - 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)); - } - - /// Pump thread: the registry table and the carried Guardian Hands. - private void Scan() - { - _rows = _tracker.Evaluate().ToArray(); - var inv = _ctx.Inventory; - var hands = new List(); - foreach (var wo in inv.Items().Where(IsGuardianHand)) - hands.Add(new HandRow(wo.Id, wo.Name, inv.CharmStatus(wo), _ctx.Options.IsOff(IltFeature.Charm("Guardian Hand")))); - _hands = hands.ToArray(); - } - - /// Uses (toggles) a charm (pump thread). - private void Toggle(int id) - { - var wo = _ctx.Inventory.Cache?[id]; - if (wo == null) return; - if (_ctx.Inventory.IsBusy) { _ctx.Chat("[Mini Remote] Busy - try the charm again in a moment."); return; } - _ctx.Inventory.Use(wo); - _lastScan = 0; // re-read the status soon (the appraisal refresh is throttled per item) - } - - /// - /// A Toggle from another plugin ("RynthILT.Data" ToggleCharm). Only - /// a registry charm or Guardian Hand the player carries is used, so a reader can't make the - /// client use anything else. Pump thread. True when it was used. - /// - public bool ToggleFromReader(uint id) - { - if (id == 0 || id > int.MaxValue) return false; - var inv = _ctx.Inventory; - foreach (var wo in inv.Items()) - { - if (wo.Id != (int)id) continue; - if (inv.CharmDefFor(wo) == null && !IsGuardianHand(wo)) return false; - Toggle(wo.Id); - return true; - } - return false; - } - - /// - /// The "RynthILT.Data" charms JSON: the registry charms - /// (IltCharmTracker.BuildJson) plus a "hands" array, every Guardian Hand carried now with its - /// object id (the Toggle's id), status and the server's switch. Pump thread. - /// - public string BuildReaderJson() - { - string json = _tracker.BuildJson(); - if (!_ctx.Options.IsIltLikeWorld || !json.EndsWith("]}", StringComparison.Ordinal)) return json; - var inv = _ctx.Inventory; - string server = _ctx.Options.Get(IltFeature.Charm("Guardian Hand")) switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" }; - var sb = new System.Text.StringBuilder(json, 0, json.Length - 1, json.Length + 256); - sb.Append(",\"hands\":["); - bool first = true; - foreach (var wo in inv.Items().Where(IsGuardianHand)) - { - if (!first) sb.Append(','); - first = false; - string active = inv.CharmStatus(wo) switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" }; - sb.Append("{\"id\":").Append(unchecked((uint)wo.Id)); - sb.Append(",\"name\":\"").Append(IltStyle.JsonEscape(wo.Name)).Append('"'); - sb.Append(",\"active\":\"").Append(active).Append('"'); - sb.Append(",\"server\":\"").Append(server).Append("\"}"); - } - return sb.Append("]}").ToString(); - } - - // ── IIltFeature ───────────────────────────────────────────────────────── - - public void Tick(long nowMs) - { - if (!_ctx.WindowOpen || nowMs - _lastScan < ScanIntervalMs) return; - _lastScan = nowMs; - Scan(); - } - - public bool OnChat(string text) => false; - - public void OnLogout() - { - _rows = Array.Empty(); - _hands = Array.Empty(); - _lastScan = 0; - } - - // ── UI (render thread) ────────────────────────────────────────────────── - - public void Render() - { - var rows = _rows; - if (rows.Length == 0) - { - SafeImGui.TextDisabled(_ctx.WindowOpen ? "Reading your charms..." : "Open the Mini Remote to read your charms."); - RenderGuardianHand(); - return; - } - - int acquired = rows.Count(r => r.Acquired != "no"), active = rows.Count(r => r.Active == IltTri.On); - SafeImGui.TextColored(IltStyle.ColTeal, $"{acquired} of {rows.Length} acquired, {active} active"); - ImGui.SameLine(); - if (ImGui.SmallButton("Refresh##charms")) _ctx.Post(() => { _lastScan = 0; }); - - const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingFixedFit - | ImGuiTableFlags.ScrollY; - float h = Math.Max(140f, ImGui.GetContentRegionAvail().Y - 110f); - if (ImGui.BeginTable("##iltcharms", 6, flags, new Vector2(0, h))) - { - ImGui.TableSetupScrollFreeze(0, 1); - ImGui.TableSetupColumn("Charm", ImGuiTableColumnFlags.WidthStretch); - ImGui.TableSetupColumn("Acquired", ImGuiTableColumnFlags.WidthFixed, 64); - ImGui.TableSetupColumn("Status", ImGuiTableColumnFlags.WidthFixed, 44); - ImGui.TableSetupColumn("Tier", ImGuiTableColumnFlags.WidthFixed, 40); - ImGui.TableSetupColumn("Server", ImGuiTableColumnFlags.WidthFixed, 58); - ImGui.TableSetupColumn("##toggle", ImGuiTableColumnFlags.WidthFixed, 52); - ImGui.TableHeadersRow(); - for (int i = 0; i < rows.Length; i++) RenderRow(i, rows[i]); - ImGui.EndTable(); - } - - RenderGuardianHand(); - ImGui.TextDisabled("Status comes from the charm's appraisal or your ability flag; a charm not carried is inactive."); - ImGui.TextDisabled("Stored = carried by this character before (remembered per character)."); - } - - private void RenderRow(int i, IltCharmTracker.CharmState r) - { - ImGui.PushID(i); - ImGui.TableNextRow(); - - ImGui.TableNextColumn(); - bool carried = r.Acquired == "carried"; - if (carried) ImGui.TextUnformatted(r.Def.Name); - else SafeImGui.TextColored(IltStyle.ColTextMute, r.Def.Name); - if (ImGui.IsItemHovered() && r.Def.Effect.Length > 0) SafeImGui.SetTooltip(r.Def.Effect); - - ImGui.TableNextColumn(); - if (carried) SafeImGui.TextColored(IltStyle.ColGreen, r.Count > 1 ? $"Carried x{r.Count}" : "Carried"); - else if (r.Acquired == "seen") - { - ImGui.TextColored(IltStyle.ColAmber, "Stored"); - if (ImGui.IsItemHovered() && r.LastSeenUtc != default) - SafeImGui.SetTooltip("Last carried " + r.LastSeenUtc.ToString("yyyy-MM-dd")); - } - else ImGui.TextDisabled("No"); - - ImGui.TableNextColumn(); - if (!carried) ImGui.TextDisabled("-"); - else if (r.Active == IltTri.On) ImGui.TextColored(IltStyle.ColGreen, "ON"); - else if (r.Active == IltTri.Off) ImGui.TextColored(IltStyle.ColTextMute, "OFF"); - else - { - ImGui.TextColored(IltStyle.ColAmber, "?"); - if (ImGui.IsItemHovered()) ImGui.SetTooltip("Waiting for the charm's appraisal."); - } - - ImGui.TableNextColumn(); - ImGui.TextUnformatted(r.Tier <= 0 ? "-" : r.MaxTier > 0 ? $"{r.Tier}/{r.MaxTier}" : r.Tier.ToString()); - - ImGui.TableNextColumn(); - if (r.Server == IltTri.Off) - { - ImGui.TextColored(IltStyle.ColHp, "Disabled"); - if (ImGui.IsItemHovered()) ImGui.SetTooltip("The server refused or reported this charm as disabled."); - } - else if (r.Server == IltTri.On) ImGui.TextColored(IltStyle.ColGreen, "Enabled"); - else - { - ImGui.TextDisabled("-"); - if (ImGui.IsItemHovered()) ImGui.SetTooltip("Not reported. The server only tells players when a charm is refused."); - } - - ImGui.TableNextColumn(); - if (carried && r.ToggleId != 0 && r.Server != IltTri.Off) - { - int id = r.ToggleId; - if (ImGui.SmallButton("Toggle")) _ctx.Post(() => Toggle(id)); - } - ImGui.PopID(); - } - - /// The Guardian Hand (not a registry charm): each carried one with a Toggle, and how it is matched. - private void RenderGuardianHand() - { - var hands = _hands; - foreach (var h in hands) - { - ImGui.PushID(h.Id); - if (h.ServerDisabled) SafeImGui.TextDisabled($"{h.Name} - disabled on this server"); - else - { - var col = h.Status == IltTri.On ? IltStyle.ColGreen - : h.Status == IltTri.Off ? IltStyle.ColTextMute : IltStyle.ColAmber; - SafeImGui.TextColored(col, h.Status == IltTri.On ? "ON " : h.Status == IltTri.Off ? "OFF" : " ? "); - ImGui.SameLine(); - ImGui.TextUnformatted(h.Name); - ImGui.SameLine(); - int id = h.Id; - if (ImGui.SmallButton("Toggle")) _ctx.Post(() => Toggle(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.RynthILT/Hub/IltChatCapture.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChatCapture.cs deleted file mode 100644 index 1a31b5d..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChatCapture.cs +++ /dev/null @@ -1,217 +0,0 @@ -// IltChatCapture.cs — Shared "send a server command and collect its reply" helper. -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// -// Every ILT Hub feature that talks to ACECustom (/bank, /aug, /qb, /pets, /xp, /pb, -// the login probe, /myquests, ...) 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.RynthILT.Hub; - -/// 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: only these response lines arm / refresh the idle timer. Header / banner lines - /// still capture, but idle completion waits until a progress line arrives (UB's /aug fetch: - /// dashes and "Advanced Augmentation Levels:" must not start the 2s idle before Creature:). - /// - public Func? ArmsIdle; - /// 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; - /// True once a response line that arms idle has arrived (always true when is null). - private bool _idleArmed; - - /// 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; - // Idle completion only after a progress line when ArmsIdle is set (header alone is not enough). - bool idleReady = _active.ArmsIdle == null || _idleArmed; - if (gotAny && idleReady && now - _lastLineAt >= _active.IdleEndMs) - Finish(); - else if ((!gotAny || !idleReady) && 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); - // Header-only replies (e.g. /aug dashes + banner) must not start the idle clock. - if (_active.ArmsIdle == null || _active.ArmsIdle(text)) - { - _idleArmed = true; - _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; - _idleArmed = req.ArmsIdle == null; // no progress gate → idle can finish after any response line - _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; - _idleArmed = false; - 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.RynthILT/Hub/IltChunkClap.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChunkClap.cs deleted file mode 100644 index c3190ca..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltChunkClap.cs +++ /dev/null @@ -1,672 +0,0 @@ -// IltChunkClap.cs — Lugian-hammer chunking and /clap automation (Gear tab). -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// -// Chunk: uses the Lugian Aetheria Hammer on eligible items, one at a time. The rules follow ub-IT -// (Leaftide AetheriaChunkGuard / IsValidCorruptedWep / CorruptedChunkGuard): -// Aetheria — "Aetheria"/"Coalesced Aetheria" gems, not equipped, appraised, not flagged -// never-chunk (bool 9030), not tinkered (171) or imbued (179), never levelled -// (ItemTotalXp quad 4 == 0), no kept C / CD / CDR rating (gear ints 372 / 374 / 375; -// on by default; only a rating at or above the "rating level" keeps, a lower one -// chunks), and max level (int 319, up to 10 on ILT) under the configured cap. -// A levelled Coalesced piece gets the cap too; an unlevelled one (319 = 0 after -// appraisal, normal for Coalesced) is chunkable, as in ub-IT. RynthILT used to keep -// every unlevelled Coalesced piece forever. -// Corrupted — "Corrupted" melee/missile weapons, not equipped, not never-chunk, no tinks (171), -// no imbue (179), loot-gen workmanship (105) > 0, and cleave (292) <= 1, or <= 2 on a -// two-handed weapon that is not a thrust weapon (RynthILT used to cap every weapon -// at 1, so no two-handed corrupted weapon was ever chunked). Optional keep rules -// (Crushing Blow, Biting Strike, Armor Cleaving, slayer, multi-strike, elemental -// bonus, any spell, max damage, spell ids) are all off by default. -// Peace mode only unless ChunkInCombat. With ChunkInCombat on, a busy client in combat mode no -// longer blocks the hammer (a swinging bot is always busy); peace mode still waits for idle. -// Waits for the result line (10 s max); a target that leaves the pack first counts as chunked -// (ILT does not always send a known line). Each item's skip reason is logged when it changes -// and tallied in the status line. -// The tool is the "Lugian Aetheria Hammer" only. The Lugian Hammer weapons (Flaming, Acid, ...) -// are loot and chunk nothing: the server answers with no result line, so every item timed out -// into the skip list and the status sat on "nothing eligible" (SilentKelpie, 2026-10-15). -// Clap: "/clap all" converts aetheria + trinkets into coins server-side: red (Coalesced level 1-3, -// chunks, powder) with Empyrean Trinkets, blue with Falatacot Trinkets. Auto-clap sends it only -// when a pair is carried. Needs the AutoCraftingEnabled stamp; 30 min ± 2 min interval, first -// attempt ~1 min after enable. -using System; -using System.Collections.Generic; -using System.Linq; -using ImGuiNET; -using RynthCore.Loot; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT.Hub; - -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; - // Last skip reason per item, so each reason is logged once instead of every pass. - private readonly Dictionary _lastSkip = new(); - // Skip reasons of the current pass (reason -> items), shown in the status line. - private readonly Dictionary _passSkips = new(); - - // 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 ─────────────────────────────────────────────────────────────── - - /// Infinite Leaftide's chunking tool. - internal const string HammerName = "Lugian Aetheria Hammer"; - - /// True for the chunking tool only, never a Lugian Hammer weapon. Pure: the tests drive it. - internal static bool IsChunkHammer(string name) => name.Equals(HammerName, StringComparison.OrdinalIgnoreCase); - - private WorldObject? FindHammer() - => _ctx.Inventory.Items().FirstOrDefault(wo => IsChunkHammer(wo.Name) && !_ctx.Inventory.IsEquipped(wo)); - - /// Item kinds the hammer works on (the name and class gate, before any appraisal). - internal enum ChunkKind { None, Aetheria, Corrupted } - - /// - /// Which chunk rules an item falls under, by class and name only. Aetheria chunks and powder - /// are clap material, not hammer targets. Pure: the tests drive it. - /// - internal static ChunkKind KindOf(AcObjectClass cls, string name) - { - if (cls == AcObjectClass.Gem) - { - if (name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase)) return ChunkKind.Aetheria; - if (name.Contains("Aetheria", StringComparison.OrdinalIgnoreCase) - && !name.Contains("Chunk", StringComparison.OrdinalIgnoreCase) - && !name.Contains("Powder", StringComparison.OrdinalIgnoreCase)) - return ChunkKind.Aetheria; - return ChunkKind.None; - } - if (cls is AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon - && name.Contains("Corrupted", StringComparison.OrdinalIgnoreCase)) - return ChunkKind.Corrupted; - return ChunkKind.None; - } - - /// An aetheria piece's chunk facts, read after appraisal. - internal readonly record struct AetheriaFacts( - bool Coalesced, int MaxLevel, bool NeverChunk, long ItemXp, int Tinkers, int Imbue, - int Crit, int CritDamage, int CritDamageResist, string? Unreadable = null); - - /// - /// Why an aetheria piece is kept, or null when it may be chunked (ub-IT AetheriaChunkGuard plus - /// RynthILT's C / CD / CDR keep switches). Pure: the tests drive it. - /// - /// is set when the item's properties could not be read (the - /// host lacks a reader or the appraisal never arrived). A property that failed to read looks - /// exactly like one the item lacks (level 0, no XP, no tinks), so such a piece is kept: an - /// "unlevelled" Coalesced piece is only chunked when its level was truly read as none. - /// - /// - internal static string? AetheriaSkip(IltGearState g, in AetheriaFacts f) - { - if (f.Unreadable != null) return $"item data unreadable ({f.Unreadable})"; - if (f.NeverChunk) return "never-chunk flag"; - if (f.Tinkers != 0 || f.Imbue != 0) return "tinkered or imbued"; - if (f.ItemXp != 0) return "has item XP"; - if (KeptForRatings(g, f.Crit, f.CritDamage, f.CritDamageResist)) return "kept for its C / CD / CDR rating"; - if (!UnderChunkCap(f.MaxLevel, g.ChunkAetheriaUnderLevel, f.Coalesced)) - return f.MaxLevel > 0 ? "level at or above the cap" : "no level read"; - return null; - } - - /// Why an aetheria item is kept (null = chunk it); "appraising" while its data is missing. - private string? AetheriaSkip(WorldObject wo) - { - var inv = _ctx.Inventory; - if (inv.IsEquipped(wo)) return "equipped"; - if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return Appraising; } - string? gap = inv.ReadGap(wo, quads: true); - var f = new AetheriaFacts( - Coalesced: wo.Name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase), - MaxLevel: inv.Int(wo, IltInventory.IntItemMaxLevel), - NeverChunk: inv.Bool(wo, IltInventory.BoolNeverChunk), - ItemXp: inv.Quad(wo, IltInventory.QuadItemTotalXp), - Tinkers: inv.Int(wo, IltInventory.IntNumTimesTinkered), - Imbue: inv.Int(wo, IltInventory.IntImbuedEffect), - Crit: inv.Int(wo, IltInventory.IntGearCrit), - CritDamage: inv.Int(wo, IltInventory.IntGearCritDamage), - CritDamageResist: inv.Int(wo, IltInventory.IntGearCritDamageResist), - Unreadable: gap); - return AetheriaSkip(G, f); - } - - /// The chunk cap in range: 1 (chunk nothing by level) to one past the ILT maximum (every level). - internal static int ClampUnderLevel(int under) => Math.Clamp(under, 1, IltInventory.AetheriaMaxLevel + 1); - - /// - /// True when an aetheria's max level (int 319) is under the cap. A levelled Coalesced piece - /// (ACECustom rolls 1-10; level 6+ can carry a rating) gets the same cap. Level 0 after - /// appraisal: an unlevelled Coalesced piece is chunkable (ub-IT: "ItemMaxLevel 0 after assess - /// is normal"); any other aetheria with no level is never chunked. Pure: the tests drive it. - /// - internal static bool UnderChunkCap(int maxLevel, int under, bool coalesced = false) - => maxLevel > 0 ? maxLevel < ClampUnderLevel(under) : coalesced && maxLevel == 0; - - /// Highest rating level the keep threshold accepts. - internal const int MaxRatingLevel = 50; - - /// The rating keep threshold in range: 1 (any rating keeps) to . - internal static int ClampRatingLevel(int level) => Math.Clamp(level, 1, MaxRatingLevel); - - /// - /// True when an aetheria's C / CD / CDR rating is one the settings keep: its keep switch is on and - /// the rating is at or above the rating level (). - /// A rating below that level does not protect the piece, so e.g. a C 1 Coalesced Aetheria chunks - /// with the level at 2 while a C 2 one is kept. Pure: the tests drive it. - /// - internal static bool KeptForRatings(IltGearState g, int crit, int critDamage, int critDamageResist) - { - int min = ClampRatingLevel(g.KeepAetheriaRatingAtLeast); - return (g.KeepAetheriaWithCrit && crit >= min) - || (g.KeepAetheriaWithCritDamage && critDamage >= min) - || (g.KeepAetheriaWithCritDamageResist && critDamageResist >= min); - } - - private const string Appraising = "appraising"; - private const int SkillTwoHandedCombat = 41; - private const int WeaponTypeTwoHanded = 11; - private const int AttackTypeThrust = 2; - - /// A corrupted weapon's chunk facts, read after appraisal. - internal sealed record CorruptedFacts - { - public bool NeverChunk { get; init; } - public int Tinkers { get; init; } - public int Imbue { get; init; } - public int Workmanship { get; init; } - public int AttackType { get; init; } - public int Cleaving { get; init; } - public int WieldSkill { get; init; } - public int WeaponType { get; init; } - public double CritFrequency { get; init; } - public double CritMultiplier { get; init; } - public double IgnoreArmor { get; init; } - public int Slayer { get; init; } - public int ElementalBonus { get; init; } - public int MaxDamage { get; init; } - public IReadOnlyList Spells { get; init; } = Array.Empty(); - /// What could not be read (null = everything the rules need was); see AetheriaFacts.Unreadable. - public string? Unreadable { get; init; } - } - - /// - /// The most cleave a chunkable corrupted weapon may have (ub-IT IsValidCorruptedWep): 2 on a - /// two-handed weapon that is not a thrust weapon, 1 on everything else. Pure: the tests drive it. - /// - internal static int MaxChunkCleave(int wieldSkill, int weaponType, int attackType) - => (wieldSkill == SkillTwoHandedCombat || weaponType == WeaponTypeTwoHanded) && attackType != AttackTypeThrust ? 2 : 1; - - /// - /// Why a corrupted weapon is kept, or null when it may be chunked: ub-IT's hard rules, then its - /// IdleActs keep rules from the settings. Pure: the tests drive it. - /// - internal static string? CorruptedSkip(IltGearState g, CorruptedFacts f) - { - // A property that failed to read looks like one the weapon lacks (0), which would chunk it. - if (f.Unreadable != null) return $"item data unreadable ({f.Unreadable})"; - - // Hard rules (always on). - if (f.NeverChunk) return "never-chunk flag"; - if (f.Tinkers != 0 || f.Imbue != 0) return "tinkered or imbued"; - if (f.Workmanship <= 0) return "no workmanship"; - if (f.Cleaving > MaxChunkCleave(f.WieldSkill, f.WeaponType, f.AttackType)) return "cleave over the limit"; - - // Keep rules (each off by default). - if (g.KeepCorruptedCrushingBlow && f.CritFrequency > 0) return "kept: Crushing Blow"; - if (g.KeepCorruptedBitingStrike && f.CritMultiplier > 0) return "kept: Biting Strike"; - if (g.KeepCorruptedArmorCleaving && f.IgnoreArmor > 0) return "kept: Armor Cleaving"; - if (g.KeepCorruptedAnySlayer && f.Slayer > 0) return "kept: slayer"; - if (g.KeepCorruptedMultiStrike && f.AttackType is 160 or 166 or 486) return "kept: multi-strike"; - if (g.KeepCorruptedElementalBonus && f.ElementalBonus > 0) return "kept: elemental bonus"; - if (g.KeepCorruptedMaxDamageAtLeast > 0 && f.MaxDamage >= g.KeepCorruptedMaxDamageAtLeast) return "kept: max damage"; - if (f.Spells.Count > 0) - { - if (g.KeepCorruptedAnySpell) return "kept: has a spell"; - var deny = ParseSpellIds(g.KeepCorruptedSpellIds); - if (deny.Count > 0 && f.Spells.Any(deny.Contains)) return "kept: listed spell"; - } - return null; - } - - /// Positive spell ids from a comma / semicolon / whitespace separated list. Pure: the tests drive it. - internal static HashSet ParseSpellIds(string? csv) - { - var ids = new HashSet(); - if (string.IsNullOrWhiteSpace(csv)) return ids; - foreach (var part in csv.Split(new[] { ',', ';', ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) - if (int.TryParse(part, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int id) && id > 0) - ids.Add(id); - return ids; - } - - /// Why a corrupted weapon is kept (null = chunk it); "appraising" while its data is missing. - private string? CorruptedSkip(WorldObject wo) - { - var inv = _ctx.Inventory; - if (inv.IsEquipped(wo)) return "equipped"; - if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return Appraising; } - bool needDoubles = G.KeepCorruptedCrushingBlow || G.KeepCorruptedBitingStrike || G.KeepCorruptedArmorCleaving; - bool needSpells = G.KeepCorruptedAnySpell || !string.IsNullOrWhiteSpace(G.KeepCorruptedSpellIds); - var f = new CorruptedFacts - { - Unreadable = inv.ReadGap(wo, doubles: needDoubles, spells: needSpells), - NeverChunk = inv.Bool(wo, IltInventory.BoolNeverChunk), - Tinkers = inv.Int(wo, IltInventory.IntNumTimesTinkered), - Imbue = inv.Int(wo, IltInventory.IntImbuedEffect), - Workmanship = inv.Int(wo, IltInventory.IntItemWorkmanship), - AttackType = inv.Int(wo, IltInventory.IntAttackType), - Cleaving = inv.Int(wo, IltInventory.IntCleaving), - WieldSkill = inv.Int(wo, IltInventory.IntWieldSkillType), - WeaponType = inv.Int(wo, IltInventory.IntWeaponType), - CritFrequency = inv.Double(wo, IltInventory.FloatCriticalFrequency), - CritMultiplier = inv.Double(wo, IltInventory.FloatCriticalMultiplier), - IgnoreArmor = inv.Double(wo, IltInventory.FloatIgnoreArmor), - Slayer = inv.Int(wo, IltInventory.IntSlayerCreatureType), - ElementalBonus = inv.Int(wo, IltInventory.IntElementalDamageBonus), - MaxDamage = inv.Int(wo, IltInventory.IntDamage), - // Spells are only read when a spell rule is on (the read copies the item's spell list). - Spells = needSpells ? inv.SpellIds(wo) : Array.Empty(), - }; - return CorruptedSkip(G, f); - } - - /// - /// Chunk is allowed while the client is busy only in combat mode with ChunkInCombat on (ub-IT - /// AutoChunkCombatBusyPolicy v2.0.1059: a swinging bot is always busy). Peace mode still waits - /// for idle so the hammer never interrupts another use. Pure: the tests drive it. - /// - internal static bool AllowsChunkWhileBusy(bool isBusy, bool isPeace, bool chunkInCombat) - => !isBusy || (!isPeace && chunkInCombat); - - private WorldObject? NextChunkTarget() - { - _passSkips.Clear(); - foreach (var wo in _ctx.Inventory.Items()) - { - if (_skip.Contains(wo.Id)) continue; - string? reason; - switch (KindOf(wo.ObjectClass, wo.Name)) - { - case ChunkKind.Aetheria when G.AutoChunkAetheria || _manualPass: - reason = AetheriaSkip(wo); - break; - case ChunkKind.Corrupted when G.AutoChunkCorrupted || _manualPass: - reason = CorruptedSkip(wo); - break; - default: - continue; - } - if (reason == null) { _lastSkip.Remove(wo.Id); return wo; } - NoteSkip(wo, reason); - } - return null; - } - - /// Tallies a skip for the status line and logs it once per item and reason. - private void NoteSkip(WorldObject wo, string reason) - { - _passSkips[reason] = _passSkips.TryGetValue(reason, out int n) ? n + 1 : 1; - if (reason == Appraising) return; - if (_lastSkip.TryGetValue(wo.Id, out string? last) && last == reason) return; - _lastSkip[wo.Id] = reason; - RynthLog.Write(LogCat.IltGear, $"chunk: keep 0x{(uint)wo.Id:X8} '{wo.Name}': {reason}"); - } - - /// "3 kept for its C / CD / CDR rating, 1 appraising" — the current pass's skips. - private string PassSkipSummary() - => string.Join(", ", _passSkips.OrderByDescending(kv => kv.Value).Select(kv => $"{kv.Value} {kv.Key}")); - - /// 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; - _skip.Clear(); // a manual pass gives the items that got no answer another try - _chunkStatus = "manual pass started"; - } - - private void TickChunk(long now) - { - if (!G.AutoChunkAetheria && !G.AutoChunkCorrupted && !_manualPass) return; - - if (_waitingOn != 0) - { - int id = _waitingOn; - switch (WaitOutcome(now - _waitStartedAt, _ctx.Inventory.Items().Any(wo => wo.Id == id))) - { - case ChunkWait.Waiting: - return; - case ChunkWait.Gone: - _chunked++; - RynthLog.Write(LogCat.IltGear, $"chunk: 0x{(uint)id:X8} left the pack with no result line; counted as chunked"); - break; - case ChunkWait.TimedOut: - _skip.Add(id); // still carried and no result line: don't hammer the same item forever - RynthLog.Write(LogCat.IltGear, $"chunk: no result line for 0x{(uint)id:X8} in {ChunkResultWaitMs / 1000} s, skipped until a manual pass"); - break; - } - _waitingOn = 0; - } - if (now - _lastChunkAt < Math.Max(500, G.ChunkIntervalMs)) return; - _lastChunkAt = now; - - bool peace = _ctx.Inventory.InPeaceMode; - if (!G.ChunkInCombat && !peace) { _chunkStatus = "waiting for peace mode"; return; } - if (!AllowsChunkWhileBusy(_ctx.Inventory.IsBusy, peace, G.ChunkInCombat)) { _chunkStatus = "waiting for idle"; return; } - - var hammer = FindHammer(); - if (hammer == null) { _chunkStatus = $"no {HammerName} carried"; _manualPass = false; return; } - var target = NextChunkTarget(); - if (target == null) - { - string kept = PassSkipSummary(); - _chunkStatus = (_chunked > 0 ? $"nothing left to chunk ({_chunked} this session)" : "nothing eligible") - + (kept.Length > 0 ? $"; not chunked: {kept}" : "") - + (_skip.Count > 0 ? $"; {_skip.Count} skipped with no answer (Chunk now retries them)" : ""); - _manualPass = false; - return; - } - if (_ctx.Inventory.UseOn(hammer, unchecked((uint)target.Id))) - { - _waitingOn = target.Id; - _waitStartedAt = now; - _chunkStatus = "chunking " + target.Name; - } - } - - // ── Clap ──────────────────────────────────────────────────────────────── - - internal enum ClapPart { None, Red, Blue, Empyrean, Falatacot } - - /// - /// Which side of /clap an item feeds (ACECustom PlayerCommands.HandleClap): red material (Red - /// Coalesced Aetheria, chunks, powder) pairs with Ancient Empyrean Trinkets, blue with Ancient - /// Falatacot Trinkets. Coalesced counts only unrevealed and at level 1-3; level 0 (not read yet) - /// counts, and the server has the last word. With no WCID yet, the chunk and trinket names - /// decide. Pure: the tests drive it. - /// - internal static ClapPart ClapPartOf(uint wcid, string name, int maxLevel) - { - bool lowCoalesced = name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase) && maxLevel <= 3; - switch (wcid) - { - case IltInventory.WcidRedCoalescedAetheria: return lowCoalesced ? ClapPart.Red : ClapPart.None; - case IltInventory.WcidBlueCoalescedAetheria: return lowCoalesced ? ClapPart.Blue : ClapPart.None; - case IltInventory.WcidRedAetheriaChunk: - case IltInventory.WcidRedAetheriaPowder: return ClapPart.Red; - case IltInventory.WcidBlueAetheriaChunk: - case IltInventory.WcidBlueAetheriaPowder: return ClapPart.Blue; - case IltInventory.WcidEmpyreanTrinket: return ClapPart.Empyrean; - case IltInventory.WcidFalatacotTrinket: return ClapPart.Falatacot; - case 0: break; - default: return ClapPart.None; - } - if (name.Equals("Red Aetheria Chunk", StringComparison.OrdinalIgnoreCase)) return ClapPart.Red; - if (name.Equals("Blue Aetheria Chunk", StringComparison.OrdinalIgnoreCase)) return ClapPart.Blue; - if (name.Equals("Ancient Empyrean Trinket", StringComparison.OrdinalIgnoreCase)) return ClapPart.Empyrean; - if (name.Equals("Ancient Falatacot Trinket", StringComparison.OrdinalIgnoreCase)) return ClapPart.Falatacot; - return ClapPart.None; - } - - /// - /// True when /clap has a pair to work with: red material and an Empyrean Trinket, or blue - /// material and a Falatacot Trinket. One side alone gets "You don't have any aetheria materials". - /// Pure: the tests drive it. - /// - internal static bool CanClap(IEnumerable parts) - { - bool red = false, blue = false, empyrean = false, falatacot = false; - foreach (var part in parts) - { - switch (part) - { - case ClapPart.Red: red = true; break; - case ClapPart.Blue: blue = true; break; - case ClapPart.Empyrean: empyrean = true; break; - case ClapPart.Falatacot: falatacot = true; break; - } - } - return (red && empyrean) || (blue && falatacot); - } - - private bool HasClapMaterials() - { - var inv = _ctx.Inventory; - return CanClap(inv.Items().Where(wo => !inv.IsEquipped(wo)) - .Select(wo => ClapPartOf(inv.Wcid(wo), wo.Name, inv.Int(wo, IltInventory.IntItemMaxLevel)))); - } - - /// 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 and trinket pair carried (red + Empyrean, blue + Falatacot)"; 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); - } - - internal enum ChunkResult { None, Busy, Done, Refused } - - /// Where a chunk in flight stands when no chat line has ended the wait. - internal enum ChunkWait { Waiting, Gone, TimedOut } - - /// - /// The wait for a chunk with no result line yet. The hammer destroys the target, so a target - /// that has left the pack was chunked: ILT does not always send a line the classifier knows - /// (Silentkelpie 2026-10-18: a Red Aetheria Chunk arrived and UseDone had no error, yet the - /// item was still filed as skipped after 10 s). Still carried after the wait = timed out. - /// Pure: the tests drive it. - /// - internal static ChunkWait WaitOutcome(long elapsedMs, bool targetStillCarried) - => !targetStillCarried ? ChunkWait.Gone - : elapsedMs >= ChunkResultWaitMs ? ChunkWait.TimedOut - : ChunkWait.Waiting; - - /// - /// What a chat line says about the chunk in flight. ILT names the item and the tool ("You - /// smash the Corrupted Sword with the Lugian Aetheria Hammer."), so a line naming a corrupted - /// item with the hammer, powder or shatter is a result too (combat's "You smash Foo for 147" - /// names neither). Pure: the tests drive it. - /// - internal static ChunkResult ClassifyChat(string text) - { - if (text.StartsWith("You're too busy", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You are too busy", StringComparison.OrdinalIgnoreCase)) - return ChunkResult.Busy; - if (ChunkRefusedLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase))) return ChunkResult.Refused; - if (ChunkDoneLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase))) return ChunkResult.Done; - if (text.Contains("corrupted", StringComparison.OrdinalIgnoreCase) - && (text.Contains("hammer", StringComparison.OrdinalIgnoreCase) || text.Contains("powder", StringComparison.OrdinalIgnoreCase) - || text.Contains("shatter", StringComparison.OrdinalIgnoreCase))) - return ChunkResult.Done; - return ChunkResult.None; - } - - public bool OnChat(string text) - { - if (_waitingOn == 0) return false; - switch (ClassifyChat(text)) - { - case ChunkResult.Busy: - _waitingOn = 0; // retry the same item next interval - break; - case ChunkResult.Done: - _chunked++; - _waitingOn = 0; - break; - case ChunkResult.Refused: - _skip.Add(_waitingOn); - _waitingOn = 0; - break; - } - return false; - } - - public void OnLogout() - { - _waitingOn = 0; - _skip.Clear(); - _lastSkip.Clear(); - _manualPass = false; - _clapWasEnabled = false; - } - - // ── UI (render thread) ────────────────────────────────────────────────── - - public void Render() - { - SafeImGui.TextColored(IltStyle.ColTeal, $"Chunking ({HammerName})"); - 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 = ClampUnderLevel(under); - if (ImGui.IsItemHovered()) - SafeImGui.SetTooltip($"Infinite Leaftide aetheria goes up to level {IltInventory.AetheriaMaxLevel}; {IltInventory.AetheriaMaxLevel + 1} chunks every level.\nA levelled Coalesced Aetheria gets the cap too; an unlevelled one (level 0 after appraisal) is chunked, as in ub-IT."); - bool kc = G.KeepAetheriaWithCrit, kcd = G.KeepAetheriaWithCritDamage, kcdr = G.KeepAetheriaWithCritDamageResist; - ImGui.TextUnformatted("Never chunk aetheria with:"); - ImGui.SameLine(); - if (ImGui.Checkbox("C##keepc", ref kc)) G.KeepAetheriaWithCrit = kc; - if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit rating (GearCrit)."); - ImGui.SameLine(); - if (ImGui.Checkbox("CD##keepcd", ref kcd)) G.KeepAetheriaWithCritDamage = kcd; - if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit Damage rating (GearCritDamage)."); - ImGui.SameLine(); - if (ImGui.Checkbox("CDR##keepcdr", ref kcdr)) G.KeepAetheriaWithCritDamageResist = kcdr; - if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Crit Damage Resist rating (GearCritDamageResist)."); - int ratingAt = G.KeepAetheriaRatingAtLeast; - ImGui.SetNextItemWidth(100); - if (ImGui.InputInt("Keep when the rating is at least##keeprating", ref ratingAt)) G.KeepAetheriaRatingAtLeast = ClampRatingLevel(ratingAt); - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Rating level for the C / CD / CDR switches above (Coalesced Aetheria and revealed aetheria).\n" - + "At or above this level: kept. Below it: the rating does not protect the piece, so it chunks\n" - + "if the level cap and the other rules allow. 1 = any rating keeps."); - if (ImGui.TreeNode("Corrupted weapon keep rules##corrkeep")) - { - // ub-IT IdleActs > Corr Chunk: each matching rule keeps the weapon. - bool cb = G.KeepCorruptedCrushingBlow, bs = G.KeepCorruptedBitingStrike, acl = G.KeepCorruptedArmorCleaving; - bool sl = G.KeepCorruptedAnySlayer, ms = G.KeepCorruptedMultiStrike, el = G.KeepCorruptedElementalBonus, sp = G.KeepCorruptedAnySpell; - if (ImGui.Checkbox("Crushing Blow##ck", ref cb)) G.KeepCorruptedCrushingBlow = cb; - ImGui.SameLine(); - if (ImGui.Checkbox("Biting Strike##ck", ref bs)) G.KeepCorruptedBitingStrike = bs; - ImGui.SameLine(); - if (ImGui.Checkbox("Armor Cleaving##ck", ref acl)) G.KeepCorruptedArmorCleaving = acl; - if (ImGui.Checkbox("Any slayer##ck", ref sl)) G.KeepCorruptedAnySlayer = sl; - ImGui.SameLine(); - if (ImGui.Checkbox("Multi-strike##ck", ref ms)) G.KeepCorruptedMultiStrike = ms; - ImGui.SameLine(); - if (ImGui.Checkbox("Elemental bonus##ck", ref el)) G.KeepCorruptedElementalBonus = el; - if (ImGui.Checkbox("Any spell##ck", ref sp)) G.KeepCorruptedAnySpell = sp; - int maxDmg = G.KeepCorruptedMaxDamageAtLeast; - ImGui.SetNextItemWidth(100); - if (ImGui.InputInt("Keep max damage at least (0 = off)##ck", ref maxDmg)) G.KeepCorruptedMaxDamageAtLeast = Math.Max(0, maxDmg); - string ids = G.KeepCorruptedSpellIds ?? ""; - ImGui.SetNextItemWidth(220); - if (ImGui.InputText("Keep spell ids##ck", ref ids, 512)) G.KeepCorruptedSpellIds = ids; - if (ImGui.IsItemHovered()) ImGui.SetTooltip("Comma or space separated spell ids: a corrupted weapon carrying any of them is kept."); - SafeImGui.TextDisabled("Always kept: tinkered, imbued, no workmanship, cleave over 1 (2 on two-handed, non-thrust)."); - ImGui.TreePop(); - } - if (ImGui.Button("Chunk eligible items now...")) _ctx.Confirm("Chunk items", - "Run one chunk pass now on every eligible aetheria and corrupted weapon?\nChunked items are destroyed.", - ChunkNow, "Chunk"); - SafeImGui.TextDisabled("Status: " + _chunkStatus); - - ImGui.Separator(); - ImGui.TextColored(IltStyle.ColTeal, "Clap (/clap all)"); - if (_ctx.Options.IsOff(IltFeature.Clap)) - { - ImGui.TextColored(IltStyle.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(); - SafeImGui.TextDisabled(_clapStatus); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltEquipSuits.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltEquipSuits.cs deleted file mode 100644 index 23a2345..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltEquipSuits.cs +++ /dev/null @@ -1,265 +0,0 @@ -// 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 -// (IltObjects.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. -// The profile is matched by RynthAi's VTank loot evaluator (RynthAi.Hub LootKeeps), so suits need -// RynthAi. Search order: RynthILT EquipProfiles\, EquipProfiles, the same two in the RynthAi -// folder (where they lived before the move), then UB's equip folders. -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using ImGuiNET; -using RynthCore.Loot; -using RynthCore.Install; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT.Hub; - -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() - { - foreach (string baseDir in new[] { IltHubStore.SharedRoot, RynthInstallPaths.RynthAiDir }) - { - string root = Path.Combine(baseDir, "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; RynthAi evaluates the profile). - private List? SuitItems(string path, out string error) - { - error = string.Empty; - var candidates = 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; - candidates.Add(wo); - } - uint[] ids = candidates.Select(w => unchecked((uint)w.Id)).ToArray(); - if (!_ctx.Ai.LootKeeps(path, ids, out bool[] keep, out error)) return null; - var list = new List(); - for (int i = 0; i < candidates.Count; i++) - if (keep[i]) list.Add(candidates[i]); - 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 = IltObjects.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(IltStyle.ColTeal, "Equipment suits (.utl)"); - if (ImGui.SmallButton("Rescan profiles")) _ctx.Post(RefreshProfileList); - var profiles = _profiles; - if (profiles.Length == 0) - { - SafeImGui.TextDisabled($"No .utl files found ({System.IO.Path.Combine(IltHubStore.SharedRoot, "EquipProfiles")}, the RynthAi folder's 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("[Mini Remote] " + Load(pick)), "Load"); - if (_running) - { - ImGui.SameLine(); - if (ImGui.SmallButton("Cancel")) _ctx.Post(() => Cancel("cancelled by player")); - } - } - SafeImGui.TextDisabled("Status: " + _status); - foreach (string l in _preview) SafeImGui.BulletText(l); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs deleted file mode 100644 index bd88c27..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltFeatureCatalog.cs +++ /dev/null @@ -1,362 +0,0 @@ -// IltFeatureCatalog.cs — Every Infinite Leaftide feature RynthILT supports, in one list. -// -// Each entry says what the feature is, where it lives in the Rynth tools, and how its state is -// known. Detection is client-side only: the server type comes from the login (the world name, -// RynthCore's "ilt" verdict), and the ILT profile below is the known set of what Infinite -// Leaftide runs, taken from ACECustom (its ServerConfig defaults and deploy/PROD_DEPLOY_PLAN.md, -// e.g. pet bond and potency on in prod, pet strain off since launch). The server is never asked -// for a list; what it returns on its own (probe replies, chat) refines the profile: -// * Profile (IltKnown.Profile): on in ILT (T11, split arrows, pet breeding, ...). On with the -// ILT world; a server refusal seen in chat turns it off. -// * Profile off (IltKnown.ProfileOff): an ACECustom option ILT runs with off (pet strain, -// defense scaling, the pyreal refill). Off with the ILT world; a chat line only the feature -// sends (e.g. a pyreal refill) turns it on. -// * Checked (IltKnown.Checked): the login probe answers it (/bank, /aug, /xp, /pets, ...). -// "checking" until the reply arrives, then on or off. -// * No server bit at all (the Temple guardians, Paragon gear): content, on with the ILT world. -// Off an ILT world nothing is claimed: every state is unknown. -// The list feeds the ILT settings window ("/ilt settings", IltSettingsView/) and "/ra hub features". -// Server facts copied from ACECustom: Fellowship.MaxFellows = 29 (Source/ACE.Server/Entity/ -// Fellowship.cs), Zone Share (ZoneShareManager) and the fellowship luminance share. -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// One Leaftide feature: id, display text, where it lives, and the server bit that says whether it's on. -/// Stable id. -/// Display name. -/// Character, Items, Fellowship or Activities (the list's sections). -/// Where the Rynth tools handle it. -/// One line on what the server does. -/// The IltServerOptions key probes and chat refusals set; null = content built into ACECustom (on with the world). -/// How the state is known while the bit hasn't been set (see ). -internal sealed record IltFeatureInfo(string Key, string Label, string Group, string Where, string Description, string? ServerBit, - IltKnown Known = IltKnown.Profile); - -/// How a feature's state is known on an ILT world before (or without) a server answer. -internal enum IltKnown -{ - /// On in ILT: on with the ILT world unless chat shows it off. - Profile, - /// The login probe answers it: "checking" until the reply arrives. - Checked, - /// Off in ILT: off with the ILT world unless chat shows it on. - ProfileOff, -} - -/// The quest bonus list as the profile JSON carries it ("questBonus"), for RynthOracle's Quests tab. -/// The server has /qb turned off. -/// Bumped per parsed "/qb list"; 0 = not loaded this session. -/// The server's quest bonus count; -1 = unknown. -/// One line on the last request ("loading...", "12 completed, 3 incomplete", ...). -/// Completed bonus flags, sorted. -/// Incomplete bonus flags, sorted. -internal sealed record IltQuestBonusInfo(bool Disabled, int Generation, long Count, string Status, - IReadOnlyList Completed, IReadOnlyList Incomplete); - -internal static class IltFeatureCatalog -{ - public const string GroupCharacter = "Character"; - public const string GroupItems = "Items"; - public const string GroupPets = "Pets"; - public const string GroupFellowship = "Fellowship"; - public const string GroupCombat = "Combat"; - public const string GroupActivities = "Activities"; - - /// The section order of the list (ACECustom's "/ilt features" uses the same). - public static readonly string[] Groups = { GroupCharacter, GroupItems, GroupPets, GroupFellowship, GroupCombat, GroupActivities }; - - /// ACECustom's fellowship member limit (Fellowship.MaxFellows); retail is 9. - public const int IltFellowshipMax = 29; - - /// A retail fellowship's member limit. - public const int RetailFellowshipMax = 9; - - /// Every Leaftide feature RynthILT supports, in display order. - public static readonly IltFeatureInfo[] All = - { - // Character progression and money. - new("bank", "Banking", GroupCharacter, "Mini Remote > Banking tab; Remote tab bank line", - "Bank pyreals, luminance, keys and coins; deposit, withdraw and transfer (/bank).", IltFeature.Bank, IltKnown.Checked), - new("bank_notes", "Trade note banking", GroupCharacter, "Mini Remote > Banking tab (trade notes)", - "Deposit trade notes as pyreals, withdraw any note from I to MMD, transfer note value (/bank d n).", "bank_notes"), - new("guardian", "Guardian (infinite base attributes)", GroupCharacter, "Guardian panel (/rc guardian)", - "Temple of Enlightenment guardians raise base attributes past the retail cap.", null), - new("attributes", "Infinite raised attributes", GroupCharacter, "Skills > Progression > Attributes", - "Spend unassigned XP on attributes past the retail max (/xp, /attr).", IltFeature.Xp, IltKnown.Checked), - new("augmentations", "Infinite augmentations", GroupCharacter, "Skills > Progression > Augmentations", - "Luminance augmentations far past retail: Creature 6000, Item / Life / War / Void 4000 (/aug).", IltFeature.Aug, IltKnown.Checked), - new("aug_charms", "Augmentation counter charms", GroupCharacter, "Skills > Progression > Augmentations", - "Triune Weave and the school charms add to your aug counts past the purchase cap (/aug).", "aug_charms"), - new("enlightenment", "Enlightenment", GroupCharacter, "Skills > Progression > Enlightenment", - "Enlightenment tiers past retail, with medallions, sigils and crests (/enl).", IltFeature.Enl, IltKnown.Checked), - new("ilt_skills", "Spend XP and train skills in one go", GroupCharacter, "Chat: /ilt xp, /ilt train", - "Spends all unspent XP into trained skills, or trains every affordable skill, in priority order.", "ilt_skills"), - new("leaderboards", "Leaderboards", GroupCharacter, "Chat: /top", - "Server leaderboards: quest bonus, level, enlightenment, augs, bank, pets and more (/top).", "leaderboards"), - - // Items, loot and crafting. - new("paragon_armor", "Paragon armor", GroupItems, "Item info (RynthAi): Paragon sets and levels", - "Paragon armor progression; the 50th Armor Paragon gates enlightenment past 300.", null), - new("paragon_weapons", "Paragon weapons", GroupItems, "Item info (RynthAi): Paragon sets and levels", - "Paragon weapon progression (Paragon Missile, Caster and Melee sets).", null), - new("paragon_jewelry", "Paragon jewelry", GroupItems, "Item info (RynthAi): Paragon sets and levels", - "Paragon jewelry progression; the 50th Paragon gates enlightenment past 150.", null), - new("t11", "T11 items", GroupItems, "Item info and loot rules (RynthAi, RynthCore Loot Editor)", - "Tier 11 to 25 gear (Zone Control tiers): tiers, gear grades, property slots and modifiers.", "t11"), - new("t11_scaling", "T11+ weapon scaling", GroupItems, "Item info (RynthAi)", - "T11+ weapons scale with your augs and have aug wield floors; from T16, charm counts too.", "t11_scaling"), - new("t11_craft_gate", "T11+ crafting rules (crafting uniqueness)", GroupItems, "Mini Remote > Gear tab", - "On T11+ items the server refuses an imbue or tink that would replace a better value, and limits materials per item type.", - "t11_craft_gate"), - new("split_arrows", "Split arrows", GroupItems, "Mini Remote > Gear > Split arrows", - "Missile weapons carry split arrows, added with White Quartz salvage.", "split_arrows"), - new("charms", "Charms", GroupItems, "Mini Remote > Charms tab", - "Registry charms and the Guardian Hand, with their toggles; each charm is listed in the Charms section.", "charms"), - new("clap", "Chunk clap (auto craft)", GroupItems, "Mini Remote > Gear tab", - "Turns aetheria, chunks and trinkets into banked enlightened coins (/clap all).", IltFeature.Clap, IltKnown.Checked), - - // Pets. - new("pets", "Pet log", GroupPets, "Mini Remote > Pets tab", "Captured pets, registered with Professor Ruggan (/pets).", IltFeature.Pets, IltKnown.Checked), - new("shinies", "Shiny log", GroupPets, "Mini Remote > Pets tab", "Rare shiny creature variants you captured (/shinies).", IltFeature.Shinies, IltKnown.Checked), - new("monster_capture", "Monster capture", GroupPets, "Mini Remote > Pets tab", - "Siphon lenses capture a creature\'s look into a pet essence (<=20% health or under 20 HP; Asheron\'s Lens skips the gate). Auto-capture is the checkbox on the Pets roster.", "monster_capture"), - new("pet_breeding", "Pet breeding", GroupPets, "Mini Remote > Pets > Breeding", - "Breed two combat pet devices at the Seedy Motel for inherited and mutated offspring (/dance).", "pet_breeding"), - new("pet_maturity", "Pet maturity", GroupPets, "Mini Remote > Pets > Breeding", - "Bred pets start small and weak and grow up with kills.", "pet_maturity"), - new("pet_bond", "Pet bond", GroupPets, "Mini Remote > Pets tab", - "Pets gain bond XP from kills, which scales their stats (/top bonds). On in ILT (breeding needs bond 100).", IltFeature.PetBond), - new("pet_potency", "Pet potency", GroupPets, "Mini Remote > Pets tab", - "Savage Echo residue raises a pet's potency (/echo-notify). On in ILT.", IltFeature.PetPotency), - new("pet_strain", "Pet strain", GroupPets, "Mini Remote > Pets tab", - "High pet potency lowers the owner's damage rating. Off in ILT since launch.", "pet_strain", IltKnown.ProfileOff), - new("pet_refill", "Summon essence refill", GroupPets, "Mini Remote > Pets tab", - "Pays pyreals to refill an empty essence when you summon (needs its charm). Off by default; a refill message in chat shows it on.", IltFeature.PetRefill, IltKnown.ProfileOff), - new("universal_mastery", "Universal summoning mastery", GroupPets, "Mini Remote > Pets tab", - "Use pet essences of any summoning mastery (needs its charm).", IltFeature.UniversalMastery), - new("pet_naming", "Pet names", GroupPets, "Chat: /pet-name", - "Ask for a name for your pet; staff approve it (/pet-name).", "pet_naming"), - - // Fellowship. - new("fellowship_large", "Large fellowships (up to 29)", GroupFellowship, "The game's fellowship panel", - "Fellowships hold up to 29 members instead of retail's 9.", "fellowship_size"), - new("fship", "Fellowship commands", GroupFellowship, "ILT fellowship window (/ilt fellow)", - "Create, invite, invite your landblock, list nearby, leave and disband from chat (/fship).", "fship"), - new("zone_share", "Zone Share", GroupFellowship, "Mini Remote > Session Stats (luminance, pass-up)", - "XP and luminance shared with everyone in a Zone Share area, capped at a fellowship's size.", "zone_share"), - new("fellowship_luminance", "Fellowship luminance share", GroupFellowship, "Mini Remote > Session Stats (luminance, pass-up)", - "Luminance splits among fellows the way XP does.", "fellowship_luminance"), - new("fellowship_blackjack", "Fellowship Blackjack", GroupFellowship, "Mini Remote > Games tab", - "Blackjack played as a fellowship (/fblackjack).", IltFeature.FBlackjack, IltKnown.Checked), - - // Combat. - new("smart_ring", "Smart ring spells", GroupCombat, "Chat: /ilt smartring", - "Ring spells hit everything in their radius, with double and triple procs (/ilt smartring on|off).", "smart_ring"), - new("dmgformat", "Damage number format", GroupCombat, "Chat: /ilt dmgformat", - "Damage shown plain, with commas, or short (K/M/B) (/ilt dmgformat).", "dmgformat"), - new("overkill", "Overkill on kill messages", GroupCombat, "Chat: /ilt showoverkill", - "Kill and death messages show the overkill amount (/ilt showoverkill).", "overkill"), - new("missile_power", "Missile power bar damage", GroupCombat, "Combat", - "The missile accuracy bar scales damage from 1x to 2.5x.", "missile_power"), - new("t11_hit_gate", "T11+ hit gate", GroupCombat, "Combat", - "Attacks on v11+ monsters miss unless your aug counts meet that tier's requirement.", "t11_hit_gate"), - new("v11_endgame", "v11+ endgame scaling", GroupCombat, "Combat", - "Percent-of-max-HP damage, compressed vulnerabilities and tougher v11+ monsters.", "v11_endgame"), - new("defense_scaling", "Defense scaling", GroupCombat, "Combat", - "Curbs extreme evasion at very high defense skill. Off by default in ACECustom.", "defense_scaling", IltKnown.ProfileOff), - - // Activities. - new("quests", "Quest tracker", GroupActivities, "Mini Remote > Quests tab", - "Your quest timers from the server (/myquests).", IltFeature.Quests, IltKnown.Checked), - new("quest_bonus", "Quest bonus", GroupActivities, "Mini Remote > Quests tab (quest bonus)", - "Each quest completed adds to your XP bonus; the list (/qb).", IltFeature.Qb, IltKnown.Checked), - new("bounties", "Bounties", GroupActivities, "Bounties window (/rc bounties)", "ACECustom bounties and your progress.", "bounties"), - new("rifts", "Greater Rifts", GroupActivities, "Chat: /rift", "Private, timed dungeon runs that scale by tier (/rift).", "rifts"), - new("room_assign", "Room Assign dungeons", GroupActivities, "Portals and recalls", - "One-player rooms with their own spawns.", "room_assign"), - new("portal_requirements", "Aug / ENL / QB portals", GroupActivities, "Portals", - "Portals that need augmentations, an enlightenment level or a quest bonus.", "portal_requirements"), - new("powerball", "Powerball", GroupActivities, "Mini Remote > Games tab", "The Powerball lottery (/pb).", IltFeature.Powerball, IltKnown.Checked), - new("blackjack", "Blackjack", GroupActivities, "Mini Remote > Games tab", "Blackjack against the house (/blackjack).", IltFeature.Blackjack, IltKnown.Checked), - new("unstuck", "Unstuck", GroupActivities, "Chat: /unstuck", "Gets you out of a stuck portal or spot (/unstuck).", "unstuck"), - }; - - /// The entry with , or null. - public static IltFeatureInfo? Find(string key) - { - foreach (IltFeatureInfo f in All) - if (f.Key.Equals(key, StringComparison.OrdinalIgnoreCase)) return f; - return null; - } - - /// - /// A feature's state on an ILT world: what the server returned (a probe reply or a refusal in - /// chat) when it did; else the ILT profile: On for content and , - /// Off for , Unknown ("checking") for probed features. - /// Off ILT nothing is claimed: Unknown. - /// - public static IltTri StateOf(IltFeatureInfo f, bool iltWorld, Func bit) - { - if (!iltWorld) return IltTri.Unknown; - if (f.ServerBit == null) return IltTri.On; - IltTri reported = bit(f.ServerBit); - if (reported != IltTri.Unknown) return reported; - return f.Known switch - { - IltKnown.Profile => IltTri.On, - IltKnown.ProfileOff => IltTri.Off, - _ => IltTri.Unknown, - }; - } - - /// - /// A charm's state: charms are part of the ILT profile, so on with the ILT world unless the - /// server refused one in chat (e.g. "Auto-Rebuff Charm is currently disabled globally"). - /// - public static IltTri CharmStateOf(bool iltWorld, IltTri reported) - => !iltWorld ? IltTri.Unknown : reported != IltTri.Unknown ? reported : IltTri.On; - - /// Prefix of a charm's server key (IltFeature.Charm): "charm:manabarrier". - public const string CharmKeyPrefix = "charm:"; - - /// - /// Display text for a key the settings view lists: a catalog feature (its label, group and - /// description with where it lives and how its state is known), a charm ("charm:..." under - /// Charms, named from the charm registry), or any other server bit as itself under "Other". - /// - public static (string Label, string Group, string Tooltip) Describe(string key) - { - IltFeatureInfo? f = Find(key); - if (f != null) return (f.Label, f.Group, f.Description + "\nWhere: " + f.Where + "\n" + HowKnown(f)); - if (key.StartsWith(CharmKeyPrefix, StringComparison.OrdinalIgnoreCase)) - { - const string charmNote = "Part of ILT: on unless the server refuses it in chat."; - foreach (IltCharmDef def in IltInventory.Charms) - if (IltFeature.Charm(def.Name).Equals(key, StringComparison.OrdinalIgnoreCase)) - return (def.Name, GroupCharms, (def.Effect.Length > 0 ? def.Effect + "\n" : string.Empty) - + "Where: Mini Remote > Charms tab\n" + charmNote); - return (key.Substring(CharmKeyPrefix.Length), GroupCharms, charmNote); - } - return (key, GroupOther, "A server switch RynthILT reads from chat."); - } - - /// One line on where a feature's state comes from (tooltips). - private static string HowKnown(IltFeatureInfo f) => f.ServerBit == null - ? "Built into ILT: on with the world." - : f.Known switch - { - IltKnown.Checked => "Checked at login: the server's reply decides.", - IltKnown.ProfileOff => "Off in ILT: on only if the server shows it in chat.", - _ => "Part of ILT: on unless the server refuses it in chat.", - }; - - /// The settings view's extra sections after . - public const string GroupCharms = "Charms"; - public const string GroupOther = "Other"; - - /// Short state text for the list and chat: "on", "off" or "checking". - public static string StateText(IltTri state) => state switch - { - IltTri.On => "on", - IltTri.Off => "off", - _ => "checking", - }; - - /// The fellowship member limit: ACECustom's 29 on an ILT world, retail's 9 elsewhere. - public static int FellowshipMax(bool iltWorld) => iltWorld ? IltFellowshipMax : RetailFellowshipMax; - - /// - /// The "RynthILT.Server" profile JSON (schema in Plugins/Shared/RynthIltServerApi.cs). Pure: - /// everything comes in as arguments, so the tests build it without a client. Plain ASCII. - /// - public static string BuildProfileJson(bool iltWorld, string world, bool forced, string source, DateTime checkedUtc, - Func bit, IltQuestBonusInfo? questBonus = null) - { - var sb = new StringBuilder(4096); - sb.Append("{\"ilt\":").Append(iltWorld ? "true" : "false"); - sb.Append(",\"world\":\"").Append(Escape(world)).Append('"'); - sb.Append(",\"forced\":").Append(forced ? "true" : "false"); - sb.Append(",\"source\":\"").Append(Escape(source)).Append('"'); - sb.Append(",\"checked\":\"") - .Append(checkedUtc == DateTime.MinValue ? "" : checkedUtc.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture)) - .Append('"'); - - sb.Append(",\"features\":["); - for (int i = 0; i < All.Length; i++) - { - IltFeatureInfo f = All[i]; - if (i > 0) sb.Append(','); - sb.Append("{\"key\":\"").Append(Escape(f.Key)) - .Append("\",\"label\":\"").Append(Escape(f.Label)) - .Append("\",\"group\":\"").Append(Escape(f.Group)) - .Append("\",\"state\":").Append(((int)StateOf(f, iltWorld, bit)).ToString(CultureInfo.InvariantCulture)) - .Append(",\"where\":\"").Append(Escape(f.Where)).Append("\"}"); - } - sb.Append(']'); - - int State(string key) => (int)StateOf(Find(key)!, iltWorld, bit); - sb.Append(",\"fellowship\":{\"maxMembers\":").Append(FellowshipMax(iltWorld).ToString(CultureInfo.InvariantCulture)) - .Append(",\"zoneShare\":").Append(State("zone_share").ToString(CultureInfo.InvariantCulture)) - .Append(",\"blackjack\":").Append(State("fellowship_blackjack").ToString(CultureInfo.InvariantCulture)) - .Append(",\"luminanceShare\":").Append(State("fellowship_luminance").ToString(CultureInfo.InvariantCulture)) - .Append('}'); - - // The /qb list (ILT worlds only): RynthOracle's Quests tab draws it. - if (questBonus != null && iltWorld) - { - sb.Append(",\"questBonus\":{\"disabled\":").Append(questBonus.Disabled ? "true" : "false") - .Append(",\"generation\":").Append(questBonus.Generation.ToString(CultureInfo.InvariantCulture)) - .Append(",\"count\":").Append(questBonus.Count.ToString(CultureInfo.InvariantCulture)) - .Append(",\"status\":\"").Append(Escape(questBonus.Status)).Append('"'); - AppendList(sb, "completed", questBonus.Completed); - AppendList(sb, "incomplete", questBonus.Incomplete); - sb.Append('}'); - } - sb.Append('}'); - return sb.ToString(); - - static void AppendList(StringBuilder b, string name, IReadOnlyList items) - { - b.Append(",\"").Append(name).Append("\":["); - for (int i = 0; i < items.Count; i++) - { - if (i > 0) b.Append(','); - b.Append('"').Append(Escape(items[i])).Append('"'); - } - b.Append(']'); - } - } - - /// JSON string body: quotes, backslashes and control characters escaped, anything non-ASCII as \uXXXX. - private static string Escape(string? s) - { - if (string.IsNullOrEmpty(s)) return string.Empty; - var sb = new StringBuilder(s.Length + 8); - foreach (char c in s) - { - if (c == '"') sb.Append("\\\""); - else if (c == '\\') sb.Append("\\\\"); - else if (c < 0x20 || c > 0x7E) sb.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture)); - else sb.Append(c); - } - return sb.ToString(); - } - - /// The chat listing for "/ra hub features": one line per feature, ASCII only. - public static List BuildChatLines(bool iltWorld, Func bit) - { - var lines = new List(All.Length + Groups.Length); - foreach (string g in Groups) - { - var parts = new List(); - foreach (IltFeatureInfo f in All) - if (f.Group == g) parts.Add($"{f.Label} [{StateText(StateOf(f, iltWorld, bit))}]"); - lines.Add($"{g}: {string.Join(", ", parts)}"); - } - return lines; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGames.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGames.cs deleted file mode 100644 index 0a91a26..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGames.cs +++ /dev/null @@ -1,255 +0,0 @@ -// IltGames.cs — ILT Hub "Games" tab + hand HUD (P2): Blackjack, Fellowship Blackjack, Powerball. -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// -// 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.Shared; - -namespace RynthCore.Plugin.RynthILT.Hub; - -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(IltStyle.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(); - SafeImGui.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) SafeImGui.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) SafeImGui.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) SafeImGui.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)) - { - SafeImGui.TextColored(IltStyle.ColAmber, _fellowshipHand ? "Fellowship Blackjack" : "Blackjack"); - RenderHandButtons("hud"); - } - ImGui.End(); - if (!open) _ctx.State.GamesHudVisible = false; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGear.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGear.cs deleted file mode 100644 index a986d5a..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGear.cs +++ /dev/null @@ -1,78 +0,0 @@ -// IltGear.cs — ILT Hub "Gear" tab: the gear tools. -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// -// The sections are separate modules (buff keepers, chunk/clap, split arrows, equipment suits) -// that this tab just lays out, plus RynthAi's VTank .usd importer (it edits RynthAi's own rules, -// so it stayed in RynthAi and is drawn here through RynthAi.Hub RenderSection). The charm strip (registry charms and the Guardian -// Hand, with their toggles) is the Charms tab now (IltCharms). The Rings inscription chain -// (IltRingChainRunner) is SilentKelpie's RynthAi Crafting > Rings, moved here 2026-10-15. -using ImGuiNET; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal sealed class IltGear : IIltFeature -{ - public IltBuffKeepers Keepers { get; } - public IltChunkClap ChunkClap { get; } - public IltSplitArrows Split { get; } - public IltEquipSuits Suits { get; } - public IltRingChainRunner Rings { get; } - - private readonly IltHubContext _ctx; - - public IltGear(IltHubContext ctx) - { - Keepers = new IltBuffKeepers(ctx); - ChunkClap = new IltChunkClap(ctx); - Split = new IltSplitArrows(ctx); - Suits = new IltEquipSuits(ctx); - // The two pack jobs that answer craft dialogs never run together. - Rings = new IltRingChainRunner(ctx, () => Split.Running); - Split.Blocked = () => Rings.Running; - _ctx = ctx; - } - - // ── IIltFeature ───────────────────────────────────────────────────────── - - public void Tick(long nowMs) - { - Keepers.Tick(nowMs); - ChunkClap.Tick(nowMs); - Split.Tick(nowMs); - Suits.Tick(nowMs); - Rings.Tick(nowMs); - } - - public bool OnChat(string text) - { - bool eat = Keepers.OnChat(text); - eat |= ChunkClap.OnChat(text); - eat |= Split.OnChat(text); - eat |= Suits.OnChat(text); - eat |= Rings.OnChat(text); - return eat; - } - - public void OnLogout() - { - Keepers.OnLogout(); - ChunkClap.OnLogout(); - Split.OnLogout(); - Suits.OnLogout(); - Rings.OnLogout(); - } - - // ── UI (render thread) ────────────────────────────────────────────────── - - public void Render() - { - if (ImGui.CollapsingHeader("Dispel / Surging Strength", ImGuiTreeNodeFlags.DefaultOpen)) 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("Rings (inscription chain)")) Rings.Render(); - if (ImGui.CollapsingHeader("VirindiTank import") && !_ctx.Ai.RenderSection(RynthCore.Plugin.Shared.RynthAiHub.SectionVTankImport)) - ImGui.TextDisabled("The VirindiTank .usd import fills RynthAi's rules: it comes with RynthAi, which isn't loaded."); - ImGui.TextDisabled("Charms and the Guardian Hand are on the Charms tab."); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardian.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardian.cs deleted file mode 100644 index 48ad99d..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardian.cs +++ /dev/null @@ -1,656 +0,0 @@ -// IltGuardian.cs - Temple of Enlightenment guardians (ILT Hub "Guardian" window). -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// -// * 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. -// * Reader: the same state as JSON with verbs back ("RynthILT.Data" version 3), for RynthOracle's -// Quests tab. The automation (auto hand-in, buy if missing) stays here either way. -// -// 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.Shared; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.RynthILT.Hub; - -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, IltQuestBonus quests) - { - _ctx = ctx; - Attributes = new IltTempleAttributes(ctx, 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; - } - } - - // ── Reader ("RynthILT.Data" GetGuardianJson / GuardianCommand; RynthOracle's Quests tab) ── - - /// - /// The reader JSON (Plugins/Shared/RynthIltDataApi.cs header has the shape): the switches, the - /// last answer and hand-in status, and the attribute turn-in rows. Built on demand: everything it - /// reads is volatile or an immutable snapshot. Any thread. - /// - public string ReaderJson(string world) - { - TimeSpan age = LastAnswerAge; - return BuildJson(world, S.AutoDetectFromChat, S.AutoHandIn, S.BuyMissingFromVendor, S.CooldownHoursAssumed, - _lastAnswer, _lastNpc, age == TimeSpan.MaxValue ? -1 : (long)age.TotalSeconds, - IltGuardianPhrasebook.MessageOf(_lastLine), HandInRunning, _handInStatus, Attributes.SyncedUtc, Attributes.Snapshot); - } - - /// The reader JSON from its parts. Pure: the tests drive it. - internal static string BuildJson(string world, bool chat, bool auto, bool buy, int cooldownHours, - string answer, string npc, long answerAgeSec, string heard, bool running, string status, - DateTime syncedUtc, System.Collections.Generic.IReadOnlyList rows) - { - var sb = new System.Text.StringBuilder(1024); - sb.Append("{\"available\":true"); - Str(sb, "world", world); - sb.Append(",\"chat\":").Append(chat ? "true" : "false"); - sb.Append(",\"auto\":").Append(auto ? "true" : "false"); - sb.Append(",\"buy\":").Append(buy ? "true" : "false"); - sb.Append(",\"cooldownHours\":").Append(cooldownHours); - Str(sb, "answer", answer); - Str(sb, "npc", npc); - sb.Append(",\"answerAgeSec\":").Append(answerAgeSec); - Str(sb, "heard", heard); - sb.Append(",\"running\":").Append(running ? "true" : "false"); - Str(sb, "status", status); - Str(sb, "synced", syncedUtc == DateTime.MinValue ? "" : syncedUtc.ToString("yyyy-MM-ddTHH:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture)); - sb.Append(",\"rows\":["); - for (int i = 0; i < rows.Count; i++) - { - IltTempleAttrStatus r = rows[i]; - if (i > 0) sb.Append(','); - sb.Append('{'); - Str(sb, "attribute", r.Attribute, first: true); - Str(sb, "npc", r.Npc); - sb.Append(",\"count\":").Append(r.Count); - Str(sb, "status", r.Status); - Str(sb, "eta", r.Eta); - sb.Append(",\"ready\":").Append(r.Ready ? "true" : "false"); - sb.Append(",\"exact\":").Append(r.FromMyQuests ? "true" : "false"); - sb.Append('}'); - } - sb.Append("]}"); - return sb.ToString(); - } - - private static void Str(System.Text.StringBuilder sb, string name, string? value, bool first = false) - { - if (!first) sb.Append(','); - sb.Append('"').Append(name).Append("\":\"").Append(IltStyle.JsonEscape(value ?? string.Empty)).Append('"'); - } - - /// - /// A reader's verb line (header of Plugins/Shared/RynthIltDataApi.cs): handin | stop | refresh | - /// chat on|off | auto on|off | buy on|off. The reader shows the new state, so the switches don't - /// echo in chat; hand-in and refresh report as the Guardian window's buttons do. Pump thread. - /// - public void RunVerb(string line) - { - string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); - if (parts.Length == 0) return; - string arg = parts.Length > 1 ? parts[1] : ""; - switch (parts[0].ToLowerInvariant()) - { - case "handin": StartHandIn(_lastAnswer, _lastNpc, asked: true); break; - case "stop": StopHandIn(); break; - case "refresh": _ctx.Chat("[ILT Guardian] " + Attributes.Refresh()); break; - case "chat": S.AutoDetectFromChat = Toggle(arg, S.AutoDetectFromChat); break; - case "auto": S.AutoHandIn = Toggle(arg, S.AutoHandIn); break; - case "buy": S.BuyMissingFromVendor = Toggle(arg, S.BuyMissingFromVendor); break; - default: - RynthLog.Trace(LogCat.IltHub, $"[IltGuardian] reader verb ignored: {line}"); - return; - } - RynthLog.Write(LogCat.IltHub, $"[IltGuardian] reader verb: {line}"); - } - - 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); - SafeImGui.TextDisabled(IltGuardianPhrasebook.MessageOf(line)); - ImGui.PopTextWrapPos(); - } - - string answer = _lastAnswer, npc = _lastNpc; - if (answer.Length > 0) - { - SafeImGui.TextColored(IltStyle.ColTeal, answer); - ImGui.SameLine(); - SafeImGui.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."); - SafeImGui.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; - SafeImGui.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 ? IltStyle.ColGreen - : r.Status == "Unknown" ? IltStyle.ColTextMute - : IltStyle.ColAmber; - SafeImGui.TextColored(col, r.Status); - if (ImGui.IsItemHovered()) - SafeImGui.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(IltStyle.ColTextMute, "Guardian:"); - ImGui.SameLine(); - SafeImGui.TextColored(IltStyle.ColTeal, answer); - if (ImGui.IsItemHovered()) SafeImGui.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.RynthILT/Hub/IltGuardianPhrasebook.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardianPhrasebook.cs deleted file mode 100644 index 67773c7..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltGuardianPhrasebook.cs +++ /dev/null @@ -1,221 +0,0 @@ -// IltGuardianPhrasebook.cs - Temple of Enlightenment spell words and Guardian of Attribute -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// 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.RynthILT.Hub; - -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.RynthILT/Hub/IltHubContext.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubContext.cs deleted file mode 100644 index ced863c..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubContext.cs +++ /dev/null @@ -1,114 +0,0 @@ -// IltHubContext.cs — Shared services handed to every ILT Hub feature. -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. What the -// features borrowed from RynthAi's internals now comes through Ai (RynthAi.Hub, RynthAiClient). -// -// 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). -using System; -using System.Collections.Concurrent; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// A yes/no question waiting for the player (a modal over the Mini Remote). -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(); - - public IltHubContext(RynthCoreHost host, IltHubState state, IltHubStore store, IltChatCapture capture, - IltServerOptions options, IltInventory inventory, IltSettings settings, RynthAiClient ai) - { - Host = host; - State = state; - Store = store; - Capture = capture; - Options = options; - Inventory = inventory; - Settings = settings; - Ai = ai; - } - - public RynthCoreHost Host { get; } - public IltHubState State { get; } - public IltHubStore Store { get; } - public IltChatCapture Capture { get; } - public IltServerOptions Options { get; } - public IltInventory Inventory { get; } - - /// RynthILT's settings (the server list). Edits are saved through . - public IltSettings Settings { get; } - - /// Saves (pump thread). - public void SaveSettings() => IltSettingsStore.Save(Settings); - - /// RynthAi's services (the Mini Remote, /myquests, spell names, loot matching); each says when RynthAi is missing. - public RynthAiClient Ai { get; } - - /// Logged-in character name (resolved at login). - public string CharName = string.Empty; - - /// True when the Mini Remote is on screen (features use it to gate auto-refreshes). - public bool WindowOpen => State.WindowVisible; - - /// - /// Shows the Mini Remote on one of its ILT tabs (set by the controller). Any thread: it only - /// records the tab and the show request, which the next frame applies. - /// - public Action? ShowTab; - - /// 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.RynthILT/Hub/IltHubController.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs deleted file mode 100644 index c92cd46..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubController.cs +++ /dev/null @@ -1,870 +0,0 @@ -// IltHubController.cs — Owns the ILT features behind the Mini Remote's ILT tabs: state, services, -// feature modules, commands. -// Originally SilentKelpie's ILT Hub controller (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// -// RynthILTPlugin creates one controller per login session and forwards: -// OnTick → Tick() (pump thread) -// OnChatWindowText → OnChat() (pump thread; returns true to eat the line) -// OnRender → Render() (render thread: Games HUD, confirmations) -// the ILT "/ra hub ...", "/ra guardian ...", "/ra bounty ..." verbs (RynthAi forwards them -// through RynthILT.Hub Command) and "/ilt ..." → HandleCommand() -// OnLogout / teardown → OnLogout() -// The ILT sections are tabs of RynthAi's Mini Remote (RenderTab, through RynthILT.Hub); the -// Guardian is RynthCore's ILT panel (RenderGuardianPanel, RynthPluginRenderEmbed "guardian"), -// and bounties are RynthILT's Bounties window (RynthCore's ILT button), so "/ra bounty" and -// "/ra guardian window" open those engine panels. The Mini Remote's Quests and Pets tabs are -// RynthAi's (every world); RynthILT adds their ILT sections (the /qb list, the /pets and -// /shinies logs). On any world that isn't ILT-like every feature here stays dormant (no probes, -// no chat, no tabs). -using System; -using System.Collections.Generic; -using System.Linq; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal sealed class IltHubController -{ - private const long SaveIntervalMs = 5000; - - private readonly IltHubContext _ctx; - private readonly IltHubUi _ui; - private readonly List _features = new(); - private long _lastSaveAt; - private int _questGeneration; // RynthAi's /myquests refreshes seen (NoteQuestTrackerOutcome) - private bool _availabilityAnnounced; // "open the Mini Remote" hint printed this session - private volatile int _forceRequest = -1; // SetForceIlt from another thread, applied on the next tick - private long _tabDrawnAt = long.MinValue / 2; // a tab drawn as RynthCore's section view (render thread) - private const long TabDrawnMs = 2000; - - // "RynthILT.Data" (Plugins/Shared/RynthIltDataApi.cs): the charms and bank snapshots, rebuilt on - // the pump every DataRebuildMs only while a reader has asked within DataWatchMs. - private const long DataRebuildMs = 2000; - private const long DataWatchMs = 6000; - /// How often the other characters' saved balances are re-read for the bank export. - private const long SiblingReadMs = 15_000; - private long _charmsReadAt, _bankReadAt; // set by readers (any thread, Interlocked) - private long _charmsBuiltAt, _bankBuiltAt, _siblingsReadAt; - private volatile string _charmsJson = string.Empty; - private volatile string _bankJson = string.Empty; - - // "RynthILT.Server" profile JSON (RynthOracle: feature states, fellowship rules, the /qb list). Rebuilt ~1 s. - private const long ProfileRebuildMs = 1000; - private long _profileBuiltAt; - private volatile string _profileJson = string.Empty; - private List _siblings = new(); - - public IltBanking Banking { get; } - public IltSessionRates Rates { get; } - /// The quest bonus list (/qb): the Quests tab's section and the Temple tracker's stamps. - public IltQuestBonus QuestBonus { get; } - /// The /pets and /shinies logs (the Pets tab's section). - public IltPetLogs PetLogs { get; } - /// The pet breeding tracker (the Pets tab's Breeding sub-tab, and the "RynthILT.Data" breeding JSON). - public IltPetBreeding Breeding { get; } - /// The Pets tab's ACECustom sections: pet charms, the summon-from-empty refill path, siphon auto-capture. - public IltPetAutomation PetAutomation { get; } - public IltProgression Progression { get; } - public IltGear Gear { get; } - public IltGames Games { get; } - /// Registry charm acquired / active / server state (the Charms tab and RynthILTGetCharmsJson). - public IltCharmTracker Charms { get; } - /// The Mini Remote's Charms tab (registry charms with toggles, the Guardian Hand). - public IltCharms CharmsTab { get; } - /// Temple guardians: riddle translator, hand-in, attribute turn-in tracker. - public IltGuardian Guardian { get; } - /// Vaulted Dungeons keeper (Mini Remote tab). ILT-only and behind its master switch (State.VaultedDungeonsEnabled), off by default. - public IltVaultedDungeons VaultedDungeons { get; } - /// The Empyrean Handler's lethal ring: asks RynthAi to back away (RynthAi.Hub BackAwayFrom). - public IltRingEvade RingEvade { get; } - /// T11 gear: the "/aug" wield counters for RynthAi's loot rules, "/ilt t11". - public IltT11 T11 { get; } - - /// True while this character's copy from RynthAi is unfinished (IltHubStore.WritesBlocked). - /// The character's RynthAi folder while that copy is unfinished (read-only fallback). - public IltHubController(RynthCoreHost host, string charFolder, IltSettings settings, RynthAiClient ai, - Func? writesBlocked = null, string? legacyFolder = null) - { - var store = new IltHubStore(host, charFolder); - if (writesBlocked != null) store.WritesBlocked = writesBlocked; - store.LegacyFolder = legacyFolder; - var state = store.LoadState(); - var capture = new IltChatCapture(host); - var inventory = new IltInventory(host, new IltObjects(host)); - IltHubContext? ctxRef = null; - var options = new IltServerOptions(host, capture, state, text => ctxRef?.Chat(text), () => settings); - _ctx = new IltHubContext(host, state, store, capture, options, inventory, settings, ai); - ctxRef = _ctx; - - Banking = new IltBanking(_ctx); - PetLogs = new IltPetLogs(_ctx); - Breeding = new IltPetBreeding(_ctx); - PetAutomation = new IltPetAutomation(_ctx); - Rates = new IltSessionRates(_ctx); - QuestBonus = new IltQuestBonus(_ctx); - Progression = new IltProgression(_ctx); - Gear = new IltGear(_ctx); - Games = new IltGames(_ctx); - Charms = new IltCharmTracker(_ctx); - CharmsTab = new IltCharms(_ctx, Charms); - Guardian = new IltGuardian(_ctx, QuestBonus); - VaultedDungeons = new IltVaultedDungeons(_ctx); - RingEvade = new IltRingEvade(_ctx); - T11 = new IltT11(_ctx); - _features.AddRange(new IIltFeature[] { Banking, PetLogs, Breeding, PetAutomation, Rates, QuestBonus, Progression, Gear, CharmsTab, Games, VaultedDungeons, Guardian, RingEvade, T11 }); - - Banking.BalanceChanged += Rates.OnBankBalanceChanged; - Rates.MovingMoney = () => Banking.MovingMoney; - options.ProbeReplyTap = OnProbeReply; - _ui = new IltHubUi(this, _ctx); - _ctx.ShowTab = section => _ctx.Ai.MiniRemoteTab(IltSections.TabId(section), "show"); - RebuildProfile(); - } - - /// - /// The latest "RynthILT.Server" profile JSON: Leaftide features, fellowship rules and the /qb - /// list (Plugins/Shared/RynthIltServerApi.cs). Rebuilt on the pump about once a second so any - /// thread (ServerInterface) may read it. - /// - public string ProfileJson => _profileJson; - - /// Rebuilds from the current server options. Pump thread. - private void RebuildProfile() - { - IltServerOptions o = _ctx.Options; - _profileJson = IltFeatureCatalog.BuildProfileJson( - o.IsIltLikeWorld, o.WorldName, _ctx.State.ForceLeaftideFeatures, - o.Source ?? string.Empty, o.LastRefreshUtc, o.Get, - QuestBonus.Snapshot()); - } - - /// - /// The charms JSON ("RynthILT.Data" GetCharmsJson). Reading it marks the charms as watched, so - /// the pump keeps the snapshot fresh while a reader is showing it; "" until the first rebuild - /// after that. Any thread. - /// - public string CharmsJson - { - get { System.Threading.Interlocked.Exchange(ref _charmsReadAt, IltHubContext.NowMs); return _charmsJson; } - } - - /// The bank JSON ("RynthILT.Data" GetBankJson), as . - public string BankJson - { - get { System.Threading.Interlocked.Exchange(ref _bankReadAt, IltHubContext.NowMs); return _bankJson; } - } - - /// A reader's charm Toggle, posted to the pump (IltCharms checks the id). Any thread. - public void RequestCharmToggle(uint objectId) - => _ctx.Post(() => - { - if (!_ctx.Options.IsIltLikeWorld) return; - if (!CharmsTab.ToggleFromReader(objectId)) - RynthLog.Trace(LogCat.IltGear, $"reader toggle refused: 0x{objectId:X8} isn't a carried charm"); - _charmsBuiltAt = 0; // show the new state on the next tick - }); - - /// - /// The pet breeding JSON ("RynthILT.Data" GetPetBreedingJson). - /// Reading it keeps the tracker scanning; "" off an ILT world or before its first scan. Any thread. - /// - public string PetBreedingJson => _ctx.Options.IsIltLikeWorld ? Breeding.ReaderJson : string.Empty; - - /// A reader's breeding verb line, posted to the pump (IltPetBreeding.RunVerb). Any thread. - public void RequestBreedingVerb(string line) - => _ctx.Post(() => - { - if (!_ctx.Options.IsIltLikeWorld) return; - Breeding.RunVerb(line); - }); - - /// - /// The Temple guardian JSON ("RynthILT.Data" GetGuardianJson): switches, last answer, hand-in - /// status and attribute turn-ins. "" off an ILT world. Any thread. - /// - public string GuardianJson => _ctx.Options.IsIltLikeWorld ? Guardian.ReaderJson(_ctx.Options.WorldName) : string.Empty; - - /// A reader's guardian verb line, posted to the pump (IltGuardian.RunVerb). Any thread. - public void RequestGuardianVerb(string line) - => _ctx.Post(() => - { - if (!_ctx.Options.IsIltLikeWorld) return; - Guardian.RunVerb(line); - }); - - /// A reader's bank verb line, posted to the pump (IltBanking.RunVerb). Any thread. - public void RequestBankVerb(string line) - => _ctx.Post(() => - { - if (!_ctx.Options.IsIltLikeWorld) return; - Banking.RunVerb(line); - _bankBuiltAt = 0; - }); - - /// Pump: rebuilds the charms / bank snapshots a reader is watching. - private void RebuildReaderData(long now) - { - if (now - System.Threading.Interlocked.Read(ref _charmsReadAt) < DataWatchMs && now - _charmsBuiltAt >= DataRebuildMs) - { - _charmsBuiltAt = now; - _charmsJson = CharmsTab.BuildReaderJson(); - } - - bool bankWatched = now - System.Threading.Interlocked.Read(ref _bankReadAt) < DataWatchMs; - Banking.ReaderWatching = bankWatched; - if (!bankWatched || now - _bankBuiltAt < DataRebuildMs) return; - _bankBuiltAt = now; - if (_siblingsReadAt == 0 || now - _siblingsReadAt >= SiblingReadMs) - { - _siblingsReadAt = now; - _siblings = IltBankExport.ReadSiblings(_ctx.Store.CharFolder); - } - IltServerOptions o = _ctx.Options; - string me = _ctx.CharName.Length > 0 ? _ctx.CharName : System.IO.Path.GetFileName(_ctx.Store.CharFolder.TrimEnd('\\', '/')); - var rows = new List(_siblings.Count + 1) { new(me, true, _ctx.State.Bank) }; - rows.AddRange(_siblings); - int enabled = o.IsOn(IltFeature.Bank) ? 1 : o.IsOff(IltFeature.Bank) ? 0 : -1; - _bankJson = IltBankExport.Build(o.IsIltLikeWorld, enabled, o.WorldName, me, rows, Banking.LatestResult, Banking.Transactions); - } - - public IltHubState State => _ctx.State; - public IltServerOptions Options => _ctx.Options; - internal IltHubContext Context => _ctx; - - /// World is ILT-like and the server has at least one ILT feature on. - public bool Available => _ctx.Options.IsIltLikeWorld && _ctx.Options.AnyFeatureOn; - - /// - /// Whether a section can be shown now: the ILT tabs and the Guardian need server features. - /// Character (moved to RynthOracle) always answers true so its redirect is never refused. - /// - public bool SectionAvailable(IltSection section) => section switch - { - IltSection.Character => true, - IltSection.Banking => Available && !_ctx.Options.IsOff(IltFeature.Bank), - IltSection.Games => Available && Games.AnyGameAvailable, - // Content, not a server feature bit: an ILT world and the master switch. - IltSection.VaultedDungeons => _ctx.Options.IsIltLikeWorld && VaultedDungeons.MasterEnabled(), - _ => Available, - }; - - /// - /// The Mini Remote offers the Infinite Leaftide tabs: an ILT-like world (or the Force-ILT - /// override from RynthCore Options > Diagnostics). The tabs then follow . - /// - public bool OffersTabs => _ctx.Options.IsIltLikeWorld; - - /// Whether the Mini Remote's tab bar shows . - public bool TabShown(IltSection section) => OffersTabs && IltSections.IsTab(section) && SectionAvailable(section); - - /// Render thread: one Mini Remote ILT tab's body (RynthAi's MiniRemoteHud draws the tab bar). - public void RenderTab(IltSection section) => _ui.RenderTab(section); - - /// Render thread: a tab was just drawn as RynthCore's section view (it counts as the Mini Remote on screen). - public void NoteTabDrawn() => System.Threading.Interlocked.Exchange(ref _tabDrawnAt, IltHubContext.NowMs); - - /// - /// Render thread: the ILT session extras (coins, pyreals, item conversions) in RynthCore's Mini - /// Remote "Session Stats" section, below RynthAi's session stats (surface "section:ilt-rates"). - /// - public void RenderRatesSection() => _ui.RenderRatesSection(); - - /// Render thread: the /qb list in RynthILT's own Quests section (surface "section:ilt-questbonus"). - public void RenderQuestBonusSection() => _ui.RenderQuestBonusSection(); - - /// Render thread: the Guardian panel's body (RynthPluginRenderEmbed "guardian"). - public void RenderGuardianPanel() => _ui.RenderGuardianPanel(); - - /// Render thread: one of the sections RynthAi draws (RynthILT.Hub RenderSection); false = nothing drawn. - public bool RenderSection(string id) => _ui.RenderSection(id); - - /// The Force-ILT world override (world identity only; features still come from the server). Set from any thread. - public bool ForceIltWorld - { - get => _ctx.State.ForceLeaftideFeatures; - set => _forceRequest = value ? 1 : 0; - } - - /// 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)); - - // ── Lifecycle ─────────────────────────────────────────────────────────── - - /// - /// Login: remember the character, schedule the options check, import UB data once. - /// : the character's RynthAi profile had "Force enable" ticked. - /// - public void OnLoginComplete(string charName, bool forceFromMigration) - { - _ctx.CharName = charName ?? string.Empty; - if (forceFromMigration) _ctx.State.ForceLeaftideFeatures = true; - RynthLog.Event(LogEvents.IltLogin, $"login: char='{_ctx.CharName}' world='{_ctx.Options.WorldName}'"); - _ctx.Options.OnLoginComplete(); - _ctx.Inventory.Reset(); - Rates.Reset(); - _questGeneration = 0; - - 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)); - } - } - - /// A RynthAi /myquests refresh ended since the last look: tell the options (the "quests" bit). - private void PollQuestOutcome() - { - if (!_ctx.Ai.TryGetQuestStatus(out var st) || st.Generation == _questGeneration) return; - _questGeneration = st.Generation; - if (st.Generation > 0) _ctx.Options.NoteQuestTrackerOutcome(st.Disabled != 0, st.Count); - } - - /// Pump-thread tick. - public void Tick() - { - long now = IltHubContext.NowMs; - int force = _forceRequest; - if (force >= 0) - { - _forceRequest = -1; - _ctx.State.ForceLeaftideFeatures = force == 1; - } - _ctx.DrainPosted(); - _ctx.Capture.Tick(); - _ctx.Options.Tick(); - PollQuestOutcome(); - - // The charms / bank snapshots other plugins read (RynthILT.Data), only while watched. - try { RebuildReaderData(now); } - catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "RebuildReaderData"); } - - // The profile other plugins read ("RynthILT.Server"): world, feature states, fellowship, /qb. - if (now - _profileBuiltAt >= ProfileRebuildMs) - { - _profileBuiltAt = now; - try { RebuildProfile(); } - catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "RebuildProfile"); } - } - - // "Mini Remote on screen" gates bank auto-refresh and the gear / split-arrow scans: RynthAi's Mini - // Remote, or one of the tabs drawn as RynthCore's section view in the last couple of seconds. - _ctx.State.WindowVisible = _ctx.Ai.MiniRemoteVisible - || now - System.Threading.Interlocked.Read(ref _tabDrawnAt) < TabDrawnMs; - - // One hint per session once the server confirms ILT 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("[Mini Remote] ILT server features detected. Open the Mini Remote (bar button, /rc miniremote) for the ILT tabs."); - } - - // Every feature here is Infinite Leaftide's: dormant on any other world. - 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($"[Mini Remote] Confirmation for '{_pendingLabel}' expired."); - ClearPending(); - } - - if (now - _lastSaveAt >= SaveIntervalMs) - { - _lastSaveAt = now; - _ctx.Store.SaveStateIfDirty(_ctx.State); - } - } - - /// A creature's health update from the server (RynthPluginOnUpdateHealth): auto-capture's fallback health read. - public void OnUpdateHealth(uint objectId, float healthRatio) - { - if (!_ctx.Options.IsIltLikeWorld) return; - PetAutomation.NoteHealth(objectId, healthRatio); - } - - /// - /// The sub-tabs RynthILT adds to one of RynthAi's tabs (RynthILT.Hub GetSubTabs): the Pets tab's - /// Breeding on an ILT world whose server hasn't reported pet breeding off. (Id, label) pairs; the - /// id is a RenderSection id. Any thread. - /// - public (string Id, string Label)[] SubTabs(string parent) - { - if (!string.Equals(parent, RynthCore.Plugin.Shared.RynthIltHub.TabParentPets, StringComparison.OrdinalIgnoreCase) - || !_ctx.Options.IsIltLikeWorld || _ctx.Options.IsOff(RynthCore.Plugin.Shared.RynthIltHub.FeaturePetBreeding)) - return Array.Empty<(string, string)>(); - return new[] { (RynthCore.Plugin.Shared.RynthIltHub.SectionPetBreeding, "Breeding") }; - } - - /// - /// RynthILT.Hub GetSetting: a setting another plugin mirrors (RynthIltHub.Setting*), -1 when not offered - /// (unknown key, or off an ILT world: the engine row then hides). Any thread. - /// - public int GetSetting(string key) => key switch - { - RynthCore.Plugin.Shared.RynthIltHub.SettingVaultedDungeons when _ctx.Options.IsIltLikeWorld - => _ctx.State.VaultedDungeonsEnabled ? 1 : 0, - _ => -1, - }; - - /// - /// RynthILT.Hub GetText: a short text RynthAi shows (RynthIltHub.Text*); "" for an unknown id, and - /// the session tail off ILT. Any thread. - /// - public string GetText(string id) => id switch - { - RynthCore.Plugin.Shared.RynthIltHub.TextServerId => IltSectionsManifest.Server, - RynthCore.Plugin.Shared.RynthIltHub.TextSessionReport when _ctx.Options.IsIltLikeWorld => _ui.SessionReportTail(), - _ => string.Empty, - }; - - /// RynthILT.Hub SetSetting: false for an unknown key. Saved with the state (next periodic save). Any thread. - public bool SetSetting(string key, int value) - { - if (key != RynthCore.Plugin.Shared.RynthIltHub.SettingVaultedDungeons) return false; - bool on = value != 0; - if (_ctx.State.VaultedDungeonsEnabled != on) - RynthLog.Write(LogCat.IltHub, $"Vaulted Dungeons master switch {(on ? "on" : "off")} (Settings window)"); - _ctx.State.VaultedDungeonsEnabled = on; - return true; - } - - /// The server's killer notification (pump thread): restarts the Vaulted Dungeons no-kill timer, on ILT only. - public void OnKillNotification() - { - if (!_ctx.Options.IsIltLikeWorld) return; - try { VaultedDungeons.OnKillNotification(); } - catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "VaultedDungeons.OnKillNotification"); } - } - - /// Pump-thread chat line. Returns true when the line should be hidden. - public bool OnChat(string text, int chatType = -1) - { - 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; - // The ring line needs its chat type (a player repeating it is ignored). - try { RingEvade.OnChatLine(line, chatType); } - catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "IltRingEvade.OnChatLine"); } - 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, - IltPetLogs or IltPetBreeding or IltPetAutomation => LogCat.IltPets, - IltSessionRates => LogCat.IltRates, - IltQuestBonus => LogCat.IltQuests, - IltProgression => LogCat.IltProgression, - IltGear or IltCharms => LogCat.IltGear, - IltGames => LogCat.IltGames, - IltVaultedDungeons => LogCat.IltHub, - _ => LogCat.IltHub, - }; - - /// 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 (RynthILTGetProgressionJson). - /// "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(IltStyle.JsonEscape(_ctx.Options.WorldName ?? string.Empty)).Append("\","); - Progression.AppendSnapshotJson(sb); - sb.Append('}'); - return sb.ToString(); - } - - /// JSON for RynthILTGetCharmsJson / RynthPluginGetCharmsJson (an older engine's Settings "Charms Tracking" tab). Pump thread. - public string BuildCharmsJson() => Charms.BuildJson(); - - /// Render thread: Games HUD and confirmation popups. - 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); - // Probe's OnComplete is not RequestAugs' — drain a queued Refresh current / empty retry. - Progression.AfterExternalAugCapture(); - break; - case IltFeature.Pets: PetLogs.ApplyRoster(false, r.Lines); break; - case IltFeature.Shinies: PetLogs.ApplyRoster(true, r.Lines); break; - case IltFeature.Qb: QuestBonus.ApplyQbProbe(r.Lines); break; - // Bank lines are parsed passively by IltBanking.OnChat as they arrive. - } - } - - // ── Commands ──────────────────────────────────────────────────────────── - - /// - /// The ILT verbs: "/ra hub [open <ILT tab> [show|hide|toggle]|tab <ILT tab>|refresh|bank|status| - /// force on|off|servers [list]|profile save|load|list ...|suit list|test|load ...|clap|attr ...| - /// confirm|cancel]" (RynthAi keeps show/hide/toggle and its own Quests / Pets tabs, and forwards - /// the rest here; "/ilt hub ..." comes straight here), "/ra bounty [show|hide|toggle]" (aliases - /// bounties / bountys: RynthCore's ILT Bounties panel), "/ra guardian ..." (window: RynthCore's - /// ILT Guardian panel; the rest IltGuardian.HandleCommand) and "rates reset" (the Mini Remote's - /// Reset XP). 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("rates", StringComparison.OrdinalIgnoreCase)) - { - // "rates reset": the coin / pyreal session starts over with RynthAi's session stats. - Rates.Reset(); - return true; - } - if (IsBountyVerb(verb)) - { - // Bounties are RynthILT's Bounties window (RynthCore's ILT button); open that panel. - OpenEnginePanel("bounties", "Bounties", args.Length > 0 ? args[0] : "toggle"); - return true; - } - if (verb.Equals("guardian", StringComparison.OrdinalIgnoreCase)) - { - // "/ra guardian window [show|hide|toggle]" opens RynthCore's ILT Guardian panel; - // everything else is the Guardian's. - if (args.Length > 0 && args[0].Equals("window", StringComparison.OrdinalIgnoreCase)) - OpenEnginePanel("guardian", "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() : "help"; - string rest = args.Length > 1 ? string.Join(" ", args.Skip(1)) : string.Empty; - switch (cmd) - { - case "show": - case "hide": - case "toggle": - // The Mini Remote is RynthAi's ("/ilt hub show" lands here). - _ctx.Chat("[Mini Remote] " + _ctx.Ai.MiniRemoteTab(IltSections.RemoteTab, cmd)); - break; - case "open": - if (args.Length > 1 && IsBountyVerb(args[1])) - { - OpenEnginePanel("bounties", "Bounties", args.Length > 2 ? args[2] : "toggle"); - break; - } - if (args.Length < 2 || !IltSections.TryParse(args[1], out IltSection section)) - { - // Quests and Pets are RynthAi's tabs: not ours to open. - if (args.Length >= 2 && IltSections.IsUniversalTabName(args[1])) return false; - _ctx.Chat("[Mini Remote] Usage: /ra hub open pets|banking|gear|charms|games|vaulted|guardian|bounties [show|hide|toggle] (character: /ro character, quests: /ro)"); - break; - } - OpenSection(section, args.Length > 2 ? args[2] : "toggle"); - break; - case "tab": - // The engine's dashboard: it opens its Mini Remote window itself, so only switch tabs. - if (args.Length > 1 && IltSections.TryParse(args[1], out IltSection tab) && IltSections.MovedCommand(tab) is string moved) - OpenMoved(tab, moved); - else if (args.Length > 1 && IltSections.TryParse(args[1], out tab) && IltSections.IsTab(tab)) - _ctx.Ai.MiniRemoteTab(IltSections.TabId(tab), "select"); - else - return false; // the Remote tab or a RynthAi tab: RynthAi's - break; - case "refresh": _ctx.Options.Refresh(manual: true); break; - case "bank": Banking.RequestRefresh(quiet: false); break; - // "/ilt qb": reads the /qb list again (the Quests tab's quest bonus section). - case "qb": _ctx.Chat("[RynthILT] " + QuestBonus.RefreshQb()); break; - case "status": PrintStatus(); break; - case "features": PrintFeatures(); break; - case "force": - _ctx.State.ForceLeaftideFeatures = !rest.Equals("off", StringComparison.OrdinalIgnoreCase); - _ctx.Chat(IltServerOptions.EngineDecides - ? $"[Mini Remote] Force ILT world: {(_ctx.State.ForceLeaftideFeatures ? "on" : "off")} for this character (RynthCore counts it unless /rc server ilt off). Use /ra hub refresh to re-check the server." - : $"[Mini Remote] Force ILT world: {(_ctx.State.ForceLeaftideFeatures ? "on" : "off")}. Use /ra hub refresh to re-check the server."); - break; - case "servers": HandleServers(rest); 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 "attr": HandleAttr(args.Skip(1).ToArray()); break; - case "confirm": RunPending(); break; - case "cancel": - _ctx.Chat(_pendingAction != null ? $"[Mini Remote] Cancelled '{_pendingLabel}'." : "[Mini Remote] Nothing to cancel."); - ClearPending(); - break; - default: - _ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote)|refresh|bank|status|features|force on|off|servers [list]|clap|confirm|cancel"); - _ctx.Chat("[Mini Remote] /ra hub open pets|banking|gear|charms|games|vaulted [show|hide|toggle] (Mini Remote tabs; character: /ro character, quests: /ro)"); - _ctx.Chat("[Mini Remote] /ilt vaulted [on|off|toggle|status] (Vaulted Dungeons; master switch: /ilt settings or Settings > Navigation > Vaulted Dungeons)"); - _ctx.Chat("[Mini Remote] /ra hub profile list|save [shared]|load /ra hub suit list|test|load [name]"); - _ctx.Chat("[Mini Remote] /ra hub attr run|stop|costs|status|auto on|off|every |raise (Skills panel > Progression)"); - _ctx.Chat("[Mini Remote] /ra quests refresh (quiet /myquests) /ra pets [show|hide] /ilt qb (the quest bonus list)"); - _ctx.Chat("[Mini Remote] /ra guardian [window|translate |handin|stop|chat on|off|auto on|off|buy on|off|refresh|status] (window: ILT button > Guardian)"); - _ctx.Chat("[Mini Remote] /ra bounty [show|hide|toggle] (RynthCore's ILT button > Bounties, /rc bounties)"); - _ctx.Chat("[Mini Remote] The ILT verbs also work as /ilt hub ..., /ilt guardian ... (RynthILT)."); - break; - } - return true; - } - - /// "/ra hub features": every Leaftide feature RynthILT supports, with the server's state for each. - private void PrintFeatures() - { - IltServerOptions o = _ctx.Options; - string world = o.WorldName.Length > 0 ? o.WorldName : "unknown world"; - _ctx.Chat($"[Mini Remote] Leaftide features on {world} ({(o.IsIltLikeWorld ? "ILT world" : "not an ILT world")}, " - + $"fellowships up to {IltFeatureCatalog.FellowshipMax(o.IsIltLikeWorld)}):"); - foreach (string line in IltFeatureCatalog.BuildChatLines(o.IsIltLikeWorld, o.Get)) - _ctx.Chat("[Mini Remote] " + line); - } - - /// "/ra hub servers [list | <names, comma separated> | default]": which world names count as Infinite Leaftide. - private void HandleServers(string rest) - { - string arg = rest.Trim(); - if (arg.Length > 0 && !arg.Equals("list", StringComparison.OrdinalIgnoreCase)) - { - var list = arg.Equals("default", StringComparison.OrdinalIgnoreCase) - ? new List(ServerFeatureGate.DefaultServerNames) - : ServerFeatureGate.ParseList(arg); - if (list.Count == 0) { _ctx.Chat("[Mini Remote] Usage: /ra hub servers | default | list"); return; } - _ctx.Settings.ServerNames = list; - _ctx.SaveSettings(); - } - _ctx.Chat("[Mini Remote] ILT world names: " + ServerFeatureGate.FormatList(ServerFeatureGate.Patterns(_ctx.Settings))); - _ctx.Chat("[Mini Remote] " + ServerFeatureGate.Describe(_ctx.Options.WorldName, _ctx.Settings, _ctx.State.ForceLeaftideFeatures)); - } - - /// "/ra hub attr ...": the attribute raiser from chat (same verbs as the Progression tab). - private void HandleAttr(string[] a) - { - var raiser = Progression.Attributes; - string sub = a.Length > 0 ? a[0].ToLowerInvariant() : "status"; - switch (sub) - { - case "run": raiser.HandleRemote("attrrun", new[] { "attrrun" }); break; - case "stop": raiser.HandleRemote("attrstop", new[] { "attrstop" }); break; - case "costs": raiser.HandleRemote("attrcosts", new[] { "attrcosts" }); break; - case "auto": raiser.HandleRemote("attrauto", new[] { "attrauto", a.Length > 1 ? a[1] : "off" }); break; - case "every": raiser.HandleRemote("attrevery", new[] { "attrevery", a.Length > 1 ? a[1] : "5" }); break; - case "raise" when a.Length > 2: raiser.HandleRemote("attrraise", new[] { "attrraise", a[1], a[2] }); break; - default: - var c = _ctx.State.Character; - string blocked = raiser.Blocker() ?? "ready"; - _ctx.Chat($"[Mini Remote] Attribute raiser: {blocked}; auto={(c.AttrAutoRaise ? $"on every {c.AttrAutoRaiseMinutes}m" : "off")} " - + $"mode={(IltAttributeRaiser.Mode)c.AttrRaiseMode} keep={IltParse.Compact(c.AttrKeepXp)} " - + $"stats={(c.AttrRaiseStats.Count > 0 ? string.Join(",", c.AttrOrder.Where(c.AttrRaiseStats.Contains)) : "none ticked")}"); - return; - } - } - - /// "/ra bounty", "/ra bounties" and the "/ra bountys" spelling all reach the Bounties panel. - public static bool IsBountyVerb(string verb) - => verb.Equals("bounty", StringComparison.OrdinalIgnoreCase) - || verb.Equals("bounties", StringComparison.OrdinalIgnoreCase) - || verb.Equals("bountys", StringComparison.OrdinalIgnoreCase); - - /// - /// Applies show / hide / toggle to a section: a Mini Remote tab, or for the Guardian - /// RynthCore's ILT panel. Says what happened. - /// - private void OpenSection(IltSection section, string mode) - { - if (IltSections.MovedCommand(section) is string moved) - { - // Character left the Mini Remote: open its new home instead. - if (!mode.Equals("hide", StringComparison.OrdinalIgnoreCase)) OpenMoved(section, moved); - return; - } - if (!IltSections.IsTab(section)) - { - OpenEnginePanel(IltSections.TabId(section), IltSections.Label(section), mode); - return; - } - if (section == IltSection.VaultedDungeons && !SectionAvailable(section)) - { - _ctx.Chat(_ctx.Options.IsIltLikeWorld - ? "[Mini Remote] The Vaulted Dungeons tab is off: turn on \"Vaulted Dungeons\" in the ILT settings (/ilt settings; also Settings > Navigation) (the master switch, off by default)." - : "[Mini Remote] Vaulted Dungeons is not available on this server (Infinite Leaftide / ACECustom only)."); - return; - } - string reply = _ctx.Ai.MiniRemoteTab(IltSections.TabId(section), mode); - if (!SectionAvailable(section) && !mode.Equals("hide", StringComparison.OrdinalIgnoreCase)) - reply = $"The {IltSections.Label(section)} tab shows once the server reports that feature on."; - _ctx.Chat("[Mini Remote] " + reply); - } - - /// - /// Opens the new home of a section that moved out of the Mini Remote (RynthOracle's Character - /// tab) by running its chat command, or says where it is when the command can't run (an older - /// RynthCore, or RynthOracle not loaded). Pump thread. - /// - public void OpenMoved(IltSection section, string command) - { - if (_ctx.Host.HasInvokeChatParser && _ctx.Host.InvokeChatParser(command)) - return; - _ctx.Chat($"[Mini Remote] {IltSections.Label(section)} moved to RynthOracle's Character tab ({command}); " - + "the ILT session rates are in the Mini Remote's Session Stats."); - } - - /// - /// Opens / closes one of RynthCore's ILT panels ("/rc bounties|guardian [show|hide|toggle]") - /// through the engine's chat dispatcher. Pump thread. - /// - public void OpenEnginePanel(string rcVerb, string label, string mode) - { - string m = (mode ?? string.Empty).ToLowerInvariant() switch - { - "show" or "on" or "open" => "show", - "hide" or "off" or "close" => "hide", - _ => "toggle", - }; - if (_ctx.Host.HasInvokeChatParser && _ctx.Host.InvokeChatParser($"/rc {rcVerb} {m}")) - return; - _ctx.Chat($"[Mini Remote] {label} is a RynthCore ILT panel: the bar's ILT button, or /rc {rcVerb}."); - } - - /// "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($"[Mini Remote] 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("[Mini Remote] on: " + (on.Length > 0 ? on : "-")); - _ctx.Chat("[Mini Remote] 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("[Mini Remote] Profiles: " + (names.Count > 0 ? string.Join(", ", names) : "(none)")); - return; - } - if (a.Length < 2) { _ctx.Chat("[Mini Remote] 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) - ? $"[Mini Remote] Saved {(shared ? "shared " : "")}profile '{a[1]}'." : "[Mini Remote] 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) - ? $"[Mini Remote] Loaded profile '{profile}'." : "[Mini Remote] 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($"[Mini Remote] 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("[Mini Remote] 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("[Mini Remote] 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("[Mini Remote] " + l); - break; - case "load": - // Equipping a suit swaps gear mid-session, so it needs an explicit confirm. - RequestConfirm($"equip suit '{name ?? "(auto)"}'", () => _ctx.Chat("[Mini Remote] " + Gear.Suits.Load(name))); - break; - default: - _ctx.Chat("[Mini Remote] Usage: /ra hub suit list|test [name]|load [name]"); - break; - } - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs deleted file mode 100644 index c2d34dc..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubState.cs +++ /dev/null @@ -1,364 +0,0 @@ -// IltHubState.cs — Persisted per-character state for the ILT Hub (Infinite Leaftide tools). -// Originally SilentKelpie's ILT Hub state in RynthAi; moved to RynthILT 2026-10-13. -// -// Lives in %APPDATA%\RynthCore\RynthILT\\\hub.json (IltHubStore). The first -// login with RynthILT copies RynthAi's \ilt-hub.json there (IltMigration), so the -// shape stays compatible with that file: the parts that stayed with RynthAi's universal Mini -// Remote tabs (the Pets tab's settings, the quest tracker's filter and favorites, the VTank -// import path) are simply not read here any more. Serialized with the NativeAOT source-generated -// IltHubJsonContext (IncludeFields = true), so plain public fields are used throughout. -using System; -using System.Collections.Generic; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// 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; - - /// - /// True once the RynthAi settings that moved to RynthILT on 2026-10-20 (the Pets tab's ACECustom - /// options, ...) were copied from this character's RynthAi files (IltMigration.ImportRynthAiSettings). - /// - public bool RynthAiSettingsImported; - - /// 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(); - /// Infinite Leaftide combat helpers (moved from RynthAi's profile 2026-10-20). - public IltCombatState Combat = new(); - - /// - /// The Vaulted Dungeons keeper's master switch (off by default): while off it does nothing (no - /// recalls, no /rc quit, no tab). RynthAi's "Vaulted Dungeons" setting until 2026-10-20 (copied once); - /// set in the ILT settings ("/ilt settings") or the engine's Settings > Navigation row (RynthAi - /// mirrors it through RynthILT.Hub GetSetting / SetSetting). - /// - public bool VaultedDungeonsEnabled; - - /// ACECustom T11 gear (IltT11): the item-aug override (moved from RynthAi's profile 2026-10-20). - public IltT11State T11 = new(); - - /// The ILT sections of RynthAi's Remote tab (moved from RynthAi's huds.json 2026-10-20). - public IltRemoteState Remote = new(); -} - -// ── RynthAi's Remote tab ──────────────────────────────────────────────────── - -public sealed class IltRemoteState -{ - /// The Remote tab's Bank section (ILT bank balances). Was RynthAi's MiniShowBank. - public bool ShowBank = true; - /// The Remote tab's Guardian line (the last Temple guardian answer). Was RynthAi's MiniShowGuardian. - public bool ShowGuardian = true; -} - -// ── T11 ───────────────────────────────────────────────────────────────────── - -public sealed class IltT11State -{ - /// - /// The item augmentation count T11 wield gates use ("T11: Can Wield" in RynthAi's loot rules) instead - /// of the "/aug" reply's; -1 = automatic (read from /aug). "/ilt t11 augs <n|auto>". Was RynthAi's - /// T11ItemAugsOverride. - /// - public int ItemAugsOverride = -1; -} - -// ── Combat ────────────────────────────────────────────────────────────────── - -public sealed class IltCombatState -{ - /// - /// When the Empyrean Handler channels its lethal ring and the character is inside it, have RynthAi - /// back-jump away and re-engage (IltRingEvade; RynthAi acts only while its macro runs with combat - /// on). On by default because it is gated that way. Was RynthAi's HandlerRingEvade. - /// - public bool HandlerRingEvade = true; -} - -/// Cached result of the server-options check (see IltServerOptions). -public sealed class IltServerOptionsSnapshot -{ - public string WorldName = string.Empty; - /// "probe" (the login probe) 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; - /// Bound to the character: deposit and withdraw only, never transferred. - public long PrestigeCoins; - public DateTime LastUpdated = DateTime.MinValue; - - /// Last transfer recipient typed into the transfer form. - public string TransferTarget = string.Empty; - public int TransferCurrencyIndex; - /// Transfer form's trade-note denomination (IltBankCommands.NoteDenominations; 9 = MMD). - public int TransferNoteIndex = 9; - - /// Deposit / withdraw form choices (IltBankCommands.Deposits / Withdrawals / NoteDenominations). - public int DepositIndex; - public int WithdrawIndex; - public int WithdrawNoteIndex = 9; - - /// 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 -{ - /// Last captured /pets and /shinies rosters (display only; the Pets tab's logs). - public List PetLog = new(); - public List ShinyLog = new(); - /// The breeding tracker: rules this server showed, growth stage names, recent events (IltPetBreeding). - public IltBreedingState Breeding = new(); - - // ACECustom's parts of the Pets tab (IltPetAutomation, moved from RynthAi 2026-10-20; copied once - // from RynthAi's miniremote.json by IltMigration.ImportRynthAiSettings). New names on purpose: an - // old ilt-hub.json copy still carries RynthAi's UsePyrealRefillPath / AutoCaptureEnabled / - // CaptureLensIndex from before 2026-10-13, and those stale values must not be read back. - /// - /// Summon from an EMPTY essence while the Summon Essence Refill charm is on (the server refills it - /// from banked pyreals). Still needs the server to confirm the feature (RynthAi.Hub's PetManager - /// asks AllowSummonOnEmpty). - /// - public bool RefillFromEmpty; - /// Use the chosen siphon lens on the nearest creature once it is weak enough (off by default). - public bool AutoCapture; - /// Index into PetCaptureRules.Lenses (Flawed to Asheron's). - public int CaptureLens; - // The Pets tab's own settings (roster, healing / cosmetic pets) are RynthAi's (its miniremote.json). -} - -// ── 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; - - // ── Attribute raiser (IltAttributeRaiser; Skills panel > Progression) ── - /// Spend unassigned XP on the ticked attributes/vitals every AttrAutoRaiseMinutes. - public bool AttrAutoRaise; - public int AttrAutoRaiseMinutes = 5; - /// IltAttributeRaiser.Mode: 0 priority (top of the order first), 1 round robin, 2 cheapest first. - public int AttrRaiseMode; - /// Unassigned XP the raiser never spends. - public long AttrKeepXp; - /// /attr abbreviations in raise-priority order (all nine; repaired on load). - public List AttrOrder = new(IltAttributeRaiser.DefaultOrder); - /// /attr abbreviations the raiser may spend on ("Raise now" and auto-raise). - public List AttrRaiseStats = new(); - - /// Quest bonus (/qb) list filter. (The /myquests tracker's filter and favorites are RynthAi's.) - public string QbFilter = string.Empty; - // The ILT sections are Mini Remote tabs now (HudState.MiniRemoteTab); the old per-section - // "window open" flags in older files are ignored on load. - - /// - /// 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 Aetheria too). Infinite Leaftide - /// aetheria goes up to level , so the cap runs to one past it. - /// - public int ChunkAetheriaUnderLevel = 4; - /// Never chunk aetheria carrying a Crit rating (C, GearCrit 372; ILT tier-10 sigils of level 6+). - public bool KeepAetheriaWithCrit = true; - /// Never chunk aetheria carrying a Crit Damage rating (CD, GearCritDamage 374). - public bool KeepAetheriaWithCritDamage = true; - /// Never chunk aetheria carrying a Crit Damage Resist rating (CDR, GearCritDamageResist 375). - public bool KeepAetheriaWithCritDamageResist = true; - /// - /// Rating level for the C / CD / CDR keep switches: a rating at or above this keeps the piece, - /// a lower one does not protect it (it chunks if the other rules allow). 1 = any rating keeps. - /// - public int KeepAetheriaRatingAtLeast = 1; - - // Corrupted-weapon keep rules (ub-IT IdleActs > Corr Chunk). All off by default, as in ub-IT: - // the hard rules (unmodified, workmanship, cleaving, never-chunk) always apply on top. - /// Never chunk a corrupted weapon with Crushing Blow (CriticalFrequency float 147 > 0). - public bool KeepCorruptedCrushingBlow; - /// Never chunk a corrupted weapon with Biting Strike (CriticalMultiplier float 136 > 0). - public bool KeepCorruptedBitingStrike; - /// Never chunk a corrupted weapon with Armor Cleaving (IgnoreArmor float 155 > 0). - public bool KeepCorruptedArmorCleaving; - /// Never chunk a corrupted weapon with any slayer (SlayerCreatureType int 166 > 0). - public bool KeepCorruptedAnySlayer; - /// Never chunk a multi-strike corrupted weapon (AttackType int 47 = 160 / 166 / 486). - public bool KeepCorruptedMultiStrike; - /// Never chunk a corrupted weapon with an elemental damage bonus (int 204 > 0). - public bool KeepCorruptedElementalBonus; - /// Never chunk a corrupted weapon with any spell on it. - public bool KeepCorruptedAnySpell; - /// Never chunk a corrupted weapon whose max damage (int 44) is at least this. 0 = off. - public int KeepCorruptedMaxDamageAtLeast; - /// Spell ids (comma / space separated): never chunk a corrupted weapon carrying any of them. - public string KeepCorruptedSpellIds = ""; - - // 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). (The VTank .usd import path is RynthAi's: the importer stayed there.) - public string LastEquipProfile = string.Empty; - - // Rings inscription chain (IltRingChainRunner; SilentKelpie's, moved from RynthAi's Crafting tab) - /// Recipe id (IltRingChain.Recipes) to how many times to craft it. Pump thread only. - public Dictionary RingRuns = new(StringComparer.OrdinalIgnoreCase); - /// Answer the server's craft dialog Yes for the queued combines (engine API v85). - public bool RingAnswerCraftDialog = true; - /// Craft and inscribe in combat mode too (servers with combat-mode crafting). - public bool RingAllowInCombat; -} - -// ── 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.RynthILT/Hub/IltHubStore.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubStore.cs deleted file mode 100644 index 4c15401..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubStore.cs +++ /dev/null @@ -1,494 +0,0 @@ -// IltHubStore.cs — Disk persistence for the ILT Hub. -// Originally SilentKelpie's ILT Hub store in RynthAi; moved to RynthILT 2026-10-13. -// -// Files (RynthILT's folder, %APPDATA%\RynthCore\RynthILT; = \): -// \hub.json live Hub state (IltHubState) -// \bank-transactions.json bank transaction log (capped) -// \profiles\.json named per-character Hub profiles -// Profiles\.json named profiles shared by every character -// They were ilt-hub.json, ilt-hub-transactions.json, ilt-hub-profiles\ (RynthAi's per-character -// settings folder) and RynthAi\IltHubProfiles\; IltMigration copies them over on the first login. -// 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.Plugin.Shared; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal sealed class IltHubStore -{ - /// Maximum bank transactions kept on disk (oldest dropped first). - public const int MaxTransactions = 1000; - - /// RynthILT's folder: shared profiles, aug costs and equipment suits (overridable for the tests). - public static string SharedRoot = RynthILTPlugin.SettingsRoot; - - public const string StateFile = "hub.json"; - public const string TransactionsFile = "bank-transactions.json"; - public const string ProfilesFolder = "profiles"; - - 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; - } - - /// - /// True while this character's copy from RynthAi is unfinished (IltMigration): the state, the - /// bank log and per-character profiles are not written, so no fresh file shadows a RynthAi - /// original that hasn't been copied yet. Shared profiles still save. - /// - public Func WritesBlocked = static () => false; - - /// - /// The character's RynthAi folder while its copy is unfinished: a file RynthILT doesn't have yet - /// is read from there (read only) when it can be; otherwise the Hub runs from the defaults. - /// - public string? LegacyFolder; - - private bool Blocked() - { - try { return WritesBlocked(); } - catch { return true; } - } - - /// A RynthAi original read without locking it (it may be held open elsewhere). Null when it can't be. - private string? ReadLegacy(string fileName) - { - if (string.IsNullOrEmpty(LegacyFolder)) return null; - string path = Path.Combine(LegacyFolder, fileName); - try - { - if (!File.Exists(path)) return null; - using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); - using var sr = new StreamReader(fs); - return sr.ReadToEnd(); - } - catch (Exception ex) - { - RynthLog.Write(LogCat.IltStore, $"RynthAi's {path} can't be read yet ({ex.Message}); running from the defaults until it is copied."); - return null; - } - } - - public string CharFolder => _charFolder; - private string StatePath => Path.Combine(_charFolder, StateFile); - private string TxPath => Path.Combine(_charFolder, TransactionsFile); - private string CharProfileDir => Path.Combine(_charFolder, ProfilesFolder); - internal static string SharedProfileDir => Path.Combine(SharedRoot, "Profiles"); - - // ── 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, IltHubJsonContext.Default.IltHubState); - if (s != null) - { - Normalize(s); - _lastStateJson = json; - return s; - } - } - else if (ReadLegacy("ilt-hub.json") is string legacyJson) - { - var s = JsonSerializer.Deserialize(legacyJson, IltHubJsonContext.Default.IltHubState); - if (s != null) { Normalize(s); 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, IltHubJsonContext.Default.IltHubState); - if (json == _lastStateJson) return; - if (Blocked()) return; // the copy from RynthAi isn't finished: never shadow its hub.json - // A failure is said in chat once per folder (on ILT) and logged; the next periodic save retries. - if (DataWriteGuard.TrySave("the ILT Hub state", StatePath, () => - { - 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.Breeding ??= new(); - s.Pet.Breeding.Rules ??= new(); - s.Pet.Breeding.StageNames ??= new(); - s.Pet.Breeding.Log ??= new(); - s.Pet.Breeding.LastDebug ??= new(); - s.Pet.CaptureLens = Math.Clamp(s.Pet.CaptureLens, 0, PetCaptureRules.Lenses.Length - 1); - s.Pet.Breeding.Rules.RemoveAll(r => r == null || string.IsNullOrEmpty(r.Key)); - s.Pet.Breeding.Log.RemoveAll(e => e == null); - for (int i = 0; i < s.Pet.Breeding.StageNames.Count; i++) s.Pet.Breeding.StageNames[i] ??= string.Empty; - if (s.Pet.Breeding.Log.Count > IltBreedingRules.MaxEvents) - s.Pet.Breeding.Log.RemoveRange(0, s.Pet.Breeding.Log.Count - IltBreedingRules.MaxEvents); - s.Character ??= new IltCharacterState(); - s.Character.ItemConversions ??= new(); - s.Character.AugTargets = new Dictionary(s.Character.AugTargets ?? new(), StringComparer.OrdinalIgnoreCase); - s.Character.AttrOrder = IltAttributeRaiser.RepairOrder(s.Character.AttrOrder); - s.Character.AttrRaiseStats = IltAttributeRaiser.RepairSelection(s.Character.AttrRaiseStats); - s.Character.AttrAutoRaiseMinutes = Math.Clamp(s.Character.AttrAutoRaiseMinutes, 1, 1440); - s.Character.AttrRaiseMode = Math.Clamp(s.Character.AttrRaiseMode, 0, 2); - s.Character.AttrKeepXp = Math.Max(0, s.Character.AttrKeepXp); - s.Character.CharmsSeen = new Dictionary(s.Character.CharmsSeen ?? new(), StringComparer.OrdinalIgnoreCase); - s.Gear ??= new IltGearState(); - s.Gear.DispelInclusions ??= new(); - s.Gear.DispelExclusions ??= new(); - s.Gear.RingRuns = new Dictionary(s.Gear.RingRuns ?? new(), StringComparer.OrdinalIgnoreCase); - s.Games ??= new IltGamesState(); - s.Combat ??= new IltCombatState(); - s.T11 ??= new IltT11State(); - s.Remote ??= new IltRemoteState(); - if (s.T11.ItemAugsOverride < -1) s.T11.ItemAugsOverride = -1; - 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, IltHubJsonContext.Default.IltBankTransactionList); - if (list != null) { _lastTxJson = json; return list; } - } - else if (ReadLegacy("ilt-hub-transactions.json") is string legacyJson) - { - var list = JsonSerializer.Deserialize(legacyJson, IltHubJsonContext.Default.IltBankTransactionList); - if (list != null) 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, IltHubJsonContext.Default.IltBankTransactionList); - if (json == _lastTxJson) return; - if (Blocked()) return; // as SaveStateIfDirty - if (DataWriteGuard.TrySave("the bank transaction log", TxPath, () => - { - 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; } - if (!shared && Blocked()) - { - error = "this character's Hub data is still being copied from RynthAi (see the log); save it as a shared profile, or try again later."; - return false; - } - try - { - string dir = shared ? SharedProfileDir : CharProfileDir; - var copy = Clone(state); - StripRuntime(copy); - string json = JsonSerializer.Serialize(copy, IltHubJsonContext.Default.IltHubState); - string path = Path.Combine(dir, safe + ".json"); - // The player asked for this save: the caller shows the reason (and the fix) itself. - return DataWriteGuard.TrySave("the Hub profile", path, () => - { - Directory.CreateDirectory(dir); - WriteAtomic(path, json); - }, out error, callerShows: 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), IltHubJsonContext.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; - // The breeding tracker holds this object; it is the character's own (not a profile setting). - incoming.Breeding = current.Breeding; - return incoming; - } - - private static IltHubState Clone(IltHubState s) - => JsonSerializer.Deserialize(JsonSerializer.Serialize(s, IltHubJsonContext.Default.IltHubState), - IltHubJsonContext.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.Pet.Breeding = 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.RynthILT/Hub/IltHubUi.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs deleted file mode 100644 index 1dcd3da..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltHubUi.cs +++ /dev/null @@ -1,401 +0,0 @@ -// IltHubUi.cs — The ILT sections' ImGui bodies (render thread only). -// Originally SilentKelpie's ILT Hub UI (RynthAi IltHub/); moved to RynthILT 2026-10-13, with the -// ILT parts of RynthAi's Mini Remote (the Remote tab's Bank section and Guardian line, the menu's -// Infinite Leaftide items) that read the Hub's state. -// -// The ILT sections are tabs of RynthAi's Mini Remote (its MiniRemoteHud draws the tab bar and -// calls RenderTab through RynthILT.Hub): Banking, Gear, Charms and Games. A tab is offered only -// while the server reports its feature on. The Character tab left the Mini Remote on 2026-10-13: -// - the session rates are RynthCore's Mini Remote "Session Stats" section (RenderRatesSection, -// surface "section:ilt-rates"), below RynthAi's one session; -// - the character overview and session are RynthOracle's Character tab ("/ro character"); -// - the "Treat this world as ILT" override and the ILT world names are RynthCore's -// Options > Diagnostics server selection only ("/ra hub force" and "/ra hub servers" remain). -// The /qb list (RynthAi's Quests tab before it moved to RynthOracle) is RynthILT's own "Quests" -// section on the rail (RenderQuestBonusSection, surface "section:ilt-questbonus"). -// RenderSection draws the ILT pieces inside RynthAi's own surfaces (the Remote tab, the Pets tab, -// the Mini Remote menu). The Guardian is a RynthCore ILT panel (the bar's ILT button, next to -// Bounties), drawn through RenderGuardianPanel. Render() keeps the floating extras: the Games HUD and the confirmation -// modal. 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.Shared; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal sealed class IltHubUi -{ - private const string ConfirmPopupId = "Confirm##iltconfirm"; - private static readonly Vector4 ColLabel = new(0.80f, 0.84f, 0.90f, 1f); - - /// Where a server is forced now (the only place: RynthCore's Options window). - private const string ForceHint = "To force a server, use RynthCore Options > Diagnostics > server selection (/rc diagnostics)."; - - /// RynthCore's command that opens Options > Diagnostics (RynthCore 2026.10.5.54+). - private const string DiagnosticsCommand = "/rc diagnostics"; - - private readonly IltHubController _hub; - private readonly IltHubContext _ctx; - private IltConfirmRequest? _confirm; - private bool _confirmOpened; - // The last tab body drawn (for one shown log event per tab change); -1 = none yet. - private int _lastTabLogged = -1; - - public IltHubUi(IltHubController hub, IltHubContext ctx) - { - _hub = hub; - _ctx = ctx; - } - - /// The floating extras: Games HUD and the confirmation modal. - public void Render() - { - _hub.Games.RenderHud(); - RenderConfirm(); - } - - /// Draws one Mini Remote ILT tab's body into the current (child) window. - public void RenderTab(IltSection section) - { - if ((int)section != _lastTabLogged) - { - _lastTabLogged = (int)section; - RynthLog.Event(LogEvents.IltWindowShown, $"{IltSections.Label(section)} tab shown (world='{_ctx.Options.WorldName}', available={_hub.Available})"); - } - switch (section) - { - case IltSection.Banking: _hub.Banking.Render(); break; - case IltSection.Gear: _hub.Gear.Render(); break; - case IltSection.Charms: _hub.CharmsTab.Render(); break; - case IltSection.Games: _hub.Games.Render(); break; - case IltSection.VaultedDungeons: _hub.VaultedDungeons.Render(); break; - default: - // A saved tab id from before the move: say where the section lives now. - if (IltSections.MovedCommand(section) is string moved) - MovedLink(section, moved); - break; - } - } - - /// - /// The ILT session extras in RynthCore's Mini Remote "Session Stats" section (surface - /// "section:ilt-rates", the Infinite Leaftide group): coins, pyreals and item conversions. - /// XP, luminance and kills are RynthAi's session stats, drawn above it in the same section. - /// - public void RenderRatesSection() - { - if (!_hub.Available) - { - RenderHeader(); - RenderUnavailable(); - return; - } - _hub.Rates.Render(extrasOnly: true); - ImGui.TextDisabled("XP planner, Augmentations and Enlightenment: Skills panel > Progression."); - } - - /// - /// The quest bonus list (/qb) in RynthILT's own Mini Remote "Quests" section (surface - /// "section:ilt-questbonus"); it was a section of RynthAi's Quests tab, which moved to RynthOracle. - /// - public void RenderQuestBonusSection() - { - if (!_ctx.Options.IsIltLikeWorld) - { - RenderHeader(); - RenderUnavailable(); - return; - } - _hub.QuestBonus.RenderQb(); - } - - /// - /// One of the ILT pieces RynthAi draws in its own surfaces (RynthIltHub.Section*). False when - /// there is nothing to draw (unknown id, or not an ILT world). - /// - public bool RenderSection(string id) - { - var o = _ctx.Options; - switch (id) - { - case RynthIltHub.SectionRemoteBank: - if (!o.IsIltLikeWorld || o.IsOff(IltFeature.Bank) || !_ctx.State.Remote.ShowBank) return false; - RenderRemoteBank(); - return true; - case RynthIltHub.SectionRemoteGuardian: - if (!o.IsIltLikeWorld || !_ctx.State.Remote.ShowGuardian) return false; - _hub.Guardian.RenderRemoteLine(); - return true; - case RynthIltHub.SectionRemoteStats: - if (!o.IsIltLikeWorld) return false; - RenderRemoteStats(); - return true; - case RynthIltHub.SectionRemoteOptions: - if (!o.IsIltLikeWorld) return false; - RenderRemoteOptions(); - return true; - case RynthIltHub.SectionQuestBonus: - if (!o.IsIltLikeWorld) return false; - _hub.QuestBonus.RenderSection(); - return true; - case RynthIltHub.SectionPetLogs: - if (!o.IsIltLikeWorld) return false; - _hub.PetLogs.RenderSection(); - return true; - case RynthIltHub.SectionPetBreeding: - if (!o.IsIltLikeWorld) return false; - _hub.Breeding.RenderSection(); - return true; - case RynthIltHub.SectionPetCharms: - if (!o.IsIltLikeWorld) return false; - _hub.PetAutomation.RenderCharms(); - return true; - case RynthIltHub.SectionPetCapture: - if (!o.IsIltLikeWorld) return false; - _hub.PetAutomation.RenderCapture(); - return true; - case RynthIltHub.SectionIltStatus: - return RenderIltStatus(); - case RynthIltHub.SectionServerMenu: - return RenderLocalMenu(); - default: - return false; - } - } - - /// - /// The Guardian panel's body (RynthCore's ILT Guardian panel, RynthPluginRenderEmbed - /// "guardian"), or why it's idle while the server hasn't reported ILT features. - /// - public void RenderGuardianPanel() - { - if (!_hub.SectionAvailable(IltSection.Guardian)) - { - RenderHeader(); - ImGui.Separator(); - RenderUnavailable(); - return; - } - _hub.Guardian.Render(); - } - - /// A button that opens a moved section's new home (posted: the command runs on the pump). - private void MovedLink(IltSection section, string command) - { - const string home = "RynthOracle > Character"; - SafeImGui.TextDisabled($"{IltSections.Label(section)} moved to {home}; the ILT session rates are in Session Stats."); - if (ImGui.SmallButton($"Open {home}##moved{(int)section}")) - _ctx.Post(() => _hub.OpenMoved(section, command)); - if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(command); - } - - /// The world and when the server's ILT features were last read, with a Refresh. - private void RenderHeader() - { - var o = _ctx.Options; - string world = o.WorldName.Length > 0 ? o.WorldName : "unknown world"; - SafeImGui.TextColored(o.IsIltLikeWorld ? IltStyle.ColTeal : IltStyle.ColTextMute, world); - ImGui.SameLine(); - SafeImGui.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)); - } - - private void RenderUnavailable() - { - var o = _ctx.Options; - if (!o.IsIltLikeWorld) - { - SafeImGui.TextWrapped("This is not an Infinite Leaftide / ACECustom world, so the ILT tools are idle. " + ForceHint); - } - 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 features as enabled. Press Refresh to check again."); - } - } - - // ── RynthAi's Mini Remote: the Remote tab's Stats lines and Options switches ── - - /// Coins and pyreals per hour under RynthAi's per-hour lines (the Remote tab's Stats). - private void RenderRemoteStats() - { - var r = _hub.Rates.Summary; - Stat("Coins:", Compact(r.CoinsPerHour) + "/h"); - Stat("Pyr:", Compact(r.PyrealsPerHour) + "/h"); - } - - /// The Remote tab's ILT sections' switches, in RynthAi's Options popup. - private void RenderRemoteOptions() - { - var st = _ctx.State.Remote; - bool bank = st.ShowBank, guardian = st.ShowGuardian; - if (ImGui.Checkbox("Bank##iltmrbank", ref bank)) st.ShowBank = bank; - if (ImGui.IsItemHovered()) ImGui.SetTooltip("Infinite Leaftide bank balances (RynthILT)."); - if (ImGui.Checkbox("Guardian answer##iltmrguardian", ref guardian)) st.ShowGuardian = guardian; - if (ImGui.IsItemHovered()) ImGui.SetTooltip("The last Temple guardian answer with a Give button (RynthILT)."); - } - - /// The tail of RynthAi's one-line session report: the coin / pyreal rates (RynthIltHub.TextSessionReport). - public string SessionReportTail() - { - var r = _hub.Rates.Summary; - return $", Coins {Compact(r.CoinsPerHour)}/h, Pyr {Compact(r.PyrealsPerHour)}/h"; - } - - // ── RynthAi's Mini Remote: the Remote tab's Bank section ──────────────── - - private void RenderRemoteBank() - { - var b = _ctx.State.Bank; - if (b.LastUpdated == DateTime.MinValue) - { - // Nothing read yet this install: offer a quiet /bank (the Banking tab has the full view). - ImGui.TextDisabled("Bank: not loaded yet"); - ImGui.SameLine(); - if (ImGui.SmallButton("Load##mrbank")) _ctx.Post(() => _hub.Banking.RequestRefresh(quiet: true)); - if (ImGui.IsItemHovered()) ImGui.SetTooltip("Reads your bank balances (/bank, reply hidden). The Banking tab has the details."); - BankLink(); - return; - } - Stat("P:", Compact(b.Pyreals)); - Stat("Lum:", Compact(b.Luminance)); - BankLink(); - if (!ImGui.BeginTable("##mrbank", 2, ImGuiTableFlags.SizingStretchSame)) return; - ImGui.TableNextColumn(); Stat("LK:", Compact(b.LegendaryKeys)); - ImGui.TableNextColumn(); Stat("MK:", Compact(b.MythicalKeys)); - ImGui.TableNextColumn(); Stat("EC:", Compact(b.EnlightenedCoins)); - ImGui.TableNextColumn(); Stat("WE:", Compact(b.WeaklyEnlightenedCoins)); - // Prestige Coins (ACECustom 2026-10-04): only once the server has reported some. - if (b.PrestigeCoins > 0) { ImGui.TableNextColumn(); Stat("PC:", Compact(b.PrestigeCoins)); } - ImGui.EndTable(); - } - - /// The Bank line's link to RynthILT's own Banking tab (Infinite Leaftide's bank stays RynthILT's). - private void BankLink() - { - if (!_hub.SectionAvailable(IltSection.Banking)) return; - ImGui.SameLine(); - if (ImGui.SmallButton("Bank##mrbanklink")) - _ctx.Ai.MiniRemoteTab(IltSections.TabId(IltSection.Banking), "show"); - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("The Banking tab: deposits, withdrawals and transfers (/ra hub open banking)."); - } - - private static void Stat(string label, string value) - { - SafeImGui.TextColored(ColLabel, label); - ImGui.SameLine(); - ImGui.TextUnformatted(value); - } - - /// The Mini Remote's compact numbers (RynthAi's HudDraw.Compact): 12.3k, 4.5m, 1.2b. - private 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"); - } - - // ── RynthAi's Mini Remote menu: the Infinite Leaftide section ────────── - - /// - /// Under the Infinite Leaftide section while no ILT feature is on: why, where a server is - /// forced (RynthCore Options > Diagnostics only) and a server-features refresh. False when - /// features are on. - /// - private bool RenderIltStatus() - { - if (_hub.Available) return false; - var o = _ctx.Options; - SafeImGui.TextDisabled(!o.IsIltLikeWorld ? "Not an ILT world." - : o.IsRefreshing || o.LastRefreshUtc == DateTime.MinValue ? "Checking server features..." - : "No ILT features reported."); - if (!o.IsIltLikeWorld && ImGui.MenuItem("Force a server... (Options > Diagnostics)##mrforce", DiagnosticsCommand)) - _ctx.Post(() => { if (_ctx.Host.HasInvokeChatParser) _ctx.Host.InvokeChatParser(DiagnosticsCommand); }); - if (!o.IsIltLikeWorld && ImGui.IsItemHovered()) SafeImGui.SetTooltip(ForceHint); - if (ImGui.MenuItem("Refresh server features##mrrefresh")) _hub.RequestOptionsRefresh(); - return true; - } - - /// - /// RynthILT's own Infinite Leaftide entries, for when RynthCore sends no server list (older - /// RynthCore, or its ImGui layer off): the tabs, where Character went, and the Guardian / - /// Bounties panels. - /// - private bool RenderLocalMenu() - { - if (!_hub.OffersTabs) return false; - ImGui.Separator(); - ImGui.TextDisabled("Server: Infinite Leaftide"); - foreach (IltSection section in IltSections.Tabs) - { - if (ImGui.MenuItem(IltSections.Label(section) + "##mrlocal", string.Empty, false, _hub.SectionAvailable(section))) - _ctx.Ai.MiniRemoteTab(IltSections.TabId(section), "show"); - } - if (ImGui.MenuItem("Character##mrlocal", IltSections.OracleCharacterCommand)) - _ctx.Post(() => _hub.OpenMoved(IltSection.Character, IltSections.OracleCharacterCommand)); - if (ImGui.MenuItem("Guardian##mrlocal", "/rc guardian", false, _hub.SectionAvailable(IltSection.Guardian))) - _ctx.Post(() => _hub.OpenEnginePanel("guardian", "Guardian", "show")); - if (ImGui.MenuItem("Bounties##mrlocal", "/rc bounties")) - _ctx.Post(() => _hub.OpenEnginePanel("bounties", "Bounties", "show")); - RenderIltStatus(); - return true; - } - - // ── 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)) - { - SafeImGui.TextColored(IltStyle.ColAmber, _confirm.Title); - ImGui.Separator(); - SafeImGui.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.RynthILT/Hub/IltInventory.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltInventory.cs deleted file mode 100644 index 6fe2672..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltInventory.cs +++ /dev/null @@ -1,391 +0,0 @@ -// IltInventory.cs — Shared item / player-property helper for every ILT Hub feature. -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. Items come -// from RynthILT's host-backed IltObjects instead of RynthAi's WorldObjectCache. -// -// 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.RynthILT.Hub; - -/// -/// 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 }; - // Aetheria (ACECustom Aetheria.cs / PlayerCommands /clap). The Coalesced WCIDs stay the same once - // revealed (name "Aetheria", equipment set given), and /clap takes only unrevealed level 1-3 ones. - public const uint WcidBlueCoalescedAetheria = 42635; - public const uint WcidRedCoalescedAetheria = 42636; - public const uint WcidYellowCoalescedAetheria = 42637; - public const uint WcidRedAetheriaChunk = 310147; - public const uint WcidBlueAetheriaChunk = 310149; - public const uint WcidYellowAetheriaChunk = 310150; - public const uint WcidRedAetheriaPowder = 42644; - public const uint WcidBlueAetheriaPowder = 300019; - public const uint WcidEmpyreanTrinket = 34276; - public const uint WcidFalatacotTrinket = 34277; - - // ── Property ids used by several features ─────────────────────────────── - public const uint IntStackSize = 12; - 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; - // Corrupted-weapon chunk rules (ub-IT Leaftide.IsValidCorruptedWep / CorruptedChunkGuard). - /// ACE PropertyInt.Damage — a weapon's max damage. - public const uint IntDamage = 44; - /// ACE PropertyInt.AttackType — 2 = thrust; 160 / 166 / 486 are the multi-strike masks. - public const uint IntAttackType = 47; - /// ACE PropertyInt.ItemWorkmanship — loot-gen Craft (salvage-bag workmanship is not on weapons). - public const uint IntItemWorkmanship = 105; - /// ACE PropertyInt.WieldSkillType — 41 (Two Handed Combat) for two-handed weapons. - public const uint IntWieldSkillType = 159; - /// ACE PropertyInt.SlayerCreatureType. - public const uint IntSlayerCreatureType = 166; - /// ACE PropertyInt.ElementalDamageBonus. - public const uint IntElementalDamageBonus = 204; - /// ACE PropertyInt.WeaponType — 11 = TwoHanded. - public const uint IntWeaponType = 353; - /// ACE PropertyFloat.CriticalMultiplier — Biting Strike. - public const uint FloatCriticalMultiplier = 136; - /// ACE PropertyFloat.CriticalFrequency — Crushing Blow. - public const uint FloatCriticalFrequency = 147; - /// ACE PropertyFloat.IgnoreArmor — Armor Cleaving. - public const uint FloatIgnoreArmor = 155; - public const uint IntItemMaxLevel = 319; - /// Highest aetheria level on Infinite Leaftide (ACECustom AetheriaChance rolls up to 10; retail stops at 5). - public const int AetheriaMaxLevel = 10; - /// Gear ratings ILT aetheria can carry: C, CD and CDR (PropertyInt GearCrit / GearCritDamage / GearCritDamageResist). - public const uint IntGearCrit = 372; - public const uint IntGearCritDamage = 374; - public const uint IntGearCritDamageResist = 375; - 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; - /// ACECustom PropertyInt64.BankedLuminance (sent with each XP batch). - public const uint QuadBankedLuminance = 9005; - 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 IltObjects _cache; - /// AC's CM_Combat value for peace mode (RynthAi's CombatMode.NonCombat). - private const int CombatModeNonCombat = 1; - 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, IltObjects cache) - { - _host = host; - _cache = cache; - } - - public RynthCoreHost Host => _host; - public IltObjects 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() == CombatModeNonCombat; - - 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(); - - /// 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; - - /// A float (PropertyFloat) value; 0 when the host cannot read it or the item has none. - public double Double(WorldObject wo, uint stype) - => _host.HasGetObjectDoubleProperty && _host.TryGetObjectDoubleProperty(unchecked((uint)wo.Id), stype, out double v) ? v : 0; - - /// The spell ids on an item (empty when none or the host cannot read them). - public IReadOnlyList SpellIds(WorldObject wo) - { - if (!_host.HasGetObjectSpellIds) return Array.Empty(); - var buf = new uint[64]; - int n = _host.GetObjectSpellIds(unchecked((uint)wo.Id), buf, buf.Length); - if (n <= 0) return Array.Empty(); - var ids = new int[Math.Min(n, buf.Length)]; - for (int i = 0; i < ids.Length; i++) ids[i] = unchecked((int)buf[i]); - return ids; - } - - public string Str(WorldObject wo, uint stype) - => _host.HasGetObjectStringProperty && _host.TryGetObjectStringProperty(unchecked((uint)wo.Id), stype, out string v) ? v ?? string.Empty : string.Empty; - - /// 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)); - - /// - /// Why an item's property reads cannot be trusted (null = they can). Every property read here - /// answers 0 / false both for "the item has none" and for "the host cannot read it", so a chunk - /// rule that acts on a 0 must first know the read was real: the host must expose the readers - /// and confirm the item's appraisal arrived. adds the 64-bit reads - /// (item XP), the float reads and the - /// spell list, for the rules that use them. - /// - public string? ReadGap(WorldObject wo, bool quads = false, bool doubles = false, bool spells = false) - { - if (!_host.HasGetObjectIntProperty) return "int properties"; - if (!_host.HasGetObjectBoolProperty) return "bool properties"; - if (quads && !_host.HasGetObjectQuadProperty) return "item XP"; - if (doubles && !_host.HasGetObjectDoubleProperty) return "float properties"; - if (spells && !_host.HasGetObjectSpellIds) return "spells"; - if (!_host.HasHasAppraisalData || !_host.HasAppraisalData(unchecked((uint)wo.Id))) return "appraisal"; - return null; - } - - /// 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)); - - /// Total stack count of a sigil-chain item (singular or plural stack name; see IltSigilChain.NameIs). - public long CountByChainName(string chainName) - => Items().Where(wo => IltSigilChain.NameIs(wo.Name, chainName)).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; - int player = unchecked((int)PlayerId); - int capacity = PlayerInt(IltObjects.IntItemsCapacity, 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(); - _cache.Clear(); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltLog.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltLog.cs deleted file mode 100644 index 7e728fc..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltLog.cs +++ /dev/null @@ -1,196 +0,0 @@ -// IltLog.cs - RynthILT's diagnostics log: the ILT features' trace categories and key events, -// written to %APPDATA%\RynthCore\RynthILT\Logs\RynthILT_yyyy-MM-dd.txt. -// -// The ILT Hub logged through RynthAi's RynthLog (LogCat.Ilt*, LogEvents.Ilt*) while it lived in -// RynthAi; the moved code keeps the same calls (RynthLog.Write / Trace / Exception / Event), so -// this is a small RynthLog of RynthILT's own: -// Write file (always) and the engine log -// Trace file, only while that category is traced ("/ilt trace on|off") -// Exception file and the engine log, always -// Event as Write for the key events (login, options refreshed, ...); trace-only events -// as Trace -// "/ilt debug on" echoes trace and exception lines to chat (local only). Lines are queued on any -// thread and written by Pump() on the plugin pump. -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Text; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.RynthILT; - -/// One trace category per ILT feature (the names RynthAi's ILT Hub used). -internal enum LogCat -{ - IltHub, - IltOptions, - IltChat, - IltStore, - IltBanking, - IltPets, - IltQuests, - IltProgression, - IltRates, - IltGear, - IltGames, -} - -/// Named key events (the ILT Hub's catalogue in RynthAi's RynthLog). -internal static class LogEvents -{ - 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"; - /// /aug ApplyAugLines outcome (Progress Refresh current / login probe). - public const string IltAugLoad = "IltHub.AugLoad"; - - /// Events written as a normal log line; the rest only while their category is traced. - internal static readonly Dictionary Catalog = new(StringComparer.Ordinal) - { - [IltLogin] = (LogCat.IltHub, true), - [IltWorldCheck] = (LogCat.IltOptions, true), - [IltOptionsRefreshStart] = (LogCat.IltOptions, false), - [IltOptionsRefreshed] = (LogCat.IltOptions, true), - [IltWindowShown] = (LogCat.IltHub, true), - [IltWindowHidden] = (LogCat.IltHub, false), - [IltCommand] = (LogCat.IltHub, false), - [IltConfirmation] = (LogCat.IltHub, false), - [IltLogout] = (LogCat.IltHub, false), - [IltAugLoad] = (LogCat.IltProgression, true), - }; -} - -internal static class RynthLog -{ - private static readonly ConcurrentQueue Pending = new(); - private static readonly ConcurrentQueue PendingChat = new(); - private static readonly bool[] Traced = new bool[Enum.GetValues().Length]; - private static RynthCoreHost _host; - private static bool _hasHost; - private static string _directory = string.Empty; - - /// Echo trace and exception lines to the chat window ("/ilt debug on"). - public static volatile bool DebugToChat; - - /// Where the daily files go (tests point it at a scratch folder). - public static string Directory => _directory; - - public static void Init(RynthCoreHost host, string? directory = null) - { - _host = host; - _hasHost = true; - _directory = directory ?? Path.Combine(RynthILTPlugin.SettingsRoot, "Logs"); - } - - /// Drops the host (plugin shutdown): nothing is written to it afterwards. - public static void Shutdown() - { - Pump(); - _hasHost = false; - } - - public static void Write(LogCat cat, string message) - { - Enqueue(cat, message); - HostLog(message); - } - - public static void Trace(LogCat cat, string message) - { - if (!IsTracing(cat)) return; - Enqueue(cat, message); - if (DebugToChat) Chat($"[RynthILT {cat}] {message}"); - } - - public static void Exception(LogCat cat, Exception ex, string context = "") - { - string line = $"EXCEPTION {(context.Length > 0 ? context + ": " : "")}{ex.GetType().Name}: {ex.Message}"; - Enqueue(cat, line + Environment.NewLine + ex.StackTrace); - HostLog(line); - if (DebugToChat) Chat($"[RynthILT {cat}] {line}"); - } - - public static void Event(string eventKey, string message) - { - if (!LogEvents.Catalog.TryGetValue(eventKey, out var e)) { Write(LogCat.IltHub, $"[{eventKey}] {message}"); return; } - if (e.Info) Write(e.Cat, $"[{eventKey}] {message}"); - else Trace(e.Cat, $"[{eventKey}] {message}"); - } - - /// True when would record the event (an Info event, or a traced Trace one). - public static bool IsEventEnabled(string eventKey) - => !LogEvents.Catalog.TryGetValue(eventKey, out var e) || e.Info || IsTracing(e.Cat); - - public static bool IsTracing(LogCat cat) => (int)cat >= 0 && (int)cat < Traced.Length && Traced[(int)cat]; - - public static void SetTracing(LogCat cat, bool on) - { - if ((int)cat >= 0 && (int)cat < Traced.Length) Traced[(int)cat] = on; - } - - /// Every category on or off; returns how many. - public static int SetTracingAll(bool on) - { - for (int i = 0; i < Traced.Length; i++) Traced[i] = on; - return Traced.Length; - } - - public static bool TryParseCategory(string name, out LogCat cat) - { - if (Enum.TryParse(name, ignoreCase: true, out cat)) return true; - return Enum.TryParse("Ilt" + name, ignoreCase: true, out cat); - } - - public static string TracedList() - { - var on = new List(); - foreach (LogCat c in Enum.GetValues()) if (IsTracing(c)) on.Add(c.ToString()); - return on.Count == 0 ? "none" : string.Join(", ", on); - } - - /// Writes the queued lines (plugin pump). - public static void Pump() - { - int lines = 0; - while (lines++ < 20 && PendingChat.TryDequeue(out string? chat)) - { - if (!_hasHost) continue; - try { if (_host.HasWriteToChat) _host.WriteToChat(chat, 1); } catch { } - } - if (Pending.IsEmpty || _directory.Length == 0) return; - var sb = new StringBuilder(); - int n = 0; - while (n++ < 2000 && Pending.TryDequeue(out string? line)) sb.Append(line).Append(Environment.NewLine); - try - { - System.IO.Directory.CreateDirectory(_directory); - File.AppendAllText(Path.Combine(_directory, $"RynthILT_{DateTime.Now:yyyy-MM-dd}.txt"), sb.ToString()); - } - catch { /* a log that can't be written must never break a feature */ } - } - - private static void Enqueue(LogCat cat, string message) - { - if (Pending.Count > 20000) return; // nothing is draining (no pump): don't grow forever - Pending.Enqueue($"{DateTime.Now:HH:mm:ss.fff} [{cat}] {message}"); - } - - private static void HostLog(string message) - { - if (!_hasHost) return; - try { _host.Log("[RynthILT] " + message); } catch { } - } - - /// Queued for the pump (trace lines can come from the render thread). - private static void Chat(string text) - { - if (PendingChat.Count < 200) PendingChat.Enqueue(text); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltMigration.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltMigration.cs deleted file mode 100644 index 0955cb8..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltMigration.cs +++ /dev/null @@ -1,344 +0,0 @@ -// IltMigration.cs - Carries the ILT Hub's saved data over from RynthAi (2026-10-13). -// -// While the ILT Hub lived in RynthAi it saved per character in RynthAi's settings folder -// (\SettingsProfiles\\\: ilt-hub.json, -// ilt-hub-transactions.json, ilt-hub-profiles\) and for every character in the RynthAi folder -// (IltHubProfiles\, ilt-aug-costs.json); the server list and the "Force enable" override were -// fields of each RynthAi profile (FeatureServerNames, ForceServerFeatures). -// -// RynthILT keeps its own files (IltHubStore, IltSettingsStore). On a character's first login -// with RynthILT (no hub.json yet) the old files are COPIED, never moved or deleted: RynthAi no -// longer reads them, and a rollback to an older RynthAi still finds them. Existing RynthILT files -// are never overwritten. The character's active RynthAi profile adds its world names to -// RynthILT's list and, when it had "Force enable" ticked, ticks this character's "Treat this world -// as ILT". The shared files are copied once (IltSettings.SharedFilesMigrated). Pump thread. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Text.Json; -using RynthCore.Install; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// -/// The fields of a RynthAi profile RynthILT reads (the rest of the file is ignored): the two Server -/// Features fields, and the settings that moved to RynthILT on 2026-10-20 (null when the profile -/// predates them: the default applies). -/// -public sealed class IltLegacyProfileFlags -{ - public List? FeatureServerNames; - public bool ForceServerFeatures; - /// RynthAi's Empyrean Handler ring evade (on by default there too). - public bool? HandlerRingEvade; - /// RynthAi's Vaulted Dungeons master switch (off by default). - public bool? EnableVaultedDungeons; - /// RynthAi's T11 item-aug override (-1 = automatic). - public int? T11ItemAugsOverride; -} - -/// The Remote tab switches of RynthAi's huds.json that moved to RynthILT (2026-10-20). -public sealed class IltLegacyHuds -{ - public bool? MiniShowBank; - public bool? MiniShowGuardian; -} - -/// The Pets tab fields of RynthAi's miniremote.json that moved to RynthILT (2026-10-20). -public sealed class IltLegacyMiniRemote -{ - public IltLegacyPetTab? Pet; -} - -public sealed class IltLegacyPetTab -{ - public bool? UsePyrealRefillPath; - public bool? AutoCaptureEnabled; - public int? CaptureLensIndex; -} - -internal static class IltMigration -{ - /// RynthAi's per-server profile folders (overridable for the tests). - public static string LegacyProfilesBase = Path.Combine(RynthInstallPaths.RynthAiDir, "SettingsProfiles"); - - /// RynthAi's folder (shared profiles, aug costs; overridable for the tests). - public static string LegacySharedRoot = RynthInstallPaths.RynthAiDir; - - /// RynthAi's folder for profiles saved before they went per server. - private const string LegacyServerFolder = "ACEmulator"; - - /// RynthAi's file-name sanitizer (LegacyDashboardRenderer.SanitizeFileName). - internal static string RynthAiSafeName(string name) - { - var sb = new StringBuilder(name.Length); - foreach (char c in name) - sb.Append(char.IsLetterOrDigit(c) || c == '\'' || c == '-' ? c : '_'); - return sb.ToString(); - } - - /// RynthAi's settings folder for this character: the world's, else the pre-per-server one. Null when neither exists. - public static string? FindLegacyCharFolder(string world, string charName) - { - if (string.IsNullOrWhiteSpace(charName)) return null; - string safeChar = RynthAiSafeName(charName.Trim()); - var candidates = new List(); - if (!string.IsNullOrWhiteSpace(world)) - { - string safeWorld = RynthAiSafeName(world.Trim()); - if (safeWorld.Length > 0) candidates.Add(Path.Combine(LegacyProfilesBase, safeWorld, safeChar)); - } - candidates.Add(Path.Combine(LegacyProfilesBase, LegacyServerFolder, safeChar)); - foreach (string dir in candidates) - if (Directory.Exists(dir) && (File.Exists(Path.Combine(dir, "ilt-hub.json")) - || File.Exists(Path.Combine(dir, "ilt-hub-transactions.json")) - || Directory.Exists(Path.Combine(dir, "ilt-hub-profiles")) - || File.Exists(Path.Combine(dir, "active_profile.txt")) - || File.Exists(Path.Combine(dir, LegacyMiniRemoteFile)) - || File.Exists(Path.Combine(dir, "Default.json")))) - return dir; - return null; - } - - /// Whether 's copy from RynthAi failed and hasn't been finished yet. - public static bool IsPending(IltSettings settings, string charFolder) - { - if (string.IsNullOrEmpty(charFolder)) return false; - foreach (string f in settings.PendingCharacterMigrations ?? new List()) - if (string.Equals(f, charFolder, StringComparison.OrdinalIgnoreCase)) return true; - return false; - } - - private static void SetPending(IltSettings settings, string charFolder, bool pending) - { - settings.PendingCharacterMigrations ??= new List(); - settings.PendingCharacterMigrations.RemoveAll(f => string.Equals(f, charFolder, StringComparison.OrdinalIgnoreCase)); - if (pending) settings.PendingCharacterMigrations.Add(charFolder); - } - - /// - /// First login of a character with RynthILT: copies its RynthAi ILT Hub files into - /// (only when it has no hub.json yet, or an earlier copy failed - /// part-way) and folds its RynthAi Server Features into . - /// says whether the profile had "Force enable" ticked. Returns what - /// was done (for the log), empty when nothing. When a file can't be copied the folder is marked - /// pending in (save them): the Hub then writes nothing there and the - /// next call copies what is still missing (never overwriting). - /// - public static List MigrateCharacter(string newFolder, string world, string charName, IltSettings settings, out bool forceIlt) - { - forceIlt = false; - var done = new List(); - if (string.IsNullOrEmpty(newFolder)) return done; - bool wasPending = IsPending(settings, newFolder); - if (!wasPending && File.Exists(Path.Combine(newFolder, IltHubStore.StateFile))) return done; - string? legacy = FindLegacyCharFolder(world, charName); - if (legacy == null) - { - // The RynthAi files are gone: nothing left to wait for. - if (wasPending) { SetPending(settings, newFolder, false); done.Add("the RynthAi files of an unfinished copy are gone; RynthILT's own files are used from now on"); } - return done; - } - - int failed = 0; - if (CopyIfMissing(Path.Combine(legacy, "ilt-hub.json"), Path.Combine(newFolder, IltHubStore.StateFile), ref failed)) - done.Add("ilt-hub.json"); - if (CopyIfMissing(Path.Combine(legacy, "ilt-hub-transactions.json"), Path.Combine(newFolder, IltHubStore.TransactionsFile), ref failed)) - done.Add("ilt-hub-transactions.json"); - int profiles = CopyFolder(Path.Combine(legacy, "ilt-hub-profiles"), Path.Combine(newFolder, IltHubStore.ProfilesFolder), ref failed); - if (profiles > 0) done.Add($"{profiles} Hub profile(s)"); - if (failed > 0) - { - SetPending(settings, newFolder, true); - done.Add($"{failed} file(s) NOT copied (see the lines above; the originals in {legacy} are untouched). " + - "The Hub saves nothing for this character until they are; tried again every few minutes and at each login"); - } - else if (wasPending) - { - SetPending(settings, newFolder, false); - done.Add("the earlier unfinished copy is complete"); - } - - if (ReadProfileFlags(legacy, out IltLegacyProfileFlags flags)) - { - int added = MergeServerNames(settings, flags.FeatureServerNames); - if (added > 0) done.Add($"{added} server name(s) from the RynthAi profile"); - if (flags.ForceServerFeatures) - { - forceIlt = true; - done.Add("\"Force enable\" -> Treat this world as ILT"); - } - } - return done; - } - - /// - /// Once for every character: RynthAi's shared Hub profiles and aug-cost table into - /// (never over a file RynthILT already has). Returns what was done. - /// Marked done only when every copy worked: a failed one is tried again at the next login. - /// - public static List MigrateShared(IltSettings settings, string newRoot) - { - var done = new List(); - if (settings.SharedFilesMigrated) return done; - int failed = 0; - int profiles = CopyFolder(Path.Combine(LegacySharedRoot, "IltHubProfiles"), Path.Combine(newRoot, "Profiles"), ref failed); - if (profiles > 0) done.Add($"{profiles} shared Hub profile(s)"); - if (CopyIfMissing(Path.Combine(LegacySharedRoot, "ilt-aug-costs.json"), Path.Combine(newRoot, "ilt-aug-costs.json"), ref failed)) - done.Add("ilt-aug-costs.json"); - if (failed == 0) settings.SharedFilesMigrated = true; - else done.Add($"{failed} shared file(s) NOT copied; tried again at the next login"); - return done; - } - - /// RynthAi's per-character Mini Remote file (the Pets tab's settings). - public const string LegacyMiniRemoteFile = "miniremote.json"; - - /// RynthAi's per-character HUD file (the Remote tab's section switches). - public const string LegacyHudsFile = "huds.json"; - - /// - /// Once per character (IltHubState.RynthAiSettingsImported): the RynthAi settings that moved to - /// RynthILT on 2026-10-20 are copied from the character's RynthAi files into : - /// from miniremote.json the Pets tab's ACECustom options (summon from empty with the refill - /// charm, siphon auto-capture and its lens); from the active profile (as ReadProfileFlags) the - /// Empyrean Handler ring evade, the Vaulted Dungeons master switch and the T11 item-aug override; - /// from huds.json the Remote tab's Bank / Guardian switches. The RynthAi files are only read (RynthAi keeps the - /// old fields readable and no longer uses them). A character with no RynthAi files keeps - /// RynthILT's defaults. Returns what was copied (for the log); empty when nothing was done. - /// - public static List ImportRynthAiSettings(IltHubState state, string world, string charName) - { - var done = new List(); - if (state.RynthAiSettingsImported || string.IsNullOrWhiteSpace(charName)) return done; - string? legacy = FindLegacyCharFolder(world, charName); - if (legacy != null) - { - if (ReadJson(Path.Combine(legacy, LegacyMiniRemoteFile), IltHubJsonContext.Default.IltLegacyMiniRemote) is { Pet: { } pet }) - { - if (pet.UsePyrealRefillPath is bool refill) { state.Pet.RefillFromEmpty = refill; done.Add($"summon from empty essences {(refill ? "on" : "off")}"); } - if (pet.AutoCaptureEnabled is bool capture) { state.Pet.AutoCapture = capture; done.Add($"auto-capture {(capture ? "on" : "off")}"); } - if (pet.CaptureLensIndex is int lens) - { - state.Pet.CaptureLens = Math.Clamp(lens, 0, PetCaptureRules.Lenses.Length - 1); - done.Add("capture lens " + PetCaptureRules.LensAt(state.Pet.CaptureLens).Name); - } - } - if (ReadJson(Path.Combine(legacy, LegacyHudsFile), IltHubJsonContext.Default.IltLegacyHuds) is { } huds) - { - if (huds.MiniShowBank is bool bank) { state.Remote.ShowBank = bank; if (!bank) done.Add("the Remote tab's Bank hidden"); } - if (huds.MiniShowGuardian is bool g) { state.Remote.ShowGuardian = g; if (!g) done.Add("the Remote tab's Guardian line hidden"); } - } - if (ReadProfileFlags(legacy, out IltLegacyProfileFlags flags)) - { - if (flags.HandlerRingEvade is bool ring) { state.Combat.HandlerRingEvade = ring; done.Add($"Empyrean Handler ring evade {(ring ? "on" : "off")}"); } - if (flags.EnableVaultedDungeons is bool vaulted) { state.VaultedDungeonsEnabled = vaulted; done.Add($"Vaulted Dungeons master switch {(vaulted ? "on" : "off")}"); } - if (flags.T11ItemAugsOverride is int augs && augs >= 0) { state.T11.ItemAugsOverride = augs; done.Add($"T11 item augmentations fixed at {augs:N0}"); } - } - } - state.RynthAiSettingsImported = true; - if (done.Count == 0) done.Add(legacy == null ? "no RynthAi settings for this character (defaults kept)" : "nothing set in RynthAi (defaults kept)"); - return done; - } - - /// A JSON file read with , or null (missing or unreadable: logged). - private static T? ReadJson(string path, System.Text.Json.Serialization.Metadata.JsonTypeInfo info) where T : class - { - try - { - return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllText(path), info) : null; - } - catch (Exception ex) - { - RynthLog.Exception(LogCat.IltStore, ex, $"migration: read {path}"); - return null; - } - } - - /// The character's active RynthAi profile's Server Features fields. - internal static bool ReadProfileFlags(string legacyCharFolder, out IltLegacyProfileFlags flags) - { - flags = new IltLegacyProfileFlags(); - try - { - string active = "Default"; - string marker = Path.Combine(legacyCharFolder, "active_profile.txt"); - if (File.Exists(marker)) - { - string name = File.ReadAllText(marker).Trim(); - if (name.Length > 0) active = name; - } - string path = Path.Combine(legacyCharFolder, active + ".json"); - if (!File.Exists(path)) return false; - var f = JsonSerializer.Deserialize(File.ReadAllText(path), IltHubJsonContext.Default.IltLegacyProfileFlags); - if (f == null) return false; - flags = f; - return true; - } - catch (Exception ex) - { - RynthLog.Exception(LogCat.IltStore, ex, "migration: RynthAi profile read"); - return false; - } - } - - /// Adds the names the list doesn't have yet (case-insensitive); returns how many. - internal static int MergeServerNames(IltSettings settings, IEnumerable? names) - { - if (names == null) return 0; - int added = 0; - foreach (string n in ServerFeatureGate.ParseList(string.Join(",", names))) - { - if (settings.ServerNames.Any(have => have.Equals(n, StringComparison.OrdinalIgnoreCase))) continue; - settings.ServerNames.Add(n); - added++; - } - return added; - } - - /// - /// Copies to unless the source is missing or the - /// target exists. A failed copy is never silent: it is logged and said in chat once per folder - /// (DataWriteGuard, on ILT), with the reason and the fix and where the original still is, and - /// counted in . - /// - private static bool CopyIfMissing(string from, string to, ref int failed) - { - try - { - if (!File.Exists(from) || File.Exists(to)) return false; - } - catch { return false; } - string fromDir = Path.GetDirectoryName(from) ?? from; - bool ok = DataWriteGuard.TrySave($"{Path.GetFileName(from)} carried over from RynthAi (the original is still in {fromDir})", to, () => - { - Directory.CreateDirectory(Path.GetDirectoryName(to)!); - File.Copy(from, to); - }); - if (!ok) failed++; - return ok; - } - - private static int CopyFolder(string from, string to, ref int failed) - { - int n = 0; - string[] files; - try - { - if (!Directory.Exists(from)) return 0; - files = Directory.GetFiles(from, "*.json"); - } - catch (Exception ex) - { - failed++; - RynthLog.Exception(LogCat.IltStore, ex, $"migration: list {from}"); - return 0; - } - foreach (string f in files) - if (CopyIfMissing(f, Path.Combine(to, Path.GetFileName(f)), ref failed)) n++; - return n; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltParse.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltParse.cs deleted file mode 100644 index d111074..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltParse.cs +++ /dev/null @@ -1,129 +0,0 @@ -// IltParse.cs — Shared parsing / formatting helpers for ILT Hub server output. -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// -// 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.RynthILT.Hub; - -internal static class IltParse -{ - private const RegexOptions Opt = RegexOptions.Compiled | RegexOptions.CultureInvariant; - - /// - /// "/aug" level line: "Creature:1,234", "Duration: 1,234", or "Specialize: 2". - /// Trailing notes ("Triune Weave: 5 (adds ...)") are allowed; the planner only keeps known keys. - /// - public static readonly Regex AugLine = new(@"^(\w+)\s*:\s*(\d[\d,.\s']*)", 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); - - /// "/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); - - private static readonly Regex GroupedInt = new(@"^\d{1,3}(?:[,.\s']\d{3})+|^\d+", RegexOptions.CultureInvariant); - - /// - /// The level in an AugLine value: digits grouped by a comma, period, space or apostrophe - /// ("4,300", "4.300", "4 300", "4'300") read as one number; "2 (adds 5)" as 2; "1.5" as 1. 0 when absent. - /// - public static long ParseAugValue(string text) - { - if (string.IsNullOrEmpty(text)) return 0; - var m = GroupedInt.Match(text.Trim()); - if (!m.Success) return 0; - var digits = new System.Text.StringBuilder(m.Value.Length); - foreach (char c in m.Value) if (char.IsDigit(c)) digits.Append(c); - return long.TryParse(digits.ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out long v) ? v : 0; - } - - /// 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.RynthILT/Hub/IltPetAutomation.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetAutomation.cs deleted file mode 100644 index e24efa5..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetAutomation.cs +++ /dev/null @@ -1,394 +0,0 @@ -// IltPetAutomation.cs — ACECustom's parts of RynthAi's Pets tab: the pet charms, the "summon from an -// empty essence" refill path and siphon-lens auto-capture. -// Moved out of RynthAi's MiniRemote/PetsTab.cs 2026-10-20 (originally SilentKelpie's IltPets, ILT -// Hub): summoning is every server's, so the roster, healing and cosmetic pets stay RynthAi's, but -// these three are ACECustom content and live here now. -// -// * Pet charms (section "pets-charms"): Summon Essence Refill (the server refills an empty essence -// from banked pyreals) and Universal Summoning Mastery, read from the charm's appraisal text and -// the player bools the server stamps, plus the "no spell components" warning when the server -// requires them. The refill opt-in feeds RynthAi's PetManager through RynthILT.Hub -// AllowSummonOnEmpty (cached here every tick; an unknown state never spends pyreals). -// * Auto siphon capture (section "pets-capture", ACECustom MonsterCapture): when enabled, uses the -// chosen lens on the nearest attackable creature within 5 m once it is <=20% health or under -// 20 HP (Asheron's Lens skips the health gate). Resonance still needs a prior failed capture on -// the server. Bounded per creature and overall (PetCaptureThrottle). -// Ticks only on an ILT-like world (IltHubController); the sections draw nothing elsewhere. -using System; -using ImGuiNET; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal sealed class IltPetAutomation : IIltFeature -{ - private const long CaptureThinkMs = 250; - private const long CaptureCooldownMs = 2500; - private const long CaptureFailBackoffMs = 8000; - private const long CharmScanMs = 2000; - private const long GateMs = 500; - - private readonly IltHubContext _ctx; - private readonly PetCaptureThrottle _captureThrottle = new(); - private long _lastCaptureThink; - private long _captureCooldownUntil; - private long _lastCharmScan; - private long _lastGate; - - // Read by the render thread and (AllowSummonOnEmpty) by RynthAi's pump. - private volatile string _captureStatus = "off"; - private volatile bool _uiRefillActive; - private volatile bool _uiMasteryActive; - private volatile bool _uiHasCasting = true; - private volatile bool _allowSummonOnEmpty; - - // The server's health updates (RynthPluginOnUpdateHealth), for creatures the client has no vitals for. - private const int MaxHealthEntries = 512; - private readonly object _healthGate = new(); - private readonly System.Collections.Generic.Dictionary _healthRatios = new(); - - public IltPetAutomation(IltHubContext ctx) => _ctx = ctx; - - private IltPetState S => _ctx.State.Pet; - - /// The auto-capture line under the switch (render thread). - public string CaptureStatus => _captureStatus; - - /// - /// RynthILT.Hub AllowSummonOnEmpty: the last tick's answer, false off an ILT world. Any thread. - /// - public bool AllowSummonOnEmpty => _ctx.Options.IsIltLikeWorld && _allowSummonOnEmpty; - - // ── Charms / gates ────────────────────────────────────────────────────── - - /// Summon Essence Refill charm is carried and switched on (or the server stamped the player bool). - public bool RefillCharmActive() - { - var inv = _ctx.Inventory; - if (inv.PlayerBool(IltInventory.BoolPyrealRefillActive)) return true; - var charm = inv.FindByWcid(IltInventory.WcidSummonRefillCharm); - return charm != null && inv.CharmStatus(charm) == IltTri.On; - } - - public bool MasteryCharmActive() - { - if (_ctx.Options.IsOff(IltFeature.UniversalMastery)) return false; - var inv = _ctx.Inventory; - if (inv.PlayerBool(IltInventory.BoolUniversalMasteryActive)) return true; - var charm = inv.FindByWcid(IltInventory.WcidUniversalMasteryCharm); - return charm != null && inv.CharmStatus(charm) == IltTri.On; - } - - /// - /// 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 the feature check - /// reported pet_refill on, or the server stamped the player's refill bool. Pump thread. - /// - internal bool ComputeAllowSummonOnEmpty() - { - if (!S.RefillFromEmpty || !_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; - } - - // ── IIltFeature ───────────────────────────────────────────────────────── - - public void Tick(long nowMs) - { - if (nowMs - _lastGate >= GateMs) - { - _lastGate = nowMs; - _allowSummonOnEmpty = ComputeAllowSummonOnEmpty(); - } - if (nowMs - _lastCharmScan >= CharmScanMs) - { - _lastCharmScan = nowMs; - // Host reads (and appraisal requests) happen here, never on the render thread. - _uiRefillActive = RefillCharmActive(); - _uiMasteryActive = MasteryCharmActive(); - _uiHasCasting = _ctx.Inventory.HasCastingSupplies(); - } - if (nowMs - _lastCaptureThink >= CaptureThinkMs) - { - _lastCaptureThink = nowMs; - TickCapture(nowMs); - } - } - - /// ACECustom MonsterCapture replies: back off after a refuse so lenses aren't burned. Never eats. - public bool OnChat(string text) - { - if (!S.AutoCapture || string.IsNullOrEmpty(text)) return false; - long now = IltHubContext.NowMs; - if (PetCaptureLines.IsSuccess(text)) - { - _captureStatus = "captured"; - _captureThrottle.RecordSuccess(); - _captureCooldownUntil = now + CaptureCooldownMs; - } - else if (ContainsAny(text, - "too strong", - "blind rage", - "cannot be siphoned", - "cannot be captured", - "No creatures nearby", - "already dead", - "already being captured", - "hasn't failed a capture", - "echo has faded", - "Failed to consume")) - { - _captureStatus = "refused: " + Truncate(text, 48); - _captureCooldownUntil = now + CaptureFailBackoffMs; - } - else if (ContainsAny(text, "siphon failed", "lens shatters", "resisted your capture", "resonance fades")) - { - _captureStatus = "failed (creature may enrage)"; - _captureCooldownUntil = now + CaptureFailBackoffMs; - } - return false; - } - - /// A creature's health ratio from the server (RynthPluginOnUpdateHealth; any thread). - public void NoteHealth(uint objectId, float ratio) - { - if (objectId == 0 || float.IsNaN(ratio)) return; - lock (_healthGate) - { - if (_healthRatios.Count >= MaxHealthEntries) _healthRatios.Clear(); - _healthRatios[unchecked((int)objectId)] = Math.Clamp(ratio, 0f, 1f); - } - } - - /// The last health ratio the server sent for a creature, -1 when none. - private float HealthRatio(int id) - { - lock (_healthGate) return _healthRatios.TryGetValue(id, out float v) ? v : -1f; - } - - public void OnLogout() - { - lock (_healthGate) _healthRatios.Clear(); - _captureCooldownUntil = 0; - _captureStatus = "off"; - _captureThrottle.Reset(); - _allowSummonOnEmpty = false; - } - - private static bool ContainsAny(string text, params string[] parts) - { - foreach (string p in parts) - if (text.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0) return true; - return false; - } - - private static string Truncate(string s, int max) => s.Length <= max ? s : s[..(max - 3)] + "..."; - - // ── Auto siphon capture (ACECustom MonsterCapture) ─────────────────────── - - /// - /// When Auto Capture is on, use the chosen siphon lens on the nearest attackable creature within - /// 5 m once ACECustom's health gate is met (≤20% or under 20 HP; Asheron's skips it). The server - /// picks the nearest creature itself, so this fires only when that nearest candidate is already - /// weak enough: a full-health neighbour closer than the wounded target won't waste a lens. - /// - internal void TickCapture(long now) - { - if (!S.AutoCapture) - { - _captureStatus = "off"; - return; - } - if (_ctx.Options.IsOff(RynthIltHub.FeatureMonsterCapture)) - { - _captureStatus = "monster capture disabled on this server"; - return; - } - if (now < _captureCooldownUntil) - { - long left = (_captureCooldownUntil - now + 999) / 1000; - if (!_captureStatus.StartsWith("waiting", StringComparison.Ordinal)) - _captureStatus = $"waiting {left}s"; - return; - } - var inv = _ctx.Inventory; - if (inv.IsBusy) { _captureStatus = "busy"; return; } - - var lens = PetCaptureRules.LensAt(S.CaptureLens); - var lensItem = inv.FindByWcid(lens.Wcid); - if (lensItem == null) - { - _captureStatus = $"no {lens.Name} carried"; - return; - } - - if (!TryFindNearestCaptureTarget(out WorldObject? target, out double distM, out uint curHp, out uint maxHp)) - { - _captureStatus = "no attackable creature within 5 m"; - return; - } - - if (!PetCaptureRules.InRange(distM)) - { - _captureStatus = $"{target!.Name} at {distM:0.0} m (need <={PetCaptureRules.CaptureRangeM:0} m)"; - return; - } - - if (!PetCaptureRules.CanAttempt(lens, curHp, maxHp)) - { - float pct = maxHp > 0 ? curHp * 100f / maxHp : -1f; - _captureStatus = pct >= 0 - ? $"{target!.Name} at {pct:0}% / {curHp} HP (need <={PetCaptureRules.CaptureMaxHealthFraction:P0} or <{PetCaptureRules.CaptureMaxHealthPoints} HP)" - : $"{target!.Name}: health unknown"; - return; - } - - if (!_captureThrottle.MayAttempt(target!.Id, now)) - { - _captureStatus = $"{target.Name}: {PetCaptureThrottle.MaxTriesPerTarget} tries, no capture; left alone for {_captureThrottle.BlockedSecondsLeft(target.Id, now)}s"; - return; - } - - if (!inv.Use(lensItem)) - { - _captureStatus = "UseObject refused"; - return; - } - _captureThrottle.RecordAttempt(target.Id, now); - if (_captureThrottle.Exhausted) - { - // Backstop: this many lenses with no recognized capture means something is off. Stop, don't keep burning them. - S.AutoCapture = false; - RynthLog.Write(LogCat.IltPets, - $"auto-capture: {PetCaptureThrottle.MaxTriesWithoutSuccess} lens uses without a capture reply; auto-capture switched off"); - } - - float shown = maxHp > 0 ? curHp * 100f / maxHp : 0f; - _captureStatus = $"using {lens.Name} on {target.Name} ({shown:0}% / {curHp} HP)"; - _captureCooldownUntil = now + CaptureCooldownMs; - RynthLog.Write(LogCat.IltPets, - $"auto-capture: {lens.Name} -> 0x{target.Id:X8} '{target.Name}' d={distM:0.0}m hp={curHp}/{maxHp}"); - } - - /// - /// Nearest attackable landscape creature within capture range, with vitals from the host when - /// available, else the server's last health ratio (fraction-only gate). A creature with neither - /// is skipped: no health, no capture decision. - /// - private bool TryFindNearestCaptureTarget(out WorldObject? best, out double bestDist, out uint curHp, out uint maxHp) - { - best = null; - bestDist = double.MaxValue; - curHp = maxHp = 0; - var host = _ctx.Host; - var objects = _ctx.Inventory.Cache; - uint playerId = _ctx.Inventory.PlayerId; - if (playerId == 0) return false; - int pid = unchecked((int)playerId); - string ownPrefix = _ctx.CharName.Length > 0 ? _ctx.CharName + "'s " : string.Empty; - - foreach (var wo in objects.GetLandscape()) - { - if (wo == null || wo.Id == pid) continue; - if (wo.ObjectClass != RynthCore.Loot.AcObjectClass.Monster) continue; - if (ownPrefix.Length > 0 && wo.Name.StartsWith(ownPrefix, StringComparison.Ordinal)) continue; - // Skip corpses / non-attackable when the host can tell. - if (host.HasObjectIsAttackable && !host.ObjectIsAttackable(unchecked((uint)wo.Id))) continue; - - double d = objects.Distance(pid, wo.Id); - if (d < 0 || d > PetCaptureRules.CaptureRangeM || d >= bestDist) continue; - - if (!TryReadCreatureVitals(wo.Id, out uint h, out uint mh)) continue; - if (h == 0) continue; // dead - - best = wo; - bestDist = d; - curHp = h; - maxHp = mh; - } - return best != null; - } - - /// - /// Absolute vitals via TryGetTargetVitals when bound; else the health ratio as a 0-1000 scale so - /// only the fraction half of ACECustom's gate can fire. - /// - private bool TryReadCreatureVitals(int id, out uint cur, out uint max) - { - cur = max = 0; - var host = _ctx.Host; - if (host.HasGetTargetVitals - && host.TryGetTargetVitals(unchecked((uint)id), out uint h, out uint mh, out _, out _, out _, out _) - && mh > 0) - { - cur = h; - max = mh; - return true; - } - float ratio = HealthRatio(id); - if (ratio < 0f) return false; - // Synthetic scale: ratio 0.20 -> 200/1000 so IsWeakEnough's fraction half matches. - max = 1000; - cur = (uint)Math.Clamp((int)Math.Round(ratio * 1000f), 1, 1000); - return true; - } - - // ── UI (render thread): the Pets tab's ACECustom sections ──────────────── - - /// The pet charms and the refill opt-in (section "pets-charms"). - public void RenderCharms() - { - ImGui.Separator(); - SafeImGui.TextColored(IltStyle.ColTeal, "Pet charms"); - var o = _ctx.Options; - bool refillOff = o.IsOff(IltFeature.PetRefill); - ImGui.TextUnformatted("Summon Essence Refill: " + (refillOff ? "disabled on this server" : _uiRefillActive ? "ON" : "off / not carried")); - ImGui.BeginDisabled(refillOff); - bool usePath = S.RefillFromEmpty; - if (ImGui.Checkbox("Summon from empty essences while the refill charm is ON (spends banked pyreals)", ref usePath)) - S.RefillFromEmpty = usePath; - ImGui.EndDisabled(); - ImGui.TextUnformatted("Universal Summoning Mastery: " - + (o.IsOff(IltFeature.UniversalMastery) ? "disabled on this server" : _uiMasteryActive ? "ON" : "off / not carried")); - if (!o.IsOff(IltFeature.RequireComps) && !_uiHasCasting) - SafeImGui.TextColored(IltStyle.ColAmber, "No spell components or Infinite Casting Stone carried."); - } - - /// Siphon-lens auto-capture: enable + which lens to use (section "pets-capture"). - public void RenderCapture() - { - ImGui.Separator(); - SafeImGui.TextColored(IltStyle.ColTeal, "Monster capture"); - bool captureOff = _ctx.Options.IsOff(RynthIltHub.FeatureMonsterCapture); - ImGui.BeginDisabled(captureOff); - bool en = S.AutoCapture; - if (ImGui.Checkbox("Auto-capture when a creature is weak enough", ref en)) - { - S.AutoCapture = en; - _ctx.Post(_captureThrottle.Reset); - } - if (ImGui.IsItemHovered()) - { - SafeImGui.SetTooltip( - "Uses the selected siphon lens on the nearest attackable creature within 5 m once it is\n" + - "at or below 20% health or under 20 HP (ACECustom MonsterCapture). Asheron's Lens skips\n" + - "the health gate. Resonance Lens still needs a prior failed capture on the server.\n" + - "Off by default. Stops on its own after 5 tries on one creature (it is left alone for 2 min)\n" + - "or 15 lens uses in a row with no capture."); - } - ImGui.SameLine(); - ImGui.SetNextItemWidth(120); - int lens = Math.Clamp(S.CaptureLens, 0, PetCaptureRules.LensNames.Length - 1); - if (ImGui.Combo("##petcapturelens", ref lens, PetCaptureRules.LensNames, PetCaptureRules.LensNames.Length)) - S.CaptureLens = lens; - if (ImGui.IsItemHovered()) - SafeImGui.SetTooltip("Which siphon lens to use. Must be carried in your pack."); - ImGui.EndDisabled(); - if (captureOff) - SafeImGui.TextDisabled("Monster capture is disabled on this server."); - else - SafeImGui.TextDisabled("Status: " + _captureStatus); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetBreeding.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetBreeding.cs deleted file mode 100644 index 70f9147..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetBreeding.cs +++ /dev/null @@ -1,790 +0,0 @@ -// IltPetBreeding.cs - The pet breeding tracker: the Breeding sub-tab of RynthAi's Mini Remote Pets tab, -// drawn here (RynthILT.Hub section "pets-breeding"; RynthAi only hosts it), and the same data as JSON -// for other plugins ("RynthILT.Data" v2 GetPetBreedingJson / PetBreedingCommand). -// Originally SilentKelpie's (2026-10-15, his RynthILT 0.2.7); ported into RynthILT 0.3.1 without his -// RynthOracle Pet Breeding tab: breeding is Leaftide's, so only this plugin draws it. -// -// What it does, on Infinite Leaftide only: -// * reads every carried combat essence (appraisal qualities + the LongDesc breeding block) and -// evaluates it with IltBreedingEssence: stud / dam, each gate that fails, when it clears, growth; -// * counts Ivo's supplies and applies a breeding booster to an essence after the player confirms; -// * runs "@breed-debug" (quietly) for the room check and "@dance" to start the ritual; -// * logs breeding chat (ritual, charge spent, birth, guardian, growth, adulthood, imprint); -// * learns this server's rules from its own text (IltBreedingRules) and reports what it sees to -// the Leaftide feature profile (the pet_breeding / pet_maturity bits). -// Essences are read only while someone is looking (the section drawn, or a reader asking for the -// JSON within WatchMs), so an unwatched tracker costs nothing. -// Threading: Tick / OnChat / actions on the pump; Render on the ImGui thread reads only the -// immutable snapshot and posts actions. -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Numerics; -using System.Text; -using ImGuiNET; -using RynthCore.Loot; -using RynthCore.Plugin.Shared; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// Everything the breeding UI and reader JSON show, rebuilt whole on the pump. -/// is a frozen copy of the rules: the render thread plans with it while the pump learns. -internal sealed record BreedingSnapshot( - IReadOnlyList Essences, IReadOnlyList<(BreedSupplyDef Def, long Count)> Supplies, - IReadOnlyList Rules, IReadOnlyList Events, BreedDebugInfo? Debug, DateTime DebugUtc, - IltTri Enabled, IltTri Maturity, IltTri Bond, string Room, int FreeSlots, string Message, double NowUnix, bool Built, - IltBreedingRules RulesView) -{ - public static readonly BreedingSnapshot Empty = new(Array.Empty(), Array.Empty<(BreedSupplyDef, long)>(), - Array.Empty(), Array.Empty(), null, default, IltTri.Unknown, IltTri.Unknown, - IltTri.Unknown, string.Empty, -1, string.Empty, 0, false, new IltBreedingRules(new IltBreedingState())); -} - -internal sealed class IltPetBreeding : IIltFeature -{ - /// Feature bits this tracker reports (IltFeatureCatalog's pet_breeding / pet_maturity rows). - public const string BitBreeding = RynthIltHub.FeaturePetBreeding; - public const string BitMaturity = "pet_maturity"; - - /// ACE commands: the diagnostics reply, and the courtship dance. - public const string DebugCommand = "@breed-debug"; - public const string DanceCommand = "@dance"; - - // ACECustom pet device qualities (AssessmentProperty, sent with the appraisal). - private const uint StrLongDesc = 16; - private const uint IntUseRequiresLevel = 369; - private const uint IntUseLevelRequirement = 364; - private const uint IntBondLevel = 9053; - private const uint IntPotencyStored = 9056; - private const uint IntMaleCharges = 9057; - private const uint IntMutDamage = 9070, IntMutDamageResist = 9071, IntMutCrit = 9072, IntMutVitality = 9073, IntMutPotency = 9074; - private const uint IntMutationCount = 9075; - private const uint IntMaturityKills = 9077; - private const uint FloatNextBreeding = 9056; - private const uint FloatMaleRefresh = 9057; - private const uint FloatIncense = 9058; - private const uint FloatMaturityXpMult = 9059; - private const uint BoolBondAttuned = 9047; - private const uint BoolNeutered = 9051; - private const uint BoolMaleOverride = 50053; - private const uint BoolJuvenile = 50054; - private const uint BoolCatalyst = 50055; - private const uint BoolOffering = 50056; - - /// The tracker reads essences while it was looked at within this long. - private const long WatchMs = 6000; - /// How often a watched tracker re-reads the essences. - private const long ScanMs = 2000; - /// Appraisal requests per scan for essences not yet appraised. - private const int AppraisePerScan = 2; - - private readonly IltHubContext _ctx; - private readonly IltBreedingRules _rules; - private long _watchedAt; // Interlocked: render thread and readers mark it - private long _scannedAt; - private bool _refreshAll; // re-appraise every essence on the next scan (after an event) - private string _message = string.Empty; - private volatile BreedingSnapshot _snap = BreedingSnapshot.Empty; - private volatile string _readerJson = string.Empty; - - // Render-thread selections (ids of carried essences; 0 = none). - private int _studId, _damId, _targetId; - - public IltPetBreeding(IltHubContext ctx) - { - _ctx = ctx; - _rules = new IltBreedingRules(ctx.State.Pet.Breeding); - } - - /// The rules (tests and the controller). - internal IltBreedingRules Rules => _rules; - - /// The latest snapshot (any thread). - public BreedingSnapshot Snapshot => _snap; - - /// Someone is looking: keep the essences fresh for a while (any thread). - public void MarkWatched() => System.Threading.Interlocked.Exchange(ref _watchedAt, IltHubContext.NowMs); - - /// The reader JSON ("RynthILT.Data" GetPetBreedingJson); reading it marks the tracker watched. Any thread. - public string ReaderJson - { - get { MarkWatched(); return _readerJson; } - } - - private static double UnixNow => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000.0; - - // ── IIltFeature ───────────────────────────────────────────────────────── - - public void Tick(long nowMs) - { - if (nowMs - System.Threading.Interlocked.Read(ref _watchedAt) > WatchMs) return; - if (_scannedAt != 0 && nowMs - _scannedAt < ScanMs) return; - _scannedAt = nowMs; - Scan(); - } - - public bool OnChat(string text) - { - if (string.IsNullOrEmpty(text)) return false; - DateTime utc = DateTime.UtcNow; - bool changed = _rules.LearnAll(IltBreedingRules.FromChat(text), utc); - foreach (string raw in text.Split('\n')) - { - string line = raw.Trim(); - string? kind = EventKind(line); - if (kind == null) continue; - _rules.AddEvent(kind, line, utc); - changed = true; - if (kind is "ritual" or "birth" or "charge") _ctx.Options.Set(BitBreeding, IltTri.On); - if (kind is "growth" or "adult") - { - _ctx.Options.Set(BitMaturity, IltTri.On); - if (IltBreedingRules.TryParseGrownInto(line, out int stage, out string name)) _rules.LearnStageName(stage, name); - } - // The essences changed on the server (charges, rest, a baby, growth): read them again soon. - if (kind is not "dance") { _refreshAll = true; _scannedAt = 0; } - } - if (changed) RynthLog.Trace(LogCat.IltPets, "breeding: chat updated rules / events"); - return false; - } - - public void OnLogout() - { - _snap = BreedingSnapshot.Empty; - _readerJson = string.Empty; - _scannedAt = 0; - _message = string.Empty; - } - - /// The event kind of a breeding chat line, or null for any other line. - internal static string? EventKind(string line) - { - if (line.Length == 0) return null; - if (line.StartsWith("The mating ritual has begun between", StringComparison.OrdinalIgnoreCase)) return "ritual"; - if (line.Contains("spent a breeding charge", StringComparison.OrdinalIgnoreCase)) return "charge"; - if (line.Contains("A baby pet has been born", StringComparison.OrdinalIgnoreCase)) return "birth"; - if (line.StartsWith("The union stirs something", StringComparison.OrdinalIgnoreCase)) return "guardian"; - if (line.Contains("yields to its parents", StringComparison.OrdinalIgnoreCase)) return "guardian"; - if (line.Contains("Awakened Blessing", StringComparison.OrdinalIgnoreCase)) return "mutation"; - if (line.Contains("spectral guardian dissolves", StringComparison.OrdinalIgnoreCase)) return "guardian"; - if (line.Contains("has grown into a", StringComparison.OrdinalIgnoreCase)) return "growth"; - if (line.Contains("has reached adulthood", StringComparison.OrdinalIgnoreCase)) return "adult"; - if (line.Contains("has imprinted on you", StringComparison.OrdinalIgnoreCase)) return "imprint"; - if (line.StartsWith("[Breeding] Your pet performs the courtship dance", StringComparison.OrdinalIgnoreCase)) return "dance"; - if (line.StartsWith("You administer the Nurturing Draught", StringComparison.OrdinalIgnoreCase)) return "supply"; - if (line.StartsWith("You have permanently spayed/neutered", StringComparison.OrdinalIgnoreCase)) return "supply"; - return null; - } - - // ── Scan (pump) ───────────────────────────────────────────────────────── - - /// Reads every carried combat essence and the supplies, then rebuilds the snapshot and reader JSON. - private void Scan() - { - IltInventory inv = _ctx.Inventory; - RynthCoreHost host = _ctx.Host; - double now = UnixNow; - DateTime utc = DateTime.UtcNow; - var essences = new List(); - int appraised = 0; - bool sawBlock = false, sawGrowth = false; - - foreach (WorldObject wo in inv.Items()) - { - uint wcid = inv.Wcid(wo); - if (!IltBreedingEssence.IsCombatEssence(wcid) && !LooksLikeEssence(wo, inv)) continue; - - BreedEssenceFacts f = ReadFacts(host, inv, wo, wcid); - if (f.LongDesc.Contains("Sex:", StringComparison.Ordinal)) sawBlock = true; - if (f.LongDesc.Contains("Growth:", StringComparison.Ordinal)) sawGrowth = true; - _rules.LearnAll(IltBreedingRules.FromAppraisal(f.LongDesc, f.MaleRefreshUnix, now), utc); - if (IltBreedingRules.TryParseGrowth(f.LongDesc, out string stageName, out int stage, out _, out _, out _, out _)) - _rules.LearnStageName(stage, stageName); - essences.Add(IltBreedingEssence.Evaluate(f, _rules, now)); - - // Appraise what isn't loaded (a few per scan), or everything after a breeding event. - if ((_refreshAll || !f.HasId) && appraised < (_refreshAll ? 32 : AppraisePerScan) && inv.RequestAppraisal(wo)) - appraised++; - } - _refreshAll = false; - - // The server only writes the breeding block while breeding is on: seeing it is the server saying so. - if (sawBlock) _ctx.Options.Set(BitBreeding, IltTri.On); - if (sawGrowth) _ctx.Options.Set(BitMaturity, IltTri.On); - - essences.Sort((a, b) => - { - int c = b.Ready.CompareTo(a.Ready); - if (c != 0) return c; - c = b.Male.CompareTo(a.Male); - return c != 0 ? c : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); - }); - - var supplies = new List<(BreedSupplyDef, long)>(IltBreedingSupplies.All.Length); - foreach (BreedSupplyDef s in IltBreedingSupplies.All) supplies.Add((s, inv.CountByWcid(s.Wcid))); - - IltBreedingState st = _rules.State; - BreedDebugInfo? debug = st.LastDebug.Count > 0 ? IltBreedingRules.ParseDebug(st.LastDebug) : null; - var events = st.Log.Select(e => new IltBreedingEvent { Utc = e.Utc, Kind = e.Kind, Text = e.Text }).ToArray(); - - var snap = new BreedingSnapshot(essences, supplies, _rules.All(), events, debug, st.LastDebugUtc, - EnabledState(), _ctx.Options.Get(BitMaturity), _ctx.Options.Get(IltFeature.PetBond), - _rules.RoomText(), inv.FreeMainPackSlots(), _message, now, true, _rules.Frozen()); - _snap = snap; - _readerJson = BuildJson(snap, _rules, _ctx.Options.WorldName); - } - - /// The pet_breeding state the Leaftide profile shows (reported, else the ILT profile's "on"). - private IltTri EnabledState() - { - IltTri t = _ctx.Options.Get(BitBreeding); - return t != IltTri.Unknown ? t : _ctx.Options.IsIltLikeWorld ? IltTri.On : IltTri.Unknown; - } - - /// An essence outside the WCID table (a new family) that the server gave a breeding block. - private static bool LooksLikeEssence(WorldObject wo, IltInventory inv) - => wo.Name.EndsWith("Essence", StringComparison.OrdinalIgnoreCase) - && inv.Str(wo, StrLongDesc).Contains("Sex:", StringComparison.Ordinal); - - private static BreedEssenceFacts ReadFacts(RynthCoreHost host, IltInventory inv, WorldObject wo, uint wcid) - { - uint id = unchecked((uint)wo.Id); - var f = new BreedEssenceFacts - { - Id = wo.Id, - Name = wo.Name, - Wcid = wcid, - HasId = inv.HasAppraisal(wo), - Bond = inv.Int(wo, IntBondLevel), - PotencyStored = inv.Int(wo, IntPotencyStored), - MutDamage = inv.Int(wo, IntMutDamage), - MutDamageResist = inv.Int(wo, IntMutDamageResist), - MutCrit = inv.Int(wo, IntMutCrit), - MutVitality = inv.Int(wo, IntMutVitality), - MutPotency = inv.Int(wo, IntMutPotency), - MutationCount = inv.Int(wo, IntMutationCount), - Neutered = TryBool(host, id, BoolNeutered, out bool n) && n, - JuvenileFlag = TryBool(host, id, BoolJuvenile, out bool j) && j, - Catalyst = TryBool(host, id, BoolCatalyst, out bool c) && c, - Offering = TryBool(host, id, BoolOffering, out bool o) && o, - Attuned = TryBool(host, id, BoolBondAttuned, out bool a) && a, - NextBreedUnix = TryDouble(host, id, FloatNextBreeding), - MaleRefreshUnix = TryDouble(host, id, FloatMaleRefresh), - Incense = TryDouble(host, id, FloatIncense), - MaturityXpMult = TryDouble(host, id, FloatMaturityXpMult), - LongDesc = inv.Str(wo, StrLongDesc), - }; - f.UseLevel = inv.Int(wo, IntUseRequiresLevel); - if (f.UseLevel <= 0) f.UseLevel = inv.Int(wo, IntUseLevelRequirement); - if (TryBool(host, id, BoolMaleOverride, out bool male)) f.MaleOverride = male; - // Absent and 0 differ for these two: absent = never bred / a full stud. - f.MaturityKills = TryInt(host, id, IntMaturityKills, out int kills) ? kills : -1; - f.MaleCharges = TryInt(host, id, IntMaleCharges, out int charges) ? charges : -1; - return f; - } - - 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 double TryDouble(RynthCoreHost host, uint id, uint stype) - => host.HasGetObjectDoubleProperty && host.TryGetObjectDoubleProperty(id, stype, out double v) ? v : 0; - - // ── Actions (pump) ────────────────────────────────────────────────────── - - /// Re-appraises every essence and rescans. - public void RefreshAll() - { - _refreshAll = true; - _scannedAt = 0; - MarkWatched(); - } - - /// Runs "@breed-debug" quietly and keeps its reply (the room check, partners nearby). - public void RequestDebug() - { - if (_ctx.Capture.IsPending(DebugCommand)) return; - _message = "Asking the server for breeding diagnostics..."; - _ctx.Capture.Enqueue(new IltChatRequest - { - Command = DebugCommand, - IsResponseLine = IltBreedingRules.IsDebugLine, - IsTerminator = IltBreedingRules.IsDebugEnd, - IdleEndMs = 1500, - FirstLineTimeoutMs = 8000, - Eat = true, - OnComplete = ApplyDebug, - }); - _scannedAt = 0; - } - - private void ApplyDebug(IltChatResult r) - { - if (r.UnknownCommand) { _message = "This server has no @breed-debug (no pet breeding here)."; _ctx.Options.Set(BitBreeding, IltTri.Off); return; } - if (r.NotSent) { _message = "This RynthCore can't send chat commands."; return; } - if (r.Lines.Count == 0) { _message = "No reply to @breed-debug."; return; } - DateTime utc = DateTime.UtcNow; - IltBreedingState st = _rules.State; - st.LastDebug = new List(r.Lines); - st.LastDebugUtc = utc; - foreach (string l in r.Lines) _rules.LearnAll(IltBreedingRules.FromChat(l), utc); - BreedDebugInfo d = IltBreedingRules.ParseDebug(r.Lines); - if (d.Enabled.HasValue) _ctx.Options.Set(BitBreeding, d.Enabled.Value ? IltTri.On : IltTri.Off); - _message = d.Enabled == false ? "The server says breeding is switched off." - : d.LocationOk == true ? $"You're in the breeding room. Partners nearby: {Math.Max(0, d.Partners)}." - : d.LocationOk == false ? $"Not in the breeding room ({_rules.RoomText()})." - : "Diagnostics read."; - _rules.AddEvent("debug", _message, utc); - _scannedAt = 0; - } - - /// Starts the courtship dance ("@dance"); the breed happens when a partner dances in time. - public void Dance() - { - if (!_ctx.Host.HasInvokeChatParser) { _message = "This RynthCore can't send chat commands."; return; } - _ctx.Host.InvokeChatParser(DanceCommand); - _message = $"Danced. Your partner must *dance* within {_rules.Get(IltBreedingRules.DanceWindow):0.#}s with their pet in the same room."; - _scannedAt = 0; - } - - /// - /// Uses a supply on a carried essence, re-checking both are still here and that the server would - /// take it. Returns a message for the UI. Called after the player confirmed. - /// - public string ApplySupply(string key, int essenceId) - { - BreedSupplyDef? def = IltBreedingSupplies.Find(key); - if (def == null || !def.Apply) return _message = "That supply isn't applied from here."; - IltInventory inv = _ctx.Inventory; - WorldObject? item = inv.FindByWcid(def.Wcid); - if (item == null) return _message = $"No {def.Name} in your pack."; - BreedEssence? e = _snap.Essences.FirstOrDefault(x => x.Id == essenceId); - if (e == null || !inv.Items().Any(wo => wo.Id == essenceId)) return _message = "That essence isn't in your pack any more."; - string? refuse = IltBreedingSupplies.RefuseReason(def, e, _rules); - if (refuse != null) return _message = refuse; - if (inv.IsBusy) return _message = "You're busy; try again in a moment."; - bool sent = inv.UseOn(item, unchecked((uint)essenceId)); - _message = sent ? $"Used {def.Name} on {e.Name}." : $"Couldn't use {def.Name} (the engine refused)."; - if (sent) _rules.AddEvent("supply", _message, DateTime.UtcNow); - RefreshAll(); - return _message; - } - - /// - /// A reader's verb line ("RynthILT.Data" PetBreedingCommand): refresh, debug, dance, - /// or "apply <supplyKey> <essenceId>" (the reader confirmed it with the player). Pump thread. - /// - public void RunVerb(string line) - { - string[] parts = (line ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); - if (parts.Length == 0) return; - switch (parts[0].ToLowerInvariant()) - { - case "refresh": RefreshAll(); break; - case "debug": RequestDebug(); break; - case "dance": Dance(); break; - case "apply" when parts.Length == 3 && int.TryParse(parts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out int id): - ApplySupply(parts[1], id); - break; - default: - RynthLog.Trace(LogCat.IltPets, $"breeding: unknown reader verb '{line}'"); - break; - } - } - - // ── Reader JSON ───────────────────────────────────────────────────────── - - /// The reader JSON (Plugins/Shared/RynthIltDataApi.cs header has the shape). - internal static string BuildJson(BreedingSnapshot s, IltBreedingRules r, string world) - { - var sb = new StringBuilder(4096); - sb.Append("{\"available\":true"); - Str(sb, "world", world); - Str(sb, "enabled", TriText(s.Enabled)); - Str(sb, "maturity", TriText(s.Maturity)); - Str(sb, "bond", TriText(s.Bond)); - Str(sb, "room", s.Room); - sb.Append(",\"freeSlots\":").Append(s.FreeSlots); - Str(sb, "message", s.Message); - - sb.Append(",\"essences\":["); - for (int i = 0; i < s.Essences.Count; i++) - { - BreedEssence e = s.Essences[i]; - if (i > 0) sb.Append(','); - sb.Append("{\"id\":").Append(e.Id); - Str(sb, "name", e.Name); - Str(sb, "sex", e.Male ? "M" : "F"); - sb.Append(",\"tier\":").Append(e.Tier).Append(",\"bond\":").Append(e.Bond); - sb.Append(",\"ready\":").Append(e.Ready ? "true" : "false"); - Str(sb, "status", e.Status); - double readyIn = e.ReadyAtUnix > s.NowUnix ? e.ReadyAtUnix - s.NowUnix : 0; - sb.Append(",\"readyIn\":").Append((long)Math.Ceiling(readyIn)); - sb.Append(",\"charges\":").Append(e.Charges).Append(",\"chargesMax\":").Append(e.ChargesMax); - sb.Append(",\"juvenile\":").Append(e.Juvenile ? "true" : "false"); - Str(sb, "stage", e.StageName); - sb.Append(",\"kills\":").Append(e.Kills).Append(",\"killsRequired\":").Append(e.KillsRequired); - sb.Append(",\"mutations\":").Append(e.StatMutations).Append(",\"potencyMutations\":").Append(e.MutP); - Arr(sb, "problems", e.Problems); - Arr(sb, "boosters", e.Boosters); - sb.Append('}'); - } - sb.Append(']'); - - // Ready pairings, best odds first (the fewest inherited mutations keeps the decay low). - var studs = s.Essences.Where(e => e.Male && e.Ready).ToList(); - var dams = s.Essences.Where(e => !e.Male && e.Ready).ToList(); - var pairs = new List<(BreedEssence Stud, BreedEssence Dam, BreedPairPlan Plan)>(); - foreach (BreedEssence st in studs) - foreach (BreedEssence d in dams) - pairs.Add((st, d, IltBreedingPlanner.Plan(st, d, r))); - pairs.Sort((a, b) => b.Plan.ChanceBest.CompareTo(a.Plan.ChanceBest)); - sb.Append(",\"pairs\":["); - for (int i = 0; i < pairs.Count && i < 6; i++) - { - if (i > 0) sb.Append(','); - sb.Append('{'); - Str(sb, "stud", pairs[i].Stud.Name, first: true); - Str(sb, "dam", pairs[i].Dam.Name); - sb.Append(",\"chanceBest\":").Append(pairs[i].Plan.ChanceBest.ToString("0.####", CultureInfo.InvariantCulture)); - sb.Append(",\"chanceWorst\":").Append(pairs[i].Plan.ChanceWorst.ToString("0.####", CultureInfo.InvariantCulture)); - sb.Append(",\"inheritMin\":").Append(pairs[i].Plan.InheritMin).Append(",\"inheritMax\":").Append(pairs[i].Plan.InheritMax); - sb.Append('}'); - } - sb.Append(']'); - - sb.Append(",\"supplies\":["); - for (int i = 0; i < s.Supplies.Count; i++) - { - (BreedSupplyDef def, long count) = s.Supplies[i]; - if (i > 0) sb.Append(','); - sb.Append('{'); - Str(sb, "key", def.Key, first: true); - Str(sb, "name", def.Name); - Str(sb, "effect", def.Effect); - sb.Append(",\"count\":").Append(count).Append(",\"price\":").Append(def.Price); - sb.Append(",\"apply\":").Append(def.Apply ? "true" : "false"); - // Essences the server would take this on now (the reader's Use buttons). - var targets = def.Apply && count > 0 - ? s.Essences.Where(e => IltBreedingSupplies.RefuseReason(def, e, r) == null).Select(e => e.Id).ToList() - : new List(); - sb.Append(",\"targets\":[").Append(string.Join(',', targets)).Append(']'); - sb.Append('}'); - } - sb.Append(']'); - - sb.Append(",\"rules\":["); - for (int i = 0; i < s.Rules.Count; i++) - { - BreedRuleValue v = s.Rules[i]; - if (i > 0) sb.Append(','); - sb.Append('{'); - Str(sb, "label", v.Def.Label, first: true); - Str(sb, "value", IltBreedingRules.Format(v)); - Str(sb, "source", IltBreedingRules.SourceText(v.Source)); - Str(sb, "help", v.Def.Help); - sb.Append('}'); - } - sb.Append(']'); - - sb.Append(",\"events\":["); - int start = Math.Max(0, s.Events.Count - 20); - for (int i = s.Events.Count - 1; i >= start; i--) - { - IltBreedingEvent e = s.Events[i]; - if (i != s.Events.Count - 1) sb.Append(','); - sb.Append('{'); - Str(sb, "when", e.Utc.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture), first: true); - Str(sb, "kind", e.Kind); - Str(sb, "text", e.Text); - sb.Append('}'); - } - sb.Append(']'); - - if (s.Debug != null) - { - BreedDebugInfo d = s.Debug; - sb.Append(",\"debug\":{"); - Str(sb, "when", s.DebugUtc.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture), first: true); - Str(sb, "enabled", d.Enabled == null ? "unknown" : d.Enabled.Value ? "on" : "off"); - Str(sb, "location", d.Location); - Str(sb, "match", d.LocationOk == null ? "" : d.LocationOk.Value ? "valid" : "invalid"); - Str(sb, "pet", d.ActivePet); - Str(sb, "sex", d.PetSex); - sb.Append(",\"partners\":").Append(d.Partners); - sb.Append('}'); - } - sb.Append('}'); - return sb.ToString(); - } - - private static string TriText(IltTri t) => t switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" }; - - private static void Str(StringBuilder sb, string name, string? value, bool first = false) - { - if (!first) sb.Append(','); - sb.Append('"').Append(name).Append("\":\"").Append(IltStyle.JsonEscape(value ?? string.Empty)).Append('"'); - } - - private static void Arr(StringBuilder sb, string name, IReadOnlyList values) - { - sb.Append(",\"").Append(name).Append("\":["); - for (int i = 0; i < values.Count; i++) - { - if (i > 0) sb.Append(','); - sb.Append('"').Append(IltStyle.JsonEscape(values[i])).Append('"'); - } - sb.Append(']'); - } - - // ── UI (render thread): Mini Remote > Pets > Breeding ─────────────────── - - /// The Breeding tab's body (RynthIltHub.SectionPetBreeding). - public void RenderSection() - { - MarkWatched(); - BreedingSnapshot s = _snap; - - RenderHeader(s); - if (!s.Built) - { - ImGui.TextDisabled("Reading your essences..."); - return; - } - ImGui.Separator(); - RenderEssences(s); - RenderPlanner(s); - RenderSupplies(s); - RenderRules(s); - RenderEvents(s); - RenderGuide(s); - } - - private void RenderHeader(BreedingSnapshot s) - { - Vector4 col = s.Enabled == IltTri.Off ? IltStyle.ColHp : IltStyle.ColTeal; - SafeImGui.TextColored(col, s.Enabled switch - { - IltTri.Off => "Pet breeding is off on this server.", - IltTri.On => $"Pet breeding: on. Breeding room: {s.Room}.", - _ => "Pet breeding: not confirmed yet (run Diagnostics in the breeding room).", - }); - if (s.Bond == IltTri.Off) SafeImGui.TextColored(IltStyle.ColAmber, "Pet bond is off here, so bond can't reach the breeding minimum."); - - if (ImGui.SmallButton("Refresh##brrefresh")) _ctx.Post(RefreshAll); - if (ImGui.IsItemHovered()) ImGui.SetTooltip("Re-appraise every essence (charges, rest timers, bond, growth)."); - ImGui.SameLine(); - if (ImGui.SmallButton("Diagnostics##brdebug")) _ctx.Post(RequestDebug); - if (ImGui.IsItemHovered()) ImGui.SetTooltip("@breed-debug: are you in the breeding room, your summoned pet, partners nearby (reply hidden, shown here)."); - ImGui.SameLine(); - if (ImGui.SmallButton("Dance##brdance")) - _ctx.Confirm("Courtship dance", - "Dance now? If your partner dances within the window with both pets summoned in the same room, the breed happens:" + - " the stud spends a charge, the dam rests, incense is used up and the baby goes to the dam's owner.", - Dance, "Dance"); - if (ImGui.IsItemHovered()) ImGui.SetTooltip("@dance (the same as typing *dance*). Both owners must dance within the window."); - - if (s.Message.Length > 0) SafeImGui.TextDisabled(s.Message); - if (s.FreeSlots == 0) SafeImGui.TextColored(IltStyle.ColAmber, "Your main pack is full: as the dam's owner you couldn't receive the baby."); - } - - private void RenderEssences(BreedingSnapshot s) - { - int ready = s.Essences.Count(e => e.Ready); - if (!ImGui.CollapsingHeader($"Essences ({ready} ready of {s.Essences.Count})###bress", ImGuiTreeNodeFlags.DefaultOpen)) return; - if (s.Essences.Count == 0) - { - ImGui.TextDisabled("No combat pet essences in your pack."); - return; - } - - const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.ScrollY; - float h = Math.Min(260f, 26f + s.Essences.Count * ImGui.GetTextLineHeightWithSpacing()); - if (!ImGui.BeginTable("##brtable", 6, flags, new Vector2(0, h))) return; - ImGui.TableSetupScrollFreeze(0, 1); - ImGui.TableSetupColumn("Essence", ImGuiTableColumnFlags.WidthStretch); - ImGui.TableSetupColumn("Sex", ImGuiTableColumnFlags.WidthFixed, 34); - ImGui.TableSetupColumn("Tier", ImGuiTableColumnFlags.WidthFixed, 34); - ImGui.TableSetupColumn("Bond", ImGuiTableColumnFlags.WidthFixed, 38); - ImGui.TableSetupColumn("Breeding", ImGuiTableColumnFlags.WidthFixed, 130); - ImGui.TableSetupColumn("Muts", ImGuiTableColumnFlags.WidthFixed, 40); - ImGui.TableHeadersRow(); - for (int i = 0; i < s.Essences.Count; i++) - { - BreedEssence e = s.Essences[i]; - ImGui.PushID(i); - ImGui.TableNextRow(); - ImGui.TableNextColumn(); - bool picked = e.Id == _studId || e.Id == _damId; - if (ImGui.Selectable(SafeText(e.Name) + "##sel", picked, ImGuiSelectableFlags.SpanAllColumns)) - { - if (e.Male) _studId = e.Id; else _damId = e.Id; - _targetId = e.Id; - } - if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(Tooltip(e)); - ImGui.TableNextColumn(); - ImGui.TextUnformatted(e.Male ? "M" : "F"); - ImGui.TableNextColumn(); - ImGui.TextUnformatted(e.Tier > 0 ? e.Tier.ToString(CultureInfo.InvariantCulture) : "?"); - ImGui.TableNextColumn(); - ImGui.TextUnformatted(e.HasId ? e.Bond.ToString(CultureInfo.InvariantCulture) : "?"); - ImGui.TableNextColumn(); - Vector4 col = e.Ready ? IltStyle.ColGreen - : e.Gate is BreedGate.Resting or BreedGate.NoCharges or BreedGate.Growing or BreedGate.NeedsId ? IltStyle.ColAmber - : IltStyle.ColTextMute; - SafeImGui.TextColored(col, e.Status); - ImGui.TableNextColumn(); - ImGui.TextUnformatted(e.MutP > 0 ? $"{e.StatMutations}+{e.MutP}p" : e.StatMutations.ToString(CultureInfo.InvariantCulture)); - ImGui.PopID(); - } - ImGui.EndTable(); - ImGui.TextDisabled("Click a male to pick the stud, a female for the dam (and the supply target). Hover for details."); - } - - private static string Tooltip(BreedEssence e) - { - var sb = new StringBuilder(); - sb.Append(e.Name).Append('\n').Append(e.Role).Append(", tier ").Append(e.Tier > 0 ? e.Tier.ToString(CultureInfo.InvariantCulture) : "?") - .Append(", bond ").Append(e.Bond); - if (e.Male) sb.Append("\nCharges ").Append(e.Charges).Append('/').Append(e.ChargesMax); - if (e.Bred) sb.Append(e.Juvenile ? $"\nGrowing: {e.StageName}, {e.KillsToNext} kills to the next stage, {Math.Max(0, e.KillsRequired - e.Kills)} to Adult" : "\nBred: Adult"); - if (e.Unbound) sb.Append("\nUnbound: imprints on the first character to summon it."); - sb.Append($"\nMutations: damage {e.MutD}, damage resist {e.MutDR}, crit {e.MutC}, vitality {e.MutV}, potency {e.MutP}"); - if (e.Boosters.Count > 0) sb.Append("\nBoosters: ").Append(string.Join(", ", e.Boosters)); - foreach (string p in e.Problems) sb.Append("\n- ").Append(p); - return sb.ToString(); - } - - private void RenderPlanner(BreedingSnapshot s) - { - if (!ImGui.CollapsingHeader("Pair planner###brplan")) return; - BreedEssence? stud = s.Essences.FirstOrDefault(e => e.Id == _studId && e.Male); - BreedEssence? dam = s.Essences.FirstOrDefault(e => e.Id == _damId && !e.Male); - PickCombo("Stud##brstud", s.Essences.Where(e => e.Male).ToList(), stud, id => _studId = id); - PickCombo("Dam##brdam", s.Essences.Where(e => !e.Male).ToList(), dam, id => _damId = id); - if (stud == null || dam == null) - { - ImGui.TextDisabled("Pick a stud and a dam (yours, or an alt's carried here) to see the odds."); - ImGui.TextDisabled("Breeding needs two owners: each dances with their own summoned pet."); - return; - } - BreedPairPlan p = IltBreedingPlanner.Plan(stud, dam, s.RulesView); - if (p.CanBreed) SafeImGui.TextColored(IltStyle.ColGreen, "Both are ready to breed."); - foreach (string b in p.Blockers) SafeImGui.TextColored(IltStyle.ColAmber, b); - SafeImGui.Text($"Stat mutation chance: {Pct(p.ChanceWorst)} to {Pct(p.ChanceBest)} (baby inherits {p.InheritMin}-{p.InheritMax} stat mutations)"); - SafeImGui.Text($"Potency mutation chance: {Pct(p.PotencyChance)}" + (p.Incense > 0 ? $"; incense +{p.Incense * 100:0.#}%" : "")); - foreach (string n in p.Notes) SafeImGui.BulletText(n); - } - - private static void PickCombo(string label, List list, BreedEssence? current, Action set) - { - ImGui.SetNextItemWidth(260); - if (!ImGui.BeginCombo(label, current != null ? SafeText(current.Name) : "(none)")) return; - foreach (BreedEssence e in list) - { - if (ImGui.Selectable($"{SafeText(e.Name)} - {SafeText(e.Status)}##{e.Id}", current != null && current.Id == e.Id)) set(e.Id); - } - ImGui.EndCombo(); - } - - private void RenderSupplies(BreedingSnapshot s) - { - long carried = s.Supplies.Sum(x => x.Count); - if (!ImGui.CollapsingHeader($"Supplies ({carried} carried)###brsup")) return; - BreedEssence? target = s.Essences.FirstOrDefault(e => e.Id == _targetId); - PickCombo("Use on##brtarget", s.Essences.ToList(), target, id => _targetId = id); - ImGui.TextDisabled("Ivo sells these at the Seedy Motel. Boosters are spent by the essence's next breed."); - for (int i = 0; i < s.Supplies.Count; i++) - { - (BreedSupplyDef def, long count) = s.Supplies[i]; - ImGui.PushID("sup" + i); - Vector4 col = count > 0 ? IltStyle.ColGreen : IltStyle.ColTextMute; - SafeImGui.TextColored(col, $"{count,3} {def.Name}"); - if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"{def.Effect}\nIvo's price: {IltBreedingSupplies.PriceText(def.Price)} pyreals"); - if (def.Apply && count > 0 && target != null) - { - ImGui.SameLine(300); - string? refuse = IltBreedingSupplies.RefuseReason(def, target, s.RulesView); - if (refuse != null) - { - ImGui.TextDisabled("can't"); - if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(refuse); - } - else if (ImGui.SmallButton("Use")) - { - string key = def.Key; - int id = target.Id; - _ctx.Confirm("Use " + def.Name, - $"Use {def.Name} on {target.Name}? {def.Effect}{IltBreedingSupplies.Warning(def, target)}", - () => ApplySupply(key, id), "Use"); - } - } - ImGui.PopID(); - } - } - - private void RenderRules(BreedingSnapshot s) - { - if (!ImGui.CollapsingHeader("Server rules###brrules")) return; - ImGui.TextDisabled("Values this server showed win over the ILT profile, which wins over ACE's defaults."); - foreach (BreedRuleValue v in s.Rules) - { - SafeImGui.Text(v.Def.Label); - if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(v.Def.Help); - ImGui.SameLine(200); - SafeImGui.Text(IltBreedingRules.Format(v)); - ImGui.SameLine(280); - SafeImGui.TextColored(v.Source == BreedRuleSource.Server ? IltStyle.ColGreen : IltStyle.ColTextMute, - IltBreedingRules.SourceText(v.Source)); - } - if (s.Debug != null) - { - ImGui.Separator(); - SafeImGui.TextDisabled($"Last diagnostics ({s.DebugUtc.ToLocalTime():g}):"); - BreedDebugInfo d = s.Debug; - if (d.Location.Length > 0) SafeImGui.BulletText("You: " + d.Location); - if (d.LocationOk.HasValue) SafeImGui.BulletText(d.LocationOk.Value ? "In the breeding room" : "Not in the breeding room"); - if (d.ActivePet.Length > 0) SafeImGui.BulletText("Pet: " + d.ActivePet + (d.PetSex.Length > 0 ? " (" + d.PetSex + ")" : "")); - if (d.Partners >= 0) SafeImGui.BulletText($"Partners nearby: {d.Partners}"); - } - } - - private static void RenderEvents(BreedingSnapshot s) - { - if (!ImGui.CollapsingHeader($"Recent events ({s.Events.Count})###brevents")) return; - if (s.Events.Count == 0) ImGui.TextDisabled("Nothing yet: rituals, births, growth and charges land here."); - for (int i = s.Events.Count - 1, shown = 0; i >= 0 && shown < 20; i--, shown++) - { - IltBreedingEvent e = s.Events[i]; - SafeImGui.TextDisabled(e.Utc.ToLocalTime().ToString("MM-dd HH:mm", CultureInfo.InvariantCulture)); - ImGui.SameLine(90); - SafeImGui.TextWrapped(e.Text); - } - } - - private static void RenderGuide(BreedingSnapshot s) - { - if (!ImGui.CollapsingHeader("How to breed###brguide")) return; - SafeImGui.BulletText($"Go to the Seedy Motel (portal by Prof. Ruggan in Lin, 54.7S 73.5E); breeding room {s.Room}."); - SafeImGui.BulletText("Two owners: one summons a male (stud), the other a female (dam). Both pets in the same room."); - SafeImGui.BulletText("Both parents: tier 100+, bond 100+, adult, not shiny, not neutered. The stud needs a charge, the dam must have rested."); - SafeImGui.BulletText("Both owners *dance* (or @dance) within a few seconds. The baby goes to the dam's owner (free pack slot needed)."); - SafeImGui.BulletText("A mating guardian may rise: both parents kill it in time for an Awakened Blessing mutation."); - SafeImGui.BulletText("The baby imprints on whoever summons it first, and grows up with kills (Nurturing Draught doubles the credit)."); - } - - private static string Pct(double v) => (v * 100).ToString("0.##", CultureInfo.InvariantCulture) + "%"; - - /// Item names go into ImGui labels, where "##" would start the hidden id. - private static string SafeText(string s) => (s ?? string.Empty).Replace("#", ""); -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetCaptureRules.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetCaptureRules.cs deleted file mode 100644 index c978268..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetCaptureRules.cs +++ /dev/null @@ -1,166 +0,0 @@ -// IltPetCaptureRules.cs — ACECustom MonsterCapture thresholds for siphon lenses (pure; no host). -// Moved from RynthAi's Pets tab (MiniRemote/PetCaptureRules.cs) 2026-10-20 with the auto-capture -// itself (IltPetAutomation): monster capture is ACECustom's, so it is RynthILT's. -// -// Copied from ACECustom Source/ACE.Server/Entity/MonsterCapture.cs so the client can tell when -// a creature is weak enough to siphon before using a lens. Keep these numbers in lockstep with -// the server: CaptureMaxHealthFraction / CaptureMaxHealthPoints / CaptureRangeM and the lens -// WCID table in PetGuideController. -using System; -using System.Collections.Generic; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// One siphon lens the Pets tab can auto-use (name, WCID, whether health is gated). -internal readonly struct PetCaptureLens -{ - public PetCaptureLens(string name, uint wcid, bool bypassesHealthGate) - { - Name = name; - Wcid = wcid; - BypassesHealthGate = bypassesHealthGate; - } - - public string Name { get; } - public uint Wcid { get; } - /// Asheron's (and Debug) lenses skip the 20% / 20 HP gate. - public bool BypassesHealthGate { get; } -} - -/// -/// When a siphon lens can be used, matching ACECustom MonsterCapture.UseCaptureCrystal. -/// A creature is weak enough when its health fraction is ≤ 20% OR its current HP is under 20 -/// (whichever comes first). Asheron's Lens skips that check. -/// -internal static class PetCaptureRules -{ - /// A lens targets the nearest attackable creature within this many meters. - public const float CaptureRangeM = 5.0f; - - /// Siphon once at or below this fraction of max health… - public const float CaptureMaxHealthFraction = 0.20f; - - /// …or below this many hit points (the gate is OR with the fraction). - public const int CaptureMaxHealthPoints = 20; - - /// - /// Lenses the player can pick for auto-capture. Order is the combo index. - /// Resonance needs a prior failed capture (server-side); Asheron's bypasses the health gate. - /// - public static readonly PetCaptureLens[] Lenses = - { - new("Flawed Siphon Lens", 78780001, bypassesHealthGate: false), - new("Pristine Siphon Lens", 78780002, bypassesHealthGate: false), - new("Perfect Siphon Lens", 78780003, bypassesHealthGate: false), - new("Resonance Lens", 78780010, bypassesHealthGate: false), - new("Asheron's Lens", 78780012, bypassesHealthGate: true), - }; - - /// Combo labels for the Pets tab (same order as ). - public static readonly string[] LensNames = - { - "Flawed", "Pristine", "Perfect", "Resonance", "Asheron's", - }; - - public static PetCaptureLens LensAt(int index) - { - int i = Math.Clamp(index, 0, Lenses.Length - 1); - return Lenses[i]; - } - - /// - /// True when ACECustom would accept a siphon on this creature for a normal (non-bypass) lens. - /// Pass current/max when known; when only a 0–1 ratio is known, pass ratio as current and 1 as max - /// (then only the fraction half of the gate can fire). - /// - public static bool IsWeakEnough(uint currentHp, uint maxHp) - { - if (currentHp == 0) return false; // dead — server refuses - if (maxHp == 0) return false; - float pct = (float)currentHp / maxHp; - // Server: refuse when pct > 0.20 AND current >= 20. Allowed otherwise. - return pct <= CaptureMaxHealthFraction || currentHp < CaptureMaxHealthPoints; - } - - /// Same gate from a 0–1 health ratio only (no absolute HP). Dead / unknown = false. - public static bool IsWeakEnoughRatio(float healthRatio) - { - if (healthRatio <= 0f || healthRatio > 1f) return false; - return healthRatio <= CaptureMaxHealthFraction; - } - - /// True when this lens may be used given the creature's vitals (bypass lenses always, if alive). - public static bool CanAttempt(PetCaptureLens lens, uint currentHp, uint maxHp) - { - if (currentHp == 0) return false; - if (lens.BypassesHealthGate) return maxHp == 0 || currentHp > 0; - return IsWeakEnough(currentHp, maxHp); - } - - /// Distance gate: ACECustom CaptureRangeM. - public static bool InRange(double distanceM) => distanceM >= 0 && distanceM <= CaptureRangeM; -} - -/// -/// A brake on the auto-capture loop. Auto-capture fires a lens every couple of seconds and only stops -/// on reply strings it guesses at, so an unrecognized reply (or a creature the server never lets go of) -/// would burn lenses without end. This caps consecutive tries per target and, as a backstop, consecutive -/// tries over all targets; both reset on a recognized success. Pure: the tests drive it. -/// -internal sealed class PetCaptureThrottle -{ - /// Lens uses on one creature, with no success in between, before it is left alone. - public const int MaxTriesPerTarget = 5; - - /// How long a creature that used up its tries is left alone (ms). - public const long TargetBlockMs = 120_000; - - /// Lens uses over all creatures with no success before auto-capture switches itself off. - public const int MaxTriesWithoutSuccess = 15; - - private readonly Dictionary _tries = new(); - private readonly Dictionary _blockedUntil = new(); - private int _sinceSuccess; - - /// Consecutive lens uses with no recognized success (all targets). - public int TriesWithoutSuccess => _sinceSuccess; - - /// True when the backstop was hit: the caller should switch auto-capture off. - public bool Exhausted => _sinceSuccess >= MaxTriesWithoutSuccess; - - /// False while this target is blocked (it used its tries) or the backstop is hit. - public bool MayAttempt(int targetId, long nowMs) - { - if (Exhausted) return false; - if (_blockedUntil.TryGetValue(targetId, out long until)) - { - if (nowMs < until) return false; - _blockedUntil.Remove(targetId); // block served: a fresh set of tries - _tries.Remove(targetId); - } - return true; - } - - /// Seconds left on this target's block, 0 when it is not blocked. - public long BlockedSecondsLeft(int targetId, long nowMs) - => _blockedUntil.TryGetValue(targetId, out long until) && nowMs < until ? (until - nowMs + 999) / 1000 : 0; - - /// Count a lens use on this target; blocks it once it reaches . - public void RecordAttempt(int targetId, long nowMs) - { - _sinceSuccess++; - int n = _tries.TryGetValue(targetId, out int t) ? t + 1 : 1; - _tries[targetId] = n; - if (n >= MaxTriesPerTarget) _blockedUntil[targetId] = nowMs + TargetBlockMs; - } - - /// A recognized success reply: everything starts over. - public void RecordSuccess() => Reset(); - - public void Reset() - { - _tries.Clear(); - _blockedUntil.Clear(); - _sinceSuccess = 0; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetLogs.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetLogs.cs deleted file mode 100644 index e32b9be..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltPetLogs.cs +++ /dev/null @@ -1,87 +0,0 @@ -// IltPetLogs.cs — The ACECustom /pets and /shinies logs, shown in RynthAi's universal Pets tab -// (RynthILT.Hub section "pets-logs"). -// Originally the roster-capture part of SilentKelpie's IltPets (ILT Hub, RynthAi); split out and -// moved to RynthILT 2026-10-13. The Pets tab itself (essence roster, combat / healing / cosmetic -// pets) stayed in RynthAi (MiniRemote/PetsTab.cs): summoning is every server's, these two commands -// are ACECustom's (as are the pet charms, the refill path and siphon capture: IltPetAutomation, -// moved 2026-10-20). -using System; -using System.Collections.Generic; -using ImGuiNET; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal sealed class IltPetLogs : IIltFeature -{ - private readonly IltHubContext _ctx; - - public IltPetLogs(IltHubContext ctx) => _ctx = ctx; - - private IltPetState S => _ctx.State.Pet; - - /// 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) { } - public bool OnChat(string text) => false; - public void OnLogout() { } - - // ── UI (render thread): the Pets tab's last section ───────────────────── - - public void RenderSection() - { - ImGui.Separator(); - 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) SafeImGui.BulletText(s); - ImGui.TreePop(); - } - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltProgression.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltProgression.cs deleted file mode 100644 index 0977bc5..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltProgression.cs +++ /dev/null @@ -1,882 +0,0 @@ -// IltProgression.cs — Augmentation and Enlightenment planners, drawn by the engine's -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// Skills panel (Progression tab) from AppendSnapshotJson; edits arrive via HandleRemote. -// -// Augs : "/aug" levels + the per-server cost rules in IltAugCosts (UB's ILT model by default: -// level i costs base + (i-1)*(base*LP/100), times 1/4/8/16/24 from 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 spends unassigned XP ("/attr") before an auto-enlighten, and owns the -// infinite-attribute raiser (IltAttributeRaiser: server costs from "/xp all", manual -// or timed raises in a chosen order) drawn in the same tab. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal sealed class IltProgression : IIltFeature -{ - // ── Augmentation cost rules ───────────────────────────────────────────── - - /// Per-server aug cost rules (UB's ILT model unless this world was changed). - public IltAugCosts AugCosts { get; } = new(); - - /// The rules for the world we're on. - private IltAugCostProfile AugProfile => AugCosts.For(_ctx.Options.WorldName); - - // ── 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"; - // Opening the Progression tab pulls "/aug" once per login when nothing has loaded the levels yet. - private bool _augAutoTried; - /// Second Refresh current while /aug is already queued or in flight (UB coalesces the same way). - private bool _augRefreshAgain; - /// One silent retry after the login probe left Current empty (chat-hold / ArmsIdle race). - private bool _augProbeRetryDone; - /// Passive /aug window: accept AugLine chat until this tick (like T11's report parser). - private long _augPassiveUntilMs; - - // 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 - // 301-325 sigil chain stock (pack items by name; EnlightenedCoins = bank + pack). Pump thread only. - private IltSigilStock _chain = new(); - 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; - - /// Infinite-attribute raiser (Progression tab "Attribute raiser" section). - public IltAttributeRaiser Attributes { get; } - - public IltProgression(IltHubContext ctx) - { - _ctx = ctx; - // Never two /attr spenders at once: the raiser waits while the spend-before-/enl loop runs. - Attributes = new IltAttributeRaiser(ctx) { HoldOff = () => _spending }; - } - - private IltCharacterState C => _ctx.State.Character; - - // ── Commands ──────────────────────────────────────────────────────────── - - public void RequestAugs() - { - RynthLog.Trace(LogCat.IltProgression, $"RequestAugs()"); - if (_ctx.Options.IsOff(IltFeature.Aug)) - { - _augStatus = "/aug is off for this world"; - return; - } - // Coalesce: a click during an in-flight /aug (login probe or a prior Refresh) runs again - // when that capture finishes — including via AfterExternalAugCapture for the probe. - if (_ctx.Capture.IsPending("/aug")) - { - _augRefreshAgain = true; - _augStatus = "refresh queued (waiting for current /aug)..."; - return; - } - _augStatus = "loading..."; - _augPassiveUntilMs = IltHubContext.NowMs + 30_000; // also accept lines if capture finishes early - _ctx.Capture.Enqueue(new IltChatRequest - { - Command = "/aug", - IsResponseLine = t => t.StartsWith("---") || t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase) || IltParse.AugLine.IsMatch(t), - // Idle must not start on the banner alone — chat-hold / pump lag used to finish with 0 level lines. - ArmsIdle = t => IltParse.AugLine.IsMatch(t), - IdleEndMs = 2500, - // Login + chat-hold backlog can push Creature: past the old 15s first-line window. - FirstLineTimeoutMs = 30_000, - Eat = true, - OnComplete = r => - { - if (r.UnknownCommand) - { - _ctx.Options.Set(IltFeature.Aug, IltTri.Off); - _augStatus = "/aug not available"; - _augRefreshAgain = false; - return; - } - ApplyAugLines(r.Lines); - if (r.TimedOut) - { - int have; - lock (_augLevels) have = _augLevels.Count; - if (have == 0) - _augStatus = "timed out waiting for /aug level lines"; - } - DrainAugRefreshAgain(); - }, - }); - } - - /// - /// Login probe finished its "/aug" capture (or another path applied lines). Drains a queued - /// Refresh current and, if the probe left Current empty, retries once. - /// - public void AfterExternalAugCapture() - { - if (DrainAugRefreshAgain()) return; - int have; - lock (_augLevels) have = _augLevels.Count; - if (have > 0 || _augProbeRetryDone || _ctx.Options.IsOff(IltFeature.Aug)) return; - if (_ctx.Capture.IsPending("/aug")) return; - _augProbeRetryDone = true; - RynthLog.Event(LogEvents.IltAugLoad, "aug probe left Current empty — retrying /aug once"); - RequestAugs(); - } - - /// Runs a coalesced Refresh current if one was queued. Returns true when it did. - private bool DrainAugRefreshAgain() - { - if (!_augRefreshAgain) return false; - _augRefreshAgain = false; - RequestAugs(); - return true; - } - - /// Parses "/aug" output (also fed from the login probe and passive chat). - public void ApplyAugLines(List lines) - { - RynthLog.Trace(LogCat.IltProgression, $"ApplyAugLines(lines={lines.Count})"); - int n = 0; - foreach (string l in lines) - { - if (TryApplyAugLine(l)) n++; - } - if (n > 0) - { - _augStatus = $"{n} aug types @ {DateTime.Now:t}"; - _augPassiveUntilMs = IltHubContext.NowMs + 8_000; - } - else - { - bool sawBanner = false; - foreach (string l in lines) - { - if (l.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase)) - { sawBanner = true; break; } - } - _augStatus = sawBanner - ? "no level lines yet (banner only — waiting / retry)" - : "no aug lines in reply"; - // Keep the passive reader open so late Creature: lines still fill Current. - if (sawBanner) _augPassiveUntilMs = IltHubContext.NowMs + 15_000; - } - RynthLog.Event(LogEvents.IltAugLoad, $"ApplyAugLines: {_augStatus} (raw={lines.Count})"); - } - - /// Applies one "/aug" Type: N line. Returns true when a known planner key was updated. - private bool TryApplyAugLine(string raw) - { - var m = IltParse.AugLine.Match((raw ?? string.Empty).Trim()); - if (!m.Success) return false; - string key = m.Groups[1].Value.ToLowerInvariant(); - if (key == "specialize") key = "specialization"; - // Planner rows only; charm / Triune Weave lines are ignored here (T11 reads those). - bool known = false; - foreach (var (k, _) in IltAugCosts.Labels) - if (k.Equals(key, StringComparison.OrdinalIgnoreCase)) { known = true; break; } - if (!known) return false; - lock (_augLevels) _augLevels[key] = (int)IltParse.ParseAugValue(m.Groups[2].Value); - return true; - } - - /// 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("[Mini Remote] " + _enlStatus); - } - - // ── IIltFeature ───────────────────────────────────────────────────────── - - public void Tick(long nowMs) - { - if (nowMs - _lastFactsAt >= 2000) - { - _lastFactsAt = nowMs; - RefreshFacts(); - } - TickSpend(nowMs); - Attributes.Tick(nowMs, holdOff: _spending); - - if (_autoArmed && C.AutoEnlightenEnabled && !_spending - && nowMs - _lastAutoCheck >= Math.Max(10, C.AutoEnlightenCheckSeconds) * 1000L) - { - _lastAutoCheck = nowMs; - TryAutoEnlighten(nowMs); - } - } - - public bool OnChat(string text) - { - Attributes.OnChat(text); - // Passive /aug reader: updates Current even when the capture idle finished on the banner alone - // (chat-hold backlog) or the player typed /aug by hand. Window opens on the header. - string t = text; - if (t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase)) - _augPassiveUntilMs = IltHubContext.NowMs + 8_000; - else if (IltHubContext.NowMs <= _augPassiveUntilMs && TryApplyAugLine(t)) - { - _augPassiveUntilMs = IltHubContext.NowMs + 8_000; - int n; - lock (_augLevels) n = _augLevels.Count; - _augStatus = $"{n} aug types @ {DateTime.Now:t}"; - } - 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; - Attributes.OnLogout(); - lock (_augLevels) _augLevels.Clear(); - _augAutoTried = false; - _augRefreshAgain = false; - _augProbeRetryDone = false; - _augPassiveUntilMs = 0; - _augStatus = "not loaded"; - } - - // ── 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); - _chain = new IltSigilStock - { - Sigils = _enlHave[2], - EnlightenedCoins = _ctx.State.Bank.EnlightenedCoins + inv.CountByWcid(IltInventory.WcidEnlightenedCoin), - AscensionCoins = inv.CountByChainName(IltSigilChain.AscensionCoin), - LifebloodElixirs = inv.CountByChainName(IltSigilChain.LifebloodElixir), - LifebloomResins = inv.CountByChainName(IltSigilChain.LifebloomResin), - YalaniTrinkets = inv.CountByChainName(IltSigilChain.YalaniTrinket), - NecrolyticExtracts = inv.CountByChainName(IltSigilChain.NecrolyticExtract), - LifeSplitters = inv.CountByChainName(IltSigilChain.LifeSplitter), - Plants = inv.CountByChainName(IltSigilChain.Plant), - }; - - _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) - { - // Sigils: the server takes finished sigils only, but say how many the craft chain could still make. - string craft = cost.Wcid == IltInventory.WcidEnlSigil - ? $"; the craft chain can make {IltParse.N0(IltSigilChain.Fulfillable(_chain) - _chain.Sigils)} more" - : string.Empty; - list.Add($"Need {cost.Count} {cost.Item} (have {HaveFor(cost.Wcid)}{craft})."); - } - 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 (Attributes.Running) return; // the raiser is spending XP; check again next interval - 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":{...},"attr":{...} to . Pump thread. - public void AppendSnapshotJson(StringBuilder sb) - { - // The snapshot is only polled while the Progression tab is open, so this is "on first view". - EnsureAugs(); - Attributes.EnsureCosts(); - AppendAugJson(sb); - sb.Append(','); - AppendEnlJson(sb); - sb.Append(','); - Attributes.AppendJson(sb); - } - - /// Pulls "/aug" once per login when the levels haven't been loaded (login probe or by hand). - private void EnsureAugs() - { - if (_augAutoTried || _ctx.Options.IsOff(IltFeature.Aug) || !_ctx.Host.HasInvokeChatParser) return; - bool loaded; - lock (_augLevels) loaded = _augLevels.Count > 0; - _augAutoTried = true; - if (!loaded) RequestAugs(); - } - - /// One aug's plan line: current level, clamped target, luminance and coins to get there. - private readonly record struct AugPlan(IltAugCostRow Def, string Label, int Cur, int Tgt, int Ceiling, decimal Lum, long Coins) - { - public int Inc => Tgt - Cur; - } - - private List BuildAugPlan() - { - Dictionary levels; - lock (_augLevels) levels = new Dictionary(_augLevels, StringComparer.OrdinalIgnoreCase); - var profile = AugProfile; - var plan = new List(profile.Augs.Count); - foreach (var a in profile.Augs) - { - int cur = levels.TryGetValue(a.Key, out int c) ? c : 0; - int ceiling = IltAugCosts.Ceiling(a, cur); - int tgt = Math.Clamp(C.AugTargets.TryGetValue(a.Key, out int t) ? t : cur, cur, ceiling); - plan.Add(new AugPlan(a, IltAugCosts.Label(a.Key), cur, tgt, ceiling, - IltAugCosts.LumCost(a, profile.Multipliers, cur, tgt), (long)(tgt - cur) * a.CoinsPerLevel)); - } - return plan; - } - - private void AppendAugJson(StringBuilder sb) - { - var plan = BuildAugPlan(); - - sb.Append("\"aug\":{\"off\":").Append(Bool(_ctx.Options.IsOff(IltFeature.Aug))); - Str(sb, "status", _augStatus); - sb.Append(",\"lumPerCoin\":").Append(C.LumPerEnlightenedCoin).Append(",\"rows\":["); - for (int i = 0; i < plan.Count; i++) - { - var p = plan[i]; - if (i > 0) sb.Append(','); - sb.Append('{'); - Str(sb, "key", p.Def.Key, first: true); - Str(sb, "label", p.Label); - sb.Append(",\"cur\":").Append(p.Cur).Append(",\"tgt\":").Append(p.Tgt).Append(",\"cap\":").Append(p.Ceiling) - .Append(",\"inc\":").Append(p.Inc); - Str(sb, "lum", p.Lum > 0 ? IltParse.Compact((double)p.Lum) : "-"); - sb.Append(",\"coins\":").Append(p.Coins).Append('}'); - } - sb.Append(']'); - - decimal totalLum = plan.Sum(p => p.Lum); - long totalCoins = plan.Sum(p => p.Coins); - long bankCoins = _ctx.State.Bank.EnlightenedCoins; - long lumPerCoin = C.LumPerEnlightenedCoin; - long coinsShort = Math.Max(0, totalCoins - bankCoins); - - // Totals row (UB's TOTALS line) and the e-coin summary under the table. - sb.Append(",\"totCur\":").Append(plan.Sum(p => p.Cur)) - .Append(",\"totTgt\":").Append(plan.Sum(p => p.Tgt)) - .Append(",\"totInc\":").Append(plan.Sum(p => p.Inc)) - .Append(",\"totCoins\":").Append(totalCoins); - Str(sb, "totLum", totalLum > 0 ? IltParse.Compact((double)totalLum) : "-"); - Str(sb, "coinsLine", $"E-coins needed: {IltParse.N0(totalCoins)} banked: {IltParse.N0(bankCoins)} short: {IltParse.N0(coinsShort)}"); - Str(sb, "lumToBuy", coinsShort == 0 ? "Lum to buy e-coins: none needed" - : lumPerCoin > 0 ? $"Lum to buy e-coins: ~{IltParse.Compact((double)coinsShort * lumPerCoin)}" - : "Lum to buy e-coins: set Lum per coin"); - // Older engine builds read these three. - Str(sb, "total", $"Total: {IltParse.Compact((double)totalLum)} luminance, {IltParse.N0(totalCoins)} coins"); - Str(sb, "short", coinsShort > 0 - ? $"Coins short: {IltParse.N0(coinsShort)}" + (lumPerCoin > 0 ? $" (~{IltParse.Compact((double)coinsShort * lumPerCoin)} luminance to buy)" : "") - : string.Empty); - Str(sb, "banked", $"Banked luminance: {IltParse.Compact(_ctx.State.Bank.Luminance)}"); - Str(sb, "copyDiscord", AugDiscordText(plan)); - Str(sb, "copyIngame", AugIngameText(plan)); - AppendAugCostJson(sb); - sb.Append('}'); - } - - /// "cfg":{...}: this world's cost rules for the "Cost settings" editor. - private void AppendAugCostJson(StringBuilder sb) - { - string world = _ctx.Options.WorldName; - var p = AugProfile; - var inv = System.Globalization.CultureInfo.InvariantCulture; - sb.Append(",\"cfg\":{"); - Str(sb, "world", world.Length > 0 ? world : "unknown world", first: true); - sb.Append(",\"custom\":").Append(Bool(AugCosts.IsCustom(world))).Append(",\"mults\":["); - for (int i = 0; i < p.Multipliers.Length; i++) - sb.Append(i > 0 ? "," : "").Append(p.Multipliers[i].ToString("R", inv)); - sb.Append("],\"rows\":["); - for (int i = 0; i < p.Augs.Count; i++) - { - var r = p.Augs[i]; - if (i > 0) sb.Append(','); - sb.Append('{'); - Str(sb, "key", r.Key, first: true); - Str(sb, "label", IltAugCosts.Label(r.Key)); - sb.Append(",\"base\":").Append(r.Base) - .Append(",\"pct\":").Append(r.LinearPercent.ToString("R", inv)) - .Append(",\"coins\":").Append(r.CoinsPerLevel) - .Append(",\"s1\":").Append(r.S1).Append(",\"s2\":").Append(r.S2) - .Append(",\"s3\":").Append(r.S3).Append(",\"s4\":").Append(r.S4) - .Append(",\"cap\":").Append(r.Cap).Append('}'); - } - sb.Append("]}"); - } - - /// "augcfg <aug> <field> <value>": one cost-rule edit for this world. - private void EditAugRule(string key, string field, string value) - { - var inv = System.Globalization.CultureInfo.InvariantCulture; - bool isInt = int.TryParse(value, System.Globalization.NumberStyles.Integer, inv, out int iv); - bool isNum = double.TryParse(value, System.Globalization.NumberStyles.Float, inv, out double dv); - long amount = 0; - bool isAmount = field == "base" && IltParse.TryParseAmount(value, out amount); - if (!isInt && !isNum && !isAmount) return; - AugCosts.Edit(_ctx.Options.WorldName, p => - { - var r = p.Augs.FirstOrDefault(x => x.Key.Equals(key, StringComparison.OrdinalIgnoreCase)); - if (r == null) return; - switch (field) - { - case "base": if (isAmount) r.Base = amount; break; - case "pct": if (isNum) r.LinearPercent = dv; break; - case "coins": if (isInt) r.CoinsPerLevel = iv; break; - case "s1": if (isInt) r.S1 = iv; break; - case "s2": if (isInt) r.S2 = iv; break; - case "s3": if (isInt) r.S3 = iv; break; - case "s4": if (isInt) r.S4 = iv; break; - case "cap": if (isInt) r.Cap = iv; break; - } - }); - } - - /// - /// UB's "Copy Discord" table in a code block. ASCII only: the engine reads the snapshot as ANSI. - /// - private string AugDiscordText(List plan) - { - string name = string.IsNullOrEmpty(_ctx.CharName) ? "character" : _ctx.CharName; - string rule = new('-', 56); - var t = new StringBuilder(); - t.Append("```\n").Append("Augmentations - ").Append(name).Append('\n').Append(rule).Append('\n'); - t.Append($"{"Type",-15} {"Current",-8} {"Target",-8} {"Inc",-5} {"Lum Cost",-10} {"Coins",-6}\n").Append(rule).Append('\n'); - foreach (var p in plan) - { - if (p.Cur <= 0 && p.Tgt <= 0) continue; - string lum = p.Lum > 0 ? IltParse.Compact((double)p.Lum) : "-"; - t.Append($"{p.Label,-15} {p.Cur,-8} {p.Tgt,-8} {p.Inc,-5} {lum,-10} {p.Coins,-6}\n"); - } - decimal totalLum = plan.Sum(p => p.Lum); - t.Append(rule).Append('\n'); - t.Append($"{"TOTALS:",-15} {plan.Sum(p => p.Cur),-8} {plan.Sum(p => p.Tgt),-8} {plan.Sum(p => p.Inc),-5} " - + $"{(totalLum > 0 ? IltParse.Compact((double)totalLum) : "-"),-10} {plan.Sum(p => p.Coins),-6}\n"); - t.Append("```"); - return t.ToString(); - } - - /// UB's "Copy In-Game": one line of current levels with short names, for pasting into chat. - private string AugIngameText(List plan) - { - string name = string.IsNullOrEmpty(_ctx.CharName) ? "character" : _ctx.CharName; - var parts = plan.Where(p => p.Cur > 0).Select(p => $"{AugShortName(p.Def.Key)}: {IltParse.N0(p.Cur)}").ToList(); - return parts.Count == 0 - ? $"Augmentation Levels - {name}: none loaded" - : $"Augmentation Levels - {name} ({IltParse.N0(plan.Sum(p => p.Cur))} total): {string.Join(", ", parts)}"; - } - - private static string AugShortName(string key) => key switch - { - "creature" => "Crit", - "duration" => "Dur", - "specialization" => "Spec", - "summon" => "Sum", - "melee" => "Mel", - "missile" => "Mis", - _ => char.ToUpperInvariant(key[0]) + key.Substring(1), - }; - - 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); - - AppendEnlCalculatorJson(sb, enl, target, totals, lumTotal); - - 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('}'); - } - - /// Per-level rows the calculator lists at most (a bigger range is summarised in the totals). - private const int EnlLevelRowsMax = 100; - - /// - /// UB-IT's Enlighten calculator: per-level table (green while stock lasts, the sigil chain counted), - /// material summary (still need / have), the 301-325 sigil chain, and the e-coin line shared with - /// token conversion. Appends "levels", "materials", "chain", "chainNote", "ecoins", "ecoinsLum". - /// - private void AppendEnlCalculatorJson(StringBuilder sb, int enl, int target, Dictionary totals, decimal lumTotal) - { - // Simulated stock: tokens, medallions, crests on hand, sigils via the chain, banked luminance. - long tok = _enlHave[0], med = _enlHave[1], crest = _enlHave[3]; - decimal lum = (decimal)_ctx.State.Bank.Luminance; - var chain = _chain.Clone(); - long sigilCraftable = IltSigilChain.Fulfillable(chain); - - sb.Append(",\"levels\":["); - int last = Math.Min(Math.Max(enl + 1, target), enl + EnlLevelRowsMax); - for (int t = enl + 1; t <= last; t++) - { - var s = EnlStepCost(t); - bool ok = lum >= s.Lum; - if (ok && s.Count > 0) - { - switch (s.Wcid) - { - case IltInventory.WcidEnlToken: ok = tok >= s.Count; if (ok) tok -= s.Count; break; - case IltInventory.WcidEnlMedallion: ok = med >= s.Count; if (ok) med -= s.Count; break; - case IltInventory.WcidEnlSigil: ok = sigilCraftable >= s.Count; if (ok) sigilCraftable -= s.Count; break; - default: ok = crest >= s.Count; if (ok) crest -= s.Count; break; - } - } - if (ok) lum -= s.Lum; - if (t > enl + 1) sb.Append(','); - sb.Append("{\"t\":").Append(t); - Str(sb, "item", ShortItem(s.Item)); - sb.Append(",\"count\":").Append(s.Count); - Str(sb, "lum", s.Lum > 0 ? IltParse.Compact((double)s.Lum) : "-"); - sb.Append(",\"ok\":").Append(Bool(ok)).Append('}'); - } - sb.Append(']'); - - // Material summary: Still need = demand minus what is on hand. - long sigilsNeed = totals.TryGetValue("Enlightenment Sigils", out long sn) ? sn : 0; - var shortfall = IltSigilChain.Shortfall(sigilsNeed, _chain); - decimal bankLum = (decimal)_ctx.State.Bank.Luminance; - sb.Append(",\"materials\":["); - bool firstMat = true; - void Mat(string label, string need, string have, bool ok) - { - if (!firstMat) sb.Append(','); - firstMat = false; - sb.Append('{'); - Str(sb, "label", label, first: true); - Str(sb, "need", need); - Str(sb, "have", have); - sb.Append(",\"ok\":").Append(Bool(ok)).Append('}'); - } - if (lumTotal > 0) - { - decimal lumStill = Math.Max(0, lumTotal - bankLum); - Mat("Luminance", lumStill > 0 ? IltParse.Compact((double)lumStill) : "0", IltParse.Compact((double)bankLum), lumStill == 0); - } - void Item(string key, string label, long have, bool extraOk = false) - { - if (!totals.TryGetValue(key, out long need)) return; - long still = Math.Max(0, need - have); - Mat(label, IltParse.N0(still), IltParse.N0(have), still == 0 || extraOk); - } - Item("Enlightenment Tokens", "Tokens", _enlHave[0]); - Item("Enlightenment Medallions", "Medallions", _enlHave[1]); - Item("Enlightenment Sigils", "Sigils", _enlHave[2], extraOk: shortfall.Covered); - Item("Enlightenment Crests", "Crests", _enlHave[3]); - sb.Append(']'); - - // Sigil chain rows (only when the plan reaches 301-325). - sb.Append(",\"chain\":["); - if (sigilsNeed > 0) - { - bool firstRow = true; - void Row(string label, long need, long have, bool ok, bool craft) - { - if (!firstRow) sb.Append(','); - firstRow = false; - sb.Append('{'); - Str(sb, "label", label, first: true); - sb.Append(",\"need\":").Append(need).Append(",\"have\":").Append(have) - .Append(",\"ok\":").Append(Bool(ok)).Append(",\"craft\":").Append(Bool(craft)).Append('}'); - } - Row("Ascension Coins", shortfall.AscensionToCraft, _chain.AscensionCoins, - shortfall.AscensionToCraft == 0 || (shortfall.CoinsShort == 0 && shortfall.TrinketsShort == 0), true); - Row("Lifeblood Elixirs", shortfall.ElixirsToCraft, _chain.LifebloodElixirs, - shortfall.ElixirsToCraft == 0 || (shortfall.ExtractsShort == 0 && shortfall.SplittersShort == 0 && shortfall.PlantsShort == 0), true); - Row("Lifebloom Resins", shortfall.ResinsToCraft, _chain.LifebloomResins, - shortfall.ResinsToCraft == 0 || (shortfall.SplittersShort == 0 && shortfall.PlantsShort == 0), true); - Row("E-coins", shortfall.CoinsShort, _chain.EnlightenedCoins, shortfall.CoinsShort == 0, false); - Row("Ancient Yalani Trinkets", shortfall.TrinketsShort, _chain.YalaniTrinkets, shortfall.TrinketsShort == 0, false); - Row("Necrolytic Extracts", shortfall.ExtractsShort, _chain.NecrolyticExtracts, shortfall.ExtractsShort == 0, false); - Row("Life Splitters", shortfall.SplittersShort, _chain.LifeSplitters, shortfall.SplittersShort == 0, false); - Row("Plants", shortfall.PlantsShort, _chain.Plants, shortfall.PlantsShort == 0, false); - } - sb.Append(']'); - Str(sb, "chainNote", sigilsNeed > 0 - ? $"Sigil = Lifeblood Elixir + Ascension Coin. {IltParse.N0(shortfall.SigilsToCraft)} to craft; " - + (shortfall.Covered ? "the chain covers them." : "Need = crafts left (in-between items) or mats to get (raw items).") - : string.Empty); - - // E-coins: Ascension Coin crafts first, then token conversion at the shop price. - long tokNeed = totals.TryGetValue("Enlightenment Tokens", out long tn) ? tn : 0; - IltSigilChain.EcoinDemand(_chain.EnlightenedCoins, shortfall.CoinsForCraft, Math.Max(0, tokNeed - _enlHave[0]), - C.EnlightenedCoinsPerToken, out _, out long tokensStill, out long coinsNeeded); - Str(sb, "ecoins", tokNeed > 0 || shortfall.CoinsForCraft > 0 - ? $"E-coins needed: {IltParse.N0(coinsNeeded)} have {IltParse.N0(_chain.EnlightenedCoins)} (bank + pack)" - + (shortfall.CoinsForCraft > 0 ? $" Ascension Coins use {IltParse.N0(shortfall.CoinsForCraft)}" : "") - + (tokensStill > 0 ? $" tokens still {IltParse.N0(tokensStill)}" : "") - : string.Empty); - long lumPerCoin = C.LumPerEnlightenedCoin; - Str(sb, "ecoinsLum", coinsNeeded <= 0 ? string.Empty - : lumPerCoin > 0 ? $"Lum to buy e-coins: ~{IltParse.Compact((double)coinsNeeded * lumPerCoin)}" - : "Lum to buy e-coins: set Lum per e-coin (Augmentations)"); - } - - /// Short label for the per-level table's item column. - private static string ShortItem(string item) => item switch - { - "Enlightenment Tokens" => "Tokens", - "Enlightenment Medallions" => "Medallions", - "Enlightenment Sigils" => "Sigils", - "Enlightenment Crests" => "Crests", - _ => "-", - }; - - 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(IltStyle.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(IltStyle.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); - string verb = a[0].ToLowerInvariant(); - if (verb.StartsWith("attr", StringComparison.Ordinal) && Attributes.HandleRemote(verb, a)) return; - switch (verb) - { - case "augload": RequestAugs(); break; - case "augreset": - // UB's "Reset Target": every target back to the current level. - lock (_augLevels) - foreach (var (key, _) in IltAugCosts.Labels) - C.AugTargets[key] = _augLevels.TryGetValue(key, out int c) ? c : 0; - break; - case "augtarget" when a.Length > 2: - foreach (var def in AugProfile.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, IltAugCosts.Ceiling(def, cur)); - break; - } - break; - case "augmult" when a.Length > 2: - // "augmult ": tier 0 is below S1, tier 4 is from S4 on. - if (int.TryParse(arg1, out int tier) && tier is >= 0 and <= 4 - && double.TryParse(a[2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double mult)) - AugCosts.Edit(_ctx.Options.WorldName, p => p.Multipliers[tier] = mult); - break; - case "augcfg" when a.Length > 3: - EditAugRule(arg1, a[2].ToLowerInvariant(), a[3]); - break; - case "augcfgreset": - AugCosts.Reset(_ctx.Options.WorldName); - 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("[Mini Remote] 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.RynthILT/Hub/IltQuestBonus.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltQuestBonus.cs deleted file mode 100644 index 991a923..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltQuestBonus.cs +++ /dev/null @@ -1,209 +0,0 @@ -// IltQuestBonus.cs — The ACECustom quest bonus list ("/qb list"), shown in RynthAi's universal -// Quests tab (RynthILT.Hub section "quests-qb") and read by the Temple attribute tracker. -// Originally the /qb half of SilentKelpie's IltQuests (ILT Hub, RynthAi); split out and moved to -// RynthILT 2026-10-13. The /myquests tracker half stayed in RynthAi (MiniRemote/QuestsTab.cs): -// /myquests is every server's, /qb is ACECustom's. -// -// "/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.Linq; -using System.Numerics; -using System.Text.RegularExpressions; -using ImGuiNET; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal sealed class IltQuestBonus : IIltFeature -{ - 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 QbCooldownMs = 60_000; - - private readonly IltHubContext _ctx; - 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 - - public IltQuestBonus(IltHubContext ctx) => _ctx = ctx; - - /// The /myquests flag kinds (RynthAi's QuestsTab.Classify, which the Temple tracker reads by). - 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; - } - - /// 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; - - /// - /// Snapshot for the "RynthILT.Server" profile JSON (Oracle Quests / Fellowship). Pump thread. - /// - public IltQuestBonusInfo Snapshot() => - new(_ctx.Options.IsOff(IltFeature.Qb), _qbGeneration, _qbCount, _qbStatus, _qbCompleted, _qbIncomplete); - - /// 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) ────────────────────────────────────────────────── - - /// The Quests tab's "Quest bonus (/qb)" section (collapsed header; ILT worlds only). - public void RenderSection() - { - if (ImGui.CollapsingHeader("Quest bonus (/qb)##qbwin")) RenderQb(); - } - - public void RenderQb() - { - if (_ctx.Options.IsOff(IltFeature.Qb)) - { - ImGui.TextColored(IltStyle.ColTextMute, "/qb is disabled on this server."); - return; - } - if (ImGui.SmallButton("Load /qb list")) _ctx.Post(() => _ctx.Chat("[Mini Remote] " + RefreshQb())); - ImGui.SameLine(); - long count = _qbCount; - SafeImGui.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, IltStyle.ColAmber); - RenderQbList("Completed", _qbCompleted, filter, IltStyle.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) SafeImGui.TextColored(color, s); - ImGui.TreePop(); - } - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChain.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChain.cs deleted file mode 100644 index f0e1883..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChain.cs +++ /dev/null @@ -1,130 +0,0 @@ -// IltRingChain.cs - Infinite Leaftide's ring inscription chain (Gear tab > Rings), from UB-IT's -// ImbueSpellCraftDefinitions / SpellcraftInventoryPolicy. SilentKelpie's RynthAi Crafting > Rings -// (MiniRemote/Crafting/RingChain.cs), moved to RynthILT 2026-10-15: it is Leaftide-only. -// -// Step 1: Quill of Infliction used on a Trophy -> Enlightened Quill of Infliction -// Step 2: Enlightened Quill used on Ink of Partition -> partition quill -// Step 3: partition quill used on a Glyph -> "Inscription of ..." scroll -// Then each scroll is used on a ring / jewelry / weapon. -// -// Pure: ingredient matching (case-insensitive substrings with alternates and one exclude), the -// craft queue order and the scroll-to-target pairing. IltRingChainRunner does the using. -using System; -using System.Collections.Generic; -using System.Linq; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// One ingredient: the first of found in an item's name, unless it also has . -internal sealed record IltRingIngredient(string Label, string[] Names, string Exclude = ""); - -/// One combine: is used on . -/// 1 quill + trophy, 2 + ink, 3 + glyph: the queue runs every tier-1 run first. -/// Step 3: the words the resulting inscription scroll's name carries. -internal sealed record IltRingRecipe(string Id, int Tier, string Name, string Notes, - IltRingIngredient Tool, IltRingIngredient Target, string[] ScrollMarkers); - -internal static class IltRingChain -{ - /// Every inscription scroll's name has this. - public const string InscriptionMarker = "Inscription of"; - /// Most runs of one recipe the tab queues. - public const int MaxRuns = 99; - - private static readonly IltRingIngredient PartitionQuill = new("Enlightened Infliction Quill of Partition", - new[] { "Enlightened Infliction Quill of Partition", "Enlightened Quill of Infliction of Partition" }); - - private static IltRingRecipe Glyph(string id, string element, string scroll) => new( - id, 3, $"Step 3: {element} glyph - {scroll}", - $"Partition quill used on Glyph of {element} -> Inscription of {scroll} scroll.", - PartitionQuill, - // The full glyph name: a short one can match the wrong stack. - new IltRingIngredient($"Glyph of {element}", new[] { $"Glyph of {element}" }), - new[] { scroll, element }); - - /// The chain, in UB-IT's order. - public static readonly IltRingRecipe[] Recipes = - { - new("ring2_step1_quill_trophy", 1, "Step 1: Quill of Infliction + Trophy", - "Quill of Infliction used on a Trophy -> Enlightened Quill of Infliction.", - new IltRingIngredient("Quill of Infliction", new[] { "Quill of Infliction", "Infliction Quill" }, Exclude: "Enlightened"), - // Not plain "Trophy": scrolls and kits carry that word too. - new IltRingIngredient("Trophy", new[] { "Royal Summons", "Empyrean Trophy", "Summoning Gem" }), - Array.Empty()), - new("ring2_step2_ink", 2, "Step 2: Enlightened Quill + Ink of Partition", - "Enlightened Quill of Infliction (from Step 1) used on Ink of Partition -> partition quill.", - new IltRingIngredient("Enlightened Quill of Infliction", - new[] { "Enlightened Quill of Infliction", "Enlightened Infliction Quill", "Enlightened Infliction Quill of" }, Exclude: "Partition"), - new IltRingIngredient("Ink of Partition", new[] { "Ink of Partition", "Partition Ink" }), - Array.Empty()), - Glyph("ring2_glyph_bludgeoning", "Bludgeoning", "Tectonic Rifts"), - Glyph("ring2_glyph_lightning", "Lightning", "Eye of the Storm"), - Glyph("ring2_glyph_piercing", "Piercing", "Nuhmudira's Spines"), - Glyph("ring2_glyph_nether", "Nether", "Clouded Soul"), - Glyph("ring2_glyph_corrosion", "Corrosion", "Searing Disc"), - Glyph("ring2_glyph_frost", "Frost", "Halo of Frost"), - Glyph("ring2_glyph_slashing", "Slashing", "Horizon's Blades"), - Glyph("ring2_glyph_flame", "Flame", "Cassius' Ring of Fire"), - }; - - /// True when an item's name is this ingredient. - public static bool Matches(string? name, IltRingIngredient ing) - { - if (string.IsNullOrEmpty(name)) return false; - if (ing.Exclude.Length > 0 && name.IndexOf(ing.Exclude, StringComparison.OrdinalIgnoreCase) >= 0) return false; - foreach (string n in ing.Names) - if (n.Length > 0 && name.IndexOf(n, StringComparison.OrdinalIgnoreCase) >= 0) return true; - return false; - } - - /// - /// The craft queue: every Step 1 run, then every Step 2 run, then the glyphs, each tier in - /// definition order (a later tier's ingredients come out of the earlier one). - /// - public static List Expand(Func runs) - { - var queue = new List(); - foreach (var r in Recipes.OrderBy(r => r.Tier)) - { - int n = Math.Clamp(runs(r.Id), 0, MaxRuns); - for (int i = 0; i < n; i++) queue.Add(r); - } - return queue; - } - - /// The glyph recipe a scroll came from (null when its name has no known marker). - public static IltRingRecipe? GlyphOf(string? scrollName) - { - if (string.IsNullOrEmpty(scrollName)) return null; - foreach (var r in Recipes) - foreach (string m in r.ScrollMarkers) - if (scrollName.IndexOf(m, StringComparison.OrdinalIgnoreCase) >= 0) return r; - return null; - } - - public static bool IsInscriptionScroll(string? name) - => !string.IsNullOrEmpty(name) && name.IndexOf(InscriptionMarker, StringComparison.OrdinalIgnoreCase) >= 0; - - /// The order scrolls are listed and used in: by glyph recipe id, unknown ones last by name. - public static string ScrollOrderKey(string? scrollName) => GlyphOf(scrollName)?.Id ?? "zzz_" + scrollName; - - /// - /// Pairs scrolls with targets the way UB-IT does: scrolls by glyph recipe id (unknown ones - /// last, by name), targets by object id, one scroll per target. - /// - public static List<(int Scroll, int Target)> PairScrolls(IEnumerable<(int Id, string Name)> scrolls, IEnumerable targets) - { - var ordered = scrolls - .OrderBy(s => ScrollOrderKey(s.Name), StringComparer.Ordinal) - .ThenBy(s => s.Id) - .ToList(); - var pairs = new List<(int, int)>(); - int i = 0; - foreach (int t in targets.Distinct().OrderBy(x => x)) - { - if (i >= ordered.Count) break; - pairs.Add((ordered[i++].Id, t)); - } - return pairs; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChainRunner.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChainRunner.cs deleted file mode 100644 index d4b9106..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingChainRunner.cs +++ /dev/null @@ -1,557 +0,0 @@ -// IltRingChainRunner.cs - Crafts Infinite Leaftide's ring inscription chain and applies the scrolls -// (Gear tab > Rings). SilentKelpie's RynthAi RingChainRunner (MiniRemote/Crafting/), moved to -// RynthILT 2026-10-15 and run on the ILT Hub's context; its settings are the Gear state's -// (IltGearState.RingRuns, RingAnswerCraftDialog, RingAllowInCombat), saved with the Hub. -// -// Tick runs on the pump thread; Render on the render thread reads the volatile snapshots and -// posts the commands (IltHubContext.Post / Confirm). -// Crafting: the queue from IltRingChain.Expand, one combine at a time: -// 1. gates: peace mode (unless allowed in combat for servers with combat crafting), not busy, -// no other ILT pack job (the split-arrow imbuer); -// 2. find the tool and the target by name; a later step's ingredients come out of the earlier -// combine, so a missing one is looked for again for a while (inventory lag) before giving up; -// 3. arm the engine's confirmation answer (API v85; Yes: the player queued it) and use tool on -// target; without v85 (or with the answer off) the player clicks Yes in AC's dialog; -// 4. the combine is done when the tool or the target stack shrinks or the output shows up. -// No sign of it stops the job instead of retrying, so nothing is crafted twice. -// Scrolls: each "Inscription of ..." scroll is used on its target (the item selected in AC, or -// the carried jewelry paired the UB-IT way) and is done when it leaves the pack. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using ImGuiNET; -using RynthCore.Loot; -using RynthCore.Plugin.Shared; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// One line of the Rings scan: a recipe header (Found null) or an ingredient. -/// 0 found, 1 comes from an earlier step, 2 missing. -internal sealed record IltRingScanLine(string Text, string? Found, int State); - -internal sealed class IltRingChainRunner : IIltFeature -{ - private const uint ErrorYoureTooBusy = 0x1D; - private const long StepTimeoutMs = 15_000; - /// The player answers AC's own dialog: give them time. - private const long ManualTimeoutMs = 60_000; - private const long StepGapMs = 700; - private const long RetryDelayMs = 1_500; - private const int MaxBusyRetries = 3; - /// A missing ingredient is looked for this often and this many times (~10 s). - private const long LookAgainMs = 250; - private const int LookTries = 40; - private const long RunsViewMs = 1000; - - private static readonly Regex CannotUse = new(@"^The .+ cannot be used on the .+\.$", RegexOptions.Compiled | RegexOptions.CultureInvariant); - - private enum Mode { Idle, Craft, Apply } - - private readonly IltHubContext _ctx; - /// True while another ILT job (the split-arrow imbuer) is using the pack. - private readonly Func _blocked; - - // Job (pump thread) - private Mode _mode; - private List _queue = new(); - private List<(int Scroll, int Target)> _pairs = new(); - private int _index, _crafted, _lookTries, _busyRetries, _confSeq, _errSeq; - private bool _waiting, _manual; - private long _stepAt, _nextAt, _runsViewAt; - // Counts before the current combine (craft) / the scroll's stack (apply). - private long _toolBefore, _targetBefore, _outputBefore; - private int _scrollStackBefore; - - // Render snapshots - private volatile string _status = "idle"; - private volatile IltRingScanLine[] _scan = Array.Empty(); - private volatile (int Id, string Name)[] _scrolls = Array.Empty<(int, string)>(); - private volatile (int Id, string Name)[] _jewelry = Array.Empty<(int, string)>(); - // Runs per recipe (IltRingChain.Recipes order), copied from the Gear state on the pump. - private volatile int[] _runsView = new int[IltRingChain.Recipes.Length]; - private volatile bool _running; - - public IltRingChainRunner(IltHubContext ctx, Func blocked) - { - _ctx = ctx; - _blocked = blocked; - } - - public bool Running => _running; - public string Status => _status; - public IltRingScanLine[] ScanLines => _scan; - /// The inscription scrolls the last scan found. - public (int Id, string Name)[] Scrolls => _scrolls; - - private RynthCoreHost Host => _ctx.Host; - private IltInventory Inv => _ctx.Inventory; - private IltGearState G => _ctx.State.Gear; - - /// Pump thread: the saved run count for a recipe. - private int Runs(string id) => G.RingRuns.TryGetValue(id, out int n) ? n : 0; - - /// Pump thread: sets a recipe's run count (0 removes it) and the render copy. - public void SetRuns(string id, int runs) - { - runs = Math.Clamp(runs, 0, IltRingChain.MaxRuns); - if (runs == 0) G.RingRuns.Remove(id); - else G.RingRuns[id] = runs; - PublishRuns(); - } - - private void PublishRuns() - { - var view = new int[IltRingChain.Recipes.Length]; - for (int i = 0; i < view.Length; i++) view[i] = Runs(IltRingChain.Recipes[i].Id); - _runsView = view; - } - - // ── Inventory ─────────────────────────────────────────────────────────── - - private IEnumerable Carried() => Inv.Items().Where(w => !Inv.IsEquipped(w)); - - private WorldObject? Find(IltRingIngredient ing) => Carried().FirstOrDefault(w => IltRingChain.Matches(w.Name, ing)); - - private long Count(IltRingIngredient ing) => Carried().Where(w => IltRingChain.Matches(w.Name, ing)).Sum(w => (long)Inv.StackSize(w)); - - private long ScrollCount() => Carried().Where(w => IltRingChain.IsInscriptionScroll(w.Name)).Sum(w => (long)Inv.StackSize(w)); - - /// What a recipe makes, counted: Step 1 the enlightened quill, Step 2 the partition quill, Step 3 a scroll. - private long OutputCount(IltRingRecipe r) => r.Tier switch - { - 1 => Count(IltRingChain.Recipes[1].Tool), - 2 => Count(IltRingChain.Recipes[2].Tool), - _ => ScrollCount(), - }; - - // ── Scan ──────────────────────────────────────────────────────────────── - - /// - /// Lists every queued recipe's ingredients, marking the ones a later step only gets from an - /// earlier combine (UB-IT's "(after Step 1)"), the carried inscription scrolls and the carried - /// jewelry they can go on. Pump thread. - /// - public void Scan() - { - var lines = new List(); - bool Stocked(int tier) => IltRingChain.Recipes - .Where(r => r.Tier == tier && Runs(r.Id) > 0) - .All(r => Find(r.Tool) != null && Find(r.Target) != null); - bool tier1 = Stocked(1), tier2 = Stocked(2); - bool any = false, blocking = false; - foreach (var r in IltRingChain.Recipes) - { - int runs = Runs(r.Id); - if (runs <= 0) continue; - any = true; - lines.Add(new IltRingScanLine($"{r.Name} x{runs}", null, 0)); - foreach (var ing in new[] { r.Tool, r.Target }) - { - var found = Find(ing); - if (found != null) { lines.Add(new IltRingScanLine(ing.Label, $"{found.Name} ({Count(ing)})", 0)); continue; } - string? later = r.Tier == 2 && !tier1 ? "(after Step 1)" - : r.Tier == 3 && !tier1 ? "(after Step 1)" - : r.Tier == 3 && !tier2 ? "(after Step 2)" - : null; - if (later == null) blocking = true; - lines.Add(new IltRingScanLine(ing.Label, later ?? "(not found)", later == null ? 2 : 1)); - } - } - _scan = lines.ToArray(); - RefreshScrolls(); - _status = !any ? "set how many times to craft at least one recipe" - : blocking ? "missing ingredients are marked (not found)" - : "ready: Create runs every Step 1, then Step 2, then Step 3"; - } - - private void RefreshScrolls() - { - _scrolls = Carried().Where(w => IltRingChain.IsInscriptionScroll(w.Name)) - .Select(w => (w.Id, w.Name ?? string.Empty)) - .OrderBy(s => IltRingChain.ScrollOrderKey(s.Item2), StringComparer.Ordinal) - .ToArray(); - _jewelry = Carried().Where(w => w.ObjectClass == AcObjectClass.Jewelry) - .Select(w => (w.Id, w.Name ?? string.Empty)) - .OrderBy(j => j.Id) - .ToArray(); - } - - // ── Job control (pump thread) ─────────────────────────────────────────── - - /// Crafts the queued recipes (after the tab's confirm). - public void Create() - { - if (_running) return; - if (_blocked()) { _status = "the split-arrow imbuer is running"; return; } - var queue = IltRingChain.Expand(Runs); - if (queue.Count == 0) { _status = "set how many times to craft at least one recipe"; return; } - Begin(Mode.Craft); - _queue = queue; - _status = $"crafting {queue.Count} combine(s)"; - RynthLog.Write(LogCat.IltGear, $"[Rings] create, {queue.Count} combine(s)"); - } - - /// Uses one scroll on the item selected in AC. - public void ApplyToSelected(int scrollId) - { - uint sel = Host.GetSelectedItemId(); - if (sel == 0) { _status = "select the ring or item in AC first"; return; } - if (unchecked((int)sel) == scrollId) { _status = "the scroll itself is selected: select the ring or item"; return; } - ApplyPairs(new List<(int, int)> { (scrollId, unchecked((int)sel)) }); - } - - /// Pairs the carried scrolls with these items (the carried jewelry) and uses them. - public void ApplyToItems(IReadOnlyList targetIds) - { - RefreshScrolls(); - if (_scrolls.Length == 0) { _status = "no inscription scroll in the pack (name has \"Inscription of\")"; return; } - if (targetIds.Count == 0) { _status = "no jewelry carried (worn items aren't inscribed)"; return; } - ApplyPairs(IltRingChain.PairScrolls(_scrolls, targetIds)); - } - - private void ApplyPairs(List<(int Scroll, int Target)> pairs) - { - if (_running) return; - if (_blocked()) { _status = "the split-arrow imbuer is running"; return; } - if (pairs.Count == 0) { _status = "nothing to apply"; return; } - Begin(Mode.Apply); - _pairs = pairs; - _status = $"applying {pairs.Count} inscription(s)"; - RynthLog.Write(LogCat.IltGear, $"[Rings] apply {pairs.Count} inscription(s)"); - } - - private void Begin(Mode mode) - { - _mode = mode; - _index = 0; - _crafted = 0; - _lookTries = 0; - _busyRetries = 0; - _waiting = false; - _nextAt = 0; - _running = true; - } - - public void Stop(string why) - { - if (_waiting && Host.HasConfirmationAnswers) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0); - _mode = Mode.Idle; - _waiting = false; - _running = false; - _queue = new List(); - _pairs = new List<(int, int)>(); - _status = why; - } - - // ── IIltFeature ───────────────────────────────────────────────────────── - - public void OnLogout() - { - Stop("idle"); - _scan = Array.Empty(); - _scrolls = Array.Empty<(int, string)>(); - _jewelry = Array.Empty<(int, string)>(); - } - - public void Tick(long nowMs) - { - if (nowMs - _runsViewAt >= RunsViewMs) - { - // A profile load replaces the Gear state: follow it. - _runsViewAt = nowMs; - PublishRuns(); - } - if (_mode == Mode.Idle) return; - if (_waiting) { Wait(nowMs); return; } - if (nowMs < _nextAt) return; - if (!G.RingAllowInCombat && !Inv.InPeaceMode) { _status = "waiting for peace mode"; return; } - if (Inv.IsBusy) return; - - if (_mode == Mode.Craft) NextCombine(nowMs); - else NextScroll(nowMs); - } - - private void NextCombine(long nowMs) - { - if (_index >= _queue.Count) - { - Stop($"done - {_crafted} combine(s)"); - RefreshScrolls(); - RynthLog.Write(LogCat.IltGear, $"[Rings] done, {_crafted} combine(s)"); - return; - } - var r = _queue[_index]; - var tool = Find(r.Tool); - var target = Find(r.Target); - if (tool == null || target == null) - { - string label = tool == null ? r.Tool.Label : r.Target.Label; - if (++_lookTries <= LookTries) - { - _nextAt = nowMs + LookAgainMs; - _status = $"{r.Name}: looking for {label}"; - return; - } - Stop($"{r.Name}: no {label} in the pack"); - return; - } - _lookTries = 0; - - _toolBefore = Count(r.Tool); - _targetBefore = Count(r.Target); - _outputBefore = OutputCount(r); - if (!Use(tool, target, $"Rings: {r.Name} ({_index + 1}/{_queue.Count})")) - { - Stop($"{r.Name}: the use request didn't go out"); - return; - } - string ask = _manual ? " - click Yes in AC's craft dialog" : ""; - _status = $"{r.Name} ({_index + 1}/{_queue.Count}): {tool.Name} on {target.Name}{ask}"; - } - - private void NextScroll(long nowMs) - { - if (_index >= _pairs.Count) - { - Stop($"done - {_crafted} inscription(s) applied"); - RefreshScrolls(); - return; - } - var (scrollId, targetId) = _pairs[_index]; - var scroll = Inv.Cache?[scrollId]; - var target = Inv.Cache?[targetId]; - if (scroll == null || target == null) - { - // UB-IT moves on past a pair whose scroll or item is gone. - _status = $"inscription {_index + 1}: the scroll or the item is gone - skipped"; - _index++; - _nextAt = nowMs + StepGapMs; - return; - } - if (Inv.IsEquipped(target)) { Stop($"{target.Name} is equipped: take it off to inscribe it"); return; } - _scrollStackBefore = Inv.StackSize(scroll); - if (!Use(scroll, target, $"Rings: {scroll.Name} on {target.Name}")) - { - Stop("the use request didn't go out"); - return; - } - string ask = _manual ? " - click Yes in AC's dialog" : ""; - _status = $"inscription {_index + 1}/{_pairs.Count}: {scroll.Name} on {target.Name}{ask}"; - } - - /// Arms the dialog answer (Yes: the player asked for this) and uses source on target. - private bool Use(WorldObject source, WorldObject target, string why) - { - _manual = !(G.RingAnswerCraftDialog && Host.HasConfirmationAnswers - && Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, (int)StepTimeoutMs) == 1); - _confSeq = Host.TryGetLastConfirmation(out int cs, out _, out _, out _, out _) ? cs : 0; - _errSeq = Host.TryGetLastWeenieError(out int es, out _, out _, out _) ? es : 0; - if (!Host.UseOnFor(unchecked((uint)source.Id), unchecked((uint)target.Id), "IltRings", why, UseKind.Asked)) - { - if (!_manual) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0); - return false; - } - _waiting = true; - _stepAt = Environment.TickCount64; - return true; - } - - private void Wait(long nowMs) - { - if (Host.TryGetLastConfirmation(out int seq, out uint type, out int pct, out int outcome, out _) - && seq != _confSeq && type == RynthCoreHost.ConfirmationKind.CraftInteraction) - { - _confSeq = seq; - if (outcome == RynthCoreHost.ConfirmationOutcome.Declined) { Stop("the craft dialog was answered No"); return; } - if (outcome is RynthCoreHost.ConfirmationOutcome.Shown or RynthCoreHost.ConfirmationOutcome.SendFailed) - { - _manual = true; - _status = $"click Yes in AC's craft dialog ({(pct >= 0 ? pct + "%" : "chance not shown")})"; - } - } - - if (Host.TryGetLastWeenieError(out int es, out uint error, out _, out _) && es != _errSeq) - { - _errSeq = es; - // Busy: the server did nothing, so the same combine can go again. - if (error == ErrorYoureTooBusy && ++_busyRetries <= MaxBusyRetries) - { - _waiting = false; - _nextAt = nowMs + RetryDelayMs; - _status = $"server says busy - trying again ({_busyRetries}/{MaxBusyRetries})"; - return; - } - Stop($"the server refused it (error 0x{error:X})"); - return; - } - - if (Done()) { Next(nowMs); return; } - - if (nowMs - _stepAt > (_manual ? ManualTimeoutMs : StepTimeoutMs)) - Stop(_manual ? "no answer to AC's dialog - stopped" : "no result seen - stopped (check the pack before going on)"); - } - - /// The current combine or inscription went through. - private bool Done() - { - if (_mode == Mode.Craft) - { - var r = _queue[_index]; - return Count(r.Tool) < _toolBefore || Count(r.Target) < _targetBefore || OutputCount(r) > _outputBefore; - } - var scroll = Inv.Cache?[_pairs[_index].Scroll]; - return scroll == null || Inv.StackSize(scroll) < _scrollStackBefore; - } - - private void Next(long nowMs) - { - _waiting = false; - _busyRetries = 0; - _crafted++; - _index++; - _nextAt = nowMs + StepGapMs; - } - - /// "cannot be used on" ends the job: the names didn't match what the server expects. Never eaten. - public bool OnChat(string text) - { - if (!_waiting || string.IsNullOrEmpty(text)) return false; - if (CannotUse.IsMatch(text)) Stop(text); - return false; - } - - // ── UI (render thread) ────────────────────────────────────────────────── - - /// The ring inscription chain: runs per recipe, Scan / Create / Stop, then the scrolls. - public void Render() - { - ImGui.TextDisabled("Quill of Infliction -> Enlightened Quill -> partition quill -> glyph -> Inscription scroll -> ring."); - int[] runsView = _runsView; - if (ImGui.BeginTable("##ringrecipes", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp)) - { - ImGui.TableSetupColumn("Runs", ImGuiTableColumnFlags.WidthFixed, 100); - ImGui.TableSetupColumn("Recipe"); - for (int i = 0; i < IltRingChain.Recipes.Length; i++) - { - var r = IltRingChain.Recipes[i]; - ImGui.PushID(r.Id); - ImGui.TableNextRow(); - ImGui.TableNextColumn(); - int n = i < runsView.Length ? runsView[i] : 0; - ImGui.SetNextItemWidth(90); - if (ImGui.InputInt("##runs", ref n, 1)) - { - string id = r.Id; - int runs = Math.Clamp(n, 0, IltRingChain.MaxRuns); - var shown = (int[])runsView.Clone(); - shown[i] = runs; - _runsView = shown; // shown at once; the pump saves it and republishes - _ctx.Post(() => SetRuns(id, runs)); - } - ImGui.TableNextColumn(); - ImGui.TextUnformatted(r.Name); - if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(r.Notes); - ImGui.PopID(); - } - ImGui.EndTable(); - } - - bool answer = G.RingAnswerCraftDialog, combat = G.RingAllowInCombat; - if (ImGui.Checkbox("Answer the craft dialog##rings", ref answer)) G.RingAnswerCraftDialog = answer; - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Answers AC's craft confirmation Yes for each combine you queued (needs RynthCore plugin API v85).\nOff, or on an older RynthCore: click Yes in AC's dialog yourself."); - ImGui.SameLine(); - if (ImGui.Checkbox("Allow in combat mode##rings", ref combat)) G.RingAllowInCombat = combat; - if (ImGui.IsItemHovered()) ImGui.SetTooltip("Only for servers that allow crafting in combat mode."); - - bool running = Running; - bool blocked = _blocked(); - ImGui.BeginDisabled(running); - if (ImGui.Button("Scan##rings")) _ctx.Post(Scan); - ImGui.SameLine(); - ImGui.BeginDisabled(blocked); - if (ImGui.Button("Create##rings")) - { - int[] view = _runsView; - int total = IltRingChain.Expand(id => - { - int k = Array.FindIndex(IltRingChain.Recipes, x => x.Id == id); - return k >= 0 && k < view.Length ? view[k] : 0; - }).Count; - _ctx.Confirm("Rings chain", $"Craft {total} combine(s)?\n\nEvery Step 1 run goes first, then Step 2, then Step 3.\nThe ingredients are used up.", - Create, "Create"); - } - ImGui.EndDisabled(); - ImGui.EndDisabled(); - ImGui.SameLine(); - ImGui.BeginDisabled(!running); - if (ImGui.Button("Stop##rings")) _ctx.Post(() => Stop("stopped by player")); - ImGui.EndDisabled(); - ImGui.SameLine(); - if (blocked && !running) ImGui.TextColored(IltStyle.ColAmber, "the split-arrow imbuer is running"); - else SafeImGui.TextDisabled(Status); - - var lines = ScanLines; - if (lines.Length > 0 && ImGui.BeginTable("##ringscan", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.Borders | ImGuiTableFlags.SizingStretchProp)) - { - foreach (var l in lines) - { - ImGui.TableNextRow(); - ImGui.TableNextColumn(); - if (l.Found == null) { SafeImGui.TextColored(IltStyle.ColTeal, l.Text); continue; } - ImGui.TextUnformatted(" " + l.Text); - ImGui.TableNextColumn(); - if (l.State == 0) ImGui.TextUnformatted(l.Found); - else if (l.State == 1) SafeImGui.TextDisabled(l.Found); - else SafeImGui.TextColored(IltStyle.ColAmber, l.Found); - } - ImGui.EndTable(); - } - - ImGui.Separator(); - RenderScrolls(running || blocked); - } - - /// The carried inscription scrolls: one to the selected item, or all to the carried jewelry. - private void RenderScrolls(bool busy) - { - ImGui.TextColored(IltStyle.ColTeal, "Inscription scrolls"); - var scrolls = Scrolls; - if (scrolls.Length == 0) { ImGui.TextDisabled("None carried (Scan to look again)."); return; } - - ImGui.BeginDisabled(busy); - foreach (var (id, name) in scrolls) - { - ImGui.PushID(id); - if (ImGui.SmallButton("Apply to selected")) - { - int scrollId = id; - string scrollName = name; - _ctx.Confirm("Ring inscription", $"Use {scrollName} on the item selected in AC?", - () => ApplyToSelected(scrollId), "Apply"); - } - ImGui.SameLine(); - ImGui.TextUnformatted(name); - ImGui.PopID(); - } - - // UB-IT pairs the scrolls with a scan's items; here the carried (not worn) jewelry. - var jewelry = _jewelry; - var targets = jewelry.Select(j => j.Id).ToList(); - ImGui.BeginDisabled(targets.Count == 0); - if (ImGui.Button($"Apply all to the carried jewelry ({targets.Count})")) - { - int pairs = Math.Min(targets.Count, scrolls.Length); - _ctx.Confirm("Ring inscriptions", $"Use {pairs} inscription scroll(s) on the carried jewelry, one each?", - () => ApplyToItems(targets), "Apply"); - } - ImGui.EndDisabled(); - if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) - SafeImGui.SetTooltip("Scrolls in glyph order go on the jewelry in your pack (not worn) in id order (UB-IT's pairing).\n" - + (jewelry.Length == 0 ? "No jewelry carried (Scan to look again)." - : string.Join("\n", jewelry.Select(j => j.Name)))); - ImGui.EndDisabled(); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingEvade.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingEvade.cs deleted file mode 100644 index aa7eb6d..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltRingEvade.cs +++ /dev/null @@ -1,121 +0,0 @@ -// IltRingEvade.cs — Infinite Leaftide's Empyrean Handler lethal ring: hear it, and have RynthAi jump clear. -// Moved out of RynthAi's CombatManager 2026-10-20 (Silentkelpie's PR 12): the Handler is ACECustom -// content, so the detection and its setting are RynthILT's; RynthAi keeps the generic back-away it -// does on request (RynthAi.Hub BackAwayFrom: face the danger, run-back jump, hold attacks until the -// jump settles, re-engage the same target; only while its macro runs with combat on). -// -// ACECustom's Handler emote: "The handler briefly channels infused Empyrean hatred to release a lethal -// ring." The ring can't be melee-evaded; inside its cast radius the character dies. On that line, when -// an Empyrean Handler is near, ask RynthAi to back away from the nearest one (12 yards, or Ring Range -// when RynthAi's is larger). One request per HandlerRingCooldownMs. -// Setting: IltHubState.Combat.HandlerRingEvade (on by default; the ILT settings view, "/ilt settings"). -using System; -using RynthCore.Loot; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal sealed class IltRingEvade : IIltFeature -{ - internal const string ChannelHint = "channels infused Empyrean hatred to release a lethal ring"; - internal const string ChannelStart = "The handler briefly channels"; - internal const string HandlerName = "Empyrean Handler"; - /// Yards: the Handler's lethal ring is treated as at least this wide (RynthAi widens it to Ring Range). - internal const float DangerYards = 12f; - /// Back-jump charge (ms): run-back + jump must clear about the ring's radius. - internal const int JumpHoldMs = 750; - internal const long CooldownMs = 4_000; - - private readonly IltHubContext _ctx; - private long _lastRequestAt = long.MinValue; - - public IltRingEvade(IltHubContext ctx) => _ctx = ctx; - - /// What the last ring line did (for the log and the tests). - public string LastOutcome { get; private set; } = string.Empty; - - /// - /// True when is the Handler's channel line (not a player repeating it). - /// The channel is an Emote (0x0C), which counts as player speech elsewhere, so it is anchored on - /// the phrase that starts the line; mid-line only for a chat type that can't be player speech. - /// - internal static bool IsChannelLine(string? text, int chatType) - { - if (string.IsNullOrEmpty(text)) return false; - bool anchored = - ChatSource.StartsWithMarker(text, ChannelStart, StringComparison.OrdinalIgnoreCase) - || (ChatSource.StartsWithMarker(text, "The handler", StringComparison.OrdinalIgnoreCase) - && text.IndexOf(ChannelHint, StringComparison.OrdinalIgnoreCase) >= 0); - if (anchored) return true; - // Mid-line only when the type is clearly not player speech (some clients strip "The "). - if (chatType is ChatSource.Speech or ChatSource.Tell or ChatSource.OutgoingTell or ChatSource.Channel - or ChatSource.ChannelSend or ChatSource.Allegiance or ChatSource.Fellowship) - return false; - if (text.IndexOf(ChannelHint, StringComparison.OrdinalIgnoreCase) < 0) return false; - return text.IndexOf(" says,", StringComparison.OrdinalIgnoreCase) < 0 - && text.IndexOf(" tells you,", StringComparison.OrdinalIgnoreCase) < 0; - } - - /// - /// A chat line with its type (pump thread; IltHubController.OnChat, ILT only). On the Handler's - /// channel line asks RynthAi to back away from the nearest Handler. Never eats the line. - /// - public void OnChatLine(string text, int chatType) - { - if (!_ctx.State.Combat.HandlerRingEvade || !IsChannelLine(text, chatType)) return; - long now = IltHubContext.NowMs; - if (_lastRequestAt != long.MinValue && now - _lastRequestAt < CooldownMs) return; - - if (!TryFindNearestHandler(out int handlerId, out double dist)) - { - Outcome("Handler lethal-ring channel heard, but no Empyrean Handler is nearby: no jump."); - return; - } - _lastRequestAt = now; - int r = _ctx.Ai.BackAwayFrom(unchecked((uint)handlerId), DangerYards, JumpHoldMs); - Outcome(r switch - { - RynthAiHub.BackAwayStarted => $"Empyrean Handler lethal ring: RynthAi backs away from it ({dist:0.0} m).", - RynthAiHub.BackAwayOutside => $"Empyrean Handler lethal ring: the Handler is {dist:0.0} m away, outside the ring; staying put.", - RynthAiHub.BackAwayUnknownObject => "Empyrean Handler lethal ring: RynthAi has no position for the Handler; no jump.", - RynthAiHub.BackAwayJumpRefused => "Empyrean Handler lethal ring: in range, but RynthAi's back-jump did not start.", - int.MinValue => "Empyrean Handler lethal ring: " + RynthAiClient.NotLoaded + " (the back-away is RynthAi's).", - _ => "Empyrean Handler lethal ring: RynthAi isn't fighting (macro or combat off), so it doesn't take the keyboard.", - }); - } - - private void Outcome(string text) - { - LastOutcome = text; - RynthLog.Write(LogCat.IltHub, "[RingEvade] " + text); - } - - /// The nearest Empyrean Handler the client knows (a creature with that in its name). - private bool TryFindNearestHandler(out int id, out double dist) - { - id = 0; - dist = double.MaxValue; - var objects = _ctx.Inventory.Cache; - int me = unchecked((int)_ctx.Inventory.PlayerId); - if (me == 0) return false; - foreach (var wo in objects.GetLandscape()) - { - if (wo == null || wo.ObjectClass != AcObjectClass.Monster) continue; - if (wo.Name.IndexOf(HandlerName, StringComparison.OrdinalIgnoreCase) < 0) continue; - double d = objects.Distance(me, wo.Id); - if (d >= dist) continue; - dist = d; - id = wo.Id; - } - return id != 0; - } - - // ── IIltFeature ───────────────────────────────────────────────────────── - - public void Tick(long nowMs) { } - - /// Unused: the controller passes the chat type (OnChatLine). - public bool OnChat(string text) => false; - - public void OnLogout() => _lastRequestAt = long.MinValue; -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSalvage.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSalvage.cs deleted file mode 100644 index 342c92a..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSalvage.cs +++ /dev/null @@ -1,81 +0,0 @@ -// IltSalvage.cs - Infinite Leaftide's own tinkering salvage, for the Mini Remote's Crafting tab. -// -// Served through RynthILT's "RynthServer.Profile" JSON (ProfileInterface.cs, the "salvage" list), -// which RynthAi's Crafting tab shows under "Server tinkering" on ILT; RynthAi itself knows no -// server's recipes. Taken from UB-IT's LeaftideImbueHelper via SilentKelpie (his RynthAi Crafting -// tab, rynth/RynthSuite PR 12, moved here 2026-10-15): the weapon crit lines (Yellow Garnet, -// Turquoise, White Quartz, Abyssal-Touched Gems, Tourmaline, Wool), Tiger Eye on missile weapons, -// Leather as the post-cap tink, the jewelry rating salvages (Silver, Copper, Green Jade, -// Tourmaline, and Serpentine + Steel sharing a cap of 10) and the trinket tiers (Diamond, Ruby, -// Gromnie Hide, Pyreal, prepared on Ammunition). ILT's recipes live in its database, so their -// chances are the server's: the Crafting runner reads the confirmation's percent. -using RynthCore.Plugin.ServerPack; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal static class IltSalvage -{ - /// - /// Leaftide trinkets (compass, goggles, scarab, watch, puzzle box, tops): jewelry that takes the - /// Trinkets bench's recipes (UB-IT's IsLeaftideTrinketJewelry; RynthAi's TinkerCatalog.IsTrinket until - /// 2026-10-20). Sent in the profile's "trinkets" (RynthServer.Profile). - /// - internal static readonly string[] TrinketNames = { "compass", "goggles", "scarab", "watch", "puzzle box", "top" }; - /// "top" but not "topaz". - internal static readonly string[] TrinketExcept = { "topaz" }; - - // MaterialType (131) ids. - private const int Wool = 8, BlackGarnet = 15, Diamond = 20, GreenJade = 24, Ruby = 38, TigerEye = 42, Tourmaline = 43, - Turquoise = 44, WhiteQuartz = 46, YellowGarnet = 48, Leather = 52, GromnieHide = 54, Copper = 59, Pyreal = 62, - Silver = 63, Steel = 64, Serpentine = 71; - - // ILT's flag ints on the item: 2 = that salvage is on. - public const int IntJewelCopper = 370, IntJewelGreenJade = 371, IntJewelSilver = 374, IntJewelTourmaline = 375; - public const int IntTrinketDiamond = 384, IntTrinketRuby = 385, IntTrinketGromnie = 386, IntTrinketPyreal = 387; - - /// Steel and Serpentine stack on ILT jewelry, at most this many combined. - public const string JewelryStackGroup = "jewelry-stack"; - public const int JewelryStackCap = 10; - - private const string Once = "once", Tink = "tink"; - private const string PostCap = "100% tink once the 10 ordinary tinks are on"; - - public static readonly ServerSalvage[] Rows = - { - new("melee", YellowGarnet, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 70), - new("melee", Turquoise, "Crushing Blow (no tink slot)", Once, UsesTinkSlot: false, Order: 80), - new("melee", WhiteQuartz, "Cleaving (no tink slot)", Once, UsesTinkSlot: false, Order: 90), - new("melee", BlackGarnet, "Crit line (bag of Abyssal-Touched Gems)", Once, NameMatch: "Abyssal", Order: 100), - new("melee", Tourmaline, "Crit line (no tink slot)", Once, UsesTinkSlot: false, Order: 104), - new("melee", Wool, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 108), - new("melee", Leather, PostCap, Once, UsesTinkSlot: false, Order: 995, AfterCap: true), - - new("missile", YellowGarnet, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 70), - new("missile", Turquoise, "Crushing Blow (no tink slot)", Once, UsesTinkSlot: false, Order: 80), - new("missile", BlackGarnet, "Crit line (bag of Abyssal-Touched Gems)", Once, NameMatch: "Abyssal", Order: 100), - new("missile", Tourmaline, "Crit line (no tink slot)", Once, UsesTinkSlot: false, Order: 104), - new("missile", Wool, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 108), - new("missile", TigerEye, "+missile defense bonus", Tink, Order: 230), - new("missile", Leather, PostCap, Once, UsesTinkSlot: false, Order: 995, AfterCap: true), - - new("caster", YellowGarnet, "Biting Strike (no tink slot)", Once, UsesTinkSlot: false, Order: 70), - new("caster", Turquoise, "Crushing Blow (no tink slot)", Once, UsesTinkSlot: false, Order: 80), - new("caster", Leather, PostCap, Once, UsesTinkSlot: false, Order: 995, AfterCap: true), - - // ILT keeps these in their own ints (370-376) with their own cap, not the 10 tinker slots. - new("jewelry", Silver, "+1 critical damage rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelSilver, Order: 10), - new("jewelry", Copper, "+1 damage rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelCopper, Order: 20), - new("jewelry", GreenJade, "+1 damage resist rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelGreenJade, Order: 30), - new("jewelry", Tourmaline, "+1 critical damage resist rating", Once, UsesTinkSlot: false, AppliedInt: IntJewelTourmaline, Order: 40), - new("jewelry", Serpentine, "+1 critical rating (stacks with Steel, 10 max)", Tink, UsesTinkSlot: false, Order: 50, - StackGroup: JewelryStackGroup, StackCap: JewelryStackCap), - new("jewelry", Steel, "Steel stack tier (stacks with Serpentine, 10 max)", Tink, UsesTinkSlot: false, Order: 60, - StackGroup: JewelryStackGroup, StackCap: JewelryStackCap), - - // UB-IT's trinket imbues, in its order: Diamond, Ruby, Gromnie Hide, Pyreal. - new("trinkets", Diamond, "Trinket tier: Diamond", Once, UsesTinkSlot: false, AppliedInt: IntTrinketDiamond, Prepared: true, Order: 10), - new("trinkets", Ruby, "Trinket tier: Ruby", Once, UsesTinkSlot: false, AppliedInt: IntTrinketRuby, Prepared: true, Order: 20), - new("trinkets", GromnieHide, "Trinket tier: Gromnie Hide", Once, UsesTinkSlot: false, AppliedInt: IntTrinketGromnie, Prepared: true, Order: 30), - new("trinkets", Pyreal, "Trinket tier: Pyreal", Once, UsesTinkSlot: false, AppliedInt: IntTrinketPyreal, Prepared: true, Order: 40), - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs deleted file mode 100644 index 0972686..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSections.cs +++ /dev/null @@ -1,144 +0,0 @@ -// IltSections.cs - The Infinite Leaftide tabs of RynthAi's Mini Remote and the Guardian panel. -// Originally SilentKelpie's ILT Hub sections (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// -// Banking, Gear, Charms, Games and Vaulted Dungeons are Mini Remote tabs: RynthAi's MiniRemoteHud draws the tab bar -// (after its Remote, Pets and Crafting tabs) and asks RynthILT for each tab's body (RynthILT.Hub -// GetTabs / RenderTab); "/ra hub open
" picks one, and with RynthCore's sections rail -// RynthAi lists them as "section:" views (Inventory). Guardian is a RynthCore ILT panel -// instead (the bar's ILT button, next to Bounties; "/rc guardian"), drawn by this plugin through -// RynthPluginRenderEmbed("guardian"). The Pets tab is RynthAi's (every server: summoning essences -// aren't ILT's); quests are RynthOracle's. -// -// Character was a Mini Remote tab until 2026-10-13. It moved out: -// the character overview and session -> RynthOracle's Character tab ("/ro character"); -// the ILT session rates -> RynthCore's Mini Remote "Session Stats" section -// (RynthILT's own surface "section:ilt-rates"); -// the force-server override -> RynthCore Options > Diagnostics only. -// Its names still parse, so old links and commands land on the new home (MovedCommand). Charms and -// Banking are Infinite Leaftide's own screens and stay RynthILT's tabs. -using System; -using System.Numerics; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// ILT sections: the Mini Remote's ILT tabs, the one that moved out, then the Guardian panel. -internal enum IltSection -{ - /// Moved out (2026-10-13): RynthOracle's Character tab and the Session Stats section. - Character, - Banking, - Gear, - Games, - /// - /// Vaulted Dungeons keeper (portal-recall gem + kill-client). A Mini Remote tab on ILT worlds only, - /// and only while its "Vaulted Dungeons" master switch (/ilt settings, Settings > Navigation) is on. - /// - VaultedDungeons, - /// Registry charms (acquired / status / tier / server) and the Guardian Hand. - Charms, - // Keep Guardian last. - Guardian, -} - -internal static class IltSections -{ - /// The ILT tabs, in tab-bar order (RynthAi puts them after its own tabs). - public static readonly IltSection[] Tabs = - { - IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games, IltSection.VaultedDungeons, - }; - - /// The Mini Remote's own tab (the remote itself): its tab id. - public const string RemoteTab = ""; - - /// RynthOracle's Character tab: the character overview and this session. - public const string OracleCharacterCommand = "/ro character"; - - public static string Label(IltSection s) => s switch - { - IltSection.Character => "Character", - IltSection.Banking => "Banking", - IltSection.Gear => "Gear", - IltSection.Games => "Games", - IltSection.VaultedDungeons => "Vaulted Dungeons", - IltSection.Charms => "Charms", - IltSection.Guardian => "Guardian", - _ => s.ToString(), - }; - - /// - /// The section's tab id: saved as RynthAi's HudState.MiniRemoteTab and sent by the engine's - /// dashboard ("/ra hub tab <id>", "/rc miniremote tab <id>"). TryParse reads it back. - /// - public static string TabId(IltSection s) => s switch - { - IltSection.Character => "character", - IltSection.Banking => "banking", - IltSection.Gear => "gear", - IltSection.Games => "games", - IltSection.VaultedDungeons => "vaulted", - IltSection.Charms => "charms", - IltSection.Guardian => "guardian", - _ => s.ToString().ToLowerInvariant(), - }; - - /// True for the sections drawn as Mini Remote tabs (Banking, Gear, Charms, Games, Vaulted Dungeons). - public static bool IsTab(IltSection s) => s is IltSection.Banking or IltSection.Gear or IltSection.Charms or IltSection.Games - or IltSection.VaultedDungeons; - - /// - /// Where a section that moved out of the Mini Remote lives now, as the chat command that opens - /// it; null for a section that is still RynthILT's (a tab or the Guardian panel). - /// - public static string? MovedCommand(IltSection s) => s switch - { - IltSection.Character => OracleCharacterCommand, - _ => null, - }; - - /// "quests" / "pets" (and their aliases): not ILT sections (RynthAi's Pets tab, RynthOracle's quests). - public static bool IsUniversalTabName(string text) => (text ?? string.Empty).Trim().ToLowerInvariant() switch - { - "quests" or "quest" or "pets" or "pet" => true, - _ => false, - }; - - /// 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 "banking": case "bank": section = IltSection.Banking; return true; - case "gear": section = IltSection.Gear; return true; - case "games": case "game": section = IltSection.Games; return true; - case "vaulted": case "vaulteddungeons": case "vaulted-dungeons": - section = IltSection.VaultedDungeons; return true; - case "charms": case "charm": section = IltSection.Charms; return true; - case "guardian": case "temple": case "riddle": section = IltSection.Guardian; return true; - default: section = IltSection.Gear; return false; - } - } - - /// - /// Size of a Mini Remote tab's body (the old section window's default size): the tab draws in a - /// child this big, and the Mini Remote (or the engine window hosting it) fits to it. - /// - public static Vector2 TabSize(IltSection section) => section switch - { - IltSection.Banking => new Vector2(560, 520), - IltSection.Gear => new Vector2(560, 520), - IltSection.Charms => new Vector2(560, 520), - IltSection.Games => new Vector2(520, 440), - IltSection.VaultedDungeons => new Vector2(360, 420), - _ => new Vector2(520, 440), - }; - - /// "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.RynthILT/Hub/IltServerOptions.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltServerOptions.cs deleted file mode 100644 index 15ddef1..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltServerOptions.cs +++ /dev/null @@ -1,376 +0,0 @@ -// IltServerOptions.cs — Per-feature enable bits for the ILT Hub, read from the server. -// Originally SilentKelpie's ILT Hub (RynthAi); moved to RynthILT 2026-10-13. -// -// 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: ServerFeatureGate (RynthILT's server list, or this character's -// override / the Hub's ForceLeaftideFeatures) decides whether we even ASK — it never -// switches a feature on by itself. -// * Everything is decided on the Rynth side: the server is never asked for a feature list -// (ACECustom has none; "/ilt features" prints "Coming Soon"). IltFeatureCatalog's ILT -// profile says what the server runs, and these bits only record what the server returned: -// * Login probe: one pass 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", ...), -// and lines only an enabled feature sends flip it On (a summon-time pyreal refill). -// 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.Plugin.RynthILT.IltSettingsView; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// 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; - private readonly Func _settings; - - /// 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, - Func? settings = null) - { - _host = host; - _capture = capture; - _state = state; - _chat = chat; - _settings = settings ?? (() => null); - } - - // ── 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; - } - } - - /// RynthCore's id for Infinite Leaftide in its server verdicts. - public const string EngineServerId = "ilt"; - - /// - /// RynthCore (2026.10.5.47+) decides whether this is Infinite Leaftide: one world check for - /// the engine and every plugin, with its per-character override ("/rc server ilt on|off|auto"). - /// True once its first verdict has arrived (IltEngineVerdict). - /// - public static bool EngineDecides => IltEngineVerdict.Active.HasValue; - - /// - /// RynthILT's own verdict: the world name is in the server list (IltSettings), or this - /// character's "Treat this world as ILT" is on (ServerFeatureGate). This is what the status - /// export reports to the engine, which adds it to its own detection (never echo the engine's - /// verdict back, or it would latch on). - /// - public bool IsIltLikeWorldLocal - { - get - { - if (_state.ForceLeaftideFeatures) return true; - IltSettings? s; - try { s = _settings(); } catch { s = null; } - return ServerFeatureGate.IsEnabled(WorldName, s, _state.ForceLeaftideFeatures); - } - } - - /// - /// True when the world is (or is declared to be) an ACECustom/ILT shard. With a RynthCore - /// that sends server verdicts, its verdict (which already includes ours, IsIltLikeWorldLocal, - /// unless this character's override is off); otherwise our own. - /// - public bool IsIltLikeWorld - { - get - { - bool? engine = IltEngineVerdict.Active; - return engine ?? IsIltLikeWorldLocal; - } - } - - /// True while the login 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". RynthCore's - // verdict trails the world name by up to a second (its push), and before its first push - // there is none: keep checking for the same window rather than conclude early. - if ((string.IsNullOrEmpty(WorldName) || EngineDecides || !IltEngineVerdict.Pushed) - && 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 probe refresh. Manual refreshes report progress in chat; the login refresh is - /// silent. - /// - public void Refresh(bool manual) - { - if (_refreshInFlight) - { - if (manual) _chat("[Mini Remote] Server options refresh already running."); - return; - } - if (!IsIltLikeWorld) - { - if (manual) - _chat(EngineDecides - ? "[Mini Remote] RynthCore doesn't treat this world as Infinite Leaftide (/rc server ilt on forces it for this character; /rc server names ilt add adds the world)." - : "[Mini Remote] This world is not in the Server Features list (Settings > Misc: add it, or tick the override)."); - return; - } - - _refreshInFlight = true; - _state.ServerOptions.WorldName = WorldName; - RynthLog.Event(LogEvents.IltOptionsRefreshStart, $"refresh start (manual={manual}, world='{WorldName}')"); - if (manual) _chat("[Mini Remote] Refreshing server options..."); - - _state.ServerOptions.Source = "probe"; - RunProbes(manual); - } - - // ── 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(" IltParse.AugLine.IsMatch(t) : null, - 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($"[Mini Remote] Server options refreshed via {Source}: {on} on, {off} off."); - } - - // ── Passive refusals ──────────────────────────────────────────────────── - - /// - /// Watches every chat line for explicit server refusals (bit Off) and for lines only an - /// enabled feature sends (bit On). 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); - else if (IsPyrealRefillLine(text)) - Set(IltFeature.PetRefill, IltTri.On); - } - - /// - /// ACECustom's summon-time refill messages (PetDevice.TryApplyPyrealAutoRefillBeforeSummon). The - /// server sends them only while pet_device_pyreal_auto_refill_enabled is on, so any of them - /// proves the refill is on even when the profile says it's off. - /// - internal static bool IsPyrealRefillLine(string text) - => text.Contains("charge on your summoning essence", StringComparison.OrdinalIgnoreCase) - || text.Contains("pyreals to auto-replenish your summoning essence", StringComparison.OrdinalIgnoreCase); - - /// 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.RynthILT/Hub/IltSessionRates.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSessionRates.cs deleted file mode 100644 index 0a5f326..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSessionRates.cs +++ /dev/null @@ -1,291 +0,0 @@ -// IltSessionRates.cs — Session earnings / per-hour rates for Infinite Leaftide: the coins, pyreals and -// item conversions RynthCore's Mini Remote "Session Stats" section shows under "Server: Infinite -// Leaftide" (surface "section:ilt-rates", 2026-10-13; it was the ILT Character tab before). -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// -// Sources (all passive — nothing is sent to the server except the optional bank refresh -// the Banking tab already does): -// XP, luminance (total, last 5 min, allegiance pass-up) and kills: RynthAi's Mini Remote -// session stats (RynthAi.Hub SessionStats) — RynthTracker's SessionStats code, so this -// table, the Mini Remote and the Tracker panel count them the same way (2026-10-11). -// Without RynthAi those rows are left out. -// 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. -// A deposit or withdrawal only moves money between pack and bank: while Banking reports one -// (MovingMoney) the coin and pyreal baselines follow along without counting a gain. -using System; -using System.Collections.Generic; -using System.Linq; -using ImGuiNET; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal sealed class IltSessionRates : IIltFeature -{ - private const long PyrealsPerMmd = 250_000; - private const long SampleIntervalMs = 5000; - private const long RowsIntervalMs = 1000; - private const string PassUpLabel = " pass-up"; - - private readonly IltHubContext _ctx; - private DateTime _start = DateTime.UtcNow; - - private long _coins; - private long _pyreals; - - // 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; - private long _lastRowsAt; - - // Render snapshot. - private volatile RateRow[] _rows = Array.Empty(); - // Shared = one of RynthAi's session stats rows (XP, luminance, kills), which the Session Stats - // section already shows above this table; the embedded view leaves those out. - private sealed record RateRow(string Label, string Total, string PerHour, bool Shared = false); - - /// Coin and pyreal per-hour figures for the Mini Remote HUD (rebuilt every sample). - public sealed record RateSummary(double CoinsPerHour, double PyrealsPerHour); - private static readonly RateSummary EmptySummary = new(0, 0); - private volatile RateSummary _summary = EmptySummary; - - /// Latest coin / pyreal summary (safe from the render thread). - public RateSummary Summary => _summary; - /// When the coin / pyreal session (or the last Reset) started. - public DateTime SessionStartUtc => _start; - - public IltSessionRates(IltHubContext ctx) => _ctx = ctx; - - /// True while money moves between pack and bank (set by the controller from Banking). Pump thread. - public Func? MovingMoney { get; set; } - - private bool Moving => MovingMoney?.Invoke() ?? false; - - /// 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; - if (Moving) return; // a deposit, not income - long delta = newValue - oldValue; - if (delta <= 0) return; // spending / sending isn't income - if (key == "EnlightenedCoins") _coins += delta; - else if (key == "Pyreals") _pyreals += delta; - } - - /// Coins, pyreals and item gains start over (login, or with ). - public void Reset() - { - RynthLog.Trace(LogCat.IltRates, $"Reset()"); - _start = DateTime.UtcNow; - _coins = _pyreals = 0; - _lastInvCoins = _lastInvPyreals = -1; - _lastItemCounts.Clear(); - _itemGains.Clear(); - _lastSampleAt = 0; - _lastRowsAt = 0; - _summary = EmptySummary; - } - - /// The player's reset (this tab, the Mini Remote): coins here and the shared session stats together. Pump thread. - public void ResetAll() - { - Reset(); - _ctx.Ai.ResetSessionStats(); - } - - // ── IIltFeature ───────────────────────────────────────────────────────── - - public void Tick(long nowMs) - { - FollowSharedSession(); - // The shared stats move every 0.5 s; their rows refresh each second, coins every 5 s. - if (nowMs - _lastSampleAt < SampleIntervalMs) - { - if (nowMs - _lastRowsAt >= RowsIntervalMs) { _lastRowsAt = nowMs; BuildRows(); } - return; - } - _lastSampleAt = nowMs; - _lastRowsAt = nowMs; - var inv = _ctx.Inventory; - - long coinGain = Gain(ref _lastInvCoins, inv.CountByWcid(IltInventory.WcidEnlightenedCoin)); - long pyrealGain = Gain(ref _lastInvPyreals, inv.CountByWcid(IltInventory.WcidPyreal)); - // A withdrawal: the baselines moved, nothing earned. - if (!Moving) - { - _coins += coinGain; - _pyreals += pyrealGain; - } - - // 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(); - } - - private long _sharedStartTicks; // RynthAi's session start as last seen (0 = not yet) - - /// - /// The coins / pyreals start over with RynthAi's shared session (its Reset XP, or a session that - /// restarted): one clock for both, without RynthAi telling RynthILT. Pump thread. - /// - private void FollowSharedSession() - { - if (!_ctx.Ai.TryGetSessionStats(out SessionStatsV1 s) || s.StartUtcTicks == 0) return; - if (_sharedStartTicks != 0 && s.StartUtcTicks > _sharedStartTicks) - { - RynthLog.Trace(LogCat.IltRates, "RynthAi's session restarted: coins and pyreals start over too"); - Reset(); - } - _sharedStartTicks = s.StartUtcTicks; - } - - /// 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; - } - - // Luminance chat goes to RynthAi's session stats (its OnChatWindowText). - public bool OnChat(string text) => false; - - public void OnLogout() => Reset(); - - // ── Rows ──────────────────────────────────────────────────────────────── - - private void BuildRows() - { - double hours = Math.Max((DateTime.UtcNow - _start).TotalHours, 1.0 / 3600); - _summary = new RateSummary(_coins / hours, _pyreals / hours); - var rows = new List(); - if (_ctx.Ai.TryGetSessionStats(out SessionStatsV1 s)) - { - rows.Add(new RateRow("XP", IltParse.Compact(s.Xp), IltParse.Compact(s.XpPerHour), Shared: true)); - rows.Add(new RateRow("Luminance", IltParse.Compact(s.Lum), IltParse.Compact(s.LumPerHour), Shared: true)); - // Per hour at the last five minutes' pace. - rows.Add(new RateRow(" last 5 min", IltParse.Compact(s.LumLast5Min), IltParse.Compact(s.LumLast5Min * 12.0), Shared: true)); - if (s.PassUpTracked != 0) - rows.Add(new RateRow(PassUpLabel, IltParse.Compact(s.LumPassUp), IltParse.Compact(s.PassUpPerHour), Shared: true)); - rows.Add(new RateRow("Kills", s.Kills.ToString(), s.KillsPerHour.ToString("0"), Shared: true)); - } - rows.Add(new RateRow("Enlightened Coins", IltParse.Compact(_coins), IltParse.Compact(_coins / hours))); - rows.Add(new RateRow("Pyreals", IltParse.Compact(_pyreals), IltParse.Compact(_pyreals / hours))); - rows.Add(new RateRow(" as MMD", (_pyreals / (double)PyrealsPerMmd).ToString("0.0"), (_pyreals / (double)PyrealsPerMmd / hours).ToString("0.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(); - } - - /// What the pass-up figure is (shared with the Mini Remote's Stats). - public const string PassUpTooltip = - "Luminance that reached your bank without a \"You've banked\" line: your vassals' pass-up.\n" - + "Fellowship and Zone Share splits arrive the same silent way and are included."; - - // ── UI (render thread) ────────────────────────────────────────────────── - - /// - /// True in the Mini Remote's Session Stats section: RynthAi's XP / luminance / kills rows are - /// drawn there already (one session), so only the ILT coins, pyreals and items are listed. - /// - public void Render(bool extrasOnly = false) - { - // The session clock is RynthAi's session stats' (it and the coins reset together). - var start = _ctx.Ai.TryGetSessionStats(out SessionStatsV1 v) && v.SessionSeconds > 0 && v.StartUtcTicks > 0 - ? new DateTime(v.StartUtcTicks, DateTimeKind.Utc) : _start; - SafeImGui.TextDisabled($"Session {IltParse.Duration(DateTime.UtcNow - start)}"); - ImGui.SameLine(); - if (ImGui.SmallButton("Reset##rates")) _ctx.Post(ResetAll); - - 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) - { - if (extrasOnly && r.Shared) continue; - ImGui.TableNextRow(); - ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Label); - if (ReferenceEquals(r.Label, PassUpLabel) && ImGui.IsItemHovered()) SafeImGui.SetTooltip(PassUpTooltip); - ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Total); - ImGui.TableNextColumn(); SafeImGui.TextColored(IltStyle.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.RynthILT/Hub/IltSettings.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSettings.cs deleted file mode 100644 index ed96a5f..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSettings.cs +++ /dev/null @@ -1,95 +0,0 @@ -// IltSettings.cs - RynthILT's own settings (every character): which world names are Infinite -// Leaftide. Lives in %APPDATA%\RynthCore\RynthILT\settings.json. -// -// The list was RynthAi's Settings > Misc "Server Features" (FeatureServerNames, saved with each -// RynthAi profile). RynthILT keeps one list for every character; the first time a character -// logs in with RynthILT, IltMigration folds that character's RynthAi list into this one. -// Edited with "/ilt servers " (the Character tab's editor went with the tab, 2026-10-13; -// RynthCore Options > Diagnostics lists the world names RynthCore uses). -using System; -using System.Collections.Generic; -using System.IO; -using System.Text.Json; -using System.Text.Json.Serialization; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT.Hub; - -public sealed class IltSettings -{ - public int SchemaVersion = 1; - - /// World-name patterns that count as Infinite Leaftide ('*' wildcard, case-insensitive). - public List ServerNames = new(ServerFeatureGate.DefaultServerNames); - - /// The shared RynthAi files (Hub profiles, aug costs) were copied over once. - public bool SharedFilesMigrated; - - /// - /// RynthILT character folders whose copy from RynthAi failed part-way (IltMigration). Until it - /// succeeds the Hub writes nothing there (a fresh file would shadow the RynthAi original and - /// stop it ever being copied); the copy is retried at each login and every few minutes. - /// - public List PendingCharacterMigrations = new(); -} - -/// Loads and saves ; a broken or missing file reads as the defaults. -internal static class IltSettingsStore -{ - public const string FileName = "settings.json"; - - /// Overridable for the tests. - public static string Folder = RynthILTPlugin.SettingsRoot; - - public static string FilePath => Path.Combine(Folder, FileName); - - public static IltSettings Load() - { - try - { - if (File.Exists(FilePath)) - { - var s = JsonSerializer.Deserialize(File.ReadAllText(FilePath), IltHubJsonContext.Default.IltSettings); - if (s != null) - { - s.ServerNames = ServerFeatureGate.ParseList(string.Join(",", s.ServerNames ?? new List())); - if (s.ServerNames.Count == 0) s.ServerNames = new List(ServerFeatureGate.DefaultServerNames); - return s; - } - } - } - catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"load {FilePath}"); } - return new IltSettings(); - } - - public static void Save(IltSettings settings) - { - try - { - string json = JsonSerializer.Serialize(settings, IltHubJsonContext.Default.IltSettings); - DataWriteGuard.TrySave("RynthILT's settings", FilePath, () => - { - Directory.CreateDirectory(Folder); - string tmp = FilePath + ".tmp"; - File.WriteAllText(tmp, json); - File.Move(tmp, FilePath, overwrite: true); - }); - } - catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"save {FilePath}"); } - } -} - -// Source-generated System.Text.Json only (NativeAOT; never reflection-serialize plugin types: -// the reflection cache keeps the old plugin generation alive across a hot reload). -[JsonSerializable(typeof(IltSettings))] -[JsonSerializable(typeof(IltHubState))] -[JsonSerializable(typeof(List), TypeInfoPropertyName = "IltBankTransactionList")] -[JsonSerializable(typeof(IltAugCostFile))] -[JsonSerializable(typeof(IltLegacyProfileFlags))] -[JsonSerializable(typeof(IltLegacyMiniRemote))] -[JsonSerializable(typeof(IltLegacyHuds))] -[JsonSourceGenerationOptions( - WriteIndented = true, - IncludeFields = true, - PropertyNameCaseInsensitive = true)] -internal partial class IltHubJsonContext : JsonSerializerContext { } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSigilChain.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSigilChain.cs deleted file mode 100644 index 3e41a28..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSigilChain.cs +++ /dev/null @@ -1,115 +0,0 @@ -// IltSigilChain.cs - The Enlightenment Sigil craft chain for /enl 301-325 (ACECustom tier 5: -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// T - 5 sigils and T x 2B luminance per target level T). Every craft is one plus one makes one: -// Enlightened Coin + Ancient Yalani Trinket = Ascension Coin -// Life Splitter + Plant = Lifebloom Resin -// Lifebloom Resin + Necrolytic Extract = Lifeblood Elixir -// Lifeblood Elixir + Ascension Coin = Enlightenment Sigil -// Pure math (no host access) so the planner and the host tests share it. Mirrors UB-IT's -// EnlightenmentSigilChainPolicy. -using System; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// Stack counts of every item in the sigil chain. -internal sealed class IltSigilStock -{ - public long Sigils, AscensionCoins, LifebloodElixirs, LifebloomResins; - public long EnlightenedCoins, YalaniTrinkets, NecrolyticExtracts, LifeSplitters, Plants; - - public IltSigilStock Clone() => (IltSigilStock)MemberwiseClone(); -} - -/// -/// What a sigil demand still needs after using stock from the top of the chain down. "ToCraft" are -/// crafts left to do (intermediates); "Short" are raw materials left to get. -/// -internal sealed class IltSigilShortfall -{ - public long SigilsNeeded, SigilsToCraft, AscensionToCraft, ElixirsToCraft, ResinsToCraft; - /// E-coins the Ascension Coin crafts use (before stock). - public long CoinsForCraft; - public long CoinsShort, TrinketsShort, ExtractsShort, SplittersShort, PlantsShort; - - /// Stock (with the whole chain) covers every sigil. - public bool Covered => CoinsShort == 0 && TrinketsShort == 0 && ExtractsShort == 0 && SplittersShort == 0 && PlantsShort == 0; -} - -internal static class IltSigilChain -{ - public const int FirstTarget = 301; - public const int LastTarget = 325; - - // Item names (ACECustom ships no WCIDs for these yet, so they are counted by name). - public const string AscensionCoin = "Ascension Coin"; - public const string YalaniTrinket = "Ancient Yalani Trinket"; - public const string LifeSplitter = "Life Splitter"; - public const string Plant = "Plant"; - public const string LifebloomResin = "Lifebloom Resin"; - public const string NecrolyticExtract = "Necrolytic Extract"; - public const string LifebloodElixir = "Lifeblood Elixir"; - - public static bool IsSigilTarget(int t) => t >= FirstTarget && t <= LastTarget; - - /// Sigils for target levels current+1 .. target that fall inside 301-325 (T - 5 each). - public static long SigilsForRange(int current, int target) - { - long total = 0; - for (int t = Math.Max(current + 1, FirstTarget); t <= Math.Min(target, LastTarget); t++) - total += Math.Max(0, t - 5); - return total; - } - - /// Shortfall for : sigils first, then coins / elixirs, then resins, then raws. - public static IltSigilShortfall Shortfall(long sigilsNeeded, IltSigilStock stock) - { - var s = new IltSigilShortfall { SigilsNeeded = Math.Max(0, sigilsNeeded) }; - if (s.SigilsNeeded == 0) return s; - stock ??= new IltSigilStock(); - s.SigilsToCraft = Short(s.SigilsNeeded, stock.Sigils); - s.AscensionToCraft = Short(s.SigilsToCraft, stock.AscensionCoins); - s.ElixirsToCraft = Short(s.SigilsToCraft, stock.LifebloodElixirs); - s.CoinsForCraft = s.AscensionToCraft; - s.CoinsShort = Short(s.AscensionToCraft, stock.EnlightenedCoins); - s.TrinketsShort = Short(s.AscensionToCraft, stock.YalaniTrinkets); - s.ResinsToCraft = Short(s.ElixirsToCraft, stock.LifebloomResins); - s.ExtractsShort = Short(s.ElixirsToCraft, stock.NecrolyticExtracts); - s.SplittersShort = Short(s.ResinsToCraft, stock.LifeSplitters); - s.PlantsShort = Short(s.ResinsToCraft, stock.Plants); - return s; - } - - /// Sigils the stock can make: finished sigils plus the scarcer of the two craft paths. - public static long Fulfillable(IltSigilStock stock) - { - if (stock == null) return 0; - long coins = stock.AscensionCoins + Math.Min(stock.EnlightenedCoins, stock.YalaniTrinkets); - long resins = stock.LifebloomResins + Math.Min(stock.LifeSplitters, stock.Plants); - long elixirs = stock.LifebloodElixirs + Math.Min(resins, stock.NecrolyticExtracts); - return stock.Sigils + Math.Min(coins, elixirs); - } - - /// - /// Splits the e-coin pool between Ascension Coin crafts (served first) and token conversion. - /// is what is still to get for both. - /// - public static void EcoinDemand(long coinsHave, long coinsForSigils, long tokensShort, int coinsPerToken, - out long tokensFromCoins, out long tokensStill, out long coinsNeeded) - { - long rate = Math.Max(1, coinsPerToken); - long have = Math.Max(0, coinsHave), sigil = Math.Max(0, coinsForSigils), tok = Math.Max(0, tokensShort); - tokensFromCoins = Math.Min(tok, Math.Max(0, have - sigil) / rate); - tokensStill = tok - tokensFromCoins; - coinsNeeded = Math.Max(0, sigil - have) + tokensStill * rate; - } - - /// True for a chain item name (stack names may be plural; "Plant" must be the whole name). - public static bool NameIs(string itemName, string chainName) - { - string n = (itemName ?? string.Empty).Trim(); - return n.Equals(chainName, StringComparison.OrdinalIgnoreCase) - || n.Equals(chainName + "s", StringComparison.OrdinalIgnoreCase); - } - - private static long Short(long demand, long have) => Math.Max(0, demand - Math.Max(0, have)); -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSplitArrows.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSplitArrows.cs deleted file mode 100644 index 01d86f1..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltSplitArrows.cs +++ /dev/null @@ -1,210 +0,0 @@ -// IltSplitArrows.cs — Split-arrow imbuer (Gear tab, P2). -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// -// 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.Shared; - -namespace RynthCore.Plugin.RynthILT.Hub; - -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; - - /// True while another ILT pack job (the Rings chain) is running: no imbue starts then. - public Func? Blocked; - - 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 (Blocked?.Invoke() == true) { _status = "the Rings chain is running"; 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(IltStyle.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; - SafeImGui.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")); - SafeImGui.TextDisabled("Status: " + _status); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltStyle.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltStyle.cs deleted file mode 100644 index 55f7f15..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltStyle.cs +++ /dev/null @@ -1,59 +0,0 @@ -// IltStyle.cs - The colours the ILT tabs and panels draw with (RynthAi's dashboard palette, so -// the tabs look the same inside RynthAi's Mini Remote as when they lived there), the dashboard -// style for RynthILT's own windows, and a JSON string escaper for the hand-built exports. -using System.Numerics; -using ImGuiNET; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal static class IltStyle -{ - 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); - internal static readonly Vector4 ColGreen = new(0.25f, 0.85f, 0.45f, 1.00f); - internal static readonly Vector4 ColTextMute = new(0.55f, 0.65f, 0.75f, 1.00f); - internal static readonly Vector4 ColHp = new(0.85f, 0.20f, 0.20f, 1.00f); - - /// - /// RynthAi's dashboard colours for a window of RynthILT's own (Games HUD, confirmations, the - /// Guardian panel). Returns how many colours to pop. Inside RynthAi's Mini Remote the style - /// is already pushed. - /// - internal static int PushDashboardStyle() - { - 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; - } - - /// Minimal JSON string escaper for hand-built export JSON. - internal static string JsonEscape(string s) - { - var sb = new System.Text.StringBuilder(s.Length + 8); - foreach (char c in s) - { - switch (c) - { - case '"': sb.Append("\\\""); break; - case '\\': sb.Append("\\\\"); break; - case '\n': sb.Append("\\n"); break; - case '\r': sb.Append("\\r"); break; - case '\t': sb.Append("\\t"); break; - default: - if (c < 0x20) sb.Append("\\u").Append(((int)c).ToString("x4")); - else sb.Append(c); - break; - } - } - return sb.ToString(); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltT11.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltT11.cs deleted file mode 100644 index 1c7d642..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltT11.cs +++ /dev/null @@ -1,213 +0,0 @@ -// IltT11.cs — ACECustom T11 (tier 11+ gear): the player's wield counters for RynthAi's loot rules, and -// "/ilt t11" (also "/ra t11", which RynthAi passes on). -// Moved out of RynthAi 2026-10-20 (RynthAiT11Command.cs and its "/aug" chat feed): the counters and the -// command are ACECustom's, so RynthILT reads them; RynthAi keeps the loot keys and the evaluator -// (Loot/T11ItemSupport.cs, users' .utl profiles use them) and gets the counters through RynthAi.Hub -// SetPlayerCounter. -// -// * Counters: ACECustom doesn't send them at login ([SendOnLogin] is off), so they come from the -// "/aug" reply (RynthILT's login probe asks for it on ILT), read by the shared T11AugReportParser. -// The item-aug override (IltHubState.T11.ItemAugsOverride, "/ilt t11 augs ") replaces the -// /aug Item count. Each change is reported to RynthAi, and every ResendMs anyway (RynthAi may have -// reloaded or logged in later); -1 = unknown. -// * "/ilt t11 [status | augs | refresh | item [0xId]]": the counters, the override, a fresh -// "/aug", and how the selected item's T11 text reads (tier, grade, modifiers, the loot keys' values). -// Ticks only on an ILT-like world (IltHubController): elsewhere RynthAi's counters stay unknown. -using System; -using System.Globalization; -using System.Linq; -using RynthCore.Loot.T11; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal sealed class IltT11 : IIltFeature -{ - private const long ResendMs = 5_000; - - // ACE string properties of an item's appraisal (RynthAi's StringValueKey). - private const uint StrName = 1, StrUse = 14, StrLongDesc = 16; - - private readonly IltHubContext _ctx; - private readonly T11AugReportParser _parser = new(); - private long _sentAt = long.MinValue; - private bool _dirty = true; - private int _overrideApplied = int.MinValue; - - public IltT11(IltHubContext ctx) => _ctx = ctx; - - /// The counters this character's "/aug" reply gave, with the override applied. - public T11PlayerAugs Player { get; } = new(); - - /// How many counters the last report to RynthAi carried (for the tests). - public int LastReported { get; private set; } - - private IltT11State S => _ctx.State.T11; - - // ── IIltFeature ───────────────────────────────────────────────────────── - - public void Tick(long nowMs) - { - int ov = S.ItemAugsOverride; - if (ov != _overrideApplied) - { - _overrideApplied = ov; - Player.ItemAugOverride = ov >= 0 ? ov : null; - _dirty = true; - } - if (!_dirty && _sentAt != long.MinValue && nowMs - _sentAt < ResendMs) return; - Report(); - _sentAt = nowMs; - _dirty = false; - } - - /// The "/aug" reply's counter lines. Never eats (the login probe's capture decides that). - public bool OnChat(string text) - { - if (_parser.Feed(text, IltHubContext.NowMs, Player)) _dirty = true; - return false; - } - - public void OnLogout() - { - Player.Clear(); - _dirty = true; - _sentAt = long.MinValue; - } - - /// Every counter to RynthAi (-1 for an unknown one). Pump thread. - private void Report() - { - int n = 0; - foreach ((T11Counter counter, _) in T11Catalog.CounterNames) - { - long? v = Player.Get(counter); - if (_ctx.Ai.SetPlayerCounter(unchecked((uint)counter), v ?? -1)) n++; - } - LastReported = n; - } - - // ── "/ilt t11 ..." ────────────────────────────────────────────────────── - - /// "/ilt t11 [status | augs <n|auto> | refresh | item [0xId]]" (args after "t11"). Pump thread. - public void HandleCommand(string[] args) - { - string sub = args.Length >= 1 ? args[0].ToLowerInvariant() : string.Empty; - switch (sub) - { - case "": - case "status": - PrintStatus(); - break; - case "augs": - SetOverride(args.Length >= 2 ? args[1] : string.Empty); - break; - case "refresh": - if (!_ctx.Host.HasInvokeChatParser) { _ctx.Chat("[RynthILT] This engine can't send chat commands."); break; } - _ctx.Host.InvokeChatParser("/aug"); - _ctx.Chat("[RynthILT] T11: sent /aug - the counters update from its reply."); - break; - case "item": - PrintItem(args.Length >= 2 ? args[1] : null); - break; - default: - _ctx.Chat("[RynthILT] Usage: /ilt t11 [augs | refresh | item [0xId]] (also /ra t11)"); - break; - } - } - - /// The counters the "T11: Can Wield" loot key compares wield gates against. - private void PrintStatus() - { - string updated = Player.UpdatedUtc is DateTime t ? t.ToLocalTime().ToString("t", CultureInfo.CurrentCulture) : "never"; - _ctx.Chat($"[RynthILT] === T11 loot (last /aug read: {updated}) ==="); - foreach ((T11Counter counter, string name) in T11Catalog.CounterNames) - { - long? v = Player.Get(counter); - string source = counter == T11Counter.ItemAugmentations && S.ItemAugsOverride >= 0 ? " (override)" : string.Empty; - _ctx.Chat($"[RynthILT] {name}: {(v.HasValue ? v.Value.ToString("N0", CultureInfo.CurrentCulture) : "unknown")}{source}"); - } - if (Player.UpdatedUtc == null && S.ItemAugsOverride < 0) - _ctx.Chat("[RynthILT] Unknown counters make \"T11: Can Wield\" -1. Use /ilt t11 refresh, or /ilt t11 augs ."); - if (!_ctx.Ai.Available) - _ctx.Chat("[RynthILT] (The loot rules are RynthAi's; it isn't loaded, so nothing uses these yet.)"); - } - - /// "/ilt t11 augs <n|auto>": the item-aug override (-1 = read from /aug), saved with the Hub's state. - private void SetOverride(string arg) - { - int value; - if (arg.Equals("auto", StringComparison.OrdinalIgnoreCase) || arg == "-1") - value = -1; - else if (!int.TryParse(arg.Replace(",", string.Empty), NumberStyles.Integer, CultureInfo.InvariantCulture, out value) || value < 0) - { - _ctx.Chat("[RynthILT] Usage: /ilt t11 augs (n = your item augmentation count)"); - return; - } - S.ItemAugsOverride = value; - Tick(IltHubContext.NowMs); // applied and reported now - _ctx.Chat(value < 0 - ? "[RynthILT] T11: item augmentations now come from /aug." - : $"[RynthILT] T11: item augmentations fixed at {value:N0} for loot rules."); - } - - /// "/ilt t11 item [0xId]": the parsed T11 text of an item (the selected item by default). - private void PrintItem(string? idArg) - { - var host = _ctx.Host; - uint id = 0; - if (!string.IsNullOrEmpty(idArg)) - uint.TryParse(idArg.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? idArg[2..] : idArg, - NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id); - if (id == 0 && host.HasGetSelectedItemId) id = host.GetSelectedItemId(); - if (id == 0) { _ctx.Chat("[RynthILT] T11: select an item first (or pass 0xId)."); return; } - - int iid = unchecked((int)id); - var inv = _ctx.Inventory; - WorldObject? item = inv.Cache[iid]; - string name = item?.Name ?? string.Empty; - if (item == null) { _ctx.Chat($"[RynthILT] T11: the client doesn't know 0x{id:X8}."); return; } - if (name.Length == 0) name = inv.Str(item, StrName); - var server = new T11ServerProps(inv.Int(item, (uint)T11Catalog.PropZcTier, 0), - inv.Int(item, (uint)T11Catalog.PropWeaponAugScaleTier, 0), - inv.Int(item, (uint)T11Catalog.PropWeaponAugScaleQuality, -1)); - T11ItemInfo info = T11ItemInfo.Parse(name, inv.Str(item, StrLongDesc), inv.Str(item, StrUse), server); - if (!info.IsT11) - { - bool appraised = !host.HasHasAppraisalData || host.HasAppraisalData(id); - _ctx.Chat(appraised - ? $"[RynthILT] T11: {name} is not a T11 item." - : $"[RynthILT] T11: {name} isn't appraised yet - ID it and try again."); - return; - } - - _ctx.Chat($"[RynthILT] === T11: {name} (0x{id:X8}) ==="); - _ctx.Chat($"[RynthILT] Tier {(info.TierIsExact ? info.Tier.ToString(CultureInfo.InvariantCulture) : "~" + info.Tier.ToString(CultureInfo.InvariantCulture))}" - + (info.Grade != null ? $", grade {info.Grade} ({info.DamagePercent}% of max damage)" : string.Empty) - + (info.WeaponQuality >= 0 ? $", quality {info.WeaponQuality}/1000" : string.Empty) - + (info.GearGrade != null ? $", gear grade {info.GearGrade} ({info.GearGradeLines} lines)" : string.Empty) - + (info.ZoneLocked ? ", zone locked" : string.Empty)); - if (info.PropertySlots >= 0 || info.Tainted) - _ctx.Chat("[RynthILT] Properties " - + (info.PropertySlots < 0 ? "?" : info.PropertySlotCap > 0 ? $"{info.PropertySlots} of {info.PropertySlotCap}" : info.PropertySlots.ToString(CultureInfo.InvariantCulture)) - + (info.Tainted ? ", tainted (bags no longer work)" : string.Empty)); - foreach (T11WieldGate g in info.WieldGates) - _ctx.Chat($"[RynthILT] Wield requires {g.Amount:N0} {T11Catalog.CounterName(g.Counter)}"); - foreach (T11Modifier m in info.Modifiers) - { - string band = m.Min.HasValue && m.Max.HasValue ? $" [{m.Min}-{m.Max}] roll {m.RollPercent}%" : string.Empty; - string marks = (m.Tinkered != 0 ? $" ({m.Tinkered:+#;-#} tinkered)" : string.Empty) - + (m.BuiltIn ? " (built-in)" : string.Empty) + (m.Locked ? " (locked)" : string.Empty); - _ctx.Chat($"[RynthILT] Mod {m.Name} {(m.IsSlotSpecial ? "(special)" : "+" + m.Value)}{band}{marks}"); - } - foreach ((string proc, double chance) in info.Procs) - _ctx.Chat($"[RynthILT] Cast on strike: {proc} ({chance.ToString("0.#", CultureInfo.CurrentCulture)}%)"); - - int canWield = T11Keys.TryGetValue(info, T11Keys.CanWield, Player, out int cw) ? cw : -1; - _ctx.Chat($"[RynthILT] Can wield: {(canWield == 1 ? "yes" : canWield == 0 ? "no" : "unknown (no /aug read, or not appraised)")}" - + $", modifier ratings {info.ModifierRatingTotal}, average roll {info.AverageRollPercent}%"); - string keys = string.Join(", ", T11Keys.Names() - .Where(k => k.Id < T11Keys.ModifierBase) - .Select(k => $"{k.Name.Replace("T11: ", string.Empty)}={(T11Keys.TryGetValue(info, k.Id, Player, out int v) ? v : 0)}")); - _ctx.Chat($"[RynthILT] Loot keys (RynthAi's loot rules read the same): {keys}"); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltTempleAttributes.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltTempleAttributes.cs deleted file mode 100644 index efb6c29..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltTempleAttributes.cs +++ /dev/null @@ -1,296 +0,0 @@ -// IltTempleAttributes.cs - Temple of Enlightenment attribute turn-in tracker (Guardian window). -// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. -// -// 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; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// 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 IltQuestBonus _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, IltQuestBonus quests) - { - _ctx = ctx; - _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 RynthILT's folder, the RynthAi folder (where it lived), else UB's Documents location; built-in rows otherwise. - private static IltTempleAttrRow[] LoadRows(out string source) - { - string[] candidates = - { - Path.Combine(IltHubStore.SharedRoot, CsvName), - 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() => $"{_ctx.Ai.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!; - // /myquests is RynthAi's quest tracker (RynthAi.Hub); without RynthAi the /qb stamps decide. - foreach (string key in row.MyQuestsKeys) - if (_ctx.Ai.TryGetQuestFlag(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 (IltQuestBonus.Classify(rec)) - { - case IltQuestBonus.QuestKind.KillTask: - return new(row.Attribute, row.Npc, rec.Solves, "Kill task", $"{rec.Solves}/{rec.MaxSolves}", false, true); - case IltQuestBonus.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.RynthILT/Hub/IltVaultedDungeons.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltVaultedDungeons.cs deleted file mode 100644 index 18d362f..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltVaultedDungeons.cs +++ /dev/null @@ -1,920 +0,0 @@ -// IltVaultedDungeons.cs — Mini Remote "Vaulted Dungeons" tab (ILT / ACECustom only). -// Written by Silentkelpie (RynthSuite PR #12), a port of the UtilityBelt VaultedDungeons.lua script -// (owner 2026-09-27 / 2026-10-03): keeps the character in one Vaulted Dungeon via a tied Portal -// Recall Gem, and optionally /rc quit after N minutes without a kill. -// -// Safety rules (the owner's, added when it was taken in): -// * ILT only. The module does nothing (no tick work, no recall, no quit, no tab) unless -// IltServerOptions.IsIltLikeWorld says this is an Infinite Leaftide / ACECustom world, the same -// verdict every other ILT feature follows. A command answers "not available on this server". -// * Master switch, off by default: IltHubState.VaultedDungeonsEnabled (the ILT settings, and the -// engine's Settings > Navigation row RynthAi mirrors; RynthAi's profile setting until 2026-10-20, -// copied once). It is the only copy. While it is off the module -// ignores AutoStart, never ticks, sends no recall and no /rc quit, and the tab is hidden. Turning -// it off while running stops the keeper at once and says so once. -// * Active is never resumed from the saved settings. It starts when the player turns it on, or on -// arriving in the chosen dungeon with Auto Start On Arrival on (master on); a relog starts Off. -// * No recall gem while RynthAi is in combat, buffing or waiting on the server, or the client is -// busy: the recall waits until it is clear (a warning on the normal 30 s cadence). -// * /rc quit goes out at most once per activation, and only if Active, ILT and the master are all -// still true at the moment of sending. -// * The no-kill timer restarts on the luminance line, on the server's killer notification (a -// killing blow of yours) and on a pet-capture success reply. Kills by pets or fellows that pay -// no luminance still don't count; the tab says so. -using System; -using System.Collections.Generic; -using System.IO; -using System.Numerics; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Text.RegularExpressions; -using ImGuiNET; -using RynthCore.Plugin.Shared; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// One known Vaulted Dungeon (landblock high word; the client does not see the layer). -internal readonly record struct VaultedDungeon(string Name, uint Landblock); - -internal sealed class IltVaultedDungeons : IIltFeature -{ - // Keep order stable: saved picks are by 1-based index into this list. - private static readonly VaultedDungeon[] Dungeons = - { - new("Tyrant's Quarry", 0x01F7), - new("Tusgian Barracks", 0x8C03), - new("Wailing Cells", 0x01C2), - new("Chamber of Idols", 0x5649), - new("Fiun Redoubt", 0x0178), // added 2026-09-27 - new("Tumerok Tunnels", 0x5754), // added 2026-10-03 - }; - - private static readonly string[] GemNames = - { - "Primary Portal Recall Gem", - "Secondary Portal Recall Gem", - }; - - private static readonly (string Name, float Value)[] Powers = - { - ("Fast", 0f), ("Medium", 0.5f), ("Full Power", 1f), - }; - - private static readonly int[] QuitPresets = { 1, 2, 5, 10, 15, 30 }; - - private const long FirstRecallAfterMs = 1000; - private const long RecallAfterMs = 5000; - private const int QuitMin = 1, QuitMax = 30; - private const long WarnEveryMs = 30_000; - private const string SettingsFileName = "settings.json"; - private const string SettingsBadFileName = "settings.unreadable.json"; - - private const string CmdMetaOff = "/vt opt set EnableMeta False"; - private const string CmdNavOff = "/vt opt set EnableNav False"; - private const string CmdRepeatOn = "/ub playeroption AutoRepeatAttack on"; - private const string CmdAttackBar = "/vt setattackbar "; - private const string CmdQuit = "/rc quit"; - - // System line only (no player sender): "You've banked 1,234 Luminance." - private static readonly Regex KillLine = new( - @"^You've banked [\d,]+ Luminance\.\s*$", - RegexOptions.Compiled | RegexOptions.CultureInvariant); - - /// Why the keeper is idle (): "" = it may run. - private const string GateWorld = "world", GateMaster = "master"; - - private readonly IltHubContext _ctx; - private readonly object _gate = new(); - private Cfg _cfg = new(); - private bool _loaded; - private bool _dirty; - private string? _lastGoodJson; - - // Seams (the tests fake them): the master switch, what RynthAi is doing, the clock, the gem use. - internal Func MasterEnabled; - internal Func Activity; - internal Func Clock = () => IltHubContext.NowMs; - /// Uses the named gem from the pack; false when the pack has none. - internal Func UseGem; - - // Runtime (pump thread). - private long _outSinceMs; - private long _lastRecallMs; - private long _clockStartMs; - private long _realKillMs; - private bool _wasInside; - private bool _quitSent; - private long _lastWarnMs = -WarnEveryMs; - private string _publishedGate = "?"; - private string _state = "paused"; // paused / setup / in / out / portal / nogem - private long? _quitLeftMs; - private bool? _presentBefore; - private long _idleSecs; - private long _inSinceMs; - private long _portalSinceMs; - private int _kills; - private long _dungeonSecs; - private long _lastTickMs; - - // Snapshot for the render thread (copied under _gate). - private Snapshot _snap = Snapshot.Empty; - - public IltVaultedDungeons(IltHubContext ctx) - { - _ctx = ctx; - MasterEnabled = () => _ctx.State.VaultedDungeonsEnabled; - Activity = () => _ctx.Ai.Activity(); - UseGem = gemName => - { - var gem = _ctx.Inventory.FindByName(n => n.Equals(gemName, StringComparison.OrdinalIgnoreCase)); - if (gem == null) return false; - _ctx.Inventory.Use(gem); - return true; - }; - } - - /// Whether the keeper is running (tests, status). - internal bool IsActive => _cfg.Active; - - private long Now() => Clock(); - - /// - /// The two hard rules, asked fresh each time: an ILT-like world, and the master switch on. - /// says which one failed ("" when allowed). - /// - private bool Allowed(out string gate) - { - gate = !_ctx.Options.IsIltLikeWorld ? GateWorld : !MasterEnabled() ? GateMaster : string.Empty; - return gate.Length == 0; - } - - /// Same, for commands and the tab: why the keeper can't be used now (null = it can). - private static string? GateReply(string gate) => gate switch - { - GateWorld => "Not available on this server (Infinite Leaftide / ACECustom only).", - GateMaster => "Off: turn on \"Vaulted Dungeons\" in the ILT settings (/ilt settings; also Settings > Navigation) first (the master switch, off by default).", - _ => null, - }; - - // ── Persistence ───────────────────────────────────────────────────────── - - private string SettingsDir => Path.Combine(_ctx.Store.CharFolder, "VaultedDungeons"); - private string SettingsPath => Path.Combine(SettingsDir, SettingsFileName); - - private void EnsureLoaded() - { - if (_loaded) return; - _loaded = true; - try - { - string path = SettingsPath; - if (!File.Exists(path)) return; - string text = File.ReadAllText(path); - var cfg = JsonSerializer.Deserialize(text, IltVaultedDungeonsJsonContext.Default.Cfg); - if (cfg == null) return; - _cfg = Sanitize(cfg); - _lastGoodJson = text; - } - catch (Exception ex) - { - RynthLog.Write(LogCat.IltHub, $"Vaulted Dungeons: settings load failed: {ex.Message}"); - } - } - - private void SaveIfDirty() - { - if (!_dirty) return; - _dirty = false; - try - { - Directory.CreateDirectory(SettingsDir); - string path = SettingsPath; - // Corrupt / mid-write: keep a copy, then rewrite from last good + current cfg. - if (File.Exists(path)) - { - try - { - string existing = File.ReadAllText(path); - if (_lastGoodJson == null) - JsonSerializer.Deserialize(existing, IltVaultedDungeonsJsonContext.Default.Cfg); // throws if bad - } - catch - { - try - { - File.Copy(path, Path.Combine(SettingsDir, SettingsBadFileName), overwrite: true); - _ctx.Chat("[Vaulted Dungeons] settings.json would not read — kept a copy as " - + SettingsBadFileName + "."); - } - catch { /* best effort */ } - } - } - string json = JsonSerializer.Serialize(_cfg, IltVaultedDungeonsJsonContext.Default.Cfg); - File.WriteAllText(path, json); - _lastGoodJson = json; - } - catch (Exception ex) - { - RynthLog.Write(LogCat.IltHub, $"Vaulted Dungeons: settings save failed: {ex.Message}"); - } - } - - private static Cfg Sanitize(Cfg c) - { - // Never resumed from disk: the file keeps its "active" field, but a relog (or turning the - // master switch back on) starts Off. Auto Start On Arrival is the only way back in by itself. - c.Active = false; - c.Dungeon = ClampInt(c.Dungeon, 0, Dungeons.Length, 0); - c.Gem = ClampInt(c.Gem, 0, GemNames.Length, 0); - c.QuitMinutes = ClampInt(c.QuitMinutes, QuitMin, QuitMax, 2); - c.AttackPower = Powers[PowerIndex(c.AttackPower)].Value; - return c; - } - - private static int ClampInt(int v, int lo, int hi, int def) - => v < lo || v > hi ? def : v; - - private static int PowerIndex(float v) - { - int best = 0; - float bestGap = float.MaxValue; - for (int i = 0; i < Powers.Length; i++) - { - float gap = Math.Abs(Powers[i].Value - v); - if (gap < bestGap) { best = i; bestGap = gap; } - } - return best; - } - - private static string PowerText(float p) - { - string t = p.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture); - return t; - } - - // ── IIltFeature ───────────────────────────────────────────────────────── - - public void Tick(long nowMs) - { - // The hard rules first: ILT only, master switch on. Nothing below runs otherwise (not even - // reading the settings file), and a keeper that was running is stopped on the spot. - if (!Allowed(out string gate)) - { - StopForGate(gate); - PublishGate(gate); - return; - } - - EnsureLoaded(); - SaveIfDirty(); - - // Time in dungeon (kills/hour): only while last state was "in". - if (_lastTickMs > 0 && _state == "in") - _dungeonSecs += Math.Max(0, (nowMs - _lastTickMs) / 1000); - _lastTickMs = nowMs; - - if (!_ctx.Host.HasGetPlayerPose || !_ctx.Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _) || cell == 0) - { - Publish(); - return; - } - - uint landblock = cell >> 16; - bool portaling = _ctx.Host.HasIsPortaling && _ctx.Host.IsPortaling(); - VaultedDungeon? dungeon = _cfg.Dungeon > 0 && _cfg.Dungeon <= Dungeons.Length - ? Dungeons[_cfg.Dungeon - 1] - : null; - - // Present check (for Auto Start / arrive actions) even while Off. - if (dungeon == null) - _presentBefore = null; - else if (!portaling) - { - bool here = landblock == dungeon.Value.Landblock; - if (here && _presentBefore != true) OnArrive(dungeon.Value, nowMs); - _presentBefore = here; - } - - _quitLeftMs = null; - if (!_cfg.Active) - { - _state = "paused"; - _outSinceMs = 0; - Publish(); - return; - } - - string? gemName = _cfg.Gem > 0 && _cfg.Gem <= GemNames.Length ? GemNames[_cfg.Gem - 1] : null; - if (dungeon == null || gemName == null) - { - _state = "setup"; - _wasInside = false; - Warn(nowMs, dungeon == null - ? "Pick a dungeon in the Vaulted Dungeons tab." - : "Pick a recall gem in the Vaulted Dungeons tab."); - Publish(); - return; - } - - bool inside = landblock == dungeon.Value.Landblock; - if (inside && !portaling) - { - if (!_wasInside) - { - _clockStartMs = nowMs; - _inSinceMs = nowMs; - } - _wasInside = true; - _outSinceMs = 0; - _portalSinceMs = 0; - _state = "in"; - _idleSecs = Math.Max(0, (nowMs - _clockStartMs) / 1000); - if (_cfg.Quit) - { - long quitAfterMs = _cfg.QuitMinutes * 60_000L; - _quitLeftMs = Math.Max(0, quitAfterMs - (nowMs - _clockStartMs)); - if (nowMs - _clockStartMs >= quitAfterMs && !_quitSent) - { - // Once per activation, and only if ILT, the master switch and Active are all - // still true right now (asked again: they may have changed since the top of the tick). - string nowGate = string.Empty; - if (!_cfg.Active || !Allowed(out nowGate)) - { - StopForGate(nowGate); - PublishGate(nowGate); - return; - } - _quitSent = true; - _ctx.Chat($"[Vaulted Dungeons] No kill in {_cfg.QuitMinutes} minute" - + (_cfg.QuitMinutes == 1 ? "" : "s") + " — quitting."); - Invoke(CmdQuit); - } - } - Publish(); - return; - } - - _wasInside = false; - if (portaling) - { - _state = "portal"; - _outSinceMs = 0; - if (_portalSinceMs == 0) _portalSinceMs = nowMs; - Publish(); - return; - } - _portalSinceMs = 0; - - if (_outSinceMs == 0) _outSinceMs = nowMs; - _state = "out"; - - bool tried = _lastRecallMs >= _outSinceMs; - bool due = (!tried && nowMs - _outSinceMs >= FirstRecallAfterMs) - || (tried && nowMs - _lastRecallMs >= RecallAfterMs); - if (due) - { - // Not in the middle of a fight, a buff chain or an unanswered use/cast: the recall waits - // (still due, so it goes out on the first clear tick) and says so on the normal cadence. - string? busy = BusyReason(); - if (busy != null) - { - _state = "busy"; - Warn(nowMs, $"Waiting to use the {gemName}: {busy}."); - } - else if (UseGem(gemName)) - { - _lastRecallMs = nowMs; - _ctx.Chat($"[Vaulted Dungeons] Not in {dungeon.Value.Name} — using the {gemName}."); - } - else - { - _state = "nogem"; - Warn(nowMs, $"No {gemName} in your pack."); - } - } - Publish(); - } - - /// - /// Why a recall gem must not be used now, or null when it may. RynthAi's activity (its "RynthAi.Activity" - /// bits: combat, buffing, loot, salvage, crafting, a use/cast waiting on the server) and the client's - /// busy hourglass; RynthAi not answering counts as busy (nothing is known, so nothing is used). - /// - private string? BusyReason() - { - RynthAiActivity? a = Activity(); - if (a is null) return "RynthAi is not ready"; - RynthAiActivity f = a.Value; - if ((f & RynthAiActivity.Combat) != 0) return "RynthAi is in combat"; - if ((f & RynthAiActivity.Buffing) != 0) return "RynthAi is buffing"; - if ((f & RynthAiActivity.ServerAction) != 0) return "RynthAi is waiting on the server"; - if ((f & RynthAiActivity.Looting) != 0) return "RynthAi is looting"; - if ((f & RynthAiActivity.Salvaging) != 0) return "RynthAi is salvaging"; - if ((f & RynthAiActivity.Crafting) != 0) return "RynthAi is crafting"; - if (_ctx.Inventory.IsBusy) return "the client is busy"; - return null; - } - - /// - /// A rule failed (not ILT any more, or the master switch went off): a running keeper stops at once - /// and says so once; an idle one has nothing to do. Safe to call every tick. - /// - private void StopForGate(string gate) - { - _outSinceMs = 0; - _wasInside = false; - _quitLeftMs = null; - _presentBefore = null; - if (!_cfg.Active) return; - _cfg.Active = false; - _dirty = true; - _state = "paused"; - _ctx.Chat("[Vaulted Dungeons] Stopped: " + (gate == GateWorld - ? "this is not an Infinite Leaftide / ACECustom world." - : "\"Vaulted Dungeons\" (the master switch) was turned off.")); - SaveIfDirty(); - } - - /// The idle snapshot (only when the reason changes: nothing else runs while gated). - private void PublishGate(string gate) - { - if (gate == _publishedGate) return; - _publishedGate = gate; - Publish(gate); - } - - public bool OnChat(string text) - { - if (string.IsNullOrEmpty(text)) return false; - string line = text.TrimEnd(); - bool luminance = KillLine.IsMatch(line); - // A pet-capture success counts as a kill for the timer too (the same replies RynthAi's Pets - // tab matches); nothing else is guessed. - if (!luminance && !PetCaptureLines.IsSuccess(line)) return false; - if (!_cfg.Active || !Allowed(out _)) return false; - NoteKill(Now(), countKill: luminance); - return false; // never eat the luminance line - } - - /// - /// The server's killer notification: this character landed a killing blow (RynthILTPlugin - /// .OnKillNotification, pump thread). Restarts the no-kill timer, like the luminance line. - /// - public void OnKillNotification() - { - if (!_cfg.Active || !Allowed(out _)) return; - NoteKill(Now(), countKill: false); - } - - /// Restarts the Kill Client timer. The kill counter moves only on the luminance line (one per kill). - private void NoteKill(long now, bool countKill) - { - _clockStartMs = now; - _realKillMs = now; - if (countKill && _state == "in") _kills++; - Publish(); - } - - public void OnLogout() - { - // Logging out ends the run: Active is never carried over (see Sanitize). - _cfg.Active = false; - SaveIfDirty(); - _wasInside = false; - _outSinceMs = 0; - _presentBefore = null; - _state = "paused"; - Publish(); - } - - // ── Arrive / commands ─────────────────────────────────────────────────── - - private void OnArrive(VaultedDungeon dungeon, long nowMs) - { - // Only called while ILT and the master switch are on (Tick's gate), so Auto Start is honoured here only. - if (_cfg.AutoStart && !_cfg.Active) - { - Activate(nowMs); - _ctx.Chat($"[Vaulted Dungeons] Arrived in {dungeon.Name} — switched On (Auto Start On Arrival)."); - } - // The arrival settings are part of running the keeper: nothing is sent while it is Off. - if (!_cfg.Active) return; - if (_cfg.DisableMeta) Invoke(CmdMetaOff); - if (_cfg.DisableNav) Invoke(CmdNavOff); - if (_cfg.RepeatAttack) Invoke(CmdRepeatOn); - if (_cfg.SetPower) Invoke(CmdAttackBar + PowerText(_cfg.AttackPower)); - } - - private void Invoke(string cmd) - { - if (_ctx.Host.HasInvokeChatParser) _ctx.Host.InvokeChatParser(cmd); - } - - private void Warn(long nowMs, string text) - { - if (nowMs - _lastWarnMs < WarnEveryMs) return; - _lastWarnMs = nowMs; - _ctx.Chat("[Vaulted Dungeons] " + text); - } - - /// Pump-thread: /ilt vaulted [on|off|toggle|status]. - public bool HandleCommand(string[] args) - { - // ILT only, master switch on: otherwise the only answer is why (the keeper itself stays idle). - if (!Allowed(out string gate)) - { - if (_cfg.Active) StopForGate(gate); - _ctx.Chat("[Vaulted Dungeons] " + GateReply(gate)); - return true; - } - - EnsureLoaded(); - string sub = args.Length > 0 ? args[0].ToLowerInvariant() : "status"; - switch (sub) - { - case "on": - case "start": - SetActive(true); - return true; - case "off": - case "stop": - SetActive(false); - _ctx.Chat("[Vaulted Dungeons] Off."); - return true; - case "toggle": - SetActive(!_cfg.Active); - if (!_cfg.Active) _ctx.Chat("[Vaulted Dungeons] Off."); - return true; - default: - string d = _cfg.Dungeon > 0 && _cfg.Dungeon <= Dungeons.Length - ? Dungeons[_cfg.Dungeon - 1].Name : "(none)"; - string g = _cfg.Gem > 0 && _cfg.Gem <= GemNames.Length - ? GemNames[_cfg.Gem - 1] : "(none)"; - _ctx.Chat($"[Vaulted Dungeons] {(_cfg.Active ? "On" : "Off")} — dungeon={d}, gem={g}, " - + $"kill-client={(_cfg.Quit ? $"{_cfg.QuitMinutes}m" : "off")}, state={_state}."); - _ctx.Chat("[Vaulted Dungeons] /ilt vaulted [on|off|toggle|status] (Mini Remote tab; master switch: /ilt settings or Settings > Navigation > Vaulted Dungeons)"); - return true; - } - } - - /// Starts the keeper (the player's own action, or Auto Start On Arrival). Pump thread; ILT and master already checked. - private void Activate(long nowMs) - { - _cfg.Active = true; - _dirty = true; - _outSinceMs = 0; - _wasInside = false; // the no-kill clock starts when the first in-dungeon tick sees us inside - _clockStartMs = nowMs; - _quitSent = false; // /rc quit: once per activation - _lastRecallMs = 0; - Publish(); - } - - private void SetActive(bool value) - { - if (value) - { - // From the tab's button too (posted to the pump): re-check, the switch may have gone off since. - if (!Allowed(out string gate)) - { - _ctx.Chat("[Vaulted Dungeons] " + GateReply(gate)); - return; - } - EnsureLoaded(); - if (!_cfg.Active) - { - Activate(Now()); - _ctx.Chat("[Vaulted Dungeons] On."); - } - return; - } - _cfg.Active = false; - _outSinceMs = 0; - _dirty = true; - _clockStartMs = Now(); - _wasInside = false; - _quitLeftMs = null; - _state = "paused"; - Publish(); - } - - // ── Render snapshot ───────────────────────────────────────────────────── - - private void Publish(string gate = "") - { - _publishedGate = gate; - lock (_gate) - { - _snap = new Snapshot( - _cfg.Active, _cfg.Dungeon, _cfg.Gem, _cfg.Quit, _cfg.QuitMinutes, - _cfg.ShowInDungeon, _cfg.AutoStart, _cfg.DisableMeta, _cfg.DisableNav, - _cfg.RepeatAttack, _cfg.SetPower, _cfg.AttackPower, - _state, _quitLeftMs, _idleSecs, _inSinceMs, _outSinceMs, _portalSinceMs, - _realKillMs, _kills, _dungeonSecs, Now(), gate); - } - } - - private Snapshot Take() - { - lock (_gate) return _snap; - } - - // ── UI (render thread) ────────────────────────────────────────────────── - - private bool _showAdvanced; - // Pending edits from the UI, applied on the next pump tick via Post. - private void PostEdit(Action edit) - { - _ctx.Post(() => - { - if (!Allowed(out _)) return; // gated while it waited: an edit changes nothing - EnsureLoaded(); - edit(_cfg); - _dirty = true; - Publish(); - }); - } - - public void Render() - { - // Settings load on the pump (Tick); the window only reads the snapshot. - Snapshot s = Take(); - - Vector4 colLabel = new(0.53f, 0.53f, 0.53f, 1f); - Vector4 colValue = new(1f, 1f, 1f, 1f); - Vector4 colGreen = new(0.27f, 0.80f, 0.40f, 1f); - Vector4 colAmber = new(0.95f, 0.65f, 0.20f, 1f); - Vector4 colRed = new(0.90f, 0.30f, 0.30f, 1f); - Vector4 colPurple = new(0.72f, 0.52f, 0.95f, 1f); - Vector4 colTitleRed = new(0.85f, 0.25f, 0.25f, 1f); - - // Title row: Vaulted (red) Dungeons (white) + On/Off + Advanced. - ImGui.TextColored(colTitleRed, "Vaulted"); - ImGui.SameLine(0, ImGui.CalcTextSize(" ").X); - ImGui.TextColored(colValue, "Dungeons"); - - // Not offered right now (the tab is hidden then; this covers a stale frame or a direct open). - if (s.Gate.Length > 0) - { - ImGui.Separator(); - ImGui.TextWrapped(GateReply(s.Gate) ?? "Not available."); - return; - } - ImGui.SameLine(0, 16); - Vector4 pill = s.Active ? colGreen : new(0.85f, 0.10f, 0.10f, 1f); - ImGui.PushStyleColor(ImGuiCol.Button, pill); - ImGui.PushStyleColor(ImGuiCol.ButtonHovered, pill); - ImGui.PushStyleColor(ImGuiCol.ButtonActive, pill); - ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(0.05f, 0.05f, 0.05f, 1f)); - if (ImGui.SmallButton((s.Active ? " On " : " Off ") + "##vdactive")) - _ctx.Post(() => SetActive(!s.Active)); - ImGui.PopStyleColor(4); - if (ImGui.IsItemHovered()) - ImGui.SetTooltip(s.Active - ? "On: keeping this character in the chosen dungeon.\nClick: turn off." - : "Off: doing nothing.\nClick: turn on."); - ImGui.SameLine(); - if (ImGui.SmallButton("Advanced##vdoptions")) _showAdvanced = !_showAdvanced; - - ImGui.Separator(); - - float labelW = ImGui.CalcTextSize("Recall Gem").X + 12; - void Label(string text) - { - ImGui.AlignTextToFramePadding(); - ImGui.TextColored(colLabel, text); - ImGui.SameLine(labelW); - } - - // Status - var (statusWord, statusCol) = s.State switch - { - "in" => ("In Dungeon", colGreen), - "out" => ("Recalling", colAmber), - "portal" => ("Portal Space", colPurple), - "setup" => ("Setup Needed", colAmber), - "nogem" => ("No Gem", colRed), - "busy" => ("Waiting (busy)", colAmber), - _ => ("Not Running", colRed), - }; - long since = s.State == "in" ? s.InSinceMs - : s.State == "out" ? s.OutSinceMs - : s.State == "portal" ? s.PortalSinceMs : 0; - string statusText = statusWord; - if (since > 0) - { - long secs = Math.Max(0, (s.NowMs - since) / 1000); - long h = secs / 3600, m = (secs / 60) % 60, sec = secs % 60; - statusText += h > 0 ? $" ({h}:{m:D2}:{sec:D2})" : $" ({m}:{sec:D2})"; - } - Label("Status"); - ImGui.TextColored(statusCol, statusText); - - // Dungeon combo (0 = pick, 1..N = Dungeons[i-1]) - Label("Dungeon"); - string[] dungeonChoices = BuildDungeonChoices(); - int dungeonIdx = s.Dungeon; - ImGui.SetNextItemWidth(260); - if (ImGui.Combo("##vddungeon", ref dungeonIdx, dungeonChoices, dungeonChoices.Length)) - PostEdit(c => { c.Dungeon = dungeonIdx; }); - - Label("Recall Gem"); - string[] gemChoices = { "Pick a gem", GemNames[0], GemNames[1] }; - int gemIdx = s.Gem; - ImGui.SetNextItemWidth(260); - if (ImGui.Combo("##vdgem", ref gemIdx, gemChoices, gemChoices.Length)) - PostEdit(c => { c.Gem = gemIdx; }); - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Tie this gem to the dungeon's portal first."); - - Label("Last Kill"); - if (s.State == "in" && s.RealKillMs > 0) - ImGui.TextUnformatted($"{(s.NowMs - s.RealKillMs) / 1000} s ago"); - else - ImGui.TextUnformatted("-"); - - Label("Session"); - string perHour = s.DungeonSecs < 60 ? "-" - : Commas((long)(s.Kills * 3600.0 / Math.Max(1, s.DungeonSecs))); - ImGui.TextUnformatted($"{Commas(s.Kills)} kills ({perHour} Per Hour)"); - - if (s.QuitLeftMs is long left && s.QuitMinutes > 0) - { - float frac = (float)(left / (double)(s.QuitMinutes * 60_000L)); - string barLabel = $"Kill Client ({left / 60_000}:{(left / 1000) % 60:D2})"; - ImGui.ProgressBar(Math.Clamp(frac, 0f, 1f), new Vector2(-1, ImGui.GetTextLineHeight()), barLabel); - } - - if (_showAdvanced) - { - ImGui.Separator(); - ImGui.TextColored(colValue, "Advanced"); - - bool quit = s.Quit; - if (ImGui.Checkbox("Kill Client##vdquit", ref quit)) - { - bool on = quit; - _ctx.Post(() => - { - if (!Allowed(out _)) return; - EnsureLoaded(); - _cfg.Quit = on; - _cfg.QuitMinutes = ClampInt(_cfg.QuitMinutes, QuitMin, QuitMax, 2); - _clockStartMs = Now(); - _dirty = true; - Publish(); - }); - } - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("No kill for the set minutes in the dungeon: /rc quit closes the client (once per run).\n" - + "The timer restarts on the server's \"You've banked N Luminance.\" line, on your own killing blow,\n" - + "and on a successful pet capture. Kills by pets or fellows that pay you no luminance\n" - + "do NOT restart it, so keep the minutes generous if you hunt with pets."); - - ImGui.SameLine(); - ImGui.TextColored(colLabel, "after"); - ImGui.SameLine(); - if (ImGui.SmallButton($"{s.QuitMinutes} minute{(s.QuitMinutes == 1 ? "" : "s")}##vdmincycle")) - _ctx.Post(() => - { - if (!Allowed(out _)) return; - EnsureLoaded(); - _cfg.QuitMinutes = StepPreset(_cfg.QuitMinutes, +1); - _clockStartMs = Now(); - _dirty = true; - Publish(); - }); - if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) - _ctx.Post(() => - { - if (!Allowed(out _)) return; - EnsureLoaded(); - _cfg.QuitMinutes = StepPreset(_cfg.QuitMinutes, -1); - _clockStartMs = Now(); - _dirty = true; - Publish(); - }); - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Minutes with no kill before Kill Client quits.\nClick: longer. Right-click: shorter. (1, 2, 5, 10, 15, 30)"); - - BoolRow("Auto Start On Arrival##vdautostart", s.AutoStart, - v => PostEdit(c => c.AutoStart = v), - "Switch On by itself when you arrive in the chosen dungeon (logging in there counts)."); - - BoolRow("Disable Meta##vdnometa", s.DisableMeta, - v => PostEdit(c => c.DisableMeta = v), - "On arriving: " + CmdMetaOff); - - BoolRow("Disable Nav##vdnonav", s.DisableNav, - v => PostEdit(c => c.DisableNav = v), - "On arriving: " + CmdNavOff); - - BoolRow("Repeat Attacks On##vdrepeat", s.RepeatAttack, - v => PostEdit(c => c.RepeatAttack = v), - "On arriving: " + CmdRepeatOn); - - BoolRow("Set Attack Power##vdpower", s.SetPower, - v => PostEdit(c => c.SetPower = v), - "On arriving: " + CmdAttackBar + PowerText(s.AttackPower)); - ImGui.SameLine(); - int pi = PowerIndex(s.AttackPower); - if (ImGui.SmallButton(Powers[pi].Name + "##vdpowercycle")) - PostEdit(c => c.AttackPower = Powers[(pi + 1) % Powers.Length].Value); - if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) - PostEdit(c => c.AttackPower = Powers[(pi - 1 + Powers.Length) % Powers.Length].Value); - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Fast (0), Medium (0.5) or Full Power (1).\nClick: next. Right-click: back."); - } - - ImGui.Spacing(); - ImGui.TextDisabled("Note: the client sees the landblock, not the layer - standing in the retail copy also counts as \"in it\"."); - ImGui.TextDisabled("Kill Client: pet or fellow kills that pay you no luminance do not restart its timer."); - ImGui.TextDisabled("Recalls wait while RynthAi is in combat, buffing or waiting on the server."); - ImGui.TextDisabled("/ilt vaulted [on|off|toggle|status]"); - } - - private static void BoolRow(string id, bool value, Action set, string tip) - { - bool v = value; - if (ImGui.Checkbox(id, ref v)) set(v); - if (ImGui.IsItemHovered()) ImGui.SetTooltip(tip); - } - - private static string[] BuildDungeonChoices() - { - var list = new string[Dungeons.Length + 1]; - list[0] = "Pick a dungeon"; - for (int i = 0; i < Dungeons.Length; i++) list[i + 1] = Dungeons[i].Name; - return list; - } - - private static int StepPreset(int current, int dir) - { - if (dir > 0) - { - foreach (int m in QuitPresets) if (m > current) return m; - return QuitPresets[0]; - } - for (int i = QuitPresets.Length - 1; i >= 0; i--) - if (QuitPresets[i] < current) return QuitPresets[i]; - return QuitPresets[^1]; - } - - private static string Commas(long n) - { - string s = Math.Abs(n).ToString(); - var chars = new List(); - for (int i = 0; i < s.Length; i++) - { - if (i > 0 && (s.Length - i) % 3 == 0) chars.Add(','); - chars.Add(s[i]); - } - return (n < 0 ? "-" : "") + new string(chars.ToArray()); - } - - // ── Config / snapshot types ───────────────────────────────────────────── - - // internal (not private) so the source-generated IltVaultedDungeonsJsonContext can reach it. - internal sealed class Cfg - { - public bool Active { get; set; } - /// 0 = none, 1..N = Dungeons index. - public int Dungeon { get; set; } - /// 0 = none, 1 = primary, 2 = secondary. - public int Gem { get; set; } - public bool Quit { get; set; } - public int QuitMinutes { get; set; } = 2; - public bool ShowInDungeon { get; set; } - public bool AutoStart { get; set; } - public bool DisableMeta { get; set; } - public bool DisableNav { get; set; } - public bool RepeatAttack { get; set; } - public bool SetPower { get; set; } - public float AttackPower { get; set; } - } - - private readonly record struct Snapshot( - bool Active, int Dungeon, int Gem, bool Quit, int QuitMinutes, - bool ShowInDungeon, bool AutoStart, bool DisableMeta, bool DisableNav, - bool RepeatAttack, bool SetPower, float AttackPower, - string State, long? QuitLeftMs, long IdleSecs, long InSinceMs, long OutSinceMs, long PortalSinceMs, - long RealKillMs, int Kills, long DungeonSecs, long NowMs, string Gate) - { - /// Before the first tick (the tab is only offered while the keeper may run). - public static Snapshot Empty => new(false, 0, 0, false, 2, - false, false, false, false, false, false, 0f, - "paused", null, 0, 0, 0, 0, 0, 0, 0, 0, string.Empty); - } -} - -// Source-generated JSON only: the NativeAOT build (what the installer ships) has reflection-based -// serialization turned off, so JsonSerializer.Deserialize(text, options) failed there and the -// Vaulted Dungeons settings never loaded or saved. Same file format as before (camelCase, -// indented, nulls left out, case-sensitive property names on read). -[JsonSerializable(typeof(IltVaultedDungeons.Cfg))] -[JsonSourceGenerationOptions( - WriteIndented = true, - PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] -internal partial class IltVaultedDungeonsJsonContext : JsonSerializerContext { } diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltWorld.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/IltWorld.cs deleted file mode 100644 index 4defa34..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/IltWorld.cs +++ /dev/null @@ -1,294 +0,0 @@ -// IltWorld.cs - RynthILT's view of the game's objects, read straight from the host. -// -// The ILT Hub read items through RynthAi's WorldObjectCache while it lived in RynthAi. RynthILT -// has no cache of its own events, so this asks the client directly (the way RynthSort's -// InventoryReader does): the player's pack and side packs through GetContainerContents (the -// main pack's list also holds the side packs and the worn and wielded items), everything -// else the client knows through GetLiveObjectIds. Names, classes and container links are taken -// at each scan; property reads (Values) are live. A scan is kept for ScanMs, so the many -// Items() calls of one tick cost one walk; GetDirectInventory(forceRefresh: true) walks again. -// Pump thread only (the render thread only ever sees snapshots the features built). -using System; -using System.Collections.Generic; -using RynthCore.Loot; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// One object as RynthILT sees it: identity from the last scan, properties read live. -internal sealed class WorldObject -{ - private readonly IltObjects _owner; - - internal WorldObject(IltObjects owner, int id, string name, AcObjectClass objectClass, int container) - { - _owner = owner; - Id = id; - Name = name ?? string.Empty; - ObjectClass = objectClass; - DirectContainerId = container; - } - - public int Id { get; } - public string Name { get; } - public AcObjectClass ObjectClass { get; } - - /// The container the scan found it in (the player or a side pack); 0 off the player. - public int DirectContainerId { get; } - - /// The container it is in now (live), else where the scan found it. - public int Container => _owner.ContainerOf(Id, DirectContainerId); - - /// Who wields it (live; 0 = nobody). - public int Wielder => _owner.WielderOf(Id); - - /// Where it is wielded (live; 0 = not wielded). - public int WieldedLocation => _owner.WieldedLocationOf(Id); - - /// An int property, read live ( when unknown). - public int Values(int key, int defaultValue) => _owner.IntProperty(Id, unchecked((uint)key), defaultValue); -} - -/// The player's items and the objects around, from host calls. -internal sealed class IltObjects -{ - // Property and type ids (AC's). - internal const uint IntItemsCapacity = 6; - internal const uint IntCurrentWieldedLocation = 10; - internal const uint IntDamageType = 45; - private const uint ItemTypeCreature = 0x00000010; - private const uint ItemTypeContainer = 0x00000200; - private const long ScanMs = 1000; - private const int MainPackSlots = 102; - - private readonly RynthCoreHost _host; - private uint[] _buf = new uint[512]; - private List _inventory = new(); - private Dictionary _byId = new(); - private long _scannedAt = long.MinValue; - private uint _scannedPlayer; - - public IltObjects(RynthCoreHost host) => _host = host; - - /// Forgets the last scan (logout). - public void Clear() - { - _inventory = new List(); - _byId = new Dictionary(); - _scannedAt = long.MinValue; - _scannedPlayer = 0; - } - - // ── Inventory ─────────────────────────────────────────────────────────── - - /// Everything the player carries or wears (a snapshot, at most ScanMs old). - public IEnumerable GetInventory() => Scan(force: false); - - /// The same walk; reads the client again now. - public IReadOnlyList GetDirectInventory(bool forceRefresh = false) => Scan(forceRefresh); - - /// A carried item by id, else any object the client knows by id (null when it knows none). - public WorldObject? this[int id] - { - get - { - Scan(force: false); - if (_byId.TryGetValue(id, out var wo)) return wo; - uint uid = unchecked((uint)id); - if (id == 0 || !_host.HasGetObjectName || !_host.TryGetObjectName(uid, out string name)) return null; - return new WorldObject(this, id, name, Classify(uid), 0); - } - } - - private List Scan(bool force) - { - long now = Environment.TickCount64; - uint player = _host.GetPlayerId(); - if (!force && player == _scannedPlayer && now - _scannedAt < ScanMs) return _inventory; - _scannedAt = now; - _scannedPlayer = player; - if (player == 0 || !_host.HasGetContainerContents) { _inventory = new(); _byId = new(); return _inventory; } - - var list = new List(256); - var byId = new Dictionary(256); - int pid = unchecked((int)player); - foreach (uint id in Contents(player)) - { - if (id == 0) continue; - uint type = ItemType(id); - Add(list, byId, id, type, pid); - // Side packs: containers with room for items (foci hold none). - if ((type & ItemTypeContainer) == 0) continue; - if (!_host.TryGetObjectIntProperty(id, IntItemsCapacity, out int cap) || cap <= 0) continue; - foreach (uint inner in Contents(id)) - if (inner != 0) Add(list, byId, inner, ItemType(inner), unchecked((int)id)); - } - _inventory = list; - _byId = byId; - return list; - } - - private void Add(List list, Dictionary byId, uint id, uint type, int container) - { - int iid = unchecked((int)id); - if (byId.ContainsKey(iid)) return; - string name = _host.HasGetObjectName && _host.TryGetObjectName(id, out string n) ? n ?? string.Empty : string.Empty; - var wo = new WorldObject(this, iid, name, ClassifyByItemType(type), container); - list.Add(wo); - byId[iid] = wo; - } - - private uint[] Contents(uint container) - { - int n = _host.GetContainerContents(container, _buf); - if (n >= _buf.Length) - { - _buf = new uint[Math.Max(n + 64, _buf.Length * 2)]; - n = _host.GetContainerContents(container, _buf); - } - if (n <= 0) return Array.Empty(); - var ids = new uint[Math.Min(n, _buf.Length)]; - Array.Copy(_buf, ids, ids.Length); - return ids; - } - - // ── The world around ──────────────────────────────────────────────────── - - /// Creatures the client knows (monsters, NPCs, vendors, pets), not carried. - public IEnumerable GetLandscape() => Around(creaturesOnly: true); - - /// Every object the client knows that the player doesn't carry. - public IEnumerable GetLandscapeObjects() => Around(creaturesOnly: false); - - private List Around(bool creaturesOnly) - { - var result = new List(); - if (!_host.HasGetLiveObjectIds) return result; - Scan(force: false); - uint player = _host.GetPlayerId(); - foreach (uint id in _host.GetLiveObjectIds()) - { - if (id == 0 || id == player || _byId.ContainsKey(unchecked((int)id))) continue; - uint type = ItemType(id); - if (creaturesOnly && (type & ItemTypeCreature) == 0) continue; - if (!_host.HasGetObjectName || !_host.TryGetObjectName(id, out string name) || string.IsNullOrEmpty(name)) continue; - result.Add(new WorldObject(this, unchecked((int)id), name, ClassifyByItemType(type), 0)); - } - return result; - } - - /// Metres between two objects (double.MaxValue when either position can't be read). - public double Distance(int id1, int id2) - { - if (!_host.TryGetObjectPosition(unchecked((uint)id1), out uint cell1, out float x1, out float y1, out float z1)) return double.MaxValue; - if (!_host.TryGetObjectPosition(unchecked((uint)id2), out uint cell2, out float x2, out float y2, out float z2)) return double.MaxValue; - float gx1 = ((cell1 >> 24) & 0xFF) * 192f + x1; - float gy1 = ((cell1 >> 16) & 0xFF) * 192f + y1; - float gx2 = ((cell2 >> 24) & 0xFF) * 192f + x2; - float gy2 = ((cell2 >> 16) & 0xFF) * 192f + y2; - float dx = gx1 - gx2, dy = gy1 - gy2, dz = z1 - z2; - double d = Math.Sqrt(dx * dx + dy * dy + dz * dz); - return double.IsFinite(d) ? d : double.MaxValue; - } - - // ── Live reads ────────────────────────────────────────────────────────── - - internal int IntProperty(int id, uint stype, int defaultValue) - => _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(unchecked((uint)id), stype, out int v) ? v : defaultValue; - - internal int ContainerOf(int id, int scanned) - { - if (_host.HasGetObjectOwnershipInfo && _host.TryGetObjectOwnershipInfo(unchecked((uint)id), out uint container, out _, out _)) - return unchecked((int)container); - return scanned; - } - - internal int WielderOf(int id) - { - if (_host.HasGetObjectOwnershipInfo && _host.TryGetObjectOwnershipInfo(unchecked((uint)id), out _, out uint wielder, out _)) - return unchecked((int)wielder); - return _host.HasGetObjectWielderInfo && _host.TryGetObjectWielderInfo(unchecked((uint)id), out uint w, out _) ? unchecked((int)w) : 0; - } - - internal int WieldedLocationOf(int id) - { - if (_host.HasGetObjectOwnershipInfo && _host.TryGetObjectOwnershipInfo(unchecked((uint)id), out _, out uint wielder, out uint location) && wielder != 0) - return unchecked((int)location); - return Math.Max(0, IntProperty(id, IntCurrentWieldedLocation, 0)); - } - - private uint ItemType(uint id) => _host.HasGetItemType && _host.TryGetItemType(id, out uint t) ? t : 0; - - private AcObjectClass Classify(uint id) => ClassifyByItemType(ItemType(id)); - - // ── Packs ─────────────────────────────────────────────────────────────── - - /// - /// A side pack with at least free slots (the one with the most), - /// else the main pack when and it has a slot, else 0. Foci - /// and packs whose capacity isn't known never qualify (a move into a full pack crashes the - /// client). RynthAi's WorldObjectCache.FindPackFor, on this view. - /// - public static int FindPackFor(RynthCoreHost host, IltObjects? objects, bool includeMainPack, int requireFree) - { - if (objects == null) return 0; - int playerId = unchecked((int)host.GetPlayerId()); - if (playerId == 0) return 0; - if (requireFree < 1) requireFree = 1; - var inv = objects.GetDirectInventory(forceRefresh: true); - int bestPack = 0, bestFree = 0, mainUsed = 0; - foreach (var p in inv) - { - if (p.DirectContainerId != playerId) continue; - bool isPack = p.ObjectClass == AcObjectClass.Container; - bool isFoci = p.ObjectClass == AcObjectClass.Foci || p.Name.IndexOf("Foci", StringComparison.OrdinalIgnoreCase) >= 0; - if (!isPack && !isFoci && p.WieldedLocation <= 0 && p.Wielder == 0) mainUsed++; - if (!isPack || isFoci) continue; - int capacity = p.Values(unchecked((int)IntItemsCapacity), 0); - if (capacity <= 0) continue; - int used = 0; - foreach (var it in inv) - if (it.DirectContainerId == p.Id && it.ObjectClass != AcObjectClass.Container) used++; - int free = capacity - used; - if (free >= requireFree && free > bestFree) { bestFree = free; bestPack = p.Id; } - } - if (bestPack != 0) return bestPack; - if (!includeMainPack) return 0; - return MainPackSlots - mainUsed > 0 ? playerId : 0; - } - - // ── Classification (RynthAi's WorldObjectCache.ClassifyByItemType) ────── - - internal static AcObjectClass ClassifyByItemType(uint t) - { - if (t == 0) return AcObjectClass.Unknown; - if ((t & 0x00000010) != 0) return AcObjectClass.Monster; - if ((t & 0x00040000) != 0) return AcObjectClass.TradeNote; - if ((t & 0x00080000) != 0) return AcObjectClass.ManaStone; - if ((t & 0x00001000) != 0) return AcObjectClass.SpellComponent; - if ((t & 0x00000800) != 0) return AcObjectClass.Gem; - if ((t & 0x00004000) != 0) return AcObjectClass.Key; - if ((t & 0x10000000) != 0) return AcObjectClass.Lifestone; - if ((t & 0x40000000) != 0) return AcObjectClass.Salvage; - if ((t & 0x20000000) != 0) return AcObjectClass.Ust; - if ((t & 0x00400000) != 0) return AcObjectClass.BaseCooking; - if ((t & 0x00800000) != 0) return AcObjectClass.BaseAlchemy; - if ((t & 0x02000000) != 0) return AcObjectClass.BaseFletching; - if ((t & 0x04000000) != 0) return AcObjectClass.CraftedAlchemy; - if ((t & 0x08000000) != 0) return AcObjectClass.CraftedFletching; - if ((t & 0x00100000) != 0) return AcObjectClass.Services; - if ((t & 0x00010000) != 0) return AcObjectClass.Portal; - if ((t & 0x00002000) != 0) return AcObjectClass.Book; - if ((t & 0x00000200) != 0) return AcObjectClass.Container; - if ((t & 0x00008000) != 0) return AcObjectClass.WandStaffOrb; - if ((t & 0x00000100) != 0) return AcObjectClass.MissileWeapon; - if ((t & 0x00000002) != 0) return AcObjectClass.Armor; - if ((t & 0x00000001) != 0) return AcObjectClass.MeleeWeapon; - if ((t & 0x00000004) != 0) return AcObjectClass.Clothing; - if ((t & 0x00000008) != 0) return AcObjectClass.Jewelry; - if ((t & 0x00000020) != 0) return AcObjectClass.Food; - if ((t & 0x00000040) != 0) return AcObjectClass.Money; - if ((t & 0x00000080) != 0) return AcObjectClass.Misc; - return AcObjectClass.Unknown; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs deleted file mode 100644 index 7053f4d..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/RynthAiClient.cs +++ /dev/null @@ -1,317 +0,0 @@ -// RynthAiClient.cs - RynthILT's side of the "RynthAi.Hub" interface (Plugins/Shared/RynthAiHubApi.cs): -// the Mini Remote that hosts the ILT tabs, the /myquests tracker, spell names, VTank loot-profile -// matching, the .usd importer and the Mini Remote's session stats. -// -// The table is looked up through the host (API v68) and kept for RecheckMs; Reset() (login, logout, -// shutdown) and a table whose Version went to 0 (RynthAi shut down) force a fresh lookup, so a -// RynthAi that loads after RynthILT, is reloaded or isn't installed is handled: every call then -// reports "no RynthAi" and the ILT features that need it say so. The pointer is kept in a volatile -// field so the render thread (RenderSection) can use what the pump looked up; the table is never -// freed by RynthAi (its Version is zeroed instead), so a stale pointer is safe to read. -using System; -using System.Runtime.InteropServices; -using System.Text; -using RynthCore.Plugin.Shared; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.RynthILT.Hub; - -/// One /myquests flag as RynthAi has it (QuestRecord's fields the Temple tracker reads). -internal sealed class QuestRecord -{ - public string Key = string.Empty; - public int Solves; - public int MaxSolves; - public DateTime CompletedOn = DateTime.MinValue; - public TimeSpan RepeatTime = TimeSpan.Zero; - - /// RynthAi's QuestRecord.IsReady (UB's): the timer ran out and it isn't a once-only flag. - public bool IsReady() - { - if ((CompletedOn + RepeatTime) > DateTime.UtcNow) 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; - } -} - -internal sealed unsafe class RynthAiClient -{ - public const string NotLoaded = "needs RynthAi (not loaded)"; - private const long RecheckMs = 3000; - - private readonly RynthCoreHost _host; - private RynthAiHubApiV1* _t; // pump-thread copy - private IntPtr _renderTable; // what the render thread uses (volatile) - private bool _checked; - private long _checkedAt; - - private bool _pinned; // tests: a table handed in, never looked up - - public RynthAiClient(RynthCoreHost host) => _host = host; - - /// Tests only: use (a fake RynthAi's table) and never look it up. - internal void UseTableForTests(IntPtr table) - { - _pinned = true; - _t = (RynthAiHubApiV1*)table; - _checked = true; - System.Threading.Volatile.Write(ref _renderTable, table); - } - - /// Forget the table; the next call looks it up again (login, logout, RynthAi reload). - public void Reset() - { - if (_pinned) return; - _t = null; - _checked = false; - System.Threading.Volatile.Write(ref _renderTable, IntPtr.Zero); - } - - /// The table, looked up at most every RecheckMs (pump thread). - private RynthAiHubApiV1* Table - { - get - { - if (_pinned) return _t; - long now = Environment.TickCount64; - if (_checked && now - _checkedAt < RecheckMs && (_t == null || _t->Version >= 1)) return _t; - _checked = true; - _checkedAt = now; - _t = null; - if (_host.HasGetPluginInterface) - { - var t = (RynthAiHubApiV1*)_host.GetPluginInterface(RynthAiHub.PluginName, RynthAiHubApiV1.InterfaceName, RynthAiHubApiV1.InterfaceVersion); - if (t != null && t->Version >= 1 && t->StructSize >= RynthAiHubApiV1.BaseStructSize) _t = t; - } - System.Threading.Volatile.Write(ref _renderTable, (IntPtr)_t); - return _t; - } - } - - /// Pump thread: refreshes the lookup (the render thread only reads what this found). - public void Tick() => _ = Table; - - /// True when RynthAi's interface is there (pump thread). - public bool Available => Table != null; - - /// Any thread: the table the pump last found, if RynthAi hasn't shut down since. - private RynthAiHubApiV1* AnyThreadTable - { - get - { - var t = (RynthAiHubApiV1*)System.Threading.Volatile.Read(ref _renderTable); - return t != null && t->Version >= 1 ? t : null; - } - } - - // ── Mini Remote ───────────────────────────────────────────────────────── - - /// Puts the Mini Remote on a tab (any thread). The reply, or why it couldn't. - public string MiniRemoteTab(string tabId, string mode) - { - var t = AnyThreadTable; - if (t == null || t->MiniRemoteTab == null) return "The Mini Remote is RynthAi's; RynthAi isn't loaded."; - byte* reply = stackalloc byte[256]; - reply[0] = 0; - using var id = new Utf8(tabId); - using var m = new Utf8(mode); - int ok = t->MiniRemoteTab(id.P, m.P, reply, 256); - string text = Marshal.PtrToStringUTF8((IntPtr)reply) ?? string.Empty; - return ok != 0 ? text : (text.Length > 0 ? text : "The Mini Remote is not available yet."); - } - - /// True while the Mini Remote is on screen (any thread). - public bool MiniRemoteVisible - { - get - { - var t = AnyThreadTable; - return t != null && t->MiniRemoteVisible != null && t->MiniRemoteVisible() != 0; - } - } - - // ── Vaulted Dungeons (activity) ───────────────────────────────────────── - // The master switch is RynthILT's own since 2026-10-20 (IltHubState.VaultedDungeonsEnabled); - // RynthAi.Hub VaultedDungeonsEnabled is no longer read. - - /// - /// What RynthAi is doing now (its "RynthAi.Activity" interface: combat, buffing, loot, a use or cast - /// waiting on the server...); null when RynthAi isn't loaded or isn't ready. Resolved again every - /// call, as that interface requires (a RynthAi reload frees its table). Pump thread. - /// - public RynthAiActivity? Activity() - { - if (!_host.HasGetPluginInterface) return null; - try - { - var act = (RynthAiActivityApiV1*)_host.GetPluginInterface(RynthAiHub.PluginName, RynthAiActivityApiV1.InterfaceName, RynthAiActivityApiV1.InterfaceVersion); - if (act == null || act->Version < 1 || act->StructSize < (uint)sizeof(RynthAiActivityApiV1) || act->GetActivityFlags == null) return null; - uint flags = 0; - return act->GetActivityFlags(&flags) != 0 ? (RynthAiActivity)flags : null; - } - catch - { - return null; // a RynthAi mid-reload: not there this tick - } - } - - // ── Combat ────────────────────────────────────────────────────────────── - - /// - /// Asks RynthAi to back away from (RynthAi.Hub BackAwayFrom): a - /// RynthAiHub.BackAway* result, or int.MinValue when RynthAi isn't loaded or is older than the - /// call. Pump thread. - /// - public int BackAwayFrom(uint objectId, float radiusYards, int holdMs) - { - var t = Table; - if (t == null || !RynthAiHubApiV1.Has(t, RynthAiHubApiV1.BackAwayFromOffset) || t->BackAwayFrom == null) return int.MinValue; - return t->BackAwayFrom(objectId, radiusYards, holdMs); - } - - /// - /// Reports one player wield counter to RynthAi's loot rules (RynthAi.Hub SetPlayerCounter; the T11 - /// "Can Wield" key): < 0 = unknown. False without RynthAi (or an older one). Pump thread. - /// - public bool SetPlayerCounter(uint propertyId, long value) - { - var t = Table; - return t != null && RynthAiHubApiV1.Has(t, RynthAiHubApiV1.SetPlayerCounterOffset) - && t->SetPlayerCounter != null && t->SetPlayerCounter(propertyId, value) != 0; - } - - // ── Quests (/myquests) ────────────────────────────────────────────────── - - /// A /myquests flag from RynthAi's tracker (pump thread). - public bool TryGetQuestFlag(string key, out QuestRecord rec) - { - rec = null!; - var t = Table; - if (t == null || t->QuestFlag == null || string.IsNullOrWhiteSpace(key)) return false; - QuestFlagV1 f = default; - using var k = new Utf8(key); - if (t->QuestFlag(k.P, &f) == 0) return false; - rec = new QuestRecord - { - Key = key.ToLowerInvariant(), - Solves = f.Solves, - MaxSolves = f.MaxSolves, - CompletedOn = new DateTime(Math.Max(0, f.CompletedOnUtcTicks), DateTimeKind.Utc), - RepeatTime = TimeSpan.FromSeconds(Math.Max(0, f.RepeatSeconds)), - }; - return true; - } - - /// The tracker's state (pump thread); false without RynthAi or before login. - public bool TryGetQuestStatus(out QuestStatusV1 status) - { - status = default; - var t = Table; - if (t == null || t->QuestStatus == null) return false; - QuestStatusV1 s = default; - if (t->QuestStatus(&s) == 0) return false; - status = s; - return true; - } - - /// A quiet /myquests refresh through RynthAi's Quests tab (its cooldown applies). Pump thread. - public string RefreshQuests() - { - var t = Table; - if (t == null || t->QuestRefresh == null) return "The quest tracker " + NotLoaded + "."; - byte* reply = stackalloc byte[256]; - reply[0] = 0; - t->QuestRefresh(reply, 256); - return Marshal.PtrToStringUTF8((IntPtr)reply) ?? string.Empty; - } - - // ── Spells, loot profiles ─────────────────────────────────────────────── - - /// A spell's name from RynthAi's spell table ("" when unknown or no RynthAi). Pump thread. - public string SpellName(int spellId) - { - var t = Table; - if (t == null || t->SpellName == null || spellId <= 0) return string.Empty; - byte* buf = stackalloc byte[160]; - int n = t->SpellName(unchecked((uint)spellId), buf, 160); - return n <= 0 ? string.Empty : Marshal.PtrToStringUTF8((IntPtr)buf) ?? string.Empty; - } - - /// - /// Evaluates a VTank .utl profile on : keep[i] is true when that item's - /// first matching rule is Keep. False (with the reason) when it couldn't. Pump thread. - /// - public bool LootKeeps(string utlPath, uint[] ids, out bool[] keep, out string error) - { - keep = new bool[ids.Length]; - error = string.Empty; - var t = Table; - if (t == null || t->LootKeeps == null) { error = "equipment suits " + NotLoaded; return false; } - byte[] flags = new byte[ids.Length]; - byte* err = stackalloc byte[256]; - err[0] = 0; - int ok; - using (var p = new Utf8(utlPath)) - fixed (uint* pids = ids) - fixed (byte* pf = flags) - ok = t->LootKeeps(p.P, pids, ids.Length, pf, err, 256); - if (ok == 0) { error = Marshal.PtrToStringUTF8((IntPtr)err) ?? "could not read profile"; return false; } - for (int i = 0; i < ids.Length; i++) keep[i] = flags[i] != 0; - return true; - } - - // ── Session stats ─────────────────────────────────────────────────────── - - /// The Mini Remote's session (any thread); false without RynthAi or before login. - public bool TryGetSessionStats(out SessionStatsV1 stats) - { - stats = default; - var t = AnyThreadTable; - if (t == null || t->SessionStats == null) return false; - SessionStatsV1 s = default; - if (t->SessionStats(&s) == 0) return false; - stats = s; - return true; - } - - /// Starts the Mini Remote's session over (any thread). - public void ResetSessionStats() - { - var t = AnyThreadTable; - if (t != null && t->SessionReset != null) t->SessionReset(); - } - - // ── RynthAi's sections drawn in RynthILT's tabs ───────────────────────── - - /// Render thread: draws one of RynthAi's sections; false (nothing drawn) without RynthAi. - public bool RenderSection(string id) - { - var t = AnyThreadTable; - if (t == null || t->RenderSection == null) return false; - using var s = new Utf8(id); - return t->RenderSection(s.P) != 0; - } - - /// A NUL-terminated UTF-8 copy of a string for one call. - private readonly struct Utf8 : IDisposable - { - public readonly byte* P; - - public Utf8(string? s) - { - s ??= string.Empty; - int n = Encoding.UTF8.GetByteCount(s); - P = (byte*)NativeMemory.Alloc((nuint)(n + 1)); - fixed (char* c = s) Encoding.UTF8.GetBytes(c, s.Length, P, n); - P[n] = 0; - } - - public void Dispose() => NativeMemory.Free(P); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/Hub/ServerFeatureGate.cs b/Plugins/RynthCore.Plugin.RynthILT/Hub/ServerFeatureGate.cs deleted file mode 100644 index 3f06a8f..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/Hub/ServerFeatureGate.cs +++ /dev/null @@ -1,115 +0,0 @@ -// ServerFeatureGate.cs — Which worlds get the ILT / infinite-attribute features. -// Originally part of SilentKelpie's ILT Hub in RynthAi; moved to RynthILT 2026-10-13. -// -// One gate for everything ILT-shaped: the Mini Remote's ILT tabs, the Guardian, the Skills -// panel's Progression planners and the attribute raiser. A world is "on" when: -// * its name matches one of the server patterns (IltSettings.ServerNames, '*' wildcard, -// case-insensitive; defaults cover InfiniteLeaftide; "/ilt servers" -// edits them — they were RynthAi's Settings > Misc "Server Features" list), or -// * this character's override is on ("Treat this world as ILT", -// "/ra hub force on"; also set by migration from RynthAi's "Force enable" profile flag). -// The gate only decides whether RynthILT ASKS the server; each feature still follows the -// server's own report (IltServerOptions bits), so a shard with /xp off keeps the raiser off. -using System; -using System.Collections.Generic; -using System.Linq; - -namespace RynthCore.Plugin.RynthILT.Hub; - -internal static class ServerFeatureGate -{ - /// Patterns a fresh install starts with (the names the old hard-coded check accepted). - public static readonly string[] DefaultServerNames = { "InfiniteLeaftide", "*Leaftide*" }; - - /// The patterns in force (null settings: the defaults). - public static IReadOnlyList Patterns(IltSettings? settings) - => settings?.ServerNames is { Count: > 0 } list ? list : DefaultServerNames; - - /// True when matches one of . - public static bool NameMatches(string world, IEnumerable? patterns, out string matched) - { - matched = string.Empty; - if (string.IsNullOrWhiteSpace(world) || patterns == null) return false; - foreach (string p in patterns) - { - if (string.IsNullOrWhiteSpace(p)) continue; - if (!Matches(world.Trim(), p.Trim())) continue; - matched = p.Trim(); - return true; - } - return false; - } - - /// Case-insensitive match where '*' stands for any run of characters (anywhere in the pattern). - public static bool Matches(string text, string pattern) - { - if (pattern.Length == 0) return false; - if (!pattern.Contains('*')) return text.Equals(pattern, StringComparison.OrdinalIgnoreCase); - - string[] parts = pattern.Split('*'); - int pos = 0; - for (int i = 0; i < parts.Length; i++) - { - string part = parts[i]; - if (part.Length == 0) continue; - if (i == 0) - { - if (!text.StartsWith(part, StringComparison.OrdinalIgnoreCase)) return false; - pos = part.Length; - continue; - } - if (i == parts.Length - 1) - return text.Length - pos >= part.Length && text.EndsWith(part, StringComparison.OrdinalIgnoreCase); - int at = text.IndexOf(part, pos, StringComparison.OrdinalIgnoreCase); - if (at < 0) return false; - pos = at + part.Length; - } - return true; - } - - /// - /// RynthILT's own gate: the character's override, or the world name in the list. RynthCore's - /// verdict, once it sends one, takes over in IltServerOptions.IsIltLikeWorld; this stays ours - /// (it is what the status export reports, IltServerOptions.IsIltLikeWorldLocal). - /// - public static bool IsEnabled(string world, IltSettings? settings, bool forceOn) - => forceOn || NameMatches(world, Patterns(settings), out _); - - /// "InfiniteLeaftide, *Leaftide*" → trimmed, de-duplicated list (case-insensitive). - public static List ParseList(string? text) - { - var list = new List(); - if (string.IsNullOrWhiteSpace(text)) return list; - foreach (string raw in text.Split(new[] { ',', ';', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)) - { - string p = raw.Trim(); - if (p.Length > 0 && !list.Contains(p, StringComparer.OrdinalIgnoreCase)) list.Add(p); - } - return list; - } - - public static string FormatList(IEnumerable? patterns) - => patterns == null ? string.Empty : string.Join(", ", patterns.Where(p => !string.IsNullOrWhiteSpace(p))); - - /// One status line: the world, whether the features are on, and why. - public static string Describe(string world, IltSettings? settings, bool forceOn) - { - world = (world ?? string.Empty).Trim(); - string shown = world.Length > 0 ? $"'{world}'" : "(not logged in)"; - var engine = IltSettingsView.IltEngineVerdict.Server; - if (engine != null) - { - string why = engine.Force == "on" ? "forced on for this character" - : engine.Force == "off" ? "forced off for this character" - : engine.Detected ? "RynthCore recognises the world" : "RynthCore doesn't recognise the world"; - return $"This world {shown}: {(engine.Active ? "ON" : "OFF")} - {why}."; - } - if (NameMatches(world, Patterns(settings), out string matched)) - return $"This world {shown}: ON - matches '{matched}'."; - if (forceOn) - return $"This world {shown}: ON - \"Treat this world as ILT\" is ticked."; - return world.Length > 0 - ? $"This world {shown}: OFF - not in the list. Add it, or tick \"Treat this world as ILT\"." - : "This world: not logged in yet."; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/HubInterface.cs b/Plugins/RynthCore.Plugin.RynthILT/HubInterface.cs deleted file mode 100644 index 48b69f0..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/HubInterface.cs +++ /dev/null @@ -1,280 +0,0 @@ -// HubInterface.cs - RynthILT's side of the "RynthILT.Hub" interface (Plugins/Shared/RynthIltHubApi.cs): -// the table RynthPluginQueryInterface hands RynthAi, and the functions behind it. -// -// The table is allocated once per loaded copy of RynthILT and never freed (a plugin DLL is never -// unloaded, so its functions stay callable): RynthAi's render thread may still hold the pointer -// while plugins shut down, and every function here returns "nothing" once Release() has run -// (Version 0, no plugin). Threads as the interface says: the render-thread functions draw into -// the caller's current ImGui window; the pump-thread Command runs the ILT verb at once. -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; -using System.Threading; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT; - -internal static unsafe class HubInterface -{ - private static RynthIltHubApiV1* _table; - private static volatile bool _released; - - /// The live controller, or null (before login, after logout, after shutdown). - private static IltHubController? Hub => _released ? null : PluginExports.Runtime.Plugin?.Hub; - - /// The table for (, ), or 0 when it isn't ours. - public static IntPtr Query(string iface, uint version) - { - // Its own name, and the neutral one RynthAi asks the active server's owner for (the same table). - if ((iface != RynthIltHubApiV1.InterfaceName && iface != RynthIltHubApiV1.NeutralInterfaceName) - || version < 1 || version > RynthIltHubApiV1.InterfaceVersion || _released) - return IntPtr.Zero; - if (_table == null) - { - var t = (RynthIltHubApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthIltHubApiV1)); - t->StructSize = (uint)sizeof(RynthIltHubApiV1); - t->IsIltWorld = &IsIltWorld; - t->GetFeature = &GetFeature; - t->GetRates = &GetRates; - t->GetForceIlt = &GetForceIlt; - t->SetForceIlt = &SetForceIlt; - t->GetTabs = &GetTabs; - t->RenderTab = &RenderTab; - t->RenderSection = &RenderSection; - t->Command = &Command; - t->AllowSummonOnEmpty = &AllowSummonOnEmpty; - t->GetSubTabs = &GetSubTabs; - t->GetSetting = &GetSetting; - t->SetSetting = &SetSetting; - t->GetText = &GetText; - t->Version = RynthIltHubApiV1.InterfaceVersion; - _table = t; - } - return (IntPtr)_table; - } - - /// Plugin shutdown: callers see Version 0 and re-query; the functions answer "nothing". - public static void Release() - { - _released = true; - if (_table != null) _table->Version = 0; - } - - private static string? Utf8(byte* p) => p == null ? null : Marshal.PtrToStringUTF8((IntPtr)p); - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int IsIltWorld() - { - try { return Hub?.Options.IsIltLikeWorld == true ? 1 : 0; } - catch { return 0; } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GetFeature(byte* key) - { - try - { - var hub = Hub; - string? k = Utf8(key); - if (hub == null || string.IsNullOrEmpty(k) || !hub.Options.IsIltLikeWorld) return -1; - return (int)hub.Options.Get(k); - } - catch { return -1; } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GetRates(double* coinsPerHour, double* pyrealsPerHour) - { - try - { - var hub = Hub; - if (hub == null || !hub.Options.IsIltLikeWorld) return 0; - var r = hub.Rates.Summary; - if (coinsPerHour != null) *coinsPerHour = r.CoinsPerHour; - if (pyrealsPerHour != null) *pyrealsPerHour = r.PyrealsPerHour; - return 1; - } - catch { return 0; } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GetForceIlt() - { - try { return Hub?.ForceIltWorld == true ? 1 : 0; } - catch { return 0; } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static void SetForceIlt(int on) - { - try - { - var hub = Hub; - if (hub != null) hub.ForceIltWorld = on != 0; - } - catch { } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GetTabs(IltTabV1* tabs, int capacity) - { - try - { - var hub = Hub; - if (hub == null) return 0; - var all = IltSections.Tabs; - if (tabs != null) - { - for (int i = 0; i < all.Length && i < capacity; i++) - { - IltSection s = all[i]; - IltTabV1* t = &tabs[i]; - WriteUtf8(IltSections.TabId(s), t->Id, 24); - WriteUtf8(IltSections.Label(s), t->Label, 32); - var size = IltSections.TabSize(s); - t->Width = size.X; - t->Height = size.Y; - uint flags = 0; - if (hub.TabShown(s)) flags |= RynthIltHub.TabShown; - if (hub.SectionAvailable(s)) flags |= RynthIltHub.TabAvailable; - t->Flags = flags; - } - } - return all.Length; - } - catch { return 0; } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int RenderTab(byte* id) - { - try - { - var hub = Hub; - if (hub == null || !IltSections.TryParse(Utf8(id) ?? string.Empty, out IltSection s) || !IltSections.IsTab(s)) return 0; - hub.RenderTab(s); - return 1; - } - catch (Exception ex) - { - RynthLog.Exception(LogCat.IltHub, ex, "RenderTab"); - return 0; - } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int RenderSection(byte* id) - { - try - { - var hub = Hub; - string? s = Utf8(id); - return hub != null && s != null && hub.RenderSection(s) ? 1 : 0; - } - catch (Exception ex) - { - RynthLog.Exception(LogCat.IltHub, ex, "RenderSection"); - return 0; - } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int Command(byte* text) - { - try - { - var plugin = _released ? null : PluginExports.Runtime.Plugin; - string? line = Utf8(text); - if (plugin == null || string.IsNullOrWhiteSpace(line) || line.Length > 512) return 0; - return plugin.RunForwardedCommand(line) ? 1 : 0; - } - catch { return 0; } - } - - /// The Pets tab's summon-from-empty gate (IltPetAutomation's last tick; 0 off ILT). - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int AllowSummonOnEmpty() - { - try { return Hub?.PetAutomation.AllowSummonOnEmpty == true ? 1 : 0; } - catch { return 0; } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GetSubTabs(byte* parent, IltTabV1* tabs, int capacity) - { - try - { - var hub = Hub; - string? p = Utf8(parent); - if (hub == null || p == null) return 0; - var all = hub.SubTabs(p); - if (tabs != null) - { - for (int i = 0; i < all.Length && i < capacity; i++) - { - IltTabV1* t = &tabs[i]; - WriteUtf8(all[i].Id, t->Id, 24); - WriteUtf8(all[i].Label, t->Label, 32); - t->Width = 0; - t->Height = 0; - t->Flags = RynthIltHub.TabShown | RynthIltHub.TabAvailable; - } - } - return all.Length; - } - catch { return 0; } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GetSetting(byte* key) - { - try - { - var hub = Hub; - string? k = Utf8(key); - return hub == null || k == null ? -1 : hub.GetSetting(k); - } - catch { return -1; } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int SetSetting(byte* key, int value) - { - try - { - var hub = Hub; - string? k = Utf8(key); - return hub != null && k != null && hub.SetSetting(k, value) ? 1 : 0; - } - catch { return 0; } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GetText(byte* id, byte* buffer, int capacity) - { - try - { - var hub = Hub; - string? k = Utf8(id); - if (hub == null || k == null || buffer == null || capacity <= 0) return 0; - string text = hub.GetText(k); - if (text.Length == 0) { buffer[0] = 0; return 0; } - WriteUtf8(text, buffer, capacity); - int n = 0; - while (n < capacity && buffer[n] != 0) n++; - return n; - } - catch { return 0; } - } - - /// Writes as NUL-terminated UTF-8 into a fixed buffer, truncated to fit. - private static void WriteUtf8(string s, byte* dest, int capacity) - { - byte[] bytes = Encoding.UTF8.GetBytes(s); - int n = Math.Min(bytes.Length, capacity - 1); - for (int i = 0; i < n; i++) dest[i] = bytes[i]; - dest[n] = 0; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipCommands.cs b/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipCommands.cs deleted file mode 100644 index ef919a4..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipCommands.cs +++ /dev/null @@ -1,62 +0,0 @@ -// IltFellowshipCommands.cs - Infinite Leaftide's fellowship chat commands (ACECustom /fship). -// -// ACECustom (Source/ACE.Server/Command/Handlers/PlayerCommands.cs, "fship") adds these on top -// of retail's fellowship panel; its fellowships hold up to 29 (Fellowship.MaxFellows). The list -// is kept in the shared "servercommands" form (Plugins/Shared/ServerCommandShare.cs) and drawn by -// RynthILT's fellowship window (IltFellowshipUi, "/ilt fellow"). -// A name with spaces is sent quoted; ACE's command parser joins "two words". Pure: no ImGui, no host. -using System; -using System.Collections.Generic; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT.IltFellowship; - -internal static class IltFellowshipCommands -{ - /// The RynthCore section the commands belong to. - public const string Section = "fellowship"; - - /// RynthCore's server id for Infinite Leaftide. - public const string ServerId = "ilt"; - - /// The server's display name. - public const string ServerName = "Infinite Leaftide"; - - /// ACECustom's fellowship size (Fellowship.MaxFellows; retail is 9). - public const int MaxFellows = 29; - - /// The /fship commands, in button order. - public static readonly IReadOnlyList Commands = new[] - { - new ServerCommand("Create", "/fship create", "A", - "Create a fellowship with the name in the box (you lead it). Up to " + MaxFellows + " members on ILT."), - new ServerCommand("Invite", "/fship add", "a", - "Invite the player named in the box, or your selected player when the box is empty."), - new ServerCommand("Dismiss", "/fship remove", "ac", - "Leader: remove the player named in the box, or your selected player when the box is empty."), - new ServerCommand("Invite landblock", "/fship landblock", "c", - "Invite every player in your landblock (not in the Marketplace). Over level 50, only level 50+ players are invited."), - new ServerCommand("List nearby", "/fship list", "", - "The fellowships in your area and their leaders (wider in VOD and T10). Once every 10 seconds."), - new ServerCommand("Leave", "/fship leave", "c", - "Leave your fellowship."), - new ServerCommand("Disband", "/fship disband", "c", - "Leader: disband your fellowship."), - new ServerCommand("Help", "/fship", "", - "The server's /fship help."), - }; - - /// The set while ILT is active; with no commands when it isn't (a receiver drops it). - public static ServerCommandSet Set(bool active) => - new(Section, ServerId, ServerName, active ? Commands : Array.Empty()); - - /// The "servercommands" payload for . - public static string Payload(bool active) => ServerCommandShare.Build(Set(active)); - - /// - /// ILT is active: RynthCore's verdict once it has sent one (), - /// else the world name has "Leaftide" in it (RynthCore's default ILT names). - /// - public static bool IsActive(bool? engineActive, string? worldName) => - engineActive ?? (worldName ?? string.Empty).IndexOf("Leaftide", StringComparison.OrdinalIgnoreCase) >= 0; -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipUi.cs b/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipUi.cs deleted file mode 100644 index 6c009c9..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/IltFellowship/IltFellowshipUi.cs +++ /dev/null @@ -1,44 +0,0 @@ -// IltFellowshipUi.cs - The "ILT fellowship" view: Infinite Leaftide's /fship commands as buttons. -// -// Drawn in its own window ("/ilt fellow"). Clicks queue the chat command for the plugin tick. -// Render thread only. -using System; -using System.Numerics; -using ImGuiNET; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT.IltFellowship; - -internal sealed class IltFellowshipUi -{ - private const string WindowTitle = "ILT fellowship (RynthILT)##rynthilt_fellowship"; - - private static readonly ServerCommandSet Set = IltFellowshipCommands.Set(active: true); - - private readonly ServerCommandPanel _panel = new("iltfship"); - private readonly Func _send; - - /// The standalone window is open ("/ilt fellow"). - public bool WindowOpen; - - /// Queues a chat command for the plugin tick; false when it can't. - public IltFellowshipUi(Func send) => _send = send; - - /// The standalone window, while open. - public void RenderWindow() - { - if (!WindowOpen) return; - ImGui.SetNextWindowSize(new Vector2(420, 170), ImGuiCond.FirstUseEver); - bool open = WindowOpen; - if (ImGui.Begin(WindowTitle, ref open)) RenderBody(); - ImGui.End(); - WindowOpen = open; - } - - /// The view's content, into the current window. - public void RenderBody() - { - SafeImGui.TextDisabled("Infinite Leaftide /fship (up to " + IltFellowshipCommands.MaxFellows + " members)"); - _panel.Render(Set, _send); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltSectionsManifest.cs b/Plugins/RynthCore.Plugin.RynthILT/IltSectionsManifest.cs deleted file mode 100644 index 5cfac69..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/IltSectionsManifest.cs +++ /dev/null @@ -1,129 +0,0 @@ -// IltSectionsManifest.cs - What RynthILT adds to RynthCore's Mini Remote sections (RynthPluginGetSectionsJson, -// schema 1: UI/Sections/SectionManifest.cs in RynthCore). -// -// always (Infinite Leaftide views, shown while RynthCore treats this world as ILT) -// Session Stats ("char") the ILT session extras section:ilt-rates -// Fellowship ILT's /fship commands section:ilt-fellowship -// Quests (RynthILT's own) the /qb list section:ilt-questbonus -// while the Hub shows them (an ILT world; each once the server reports its feature) -// Inventory Gear, Charms, Banking section:gear|charms|banking -// Games (RynthILT's own) Games section:games -// Nav Vaulted Dungeons (master switch) section:vaulted -// The Mini Remote tabs were listed by RynthAi, which hosted them, until 2026-10-20; RynthILT lists and -// draws them itself now (RynthPluginRenderEmbed "section:"), so RynthAi's manifest names no -// server's tabs. Their names stay the same, so "/rc miniremote tab charms|banking" finds them. -// Pure: the tabs come in as a list, so the tests build it offline. -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Text.Json; -using RynthCore.Plugin.RynthILT.Hub; - -namespace RynthCore.Plugin.RynthILT; - -internal static class IltSectionsManifest -{ - /// RynthCore's id for Infinite Leaftide. - public const string Server = "ilt"; - - /// One Mini Remote tab as the Hub has it now. - internal readonly record struct Tab(string Id, float Width, float Height, bool Shown, bool Available); - - private const string NotReportedNote = "Shows once the server reports this ILT feature on (the ILT settings can ask again)."; - - /// Where each tab goes: section, label, order, tooltip. A tab not listed here isn't offered. - internal static readonly Dictionary Placement = new() - { - ["gear"] = ("inventory", "Gear", 210, "ILT gear tools (RynthILT)."), - ["charms"] = ("inventory", "Charms", 220, "ILT charms and Guardian Hands: acquired, status, tier, toggles (RynthILT)."), - ["banking"] = ("inventory", "Banking", 230, "Your ILT bank: balances, deposits, withdrawals and transfers (RynthILT)."), - ["games"] = ("games", "Games", 100, "ILT games (RynthILT)."), - // Listed only while the Hub shows the tab: the master switch is on, on an ILT world. - ["vaulted"] = ("nav", "Vaulted Dungeons", 220, - "Keep the character in one Vaulted Dungeon (RynthILT; master switch: /ilt settings or Settings > Navigation)."), - }; - - /// The surface of a tab's view ("section:gear"). - public static string SurfaceOf(string tabId) => "section:" + tabId; - - /// The tab a "section:<tab>" surface draws, when it names one placed here. - public static bool TryTabOf(string surface, out IltSection section) - { - section = IltSection.Gear; - if (!surface.StartsWith("section:", System.StringComparison.Ordinal)) return false; - string id = surface.Substring("section:".Length); - if (!Placement.ContainsKey(id) || !IltSections.TryParse(id, out section) || !IltSections.IsTab(section)) return false; - return IltSections.TabId(section) == id; - } - - /// The Hub's tabs now (empty without a Hub). Render thread. - public static List TabsOf(IltHubController? hub) - { - var list = new List(); - if (hub == null) return list; - foreach (IltSection s in IltSections.Tabs) - { - var size = IltSections.TabSize(s); - list.Add(new Tab(IltSections.TabId(s), size.X, size.Y, hub.TabShown(s), hub.SectionAvailable(s))); - } - return list; - } - - /// The manifest JSON (UTF-8 text, schema 1). - public static string Build(IReadOnlyList tabs) - { - using var stream = new MemoryStream(4096); - using (var w = new Utf8JsonWriter(stream)) - { - w.WriteStartObject(); - w.WriteNumber("version", 1); - w.WriteStartArray("sections"); - Section(w, "quests", "Quests", 1160); - Section(w, "games", "Games", 1150); - w.WriteEndArray(); - w.WriteStartArray("contributions"); - View(w, "char", "ILT session rates (RynthILT)", RynthILTPlugin.RatesSurface, primary: false, 0, 220, enabled: true, note: "", - "Enlightened Coins, pyreals and item conversions this session, on the same clock as RynthAi's session stats (RynthILT).", 120); - View(w, "fellowship", "ILT fellowship (RynthILT)", RynthILTPlugin.FellowshipSurface, primary: false, 0, 110, enabled: true, note: "", - "Infinite Leaftide's /fship commands: create, invite, dismiss, invite your landblock, list nearby, leave, disband (RynthILT; also /ilt fellow).", 120); - View(w, "quests", "Quest bonus (/qb)", RynthILTPlugin.QuestBonusSurface, primary: true, 520, 440, enabled: true, note: "", - "Infinite Leaftide's quest bonus list: completed and incomplete /qb flags (RynthILT; the quest list, timers and rewards are RynthOracle's, /ro).", 100); - foreach (Tab t in tabs) - { - if (!t.Shown || !Placement.TryGetValue(t.Id, out var place)) continue; - View(w, place.Section, place.Label, SurfaceOf(t.Id), primary: true, t.Width, t.Height, t.Available, - t.Available ? string.Empty : NotReportedNote, place.Tooltip, place.Order); - } - w.WriteEndArray(); - w.WriteEndObject(); - } - return Encoding.UTF8.GetString(stream.ToArray()); - } - - private static void Section(Utf8JsonWriter w, string id, string label, int order) - { - w.WriteStartObject(); - w.WriteString("id", id); - w.WriteString("label", label); - w.WriteNumber("order", order); - w.WriteEndObject(); - } - - private static void View(Utf8JsonWriter w, string section, string label, string surface, bool primary, float width, float height, - bool enabled, string note, string tooltip, int order) - { - w.WriteStartObject(); - w.WriteString("section", section); - w.WriteString("server", Server); - w.WriteString("label", label); - w.WriteString("surface", surface); - w.WriteBoolean("primary", primary); - if (width > 0) w.WriteNumber("width", width); - if (height > 0) w.WriteNumber("height", height); - w.WriteBoolean("enabled", enabled); - if (note.Length > 0) w.WriteString("note", note); - if (tooltip.Length > 0) w.WriteString("tooltip", tooltip); - w.WriteNumber("order", order); - w.WriteEndObject(); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltEngineVerdict.cs b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltEngineVerdict.cs deleted file mode 100644 index f14c026..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltEngineVerdict.cs +++ /dev/null @@ -1,32 +0,0 @@ -// IltEngineVerdict.cs - RynthCore's Infinite Leaftide verdict as RynthILT last heard it. -// -// RynthCore decides whether this world is ILT once, for itself and every plugin, with this -// character's Auto / On / Off override ("/rc server ilt"). RynthILT reads that verdict from the -// engine's server list (plugin API v86, GetServerStateJson; the plugin tick polls it into -// IltSettingsModel.Engine). The Hub's world check (IltServerOptions, ServerFeatureGate) follows it -// once one has arrived; before that, or on an engine older than v86, RynthILT's own server list -// and "Treat this world as ILT" decide. -// -// RynthILT's status export must keep reporting its own verdict, not this one: the engine adds -// RynthILT's verdict to its detection, and an echo would keep ILT on after "/rc ilt auto". -// Any thread: one volatile reference read. -using System.Threading; - -namespace RynthCore.Plugin.RynthILT.IltSettingsView; - -internal static class IltEngineVerdict -{ - private static IltSettingsModel? _model; - - /// The model the plugin feeds from RynthCore's server list (RynthILTPlugin's constructor). - public static void Attach(IltSettingsModel? model) => Volatile.Write(ref _model, model); - - /// RynthCore has sent its server list at least once since login (it may list no ILT). - public static bool Pushed => Volatile.Read(ref _model)?.Engine != null; - - /// RynthCore's ILT entry; null until a RynthCore with the server list (v86) has sent one. - public static IltServerView? Server => Volatile.Read(ref _model)?.Engine?.Server; - - /// RynthCore's verdict for this world; null when it hasn't given one. - public static bool? Active => Server?.Active; -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsModel.cs b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsModel.cs deleted file mode 100644 index 9f9076a..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsModel.cs +++ /dev/null @@ -1,114 +0,0 @@ -// IltSettingsModel.cs - RynthILT's copy of the Infinite Leaftide settings (the "ILT settings" view). -// -// Nothing here is decided by RynthILT; it shows and edits what others own: -// * RynthCore owns the world verdict, this character's Auto / On / Off override and the ILT -// world-name list. RynthILT reads the verdict from its server list (plugin API v86, -// GetServerStateJson, parsed by Plugins/Shared/EngineServerState.cs): the plugin tick polls -// it every 2 s and publishes the "ilt" entry here (ApplyServerState). The world names aren't -// in that list; "/rc server names ilt" prints them. Edits go back as RynthCore commands: -// "/rc server ilt auto|on|off" and "/rc server names ilt add|remove ". -// * RynthILT's own Hub reads which ILT features the server has on; the plugin tick publishes -// them (PublishFeatures). -// Each is one immutable snapshot published with a single reference write, so the render thread -// always reads a whole one. Pure (no host calls): RynthILT.Tests covers it. -using System; -using System.Collections.Generic; -using System.Threading; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT.IltSettingsView; - -/// RynthCore's verdict for Infinite Leaftide. -internal sealed record IltServerView(string Name, bool Active, string Force, bool Detected, string Reason); - -/// What RynthCore's server list says: the ILT verdict (null if it lists no "ilt"). -internal sealed record IltEngineView(IltServerView? Server); - -/// The Hub's server read: the world, its last check, and each feature (-1 unknown, 0 off, 1 on). -internal sealed record IltFeatureView(string World, string Source, string LastCheck, bool Checking, bool IltLike, - KeyValuePair[] Features); - -internal sealed class IltSettingsModel -{ - /// RynthCore's id for Infinite Leaftide. - public const string ServerId = EngineServerState.IltId; - - /// Longest pattern RynthCore keeps (EngineSettings.MaxIltServerNameLength). - public const int MaxPattern = 64; - - /// The RynthCore command that prints the ILT world names (and hosts) in chat. - public const string NamesListCommand = "/rc server names " + ServerId; - - private IltEngineView? _engine; - private IltFeatureView? _features; - - /// The last server list from RynthCore (null until one arrives). Any thread. - public IltEngineView? Engine => Volatile.Read(ref _engine); - - /// The last feature read (null until the Hub publishes one). Any thread. - public IltFeatureView? Features => Volatile.Read(ref _features); - - /// RynthCore's server list (GetServerStateJson); null (no answer) keeps the last one. Any thread. - public void ApplyServerState(EngineServerState? state) - { - IltEngineView? view = FromServerState(state); - if (view != null) Volatile.Write(ref _engine, view); - } - - /// The Hub's own feature read (plugin tick); null clears it. Any thread. - public void PublishFeatures(IltFeatureView? view) => Volatile.Write(ref _features, view); - - /// Logout: the next character's world and features come fresh. - public void Clear() - { - Volatile.Write(ref _engine, null); - Volatile.Write(ref _features, null); - } - - /// The ILT verdict from RynthCore's server list; null for no list. - public static IltEngineView? FromServerState(EngineServerState? state) - { - if (state == null) return null; - EngineServer? s = state.Find(ServerId); - return new IltEngineView(s == null ? null - : new IltServerView(s.Name.Length > 0 ? s.Name : "Infinite Leaftide", s.Active, NormalizeForce(s.Force), s.Detected, s.Reason)); - } - - /// "auto", "on" or "off" (anything else is shown as auto). - public static string NormalizeForce(string? force) => (force ?? string.Empty).Trim().ToLowerInvariant() switch - { - "on" => "on", - "off" => "off", - _ => "auto", - }; - - /// The RynthCore command that sets this character's override; "" for an unknown mode. - public static string ForceCommand(string mode) => mode switch - { - "auto" or "on" or "off" => "/rc server " + ServerId + " " + mode, - _ => string.Empty, - }; - - /// - /// The RynthCore command that adds or removes a world-name pattern, or "" (with - /// ) when the pattern can't be sent: empty, longer than - /// , or with a control character or '/' (it is spliced into a command). - /// - public static string NamesCommand(bool add, string? pattern, out string error) - { - error = string.Empty; - string p = (pattern ?? string.Empty).Trim(); - if (p.Length == 0) { error = "Enter a world name ('*' matches any text)."; return string.Empty; } - if (p.Length > MaxPattern) { error = $"At most {MaxPattern} characters."; return string.Empty; } - foreach (char c in p) - if (char.IsControl(c) || c == '/' || c >= 128) - { - error = "World names are plain text (no '/', line breaks or special characters)."; - return string.Empty; - } - return "/rc server names " + ServerId + (add ? " add " : " remove ") + p; - } - - /// A feature's state as text. - public static string StateText(int value) => value switch { 1 => "on", 0 => "off", _ => "unknown" }; -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs deleted file mode 100644 index 187cc48..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs +++ /dev/null @@ -1,237 +0,0 @@ -// IltSettingsUi.cs - The "ILT settings" view: RynthILT's copy of the Infinite Leaftide settings. -// -// Drawn in its own window ("/ilt settings"). Shows RynthCore's verdict and reason, this character's -// Auto / On / Off override, the ILT world names (edited through RynthCore), this character's ILT -// options (the settings that moved here from RynthAi on 2026-10-20: the Empyrean Handler ring -// evade, ...; saved in the Hub's state), and every ILT feature with the state RynthILT's Hub read -// from the server (IltSettingsModel has where each comes from). -// Edits are RynthCore commands, queued for the plugin tick; the next server-list poll shows the -// result. Render thread only. -using System; -using System.Collections.Generic; -using System.Numerics; -using ImGuiNET; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT.IltSettingsView; - -internal sealed class IltSettingsUi -{ - private static readonly Vector4 Teal = new(0.30f, 0.85f, 0.80f, 1f); - private static readonly Vector4 Mute = new(0.60f, 0.62f, 0.66f, 1f); - private static readonly Vector4 Warn = new(0.95f, 0.55f, 0.45f, 1f); - - private const string WindowTitle = "ILT settings (RynthILT)##rynthilt_settings"; - - private readonly IltSettingsModel _model; - private readonly Action _runCommand; - private readonly Func _refreshFeatures; - private readonly Func _hub; - private string _newName = string.Empty; - private string _status = string.Empty; - - /// The standalone window is open ("/ilt settings"). - public bool WindowOpen; - - /// Queues a RynthCore command (run on the plugin tick). - /// Asks the Hub to read the server's features again; false before it exists. - /// This character's Hub (its options live in the Hub's state); null before login. - public IltSettingsUi(IltSettingsModel model, Action runCommand, Func refreshFeatures, Func? hub = null) - { - _model = model; - _runCommand = runCommand; - _refreshFeatures = refreshFeatures; - _hub = hub ?? (() => null); - } - - /// The standalone window, while open. - public void RenderWindow() - { - if (!WindowOpen) return; - ImGui.SetNextWindowSize(new Vector2(440, 480), ImGuiCond.FirstUseEver); - bool open = WindowOpen; - if (ImGui.Begin(WindowTitle, ref open)) RenderBody(); - ImGui.End(); - WindowOpen = open; - } - - /// The view's content, into the current window. - public void RenderBody() - { - RenderVerdict(); - ImGui.Separator(); - RenderCharacterOptions(); - ImGui.Separator(); - RenderFeatures(); - if (_status.Length > 0) - { - ImGui.Separator(); - SafeImGui.TextWrapped(_status); - } - } - - private void RenderVerdict() - { - IltEngineView? engine = _model.Engine; - if (engine == null) - { - ImGui.TextWrapped("Waiting for RynthCore's server list (it needs plugin API v86). Until then RynthILT's own " - + "world list and this character's 'Treat this world as ILT' (/ra hub force on|off) decide."); - return; - } - - IltServerView? s = engine.Server; - if (s == null) - { - ImGui.TextDisabled("RynthCore doesn't list Infinite Leaftide."); - } - else - { - SafeImGui.TextColored(s.Active ? Teal : Mute, s.Active ? s.Name + ": on for this world" : s.Name + ": not this world"); - if (s.Reason.Length > 0) - { - ImGui.PushStyleColor(ImGuiCol.Text, Mute); - SafeImGui.TextWrapped(s.Reason); - ImGui.PopStyleColor(); - } - - // Read only: a server is forced in one place, RynthCore Options > Diagnostics (2026-10-13). - string force = s.Force switch { "on" => "forced on", "off" => "forced off", _ => "auto (detected)" }; - SafeImGui.TextDisabled("This character: " + force + " (change it in RynthCore Options > Diagnostics)"); - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("RynthCore's server selection (Options > Diagnostics) forces a server for this character,\nor /rc server ilt auto|on|off in chat."); - } - - ImGui.Spacing(); - ImGui.TextUnformatted("ILT world names"); - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Worlds whose name matches one of these count as Infinite Leaftide ('*' matches any text).\nThe launch host is checked too. Kept by RynthCore for every character."); - ImGui.SameLine(); - if (ImGui.SmallButton("List in chat##iltnames")) - { - _runCommand(IltSettingsModel.NamesListCommand); - _status = "RynthCore lists the names in chat (" + IltSettingsModel.NamesListCommand + ")."; - } - ImGui.SetNextItemWidth(220); - bool enter = ImGui.InputTextWithHint("##iltnewname", "world name, * = any text", ref _newName, (uint)IltSettingsModel.MaxPattern, - ImGuiInputTextFlags.EnterReturnsTrue); - ImGui.SameLine(); - if (ImGui.Button("Add##iltname") || enter) - { - string cmd = IltSettingsModel.NamesCommand(true, _newName, out string err); - if (Send(cmd, err, "Adding '" + _newName.Trim() + "'...")) _newName = string.Empty; - } - ImGui.SameLine(); - if (ImGui.Button("Remove##iltname")) - { - string cmd = IltSettingsModel.NamesCommand(false, _newName, out string err); - if (Send(cmd, err, "Removing '" + _newName.Trim() + "'...")) _newName = string.Empty; - } - } - - /// - /// This character's Infinite Leaftide options: the ones that were RynthAi settings until - /// 2026-10-20 (copied over once). Saved with the Hub's state. - /// - private void RenderCharacterOptions() - { - ImGui.TextUnformatted("This character"); - IltHubController? hub = _hub(); - if (hub == null) - { - ImGui.TextDisabled("Shown once this character is logged in."); - return; - } - IltHubState st = hub.State; - bool vaulted = st.VaultedDungeonsEnabled; - if (ImGui.Checkbox("Vaulted Dungeons (the keeper's master switch)##iltvaulted", ref vaulted)) st.VaultedDungeonsEnabled = vaulted; - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("Off by default. While off the Vaulted Dungeons keeper does nothing: no recalls, no /rc quit, no Mini\n" - + "Remote tab. On: the \"Vaulted Dungeons\" tab shows, where you pick a dungeon and a tied Portal Recall\n" - + "Gem and start it (/ilt vaulted on). Also in RynthCore's Settings > Navigation (it was a RynthAi setting)."); - bool ring = st.Combat.HandlerRingEvade; - if (ImGui.Checkbox("Evade the Empyrean Handler's lethal ring##iltring", ref ring)) st.Combat.HandlerRingEvade = ring; - if (ImGui.IsItemHovered()) - ImGui.SetTooltip("When an Empyrean Handler channels its lethal ring and you are within 12 yards (or RynthAi's\n" - + "Ring Range if larger), RynthAi back-jumps away and re-engages. Only while RynthAi's macro\n" - + "is running with combat on. On by default (it was RynthAi's \"Evade Handler Ring\")."); - int augs = st.T11.ItemAugsOverride; - SafeImGui.TextDisabled(augs >= 0 - ? $"T11 item augmentations: fixed at {augs:N0} for RynthAi's loot rules (/ilt t11 augs auto to read /aug)" - : "T11 item augmentations: read from /aug (/ilt t11 augs fixes them; /ilt t11 shows the counters)"); - } - - /// - /// The server's ILT features, one collapsible section per group (Character, Items, Pets, - /// Fellowship, Combat, Activities, then the charms and any other bit chat or a probe set), with - /// how many are on and each feature's state; the tooltip says where the Rynth tools handle it. - /// - private void RenderFeatures() - { - IltFeatureView? f = _model.Features; - ImGui.TextUnformatted("Server features"); - ImGui.SameLine(); - if (ImGui.SmallButton("Refresh##iltfeatures")) - _status = _refreshFeatures() ? "Checking the server again..." : "Not ready yet (log in first)."; - if (f == null) - { - ImGui.TextWrapped("RynthILT reads which ILT features the server has on once this character is logged in. Not read yet."); - return; - } - - string when = f.Checking ? "checking the server..." : f.LastCheck.Length == 0 ? "not checked yet" : "checked " + f.LastCheck; - SafeImGui.TextDisabled((f.World.Length > 0 ? f.World : "unknown world") + " - " + when - + (f.Source.Length > 0 ? " (" + f.Source + ")" : string.Empty)); - if (!f.IltLike) ImGui.TextDisabled("This world isn't treated as Infinite Leaftide, so the server isn't asked."); - if (f.Features.Length == 0) - { - ImGui.TextDisabled("The server hasn't reported any ILT features yet."); - return; - } - - var groups = new Dictionary>(StringComparer.Ordinal); - foreach (var kv in f.Features) - { - var (label, group, tooltip) = IltFeatureCatalog.Describe(kv.Key); - if (!groups.TryGetValue(group, out var rows)) groups[group] = rows = new(); - rows.Add((label, tooltip, kv.Value)); - } - foreach (string group in FeatureGroups()) - { - if (!groups.TryGetValue(group, out var rows)) continue; - int on = 0, off = 0; - foreach (var r in rows) { if (r.State == 1) on++; else if (r.State == 0) off++; } - if (!ImGui.CollapsingHeader($"{group} ({on} of {rows.Count} on)##iltfg_{group}")) continue; - for (int i = 0; i < rows.Count; i++) - { - var r = rows[i]; - SafeImGui.TextColored(r.State == 1 ? Teal : r.State == 0 ? Warn : Mute, IltSettingsModel.StateText(r.State)); - ImGui.SameLine(80); - SafeImGui.Text(r.Label); - if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(r.Tooltip); - } - } - } - - /// The feature sections in display order: the catalog's groups, then Charms and Other. - private static IEnumerable FeatureGroups() - { - foreach (string g in IltFeatureCatalog.Groups) yield return g; - yield return IltFeatureCatalog.GroupCharms; - yield return IltFeatureCatalog.GroupOther; - } - - /// Queues , or shows when it is empty. - private bool Send(string command, string error, string pending) - { - if (command.Length == 0) - { - _status = error; - return false; - } - _runCommand(command); - _status = pending; - return true; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs deleted file mode 100644 index 2f8d57d..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs +++ /dev/null @@ -1,312 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Threading; -using RynthCore.PluginCore; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.RynthILT; - -public static unsafe class PluginExports -{ - internal static readonly RynthPluginRuntime Runtime = new(); - - // Typed interfaces (host GetPluginInterface, API v68): "RynthILT.Hub" v1, the ILT tabs and - // sections RynthAi's Mini Remote hosts (Plugins/Shared/RynthIltHubApi.cs, HubInterface.cs), and - // "RynthServer.Profile" v1, ILT's settings and tinkering salvage for any reader, as every server - // plugin serves its own (Plugins/Shared/RynthServerProfileApi.cs, ProfileInterface.cs), and - // "RynthILT.Data" v1..v3, the charms list and bank balances with their actions, the pet breeding - // tracker and the Temple guardians (Plugins/Shared/RynthIltDataApi.cs, DataInterface.cs), and - // "RynthILT.Server" v1, the Leaftide feature / fellowship / quest bonus profile RynthOracle reads - // (Plugins/Shared/RynthIltServerApi.cs, ServerInterface.cs). - // Fixed signature: void* (const char* iface, uint version). - [UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })] - private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version) - { - try - { - string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? ""; - IntPtr table = HubInterface.Query(iface, version); - if (table != IntPtr.Zero) return table; - table = ServerInterface.Query(iface, version); - if (table != IntPtr.Zero) return table; - table = ProfileInterface.Query(iface, version); - return table != IntPtr.Zero ? table : DataInterface.Query(iface, version); - } - catch - { - return IntPtr.Zero; - } - } - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })] - private static int Init(RynthCoreApiNative* api) => Runtime.Init(api); - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void Shutdown() - { - // An exception escaping an UnmanagedCallersOnly export fail-fasts the client under NativeAOT. - try { Runtime.Shutdown(); } catch { } - try { HubInterface.Release(); } catch { } - try { ServerInterface.Release(); } catch { } - try { ProfileInterface.Release(); } catch { } - try { DataInterface.Release(); } catch { } - foreach (IntPtr p in new[] { Interlocked.Exchange(ref _bountiesPtr, IntPtr.Zero), Interlocked.Exchange(ref _progressionPtr, IntPtr.Zero), - Interlocked.Exchange(ref _statusPtr, IntPtr.Zero), Interlocked.Exchange(ref _sectionsPtr, IntPtr.Zero) }) - if (p != IntPtr.Zero) Marshal.FreeCoTaskMem(p); - _sectionsJson = null; - } - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetName() => RynthILTPlugin.NamePointer; - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetVersion() => RynthILTPlugin.VersionPointer; - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void Tick() => Runtime.OnTick(); - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void OnLoginComplete() => Runtime.OnLoginComplete(); - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void OnLogout() => Runtime.OnLogout(); - - // Bounty lines (and eating the reply to the tracker's own /bounty list). - [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) - => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag); - - // The ILT Hub's floating windows (Games HUD, confirmations) in the engine's ImGui frame. - [UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void Render() => Runtime.OnRender(); - - /// The 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 */ } - } - - /// - /// Engine panels drawn by RynthILT (render thread): "guardian" is the engine's Guardian ILT - /// panel (RynthCore's GuardianFace); "section:ilt-rates" (the ILT session extras, Session Stats), - /// "section:ilt-fellowship" (the /fship commands), "section:ilt-questbonus" (the /qb list, - /// RynthILT's Quests section) and "section:ilt-settings" (the ILT settings, for an engine that - /// still asks) are RynthCore's Mini Remote sections. ":popout" is added when one is popped out - /// into a window of its own, and RynthILT draws in the engine's current context either way. The - /// Guardian panel is user-sized (want echoes the size given); a section reports the height it - /// used. "section:gear|charms|banking|games|vaulted" are the Mini Remote ILT tabs as RynthCore's - /// section views (RynthILT lists them since 2026-10-20; RynthAi did before), sized to the tab. - /// 1 = drawn, 0 = not ready / unknown surface. - /// - [UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })] - public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight) - { - try - { - if (surface == null) return 0; - ReadOnlySpan name = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(surface); - if (name.EndsWith(":popout"u8)) name = name[..^":popout"u8.Length]; - var plugin = Runtime.Plugin; - if (plugin == null) return 0; - if (name.SequenceEqual("guardian"u8)) - { - if (!plugin.RenderEmbeddedGuardian()) return 0; - if (wantWidth != null) *wantWidth = width; - if (wantHeight != null) *wantHeight = height; - return 1; - } - string? view = name.SequenceEqual("section:ilt-settings"u8) ? RynthILTPlugin.SettingsSurface - : name.SequenceEqual("section:ilt-fellowship"u8) ? RynthILTPlugin.FellowshipSurface - : name.SequenceEqual("section:ilt-rates"u8) ? RynthILTPlugin.RatesSurface - : name.SequenceEqual("section:ilt-questbonus"u8) ? RynthILTPlugin.QuestBonusSurface - : null; - if (view == null) - { - // "section:gear", "section:banking", ...: the Mini Remote ILT tabs RynthILT lists (IltSectionsManifest). - if (name.Length > 64 || !name.StartsWith("section:"u8)) return 0; - if (!plugin.RenderEmbeddedTab(System.Text.Encoding.UTF8.GetString(name), out float tabW, out float tabH)) return 0; - if (wantWidth != null) *wantWidth = tabW > 0 ? tabW : width; - if (wantHeight != null) *wantHeight = tabH > 0 ? tabH : height; - return 1; - } - if (!plugin.RenderEmbedded(view, out float wantH)) return 0; - if (wantWidth != null) *wantWidth = width; - if (wantHeight != null) *wantHeight = wantH; - return 1; - } - catch - { - return 0; // an exception crossing UnmanagedCallersOnly would fail-fast the client - } - } - - // "/ilt ..." commands, and noticing a /bounty the player typed (its reply is never eaten). - [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) - => Runtime.OnChatBarEnter(textUtf16, eatFlag); - - // Creatures' health from the server (siphon auto-capture's fallback health read, IltPetAutomation). - [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) - => Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth); - - // This character's kills re-read the bounty list (while the Bounties window is open). - [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnKillNotification", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void OnKillNotification(IntPtr textUtf16) => Runtime.OnKillNotification(textUtf16); - - // ── Bounties bridge (the engine's ImGui Bounties window, UI/Data/BountiesData.cs) ────── - // UTF-8 both ways. Polling the getter is what keeps the tracker's reads running, so only - // the engine's Bounties source may call it (on the plugin pump, 1 s, on ILT only). - // Alloc-new → swap → free-old: the previous reply stays valid until the next call. - - private static IntPtr _bountiesPtr = IntPtr.Zero; - - /// The tracked bounties as JSON (BountyBridgePayload); 0 before login. - [UnmanagedCallersOnly(EntryPoint = "RynthILTGetBountiesJson", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetBountiesJson() - { - try - { - string? json = Runtime.Plugin?.Bounties?.BuildJson(); - return json == null ? IntPtr.Zero : Utf8Swap(ref _bountiesPtr, json); - } - catch { return IntPtr.Zero; } - } - - /// "refresh" or "set {option} {value}" (BountyTracker.Command). - [UnmanagedCallersOnly(EntryPoint = "RynthILTBountyCommand", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void BountyCommand(IntPtr utf8Text) - { - try - { - if (utf8Text == IntPtr.Zero) return; - string? text = Marshal.PtrToStringUTF8(utf8Text); - if (string.IsNullOrEmpty(text) || text.Length > 256) return; - Runtime.Plugin?.Bounties?.Command(text); - } - catch { } - } - - // ── The ILT Hub for the engine (the Skills panel's Progression tab, IltInfo) ───────── - - private static IntPtr _progressionPtr = IntPtr.Zero; - - /// - /// The Skills panel's Progression tab (ILT augmentations / enlightenment / the attribute raiser), - /// as RynthAi's RynthPluginGetProgressionJson was: {"available":false} until the Hub exists and - /// off ILT. UTF-8; the previous reply stays valid until the next call. Engine pump thread only. - /// - [UnmanagedCallersOnly(EntryPoint = "RynthILTGetProgressionJson", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetProgressionJson() - { - try - { - string json = Runtime.Plugin?.Hub?.BuildProgressionJson() ?? "{\"available\":false}"; - return Utf8Swap(ref _progressionPtr, json); - } - catch { return IntPtr.Zero; } - } - - /// - /// One command from the engine (UTF-8): "prog ..." (the Progression tab's edits) or an ILT - /// "/ra" verb without "/ra" ("hub refresh", "guardian handin"). Engine pump thread. - /// - [UnmanagedCallersOnly(EntryPoint = "RynthILTCommand", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void Command(IntPtr utf8Text) - { - try - { - if (utf8Text == IntPtr.Zero) return; - string? text = Marshal.PtrToStringUTF8(utf8Text); - if (string.IsNullOrWhiteSpace(text) || text.Length > 512) return; - Runtime.Plugin?.RunEngineCommand(text); - } - catch { } - } - - /// - /// (action, value) from the engine's plugin-command broker (Host.SendPluginCommand): "prog" with - /// the Progression tab's arguments (RynthAi forwards an older engine's "prog" here), or an ILT - /// verb. Copied and run on RynthILT's next tick. - /// - [UnmanagedCallersOnly(EntryPoint = "RynthPluginApplyRemoteCommand", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void ApplyRemoteCommand(IntPtr actionAnsi, IntPtr valueAnsi) - { - try - { - string action = actionAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(actionAnsi) ?? string.Empty) : string.Empty; - if (action.Length == 0 || action.Length > 32) return; - var plugin = Runtime.Plugin; - if (plugin == null) return; - if (RynthILTPlugin.IsParsedRemoteAction(action)) - { - // RynthCore's "servermenu" push (a few KB): answered here, never queued as an ILT verb. - plugin.ApplyRemoteCommand(action, valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty); - return; - } - string value = valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty; - if (action.Length + value.Length > 512) return; - plugin.EnqueueRemoteCommand(action, value); - } - catch { /* never let a managed exception cross the native boundary */ } - } - - private static IntPtr _statusPtr = IntPtr.Zero; - - /// - /// What RynthILT knows about the world (UTF-8 JSON, previous reply valid until the next call): - /// {"loaded":true,"ilt":bool,"forced":bool,"available":bool,"world":"..."}. "ilt" is RynthILT's - /// own verdict (its server list or this character's "Treat this world as ILT"), never the - /// engine's verdict echoed back: the engine's IltInfo adds it to its own detection, and an - /// echo would keep ILT on after "/rc ilt auto". Engine pump thread. - /// - [UnmanagedCallersOnly(EntryPoint = "RynthILTGetStatusJson", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetStatusJson() - { - try - { - var hub = Runtime.Plugin?.Hub; - string json = hub == null - ? "{\"loaded\":true,\"ilt\":false,\"forced\":false,\"available\":false,\"world\":\"\"}" - : "{\"loaded\":true,\"ilt\":" + (hub.Options.IsIltLikeWorldLocal ? "true" : "false") - + ",\"forced\":" + (hub.ForceIltWorld ? "true" : "false") - + ",\"available\":" + (hub.Available ? "true" : "false") - + ",\"world\":\"" + RynthCore.Plugin.RynthILT.Hub.IltStyle.JsonEscape(hub.Options.WorldName) + "\"}"; - return Utf8Swap(ref _statusPtr, json); - } - catch { return IntPtr.Zero; } - } - - private static IntPtr _sectionsPtr = IntPtr.Zero; - private static string? _sectionsJson; - - /// - /// RynthCore 2026.10.5.46+ (optional): what RynthILT adds to the Mini Remote's sections (UTF-8 - /// JSON, schema 1; RynthILTPlugin.BuildSectionsJson). Null before login. An unchanged manifest - /// keeps the same buffer. - /// - [UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSectionsJson", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetSectionsJson() - { - try - { - string? json = Runtime.Plugin?.BuildSectionsJson(); - if (json == null) return IntPtr.Zero; - if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr; - _sectionsJson = json; - return Utf8Swap(ref _sectionsPtr, json); - } - catch { return IntPtr.Zero; } - } - - private static IntPtr Utf8Swap(ref IntPtr slot, string json) - { - IntPtr newPtr = Marshal.StringToCoTaskMemUTF8(json); - IntPtr oldPtr = Interlocked.Exchange(ref slot, newPtr); - if (oldPtr != IntPtr.Zero) Marshal.FreeCoTaskMem(oldPtr); - return newPtr; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/ProfileInterface.cs b/Plugins/RynthCore.Plugin.RynthILT/ProfileInterface.cs deleted file mode 100644 index 6398efd..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/ProfileInterface.cs +++ /dev/null @@ -1,105 +0,0 @@ -// ProfileInterface.cs - RynthILT's side of "RynthServer.Profile" (Plugins/Shared/RynthServerProfileApi.cs): -// Infinite Leaftide's settings as JSON for other plugins, the same interface and JSON writer the -// server plugins use (Plugins/Shared/ServerPack/ServerPackProfile.cs). RynthCore's GetServerStateJson -// names RynthILT as the owner of "ilt"; a reader (RynthAi's Crafting tab, ...) then asks it for this. -// The profile carries ILT's tinkering salvage (Hub/IltSalvage.cs). -// -// As ServerPackInterface: the table is allocated once per loaded copy of RynthILT and never freed; -// after Release() it reports Version 0 and GetProfileJson answers 0. Before the Hub is up the profile -// still describes the server (active false, no world). -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; -using System.Threading; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.Plugin.ServerPack; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT; - -internal static unsafe class ProfileInterface -{ - private static RynthServerProfileApiV1* _table; - private static volatile bool _released; - - /// What RynthILT knows about its server (identity from the csproj's manifest properties). - internal static readonly ServerPackInfo Info = - new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) - { - Emulator = "ACE", - Salvage = IltSalvage.Rows, - // Leaftide trinkets (UB-IT's IsLeaftideTrinketJewelry): the Crafting tab's Trinkets bench, not Jewelry. - TrinketNames = IltSalvage.TrinketNames, - TrinketExcept = IltSalvage.TrinketExcept, - Source = "RynthILT; salvage from UB-IT's LeaftideImbueHelper (via SilentKelpie)", - }; - - /// The last JSON handed out, and what it was built for (rebuilt only when that changes). - private sealed record Snapshot(bool Active, string World, string Json); - private static Snapshot? _last; - - /// The table for (, ), or 0 when it isn't ours. - public static IntPtr Query(string iface, uint version) - { - if (iface != RynthServerProfileApiV1.InterfaceName || version < 1 || version > RynthServerProfileApiV1.InterfaceVersion || _released) - return IntPtr.Zero; - if (_table == null) - { - var t = (RynthServerProfileApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerProfileApiV1)); - t->StructSize = (uint)sizeof(RynthServerProfileApiV1); - t->GetProfileJson = &GetProfileJson; - t->Version = RynthServerProfileApiV1.InterfaceVersion; - _table = t; - } - return (IntPtr)_table; - } - - /// Plugin shutdown: readers see Version 0 and re-query; GetProfileJson answers 0. - public static void Release() - { - _released = true; - if (_table != null) _table->Version = 0; - } - - /// - /// The JSON to hand out for RynthILT's verdict () and the world name. - /// Any thread. - /// - internal static string CurrentJson(bool active, string? world) - { - world ??= string.Empty; - Snapshot? last = Volatile.Read(ref _last); - if (last != null && last.Active == active && last.World == world) return last.Json; - string json = ServerPackProfile.BuildJson(Info, RynthPluginInfo.Name, RynthPluginInfo.Version, active, world); - Volatile.Write(ref _last, new Snapshot(active, world, json)); - return json; - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GetProfileJson(byte* buffer, int capacity) - { - try - { - if (_released) return 0; - IltHubController? hub = PluginExports.Runtime.Plugin?.Hub; - string json = CurrentJson(hub?.Options.IsIltLikeWorld == true, hub?.Options.WorldName); - return Write(json, buffer, capacity); - } - catch { return 0; } - } - - /// - /// Copies as NUL-terminated UTF-8 into the caller's buffer when it fits, - /// and returns its byte length either way (length >= capacity: too small, nothing written). - /// - internal static int Write(string json, byte* buffer, int capacity) - { - int length = Encoding.UTF8.GetByteCount(json); - if (buffer == null || capacity <= length) return length; - fixed (char* src = json) - Encoding.UTF8.GetBytes(src, json.Length, buffer, capacity); - buffer[length] = 0; - return length; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj b/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj deleted file mode 100644 index 03e6930..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj +++ /dev/null @@ -1,135 +0,0 @@ - - - - - net10.0-windows - x86 - win-x86 - Library - true - enable - true - Shared - true - Size - false - RynthCore.Plugin.RynthILT - RynthCore.Plugin.RynthILT - x86 - - 66 - - ilt - Infinite Leaftide - infiniteleaftide.online - InfiniteLeaftide|*Leaftide* - Infinite Leaftide (ACECustom) features: the ILT Hub (the Mini Remote's ILT tabs: banking, gear, charms, games, Vaulted Dungeons; the Pets tab's charms, siphon capture and breeding), the Guardian, bounties, progression, the attribute raiser, the ring inscription chain, the Empyrean Handler ring evade, the T11 loot counters, the ILT settings and the /fship fellowship commands. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthILT/RynthILTJsonContext.cs b/Plugins/RynthCore.Plugin.RynthILT/RynthILTJsonContext.cs deleted file mode 100644 index 81a0c77..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/RynthILTJsonContext.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Text.Json.Serialization; -using RynthCore.Plugin.RynthILT.Bounty; - -namespace RynthCore.Plugin.RynthILT; - -// Source-generated System.Text.Json only: never reflection-serialize plugin types (the -// reflection cache keeps the old plugin generation alive across a hot reload). -[JsonSerializable(typeof(BountyState))] -[JsonSerializable(typeof(BountyBridgePayload))] -[JsonSourceGenerationOptions( - IncludeFields = true, - PropertyNameCaseInsensitive = true)] -internal partial class RynthILTJsonContext : JsonSerializerContext { } diff --git a/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs b/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs deleted file mode 100644 index eacb5c2..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs +++ /dev/null @@ -1,1011 +0,0 @@ -// RynthILTPlugin.cs - Infinite Leaftide (ACECustom) features, kept out of RynthAi and the engine core. -// -// Two features, both shown only on ILT: -// * Bounties (Bounty/BountyTracker.cs): the engine's Bounties window (the bar's ILT button, -// /rc bounties). Its reads run only while that window polls RynthILTGetBountiesJson, and the -// engine polls only on ILT. -// * The ILT Hub (Hub/, SilentKelpie's, moved here from RynthAi 2026-10-13): the Mini Remote's -// ILT tabs (Banking, Gear, Charms, Games; RynthAi's Mini Remote hosts them through -// RynthILT.Hub, HubInterface.cs, and lists them on RynthCore's sections rail; the Gear tab has -// the Rings inscription chain; the Character tab moved to RynthOracle's Character tab), its -// own Mini Remote sections (BuildSectionsJson: the ILT session extras in Session Stats, the -// /fship buttons in Fellowship, the /qb list in a Quests section), its sections in RynthAi's -// Pets / Remote tabs, the Guardian panel (RynthPluginRenderEmbed "guardian"), -// the Skills panel's Progression data (RynthILTGetProgressionJson, "prog ..." through -// RynthILTCommand), server feature detection, and the charms and bank balances for other -// plugins ("RynthILT.Data", DataInterface.cs). Every feature stays dormant off an ILT-like -// world (IltServerOptions: no probes, no chat). -// -// Second: a copy of the ILT settings (IltSettingsView/): RynthCore's verdict, this character's -// override (read only: it is set in RynthCore Options > Diagnostics), the ILT world names and -// every feature the Hub read from the server, in its own window ("/ilt settings"). The verdict -// comes from RynthCore's server list (plugin API v86, polled every 2 s), and the Hub follows it -// once one arrives (IltEngineVerdict). -// -// Moved from RynthAi on 2026-10-20 (Hub/): the Pets tab's ACECustom parts (IltPetAutomation), the -// Empyrean Handler ring detection (IltRingEvade; RynthAi.Hub BackAwayFrom does the jump), the T11 -// "/aug" counters and "/ilt t11" (IltT11; RynthAi.Hub SetPlayerCounter), the Vaulted Dungeons -// master switch, the Remote tab's ILT parts, and the Mini Remote ILT tab views on RynthCore's rail -// (IltSectionsManifest.cs, RenderEmbeddedTab). Their settings were copied once from the -// character's RynthAi files (IltMigration.ImportRynthAiSettings, at the Hub's start). -// -// Third: ILT's fellowship commands (IltFellowship/, ACECustom /fship) as buttons in RynthCore's -// Fellowship section and their own window ("/ilt fellow"). While ILT is active the list is also -// sent to RynthAi ("servercommands"), whose Fellowship view draws them; an empty list clears it. -// -// Threads: OnTick, OnChatWindowText, OnKillNotification, login/logout and the engine's export calls -// run on the plugin pump. OnChatBarEnter runs on AC's main thread (the engine's dispatcher queues it -// there, our own InvokeChatParser too), and RynthAi forwards its "/ra hub ..." verbs from there too, -// so commands only queue and run on the next tick. OnRender / RenderEmbed and the RynthILT.Hub -// render functions run on the render thread and only read what the pump built; the settings and -// fellowship windows queue their chat commands for the tick. -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Runtime.InteropServices; -using ImGuiNET; -using RynthCore.Plugin.RynthILT.Bounty; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.Plugin.RynthILT.IltFellowship; -using RynthCore.Plugin.RynthILT.IltSettingsView; -using RynthCore.Plugin.Shared; -using RynthCore.PluginCore; - -namespace RynthCore.Plugin.RynthILT; - -public sealed class RynthILTPlugin : RynthPluginBase -{ - internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthILT"); - // Previous release: 0.3.2. - internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.3"); - - /// - /// The settings view's surface. Not in the sections manifest (the force-server override lives - /// only in RynthCore Options > Diagnostics), but still drawn for an engine that asks. - /// - internal const string SettingsSurface = "section:ilt-settings"; - - /// The ILT session extras' surface in RynthCore's Mini Remote "Session Stats" section. - internal const string RatesSurface = "section:ilt-rates"; - - /// The fellowship commands' surface in RynthCore's Fellowship section. - internal const string FellowshipSurface = "section:ilt-fellowship"; - - /// - /// The quest bonus list (/qb) in RynthILT's own Mini Remote "Quests" section (it was part of - /// RynthAi's Quests tab, which moved to RynthOracle; Infinite Leaftide's /qb stays RynthILT's). - /// - internal const string QuestBonusSurface = "section:ilt-questbonus"; - - /// RynthAi's name for the plugin-command broker (its Fellowship view draws our commands). - private const string RynthAiPlugin = "RynthAi"; - - private readonly IltSettingsModel _settingsModel = new(); - private readonly IltSettingsUi _settingsUi; - private readonly IltFellowshipUi _fellowshipUi; - // Chat commands from the settings and fellowship windows (render thread), run on the next tick. - private readonly ConcurrentQueue _chatCommands = new(); - private const int MaxQueuedChatCommands = 32; - - public RynthILTPlugin() - { - _settingsUi = new IltSettingsUi(_settingsModel, cmd => QueueChatCommand(cmd), RefreshFeatures, () => _hub); - _fellowshipUi = new IltFellowshipUi(QueueChatCommand); - IltEngineVerdict.Attach(_settingsModel); - } - - /// Render thread: queues a chat command for the tick; false when the engine can't run one. - private bool QueueChatCommand(string command) - { - if (!Host.HasInvokeChatParser || _chatCommands.Count >= MaxQueuedChatCommands) return false; - _chatCommands.Enqueue(command); - return true; - } - - /// Wait this long after login for the character's name before tracking without a save file. - private const long NameWaitMs = 30_000; - private const long NameRetryMs = 1_000; - - private bool _loginComplete; - private long _loginAtMs; - private long _nextNameTryMs; - private long _nextHubTryMs; - private BountyTracker? _bounties; - private IltHubController? _hub; - // An unfinished copy from RynthAi (IltMigration pending): the Hub writes nothing for this - // character and the copy is retried every MigrationRetryMs; once it works the Hub restarts on - // the copied files. - private const long MigrationRetryMs = 120_000; - private volatile bool _hubWritesBlocked; - private long _nextMigrationRetryMs; - private string _hubFolder = string.Empty, _hubWorld = string.Empty, _hubChar = string.Empty; - private bool _forceOnRestart; - private RynthAiClient? _ai; - private IltSettings _settings = new(); - - // "/ilt ..." lines from OnChatBarEnter and RynthAi's forwarded "/ra" verbs, run on the next tick. - private readonly ConcurrentQueue _commands = new(); - // "/bounty ..." lines from OnChatBarEnter (typed by the player, or our own coming back through - // the engine's dispatcher), passed to the tracker before the next chat line or tick. - private readonly ConcurrentQueue _typedBounty = new(); - // Engine / plugin commands (RynthPluginApplyRemoteCommand: "prog ..." from RynthAi or an older engine). - private readonly ConcurrentQueue _engineCommands = new(); - - /// The Bounties window's tracker (PluginExports); null until login. - internal BountyTracker? Bounties => _bounties; - - /// The ILT Hub for the logged-in character (HubInterface, PluginExports); null until its name is known. - internal IltHubController? Hub => _hub; - - public override int Initialize() - { - RynthLog.Init(Host); - // The Hub's windows and RynthAi-hosted tabs draw through the engine's cimgui module. - ImGuiNativeBinding.Ensure(msg => RynthLog.Write(LogCat.IltHub, msg)); - // Every use goes through Host.UseFor (Plugins/Shared/UseAudit.cs): one log line each. - UseAudit.Reset("RynthILT", null); - // Saves (Hub state, bank log, profiles, settings, bounty list, the copies from RynthAi) say - // when they fail and why (Plugins/Shared/DataWriteGuard.cs): always in the log, in chat - // once per folder, and only on an ILT world (PostDataWriteProblems). - DataWriteGuard.Reset(); - DataWriteGuard.PluginName = "RynthILT"; - DataWriteGuard.LogSink = msg => RynthLog.Write(LogCat.IltStore, - msg.StartsWith("[RynthILT] ", StringComparison.Ordinal) ? msg.Substring(11) : msg); - _ai = new RynthAiClient(Host); - _settings = IltSettingsStore.Load(); - Host.Log("[RynthILT] Plugin initialized."); - return 0; - } - - // Also called on a freshly (re)loaded plugin while already in game. - public override void OnLoginComplete() - { - SaveBounties(); - StopHub(); - _bounties = null; - _loginComplete = true; - _loginAtMs = Environment.TickCount64; - _nextNameTryMs = 0; - _nextHubTryMs = 0; - _ai?.Reset(); - PollServerState(force: true); - TryStartBounties(); - TryStartHub(); - } - - public override void OnLogout() - { - SaveBounties(); - _bounties = null; - StopHub(); - _ai?.Reset(); - _loginComplete = false; - ClearSharedFellowshipCommands(); - while (_commands.TryDequeue(out _)) { } - while (_typedBounty.TryDequeue(out _)) { } - while (_engineCommands.TryDequeue(out _)) { } - while (_chatCommands.TryDequeue(out _)) { } - _settingsModel.Clear(); - _serverStateJson = string.Empty; - } - - // Plugin unload (hot reload, update, client closing): keep the list and the Hub state for the - // next copy. No broker call while the engine unloads us: RynthAi drops the fellowship commands - // once they stop arriving (ServerCommandModel.StaleMs). - public override void Shutdown() - { - SaveBounties(); - StopHub(); - HubInterface.Release(); - IltEngineVerdict.Attach(null); - RynthLog.Shutdown(); - } - - public override void OnTick() - { - try { RynthLog.Pump(); } catch { } - if (!_loginComplete) return; - _ai?.Tick(); - PollServerState(force: false); - if (_bounties == null) TryStartBounties(); - if (_hub == null) TryStartHub(); - DrainTypedBounty(); - while (_commands.TryDequeue(out string[]? parts)) RunCommand(parts); - while (_engineCommands.TryDequeue(out string? engineCommand)) RunEngineCommand(engineCommand); - DrainChatCommands(); - _bounties?.Tick(); - try { _hub?.Tick(); } - catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "Tick"); } - RetryPendingMigration(); - PostDataWriteProblems(); - try { PublishHubFeatures(); } - catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "PublishHubFeatures"); } - try { ShareFellowshipCommands(); } - catch (Exception ex) { Host.Log($"[RynthILT] Fellowship commands to RynthAi failed: {ex.Message}"); } - } - - // ── ILT fellowship commands for RynthAi's Fellowship view (IltFellowship/) ── - - private const long FellowshipShareCheckMs = 2000; - private const long FellowshipShareResendMs = 10_000; - private long _fellowshipShareNextAt; - private long _fellowshipShareSentAt; - // The last payload RynthAi took; empty when nothing was delivered (or after a clear). - private string _fellowshipShareLast = string.Empty; - - /// - /// Plugin tick: sends RynthAi ILT's fellowship commands while ILT is active (an empty list when - /// it isn't), when that changes and every (RynthAi may load - /// later, and drops a list that stops arriving). Nothing on an engine without the broker. - /// - private void ShareFellowshipCommands() - { - if (!Host.HasSendPluginCommand) return; - long now = Environment.TickCount64; - if (now < _fellowshipShareNextAt) return; - _fellowshipShareNextAt = now + FellowshipShareCheckMs; - - bool active = IltActive(); - // Nothing to clear when RynthAi never got a list. - if (!active && _fellowshipShareLast.Length == 0) return; - string payload = IltFellowshipCommands.Payload(active); - if (payload == _fellowshipShareLast && now - _fellowshipShareSentAt < FellowshipShareResendMs) return; - _fellowshipShareSentAt = now; - // Not delivered (RynthAi not installed or not loaded yet): the resend timer tries again. - if (Host.SendPluginCommand(RynthAiPlugin, ServerCommandShare.Action, payload)) - _fellowshipShareLast = active ? payload : string.Empty; - } - - /// Clears RynthAi's copy of the fellowship commands (logout) if it has one. - private void ClearSharedFellowshipCommands() - { - if (_fellowshipShareLast.Length == 0) return; - _fellowshipShareLast = string.Empty; - _fellowshipShareNextAt = 0; - try - { - if (Host.HasSendPluginCommand) - Host.SendPluginCommand(RynthAiPlugin, ServerCommandShare.Action, IltFellowshipCommands.Payload(active: false)); - } - catch { /* RynthAi drops a list that stops arriving */ } - } - - /// - /// The Hub's world check (RynthCore's verdict once it has one, else RynthILT's server list and - /// "Treat this world as ILT"); before the Hub exists, the engine verdict or the world name - /// (IltFellowshipCommands.IsActive). - /// - private bool IltActive() - { - var hub = _hub; - if (hub != null) return hub.Options.IsIltLikeWorld; - bool? engine = IltEngineVerdict.Active; - string world = engine == null && Host.HasGetWorldName && Host.TryGetWorldName(out string w) ? w : string.Empty; - return IltFellowshipCommands.IsActive(engine, world); - } - - // ── RynthCore's Mini Remote sections ───────────────────────────────────── - - /// - /// The broker actions answered on arrival rather than queued for the tick: RynthCore's - /// "servermenu" push (2026.10.5.47+, every 10 s) and the older "iltfeatures" text. - /// - internal static bool IsParsedRemoteAction(string action) => - action.Equals("servermenu", StringComparison.OrdinalIgnoreCase) - || action.Equals("iltfeatures", StringComparison.OrdinalIgnoreCase); - - /// - /// RynthPluginApplyRemoteCommand "servermenu" / "iltfeatures". Any thread. Taken and dropped: - /// the same verdicts, overrides and world names reach the settings model from RynthCore's - /// server list (plugin API v86, PollServerState), which RynthILT reads itself, so the push is - /// only acknowledged (it must not fall through to the ILT verbs). - /// - internal void ApplyRemoteCommand(string action, string value) { } - - /// - /// RynthPluginRenderEmbed: (Session Stats), - /// (Fellowship), (RynthILT's Quests section) or - /// in RynthCore's Mini Remote, drawn into the engine's current - /// window and context (popped-out windows have their own). is the - /// height it used. False until login or for another surface. Render thread. - /// - internal bool RenderEmbedded(string surface, out float wantHeight) - { - wantHeight = 0; - if (!_loginComplete) return false; - Action? body = surface switch - { - SettingsSurface => _settingsUi.RenderBody, - FellowshipSurface => _fellowshipUi.RenderBody, - RatesSurface => RenderRatesSurface, - QuestBonusSurface => RenderQuestBonusSurface, - _ => null, - }; - if (body == null) return false; - IntPtr previous = ImGui.GetCurrentContext(); - IntPtr context = previous != IntPtr.Zero ? previous : Host.ImGuiContext; - if (context == IntPtr.Zero) return false; - ImGui.SetCurrentContext(context); - try - { - float startY = ImGui.GetCursorPosY(); - body(); - wantHeight = MathF.Max(40f, ImGui.GetCursorPosY() - startY + 4f); - return true; - } - catch (Exception ex) - { - Host.Log($"[RynthILT] View {surface} failed: {ex.Message}"); - return false; - } - finally { ImGui.SetCurrentContext(previous); } - } - - /// The ILT session extras (render thread), or a line saying they start with the Hub. - private void RenderRatesSurface() - { - IltHubController? hub = _hub; - if (hub == null) { ImGui.TextDisabled("ILT session rates start once RynthILT's Hub is ready."); return; } - hub.RenderRatesSection(); - } - - /// The /qb list (render thread), or a line saying it starts with the Hub. - private void RenderQuestBonusSurface() - { - IltHubController? hub = _hub; - if (hub == null) { ImGui.TextDisabled("The quest bonus list starts once RynthILT's Hub is ready."); return; } - hub.RenderQuestBonusSection(); - } - - /// - /// RynthPluginGetSectionsJson (schema 1, UI/Sections/SectionManifest.cs in RynthCore): the ILT - /// session extras in Session Stats ("char"), the fellowship commands in Fellowship, the /qb list in - /// a Quests section of RynthILT's own, and the Mini Remote ILT tabs the Hub shows (Gear, Charms, - /// Banking in Inventory, Games in a section of RynthILT's own, Vaulted Dungeons in Nav), all - /// Infinite Leaftide areas (shown while RynthCore treats this world as ILT). IltSectionsManifest.cs. - /// The tabs were listed by RynthAi, which hosted them, until 2026-10-20. Null before login. - /// - internal string? BuildSectionsJson() => _loginComplete ? IltSectionsManifest.Build(IltSectionsManifest.TabsOf(_hub)) : null; - - /// - /// RynthPluginRenderEmbed "section:<tab>": one Mini Remote ILT tab as RynthCore's section view - /// (IltSectionsManifest lists them), drawn into the engine's current window and context in the - /// dashboard colours. / are the tab's - /// size. False until the Hub exists, or for a surface that is no ILT tab. Render thread. - /// - internal bool RenderEmbeddedTab(string surface, out float wantWidth, out float wantHeight) - { - wantWidth = wantHeight = 0; - IltHubController? hub = _hub; - if (!_loginComplete || hub == null || !IltSectionsManifest.TryTabOf(surface, out IltSection section)) return false; - IntPtr previous = ImGui.GetCurrentContext(); - IntPtr context = previous != IntPtr.Zero ? previous : Host.ImGuiContext; - if (context == IntPtr.Zero) return false; - ImGui.SetCurrentContext(context); - int pushed = IltStyle.PushDashboardStyle(); - try - { - var size = IltSections.TabSize(section); - wantWidth = size.X; - wantHeight = size.Y; - hub.NoteTabDrawn(); - hub.RenderTab(section); - return true; - } - catch (Exception ex) - { - RynthLog.Exception(LogCat.IltHub, ex, "RenderEmbeddedTab " + surface); - return false; - } - finally - { - ImGui.PopStyleColor(pushed); - ImGui.SetCurrentContext(previous); - } - } - - /// Plugin tick: runs the settings and fellowship views' chat commands through the engine. - private void DrainChatCommands() - { - while (_chatCommands.TryDequeue(out string? command)) - { - if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command)) - ChatLine("[RynthILT] RynthCore didn't take: " + command); - } - } - - private const long ServerStatePollMs = 2000; - private long _serverStateNextAt; - private string _serverStateJson = string.Empty; - - /// - /// Plugin tick, every 2 s (and at login): RynthCore's server list (plugin API v86, - /// GetServerStateJson) into the settings model, whose "ilt" entry the Hub's world check follows - /// (IltEngineVerdict). Parsed only when the text changed. An older engine leaves it empty, and - /// RynthILT's own list decides. - /// - private void PollServerState(bool force) - { - long now = Environment.TickCount64; - if (!force && now < _serverStateNextAt) return; - _serverStateNextAt = now + ServerStatePollMs; - try - { - if (!Host.HasGetServerStateJson || !Host.TryGetServerStateJson(out string json) || json == _serverStateJson) return; - _serverStateJson = json; - _settingsModel.ApplyServerState(EngineServerState.Parse(json)); - } - catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "PollServerState"); } - } - - private const long FeaturePublishMs = 1000; - private long _featurePublishNextAt; - - /// - /// Plugin tick, at most once a second: the Hub's server read (world, last check, feature bits) - /// for the ILT settings view (IltSettingsModel.PublishFeatures); cleared while there is no Hub. - /// - private void PublishHubFeatures() - { - long now = Environment.TickCount64; - if (now < _featurePublishNextAt) return; - _featurePublishNextAt = now + FeaturePublishMs; - var hub = _hub; - if (hub == null) - { - _settingsModel.PublishFeatures(null); - return; - } - var options = hub.Options; - DateTime last = options.LastRefreshUtc; - string when = last == default ? string.Empty : last.ToLocalTime().ToString("HH:mm:ss"); - _settingsModel.PublishFeatures(new IltFeatureView(options.WorldName, options.Source ?? string.Empty, when, - options.IsRefreshing, options.IsIltLikeWorld, BuildFeatureRows(options))); - } - - /// - /// The settings view's feature rows: every catalog feature with its state (IltFeatureCatalog), - /// then each ILT charm ("charm:...", on with the world unless refused in chat), then any other - /// bit chat or a probe set that the catalog doesn't show. Pump thread. - /// - private static KeyValuePair[] BuildFeatureRows(IltServerOptions options) - { - bool ilt = options.IsIltLikeWorld; - var rows = new List>(IltFeatureCatalog.All.Length + 32); - var shown = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (IltFeatureInfo f in IltFeatureCatalog.All) - { - rows.Add(new KeyValuePair(f.Key, (int)IltFeatureCatalog.StateOf(f, ilt, options.Get))); - if (f.ServerBit != null) shown.Add(f.ServerBit); - } - foreach (IltCharmDef def in IltInventory.Charms) - { - string key = IltFeature.Charm(def.Name); - rows.Add(new KeyValuePair(key, (int)IltFeatureCatalog.CharmStateOf(ilt, options.Get(key)))); - shown.Add(key); - } - foreach (var bit in options.SnapshotBits()) - if (shown.Add(bit.Key)) rows.Add(bit); - return rows.ToArray(); - } - - /// - /// The save failures queued by DataWriteGuard, in chat once the Hub knows this is an ILT world - /// (or "Treat this world as ILT"). Off ILT they stay in the log only: nothing ILT shows there. - /// - private void PostDataWriteProblems() - { - if (DataWriteGuard.PendingCount == 0 || _hub?.OffersTabs != true || !Host.HasWriteToChat) return; - DataWriteGuard.DrainChat(line => Host.WriteToChat(line, 2)); - } - - // ── ILT settings ───────────────────────────────────────────────────────── - - /// Asks the Hub to read the server's ILT features again (as "/ilt hub refresh", on the next tick). Render thread. - private bool RefreshFeatures() - { - if (!_loginComplete || _hub == null) return false; - _commands.Enqueue(new[] { "/ilt", "hub", "refresh" }); - return true; - } - - public override void OnChatWindowText(string? text, int chatType, ref int eat) - { - if (string.IsNullOrEmpty(text)) return; - try - { - // The Hub eats its own probe / capture replies (IltChatCapture). - if (_hub?.OnChat(text, chatType) == true) eat = 1; - } - catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnChat"); } - if (_bounties == null) return; - DrainTypedBounty(); - try - { - // Eats only the reply to the tracker's own /bounty list (BountyTracker.OnChat). - if (_bounties.OnChat(text)) eat = 1; - } - catch (Exception ex) - { - Host.Log($"[RynthILT] Bounty chat parse failed: {ex.Message}"); - } - } - - public override void OnChatBarEnter(string? text, ref int eat) - { - if (!_loginComplete || string.IsNullOrEmpty(text)) return; - string trimmed = text.Trim(); - // A /bounty going out: its reply must not be eaten (BountyTracker.NoteTypedCommand). Never eaten here. - if (BountyTracker.IsBountyCommand(trimmed)) - { - _typedBounty.Enqueue(trimmed); - return; - } - if (!trimmed.Equals("/ilt", StringComparison.OrdinalIgnoreCase) - && !trimmed.StartsWith("/ilt ", StringComparison.OrdinalIgnoreCase)) - return; - eat = 1; - _commands.Enqueue(trimmed.Split(' ', StringSplitOptions.RemoveEmptyEntries)); - } - - // A creature's health from the server: siphon auto-capture's fallback health read (ILT only). - public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) - { - try { _hub?.OnUpdateHealth(targetId, healthRatio); } - catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnUpdateHealth"); } - } - - // The server's killer notification: this character landed the killing blow. - public override void OnKillNotification(string? deathMessage) - { - _bounties?.OnKill(); - _hub?.OnKillNotification(); - } - - private void DrainTypedBounty() - { - while (_typedBounty.TryDequeue(out string? typed)) - _bounties?.NoteTypedCommand(typed); - } - - // ── Rendering (render thread) ──────────────────────────────────────────── - - /// - /// The Hub's floating extras (Games HUD, confirmations) and the standalone ILT settings and - /// fellowship windows ("/ilt settings", "/ilt fellow") in the engine's ImGui frame. - /// - public override void OnRender() - { - var hub = _hub; - if (!_loginComplete || Host.ImGuiContext == IntPtr.Zero) return; - if (hub == null && !_settingsUi.WindowOpen && !_fellowshipUi.WindowOpen) return; - IntPtr previous = ImGui.GetCurrentContext(); - ImGui.SetCurrentContext(Host.ImGuiContext); - try - { - try { hub?.Render(); } - catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnRender"); } - try { _settingsUi.RenderWindow(); } - catch (Exception ex) { Host.Log($"[RynthILT] Settings window failed: {ex.Message}"); _settingsUi.WindowOpen = false; } - try { _fellowshipUi.RenderWindow(); } - catch (Exception ex) { Host.Log($"[RynthILT] Fellowship window failed: {ex.Message}"); _fellowshipUi.WindowOpen = false; } - } - finally { ImGui.SetCurrentContext(previous); } - } - - /// The same while the engine's ImGui shell is off (RynthPluginRenderOverlay), in the dashboard colours. - internal void OnRenderOverlay() - { - var hub = _hub; - if (!_loginComplete || hub == null || Host.ImGuiContext == IntPtr.Zero) return; - IntPtr previous = ImGui.GetCurrentContext(); - ImGui.SetCurrentContext(Host.ImGuiContext); - int pushed = IltStyle.PushDashboardStyle(); - try { hub.Render(); } - catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "OnRenderOverlay"); } - finally - { - ImGui.PopStyleColor(pushed); - ImGui.SetCurrentContext(previous); - } - } - - /// - /// RynthPluginRenderEmbed "guardian": the Temple guardian tools inside RynthCore's Guardian - /// panel (the bar's ILT button), drawn into the engine's current ImGui window and context - /// (a popped-out panel has its own context, not Host.ImGuiContext; switching to the main one - /// there crashed the client, 2026-10-11). False (nothing drawn) until login and the Hub exist. - /// - internal bool RenderEmbeddedGuardian() - { - var hub = _hub; - if (!_loginComplete || hub == null || Host.ImGuiContext == IntPtr.Zero) return false; - IntPtr previous = ImGui.GetCurrentContext(); - if (previous == IntPtr.Zero) ImGui.SetCurrentContext(Host.ImGuiContext); - int pushed = IltStyle.PushDashboardStyle(); - try - { - hub.RenderGuardianPanel(); - return true; - } - catch (Exception ex) - { - RynthLog.Exception(LogCat.IltHub, ex, "RenderEmbeddedGuardian"); - return false; - } - finally - { - ImGui.PopStyleColor(pushed); - if (previous == IntPtr.Zero) ImGui.SetCurrentContext(previous); - } - } - - // ── Commands ───────────────────────────────────────────────────────────── - - /// - /// RynthILT.Hub Command: an ILT "/ra" verb RynthAi forwards ("hub bank", "guardian handin", - /// "bounty show", "rates reset"). Decides at once whether it is ours (RynthAi answers the rest) - /// and queues it for the next tick. Any thread. - /// - internal bool RunForwardedCommand(string line) - { - string[] words = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); - if (words.Length == 0 || !IsIltVerb(words)) return false; - var parts = new string[words.Length + 1]; - parts[0] = "/ra"; - Array.Copy(words, 0, parts, 1, words.Length); - _commands.Enqueue(parts); - return true; - } - - /// - /// The verbs RynthILT answers: the ILT "/ra hub" verbs (not RynthAi's Quests / Pets tabs or its - /// Remote tab), "/ra guardian", "/ra bounty|bounties|bountys", "rates" and "t11". - /// - internal static bool IsIltVerb(string[] words) - { - string verb = words[0].ToLowerInvariant(); - switch (verb) - { - case "guardian": case "bounty": case "bounties": case "bountys": case "rates": case "t11": - return true; - case "ub": - // ub-IT's ACECustom verbs RynthAi passes on ("/ub qblist", "/ub augs"). - return words.Length >= 2 && words[1].ToLowerInvariant() is "qblist" or "augs"; - case "hub": - if (words.Length < 2) return false; // "/ra hub" alone toggles RynthAi's Mini Remote - string sub = words[1].ToLowerInvariant(); - if (sub is "open") - return words.Length < 3 || !IltSections.IsUniversalTabName(words[2]); - if (sub is "tab") - return words.Length >= 3 && IltSections.TryParse(words[2], out IltSection t) && IltSections.IsTab(t); - return true; - default: - return false; - } - } - - private void RunCommand(string[] parts) - { - // RynthAi's forwarded "/ra ..." and "/ilt hub|guardian|bounty ..." reach the Hub alike. - bool fromRa = parts.Length > 0 && parts[0].Equals("/ra", StringComparison.OrdinalIgnoreCase); - string verb = parts.Length >= 2 ? parts[1].ToLowerInvariant() : "help"; - string[] args = parts.Length > 2 ? parts[2..] : Array.Empty(); - - if (!fromRa && (verb == "bounty" || verb == "bounties" || verb == "bountys")) - { - // "/ilt bounty [list|refresh]": the tracker's own chat commands ("/ra bounty" opens the window). - if (_bounties == null) ChatLine("[RynthILT] Bounties not ready (not logged in yet)."); - else _bounties.HandleChatCommand(parts); - return; - } - switch (verb) - { - case "trace": HandleTrace(args); return; - case "debug": - RynthLog.DebugToChat = args.Length > 0 ? args[0].Equals("on", StringComparison.OrdinalIgnoreCase) : !RynthLog.DebugToChat; - ChatLine($"[RynthILT] Debug-to-chat is {(RynthLog.DebugToChat ? "ON" : "off")} (traced: {RynthLog.TracedList()})."); - return; - case "servers": - verb = "hub"; - args = Prepend("servers", args); - break; - case "bounty": - case "bounties": - case "bountys": - case "guardian": - case "hub": - case "rates": - break; - case "ub": - { - // ub-IT's "/ub qblist" and "/ub augs" (RynthAi passes them on): ACECustom's own commands. - string sub = args.Length > 0 ? args[0].ToLowerInvariant() : string.Empty; - string? server = sub == "qblist" ? "/qb list" : sub == "augs" ? "/aug" : null; - if (server == null) { ChatLine("[RynthILT] /ub qblist or /ub augs"); return; } - if (_hub?.Options.IsIltLikeWorld != true) { ChatLine($"[RynthILT] /ub {sub}: not an Infinite Leaftide world."); return; } - if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(server)) ChatLine("[RynthILT] RynthCore didn't take: " + server); - return; - } - case "t11": - { - // "/ilt t11 ..." and RynthAi's "/ra t11 ..." (T11 loot counters; IltT11). - if (_hub == null) { ChatLine("[RynthILT] ILT features not ready (log in first)."); return; } - _hub.T11.HandleCommand(args); - return; - } - case "vaulted": - case "vaulteddungeons": - { - // "/ilt vaulted [on|off|toggle|status]": the Vaulted Dungeons keeper (ILT only; the - // module answers "not available" elsewhere, and while the master switch is off). - if (_hub == null) { ChatLine("[RynthILT] ILT features not ready (log in first)."); return; } - _hub.VaultedDungeons.HandleCommand(args); - return; - } - case "settings": - case "options": - { - // "/ilt settings [show|hide|toggle]": the ILT settings window. - string mode = args.Length >= 1 ? args[0].ToLowerInvariant() : "toggle"; - _settingsUi.WindowOpen = mode switch { "show" or "on" => true, "hide" or "off" => false, _ => !_settingsUi.WindowOpen }; - return; - } - case "fellow": - case "fellowship": - case "fship": - { - // "/ilt fellow [show|hide|toggle]": the ILT fellowship commands window. - string mode = args.Length >= 1 ? args[0].ToLowerInvariant() : "toggle"; - _fellowshipUi.WindowOpen = mode switch { "show" or "on" => true, "hide" or "off" => false, _ => !_fellowshipUi.WindowOpen }; - return; - } - case "help": - ChatLine("[RynthILT] /ilt hub ... (the Mini Remote's ILT tabs; same as /ra hub ...), /ilt guardian ..., /ilt servers [list||default],"); - ChatLine("[RynthILT] /ilt bounty [list|refresh] - the tracked ACECustom bounties (the Bounties window: the ILT button on the RynthCore bar, or /rc bounties),"); - ChatLine("[RynthILT] /ilt vaulted [on|off|toggle|status] - Vaulted Dungeons keeper (ILT only; master switch: /ilt settings or Settings > Navigation > Vaulted Dungeons, off by default),"); - ChatLine("[RynthILT] /ilt t11 [augs |refresh|item [0xId]] - T11 loot: the /aug wield counters RynthAi's loot rules use, the item-aug override, an item's T11 text (also /ra t11),"); - ChatLine("[RynthILT] /ilt settings [show|hide|toggle] - the ILT settings: the world verdict, the ILT world names and the server's features (force a server: RynthCore Options > Diagnostics),"); - ChatLine("[RynthILT] /ilt fellow [show|hide|toggle] - ILT's /fship commands as buttons (also in the Mini Remote's Fellowship section),"); - ChatLine("[RynthILT] /ilt trace [on|off], /ilt debug [on|off]."); - return; - default: - // "/ilt bank", "/ilt attr run", ...: the Hub's verbs without "hub". - args = Prepend(verb, args); - verb = "hub"; - break; - } - if (_hub == null) - { - ChatLine("[RynthILT] ILT features not ready (log in first)."); - return; - } - try - { - if (!_hub.HandleCommand(verb, args)) - ChatLine($"[RynthILT] Unknown command: {string.Join(" ", parts)}. /ilt help"); - } - catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "command"); } - } - - private static string[] Prepend(string first, string[] rest) - { - var a = new string[rest.Length + 1]; - a[0] = first; - Array.Copy(rest, 0, a, 1, rest.Length); - return a; - } - - /// "/ilt trace <category|all|list> [on|off]". - private void HandleTrace(string[] args) - { - string target = args.Length > 0 ? args[0] : "list"; - bool on = args.Length < 2 || !args[1].Equals("off", StringComparison.OrdinalIgnoreCase); - if (target.Equals("list", StringComparison.OrdinalIgnoreCase) || target.Equals("status", StringComparison.OrdinalIgnoreCase)) - { - ChatLine($"[RynthILT] Traced: {RynthLog.TracedList()}. Categories: {string.Join(", ", Enum.GetNames())}. Log folder: {RynthLog.Directory}"); - return; - } - if (target.Equals("all", StringComparison.OrdinalIgnoreCase) || target.Equals("ilt", StringComparison.OrdinalIgnoreCase)) - { - int n = RynthLog.SetTracingAll(on); - ChatLine($"[RynthILT] Tracing {(on ? "enabled" : "disabled")} for {n} categories."); - return; - } - if (!RynthLog.TryParseCategory(target, out LogCat cat)) - { - ChatLine($"[RynthILT] Unknown trace category '{target}'. /ilt trace list"); - return; - } - RynthLog.SetTracing(cat, on); - ChatLine($"[RynthILT] Trace {cat}: {(on ? "ON" : "off")}"); - } - - /// RynthILTCommand: "prog ..." (the Skills panel's Progression tab) and the Hub verbs, from the engine. Pump thread. - internal void RunEngineCommand(string text) - { - string[] words = text.Split(' ', StringSplitOptions.RemoveEmptyEntries); - if (words.Length == 0) return; - if (words[0].Equals("prog", StringComparison.OrdinalIgnoreCase)) - { - if (_hub == null) { ChatLine("[RynthILT] ILT features not ready (log in first)."); return; } - try { _hub.Progression.HandleRemote(words[1..]); } - catch (Exception ex) { RynthLog.Exception(LogCat.IltProgression, ex, "prog command"); } - return; - } - if (IsIltVerb(words)) RunForwardedCommand(text); - } - - /// RynthPluginApplyRemoteCommand (any thread): "prog" + its arguments, or an ILT verb; run on the next tick. - internal void EnqueueRemoteCommand(string action, string value) - { - if (_engineCommands.Count < 64) _engineCommands.Enqueue((action + " " + value).Trim()); - } - - private void ChatLine(string text) - { - if (Host.HasWriteToChat) Host.WriteToChat(text, 1); - } - - // ── The ILT Hub ────────────────────────────────────────────────────────── - - /// - /// Starts the Hub once the character's name is known (its files are per character). The first - /// time a character logs in with RynthILT its RynthAi ILT Hub files are copied over (IltMigration). - /// - private void TryStartHub() - { - long now = Environment.TickCount64; - if (now < _nextHubTryMs || _hub != null || _ai == null) return; - _nextHubTryMs = now + NameRetryMs; - - uint me = Host.GetPlayerId(); - if (me == 0 || !Host.HasGetObjectName || !Host.TryGetObjectName(me, out string charName) || string.IsNullOrWhiteSpace(charName)) - return; - string world = Host.HasGetWorldName && Host.TryGetWorldName(out string w) && !string.IsNullOrWhiteSpace(w) ? w.Trim() : string.Empty; - string folder = CharacterFolder(world, charName); - bool force = false; - try - { - var lines = new List(IltMigration.MigrateShared(_settings, SettingsRoot)); - lines.AddRange(IltMigration.MigrateCharacter(folder, world, charName, _settings, out force)); - if (lines.Count > 0) - { - IltSettingsStore.Save(_settings); - RynthLog.Write(LogCat.IltStore, $"Carried the ILT Hub's saved data over from RynthAi for {charName}: {string.Join(", ", lines)}."); - } - } - catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, "migration"); } - - force |= _forceOnRestart; - _forceOnRestart = false; - bool pending = IltMigration.IsPending(_settings, folder); - _hubWritesBlocked = pending; - _hubFolder = folder; - _hubWorld = world; - _hubChar = charName; - _nextMigrationRetryMs = now + MigrationRetryMs; - if (pending) - RynthLog.Write(LogCat.IltStore, $"{charName}'s Hub data isn't all copied from RynthAi yet: the Hub saves nothing for this character " + - "until it is (read from RynthAi's files where it can; retried every 2 minutes and at each login)."); - try - { - _hub = new IltHubController(Host, folder, _settings, _ai, () => _hubWritesBlocked, - pending ? IltMigration.FindLegacyCharFolder(world, charName) : null); - // Once per character: the RynthAi settings that moved here on 2026-10-20. - var imported = IltMigration.ImportRynthAiSettings(_hub.State, world, charName); - if (imported.Count > 0) - RynthLog.Write(LogCat.IltStore, $"Carried {charName}'s RynthAi settings that moved to RynthILT over: {string.Join(", ", imported)}."); - _hub.OnLoginComplete(charName, force); - } - catch (Exception ex) - { - _hub = null; - RynthLog.Exception(LogCat.IltHub, ex, "start"); - } - } - - /// - /// Pump: while this character's copy from RynthAi is unfinished, tries it again every - /// MigrationRetryMs. When it completes the Hub is stopped (still writing nothing, so the copied - /// files stay as they are) and started again on them. - /// - private void RetryPendingMigration() - { - if (_hub == null || !_hubWritesBlocked) return; - long now = Environment.TickCount64; - if (now < _nextMigrationRetryMs) return; - _nextMigrationRetryMs = now + MigrationRetryMs; - try - { - var lines = IltMigration.MigrateCharacter(_hubFolder, _hubWorld, _hubChar, _settings, out bool force); - if (lines.Count > 0) - { - IltSettingsStore.Save(_settings); - RynthLog.Write(LogCat.IltStore, $"Retried copying {_hubChar}'s ILT Hub data from RynthAi: {string.Join(", ", lines)}."); - } - if (IltMigration.IsPending(_settings, _hubFolder)) return; - _forceOnRestart = force; - StopHub(); // _hubWritesBlocked is still true: the logout save writes nothing - _nextHubTryMs = 0; - TryStartHub(); // loads the copied files; saves from now on - RynthLog.Write(LogCat.IltStore, $"{_hubChar}'s ILT Hub data is copied; the Hub restarted on it."); - } - catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, "migration retry"); } - } - - private void StopHub() - { - var hub = _hub; - _hub = null; - if (hub == null) return; - try { hub.OnLogout(); } - catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "logout"); } - } - - /// %APPDATA%\RynthCore\RynthILT\{world}\{character} (the bounty list's folder too). - internal static string CharacterFolder(string world, string charName) - => Path.Combine(SettingsRoot, SafeName(world.Length > 0 ? world : "UnknownWorld"), SafeName(charName)); - - // ── Bounties ───────────────────────────────────────────────────────────── - - /// Starts the tracker once the character's name is known (its save file is per character). - private void TryStartBounties() - { - long now = Environment.TickCount64; - if (now < _nextNameTryMs) return; - _nextNameTryMs = now + NameRetryMs; - - string file = BountyFilePath(out bool named); - if (!named && now - _loginAtMs < NameWaitMs) return; - if (!named) Host.Log("[RynthILT] Bounties: no character name; the list won't be saved this session."); - _bounties = new BountyTracker(SendCommand, ChatLine, Host.Log, file); - } - - private void SaveBounties() - { - try { _bounties?.Save(); } - catch (Exception ex) { Host.Log($"[RynthILT] Bounties: save failed: {ex.Message}"); } - } - - /// The tracker's only way to the server: one chat command (Host.InvokeChatParser). - private void SendCommand(string command) - { - if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command)) - throw new InvalidOperationException("the engine's chat parser is not available"); - } - - /// - /// %APPDATA%\RynthCore\RynthILT\{world}\{character}\bounties.json, or "" (no save file) while - /// the character's name is unknown. Both names are reduced to safe folder names. - /// - private string BountyFilePath(out bool named) - { - named = false; - uint me = Host.GetPlayerId(); - if (me == 0 || !Host.HasGetObjectName || !Host.TryGetObjectName(me, out string charName) - || string.IsNullOrWhiteSpace(charName)) - return string.Empty; - string world = Host.HasGetWorldName && Host.TryGetWorldName(out string w) && !string.IsNullOrWhiteSpace(w) - ? w : "UnknownWorld"; - named = true; - return Path.Combine(SettingsRoot, SafeName(world), SafeName(charName), BountyTracker.FileName); - } - - /// RynthILT's settings folder: %APPDATA%\RynthCore\RynthILT. - internal static string SettingsRoot => Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "RynthILT"); - - /// A name safe as one folder: invalid characters become '_', no leading/trailing dots or spaces, at most 64 chars. - internal static string SafeName(string name) - { - char[] invalid = Path.GetInvalidFileNameChars(); - var chars = name.Trim().ToCharArray(); - for (int i = 0; i < chars.Length; i++) - if (Array.IndexOf(invalid, chars[i]) >= 0 || chars[i] == '/' || chars[i] == '\\') chars[i] = '_'; - string s = new string(chars).Trim(' ', '.'); - if (s.Length > 64) s = s.Substring(0, 64).TrimEnd(' ', '.'); - return s.Length == 0 ? "_" : s; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthILT/ServerInterface.cs b/Plugins/RynthCore.Plugin.RynthILT/ServerInterface.cs deleted file mode 100644 index 8771b58..0000000 --- a/Plugins/RynthCore.Plugin.RynthILT/ServerInterface.cs +++ /dev/null @@ -1,81 +0,0 @@ -// ServerInterface.cs - RynthILT's side of the "RynthILT.Server" interface (Plugins/Shared/RynthIltServerApi.cs): -// the profile JSON other plugins read (RynthOracle's Fellowship / Quests qb list / feature list): -// the Leaftide feature list with the server's state for each, and the server's fellowship rules. -// -// Restored 2026-10-16: this export was dropped when "RynthServer.Profile" (salvage / identity) was -// added, so Oracle still detected ILT via RynthCore but never received feature / qb / fellowship -// data from RynthILT. Hub + Data stay separate; this table is the feature-profile channel. -// -// The table is allocated once per loaded copy of RynthILT and never freed (a plugin DLL is never -// unloaded); after Release() it reports Version 0 and GetProfileJson answers 0. Before login there -// is no controller, so the profile is the not-ILT default (every feature unknown, retail fellowships). -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthILT; - -internal static unsafe class ServerInterface -{ - private static RynthIltServerApiV1* _table; - private static volatile bool _released; - - /// The profile before any login: not an ILT world, nothing known (built once). - private static readonly string NotLoggedInJson = - IltFeatureCatalog.BuildProfileJson(false, string.Empty, false, string.Empty, DateTime.MinValue, _ => IltTri.Unknown); - - /// The table for (, ), or 0 when it isn't ours. - public static IntPtr Query(string iface, uint version) - { - if (iface != RynthIltServerApiV1.InterfaceName || version < 1 || version > RynthIltServerApiV1.InterfaceVersion || _released) - return IntPtr.Zero; - if (_table == null) - { - var t = (RynthIltServerApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthIltServerApiV1)); - t->StructSize = (uint)sizeof(RynthIltServerApiV1); - t->GetProfileJson = &GetProfileJson; - t->Version = RynthIltServerApiV1.InterfaceVersion; - _table = t; - } - return (IntPtr)_table; - } - - /// Plugin shutdown: readers see Version 0 and re-query; GetProfileJson answers 0. - public static void Release() - { - _released = true; - if (_table != null) _table->Version = 0; - } - - /// The JSON to hand out now: the live controller's snapshot, or the not-logged-in default. - internal static string CurrentJson() - => (_released ? null : PluginExports.Runtime.Plugin?.Hub?.ProfileJson) ?? NotLoggedInJson; - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GetProfileJson(byte* buffer, int capacity) - { - try - { - if (_released) return 0; - return ProfileInterface.Write(CurrentJson(), buffer, capacity); - } - catch { return 0; } - } - - /// - /// Copies as NUL-terminated UTF-8 into the caller's buffer when it fits, - /// and returns its byte length either way (length >= capacity: too small, nothing written). - /// - internal static int Write(string json, byte* buffer, int capacity) - { - int length = Encoding.UTF8.GetByteCount(json); - if (buffer == null || capacity <= length) return length; - fixed (char* src = json) - Encoding.UTF8.GetBytes(src, json.Length, buffer, capacity); - buffer[length] = 0; - return length; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthInventory/Data/BankRoster.cs b/Plugins/RynthCore.Plugin.RynthInventory/Data/BankRoster.cs deleted file mode 100644 index e9b6d09..0000000 --- a/Plugins/RynthCore.Plugin.RynthInventory/Data/BankRoster.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using System.Collections.Generic; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthInventory.Data; - -/// One character on the Banking tab: its saved balances (null = never read) and account. -internal sealed record BankRosterEntry(string Name, string Account, bool Current, IltBankRow? Bank); - -/// -/// The Banking tab's character list (2026-10-13; the Mini Remote's Banking tab moved here). Every -/// character RynthILT has bank balances for on this server (its saved per-character state, so every -/// account played on this PC), plus every character Global Inventory has recorded on the same -/// server without a balance yet, so the list covers the same characters as the inventory does. -/// Pure: the tests feed it a parsed bank view and an index. -/// -internal static class BankRoster -{ - /// - /// The merged list: the logged-in character first, then by name. A name in both lists keeps - /// RynthILT's balances and the inventory's account. - /// - public static List Build(IltBankView bank, InventoryIndex? index) - { - var byName = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (IltBankRow r in bank.Characters) - byName[r.Name] = new BankRosterEntry(r.Name, string.Empty, r.Current, r); - - if (index != null) - { - foreach (CharacterInfo ci in index.Characters) - { - // Same server only: a bank belongs to one world. - if (!SameServer(ci, bank)) continue; - string account = !string.IsNullOrEmpty(ci.Account) && ci.Account != "unknown" ? ci.Account : string.Empty; - if (byName.TryGetValue(ci.Name, out BankRosterEntry? have)) - byName[ci.Name] = have with { Account = account, Current = have.Current || ci.IsCurrentCharacter }; - else - byName[ci.Name] = new BankRosterEntry(ci.Name, account, ci.IsCurrentCharacter, null); - } - } - - var list = new List(byName.Values); - list.Sort((a, b) => a.Current != b.Current ? (a.Current ? -1 : 1) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); - return list; - } - - /// - /// A recorded character is on the bank's server: the world RynthILT names when it gave one, - /// otherwise the server Global Inventory says you are on now. - /// - private static bool SameServer(CharacterInfo ci, IltBankView bank) => - bank.World.Length > 0 ? InventoryIndex.SameName(ci.Server, bank.World) : ci.IsCurrentServer; - - /// The sums over every character with a balance (one row of the same shape). - public static IltBankRow Totals(IReadOnlyList roster) - { - long py = 0, lum = 0, lk = 0, mk = 0, ec = 0, wec = 0, pc = 0; - foreach (BankRosterEntry e in roster) - { - if (e.Bank is not { } b) continue; - py += b.Pyreals; lum += b.Luminance; lk += b.LegendaryKeys; mk += b.MythicalKeys; - ec += b.EnlightenedCoins; wec += b.WeaklyEnlightenedCoins; pc += b.PrestigeCoins; - } - return new IltBankRow("Total", false, py, lum, lk, mk, ec, wec, pc, DateTime.MinValue); - } - - /// - /// The withdraw / transfer amount typed in the form: a positive whole number (commas and spaces - /// allowed), or 0 when it isn't one. - /// - public static long ParseAmount(string? text) - { - if (string.IsNullOrWhiteSpace(text)) return 0; - string digits = text.Replace(",", string.Empty).Replace(" ", string.Empty).Trim(); - return long.TryParse(digits, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out long n) && n > 0 ? n : 0; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthInventory/InventoryContext.cs b/Plugins/RynthCore.Plugin.RynthInventory/InventoryContext.cs index 705e7ce..8e8ff6f 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/InventoryContext.cs +++ b/Plugins/RynthCore.Plugin.RynthInventory/InventoryContext.cs @@ -35,13 +35,6 @@ internal sealed class InventoryContext public bool IconsAvailable; public DateTime UtcNow; - /// RynthILT's "RynthILT.Data" (the Banking tab's balances and bank commands). - public readonly RynthCore.Plugin.Shared.RynthIltDataClient IltData = new(); - /// The bank RynthILT last reported (None without RynthILT); read while the window shows. - public RynthCore.Plugin.Shared.IltBankView Bank = RynthCore.Plugin.Shared.IltBankView.None; - /// Set by the plugin: queues a bank verb with RynthILT (IltBankView.*Verb); false when refused. - public Func BankCommand = _ => false; - public Action RequestRescan = () => { }; public Action RequestReload = () => { }; /// Forgets a character (moves its file aside). Returns a message for the player. diff --git a/Plugins/RynthCore.Plugin.RynthInventory/RynthCore.Plugin.RynthInventory.csproj b/Plugins/RynthCore.Plugin.RynthInventory/RynthCore.Plugin.RynthInventory.csproj index 2e6da18..f7c366d 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/RynthCore.Plugin.RynthInventory.csproj +++ b/Plugins/RynthCore.Plugin.RynthInventory/RynthCore.Plugin.RynthInventory.csproj @@ -41,8 +41,6 @@ - - diff --git a/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs b/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs index a82aa53..537c294 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthInventory/RynthInventoryPlugin.cs @@ -32,12 +32,6 @@ public sealed class RynthInventoryPlugin : RynthPluginBase // Previous release: 0.1.0. Keep in step with PluginExports.GetVersion. public const string Version = "0.1.1"; - // RynthILT's bank JSON: every BankTabReadMs on the Banking tab, every BankIdleReadMs with the - // window on another tab (so the Banking button appears on ILT worlds), never with it closed. - private const long BankTabReadMs = 2000, BankIdleReadMs = 10_000; - private long _nextBankReadMs; - private string _bankJson = string.Empty; - private const long IdentityRetryMs = 1000; private const long AccountWaitMs = 15_000; private const long FileCheckMs = 5000; @@ -98,7 +92,6 @@ public sealed class RynthInventoryPlugin : RynthPluginBase _c.RequestRescan = () => { _scheduler.RequestFullScan(); _forceWrite = true; }; _c.RequestReload = () => { _reloadWanted = true; _files.Clear(); }; _c.Forget = ForgetCharacter; - _c.BankCommand = SendBankVerb; _ui.Log = msg => Host.Log(msg); _view = new InventoryView(_c); @@ -133,44 +126,9 @@ public sealed class RynthInventoryPlugin : RynthPluginBase _carriedIds.Clear(); _carriedPacks.Clear(); RefreshIconSupport(); - ClearBank(); if (_window != null) { _window.Visible = _c.Settings.MainWindowOpen; _window.NeedsPass = true; } } - /// Forgets the last bank read (login, logout): the next character's comes fresh. - private void ClearBank() - { - _c.Bank = Shared.IltBankView.None; - _bankJson = string.Empty; - _nextBankReadMs = 0; - } - - /// The Banking tab's actions: a verb line for RynthILT, then a quick re-read for its reply. - private bool SendBankVerb(string verb) - { - long now = Environment.TickCount64; - bool ok = _c.InWorld && _c.IltData.BankCommand(Host, now, verb); - _nextBankReadMs = now + 500; - if (_window != null) _window.NeedsPass = true; - return ok; - } - - /// - /// Reads RynthILT's bank JSON while the window is open (more often on the Banking tab) and - /// redraws when it changed. Reading is what tells RynthILT someone is looking. - /// - private void TickBank(long now) - { - if (!_c.InWorld || _window == null || _view == null || !_window.Visible) return; - if (now < _nextBankReadMs) return; - _nextBankReadMs = now + (_view.Tab == InventoryView.TabBanking ? BankTabReadMs : BankIdleReadMs); - string json = _c.IltData.ReadBank(Host, now); - if (string.Equals(json, _bankJson, StringComparison.Ordinal)) return; - _bankJson = json; - _c.Bank = Shared.IltBankView.Parse(json); - _window.NeedsPass = true; - } - public override void OnLogout() { // Last word for this character: write what it has now (also refreshes its "scanned" time). @@ -183,7 +141,6 @@ public sealed class RynthInventoryPlugin : RynthPluginBase _ui.SubmitEmpty(Host); _c.Live = null; _indexDirty = true; - ClearBank(); while (_storagePushes.TryDequeue(out _)) { } // the next character's come fresh _lastPush = string.Empty; } @@ -282,16 +239,9 @@ public sealed class RynthInventoryPlugin : RynthPluginBase case "status": PrintStatus(); break; - case "bank": - case "banking": - // The Banking tab: every character's Infinite Leaftide bank (RynthILT's data). Shows, never toggles off. - _view?.ShowBanking(); - _nextBankReadMs = 0; - if (_window != null) { _window.Visible = true; _window.NeedsPass = true; } - break; case "help": case "?": - _c.Print("/ginv (window), /ginv (search), /ginv bank (every character's Infinite Leaftide bank), /ginv scan (rescan and save now), /ginv keep (record the open container as storage), /ginv reload, /ginv status"); + _c.Print("/ginv (window), /ginv (search), /ginv scan (rescan and save now), /ginv keep (record the open container as storage), /ginv reload, /ginv status"); break; default: _view?.SetSearch(arg); @@ -359,7 +309,6 @@ public sealed class RynthInventoryPlugin : RynthPluginBase } TickWrite(now); TickIndex(now); - TickBank(now); if (!Host.HasUi || _window == null || _view == null) return; Record(_window, now, 2000, _view.Draw); diff --git a/Plugins/RynthCore.Plugin.RynthInventory/Views/BankingTab.cs b/Plugins/RynthCore.Plugin.RynthInventory/Views/BankingTab.cs deleted file mode 100644 index e3ab000..0000000 --- a/Plugins/RynthCore.Plugin.RynthInventory/Views/BankingTab.cs +++ /dev/null @@ -1,237 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using RynthCore.Plugin.RynthInventory.Data; -using RynthCore.Plugin.RynthInventory.Ui; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthInventory.Views; - -/// -/// Banking: the Infinite Leaftide bank of every character on this server (the Mini Remote's Banking -/// tab moved here 2026-10-13). Balances, form choices and the last reply come from RynthILT's -/// "RynthILT.Data" bank JSON; the character list adds the inventory's characters on the same server -/// (BankRoster). Deposits, withdrawals, transfers and balance reads go back to RynthILT as verb lines; -/// a transfer is confirmed here first (RynthILT doesn't ask again). -/// -internal sealed partial class InventoryView -{ - private const int MaxTransactionsShown = 20; - private const float ColPyreals = 150f, ColLum = 270f, ColKeys = 380f, ColCoins = 450f, ColUpdated = 560f; - - private int _depositIndex, _withdrawIndex, _withdrawNote, _transferIndex, _transferNote; - private string _withdrawAmount = string.Empty, _transferAmount = string.Empty, _transferTo = string.Empty; - /// The transfer waiting for "Yes, send": its verb line and the sentence shown. - private (string Verb, string Text)? _confirmTransfer; - private string _bankMessage = string.Empty; - - /// - /// The Banking tab button shows when RynthILT answered on an ILT world, or when the tab was asked - /// for (/ginv bank) so it can say what is missing. - /// - private bool BankingShown => Tab == TabBanking || (_c.Bank.Loaded && _c.Bank.Available); - - /// Opens on the Banking tab ("/ginv bank", RynthAi's and RynthILT's bank links). - public void ShowBanking() - { - Tab = TabBanking; - _confirmTransfer = null; - } - - private void DrawBanking(UiWindow w) - { - IltBankView b = _c.Bank; - if (!b.Loaded) - { - w.TextDisabled("The bank comes from RynthILT (Infinite Leaftide). Load RynthILT to see every character's bank here."); - return; - } - if (!b.Available) - { - w.TextDisabled("This isn't an Infinite Leaftide world, so there is no bank to show."); - return; - } - - w.Text($"Bank on {(b.World.Length > 0 ? b.World : "this server")}"); - w.SameLine(); - w.SmallButton("Refresh", "b.refresh", () => SendBank(IltBankView.RefreshVerb(), "Reading the balance...")); - w.Tooltip("A quiet /bank balance read for the character you're on (other characters update when they log in)."); - if (b.Enabled == 0) w.TextColored(UiColors.Red, "This server has no /bank command."); - else if (b.Enabled < 0) w.TextDisabled("Whether this server has /bank isn't known yet."); - if (b.Result.Length > 0) w.TextColored(UiColors.Gold, b.Result); - if (_bankMessage.Length > 0) w.TextColored(UiColors.Yellow, _bankMessage); - - List roster = BankRoster.Build(b, _c.Index); - DrawBankTable(w, roster); - if (b.Enabled != 0) - { - DrawDeposit(w, b); - DrawWithdraw(w, b); - DrawTransfer(w, b, roster); - } - DrawTransactions(w, b); - } - - private void DrawBankTable(UiWindow w, List roster) - { - w.SeparatorText($"Characters ({roster.Count})"); - w.TextDisabled("Character"); - w.SameLine(ColPyreals); w.TextDisabled("Pyreals"); - w.SameLine(ColLum); w.TextDisabled("Luminance"); - w.SameLine(ColKeys); w.TextDisabled("Keys L/M"); - w.SameLine(ColCoins); w.TextDisabled("Coins E/W/P"); - w.SameLine(ColUpdated); w.TextDisabled("Updated"); - foreach (BankRosterEntry e in roster) - { - string name = e.Current ? e.Name + " (you)" : e.Name; - if (e.Bank is { } r) - { - w.Text(name); - if (e.Account.Length > 0) w.Tooltip("Account: " + e.Account); - BankCells(w, r); - w.SameLine(ColUpdated); - w.TextDisabled(r.UpdatedUtc == DateTime.MinValue ? "-" : InventoryIndex.Age(r.UpdatedUtc, _c.UtcNow)); - } - else - { - w.TextDisabled(name); - if (e.Account.Length > 0) w.Tooltip("Account: " + e.Account); - w.SameLine(ColPyreals); - w.TextDisabled("not read yet: log in with RynthILT loaded"); - } - } - if (roster.Count == 0) w.TextDisabled("No characters on this server yet."); - else - { - w.TextColored(UiColors.Gold, "Total"); - BankCells(w, BankRoster.Totals(roster)); - } - } - - /// The balance columns of one row (Pyreals .. Coins). - private static void BankCells(UiWindow w, IltBankRow r) - { - w.SameLine(ColPyreals); w.Text(N(r.Pyreals)); - w.SameLine(ColLum); w.Text(N(r.Luminance)); - w.SameLine(ColKeys); w.Text($"{N(r.LegendaryKeys)}/{N(r.MythicalKeys)}"); - w.SameLine(ColCoins); w.Text($"{N(r.EnlightenedCoins)}/{N(r.WeaklyEnlightenedCoins)}/{N(r.PrestigeCoins)}"); - } - - private void DrawDeposit(UiWindow w, IltBankView b) - { - if (b.Deposits.Count == 0) return; - w.SeparatorText("Deposit"); - _depositIndex = Math.Clamp(_depositIndex, 0, b.Deposits.Count - 1); - w.Combo("What", "b.dep.what", _depositIndex, b.Deposits, i => _depositIndex = i); - w.SameLine(); - int di = _depositIndex; - string label = b.Deposits[di]; - w.SmallButton("Deposit", "b.dep.go", () => SendBank(IltBankView.DepositVerb(di), "Depositing " + label + "...")); - } - - private void DrawWithdraw(UiWindow w, IltBankView b) - { - if (b.Withdrawals.Count == 0) return; - w.SeparatorText("Withdraw"); - _withdrawIndex = Math.Clamp(_withdrawIndex, 0, b.Withdrawals.Count - 1); - w.Combo("Currency", "b.wd.what", _withdrawIndex, Labels(b.Withdrawals), i => _withdrawIndex = i); - IltBankChoice choice = b.Withdrawals[_withdrawIndex]; - w.InputText(choice.Notes ? "Notes" : "Amount", "b.wd.amt", _withdrawAmount, 20, v => _withdrawAmount = v); - int note = NoteCombo(w, b, choice, "b.wd.note", _withdrawNote, i => _withdrawNote = i); - w.SameLine(); - int wi = _withdrawIndex; - w.SmallButton("Withdraw", "b.wd.go", () => - { - long amount = BankRoster.ParseAmount(_withdrawAmount); - if (amount <= 0) { _bankMessage = "Type a whole number to withdraw."; return; } - SendBank(IltBankView.WithdrawVerb(wi, amount, note), $"Withdrawing {N(amount)} {choice.Label}..."); - }); - } - - private void DrawTransfer(UiWindow w, IltBankView b, List roster) - { - if (b.Transfers.Count == 0) return; - w.SeparatorText("Transfer"); - _transferIndex = Math.Clamp(_transferIndex, 0, b.Transfers.Count - 1); - w.Combo("Currency", "b.tx.what", _transferIndex, Labels(b.Transfers), i => { _transferIndex = i; _confirmTransfer = null; }); - IltBankChoice choice = b.Transfers[_transferIndex]; - w.InputText(choice.Notes ? "Notes" : "Amount", "b.tx.amt", _transferAmount, 20, v => { _transferAmount = v; _confirmTransfer = null; }); - int note = NoteCombo(w, b, choice, "b.tx.note", _transferNote, i => { _transferNote = i; _confirmTransfer = null; }); - w.InputText("To", "b.tx.to", _transferTo, 40, v => { _transferTo = v; _confirmTransfer = null; }); - - // The other characters on this server, to fill "To" with one click. - var others = new List { "Pick a character..." }; - foreach (BankRosterEntry e in roster) if (!e.Current) others.Add(e.Name); - if (others.Count > 1) - { - w.SameLine(); - w.Combo("##pick", "b.tx.pick", 0, others, i => { if (i > 0 && i < others.Count) { _transferTo = others[i]; _confirmTransfer = null; } }); - } - - if (_confirmTransfer is { } pending) - { - w.TextColored(UiColors.Red, pending.Text); - w.SmallButton("Yes, send", "b.tx.yes", () => - { - _confirmTransfer = null; - SendBank(pending.Verb, "Transfer sent..."); - }); - w.SameLine(); - w.SmallButton("Cancel", "b.tx.no", () => _confirmTransfer = null); - return; - } - int ti = _transferIndex; - w.SmallButton("Transfer...", "b.tx.go", () => - { - long amount = BankRoster.ParseAmount(_transferAmount); - string to = (_transferTo ?? string.Empty).Trim(); - if (amount <= 0) { _bankMessage = "Type a whole number to transfer."; return; } - if (to.Length == 0) { _bankMessage = "Type (or pick) who gets the transfer."; return; } - string what = choice.Notes && note < b.Notes.Count ? $"{N(amount)} x {b.Notes[note].Label}" : $"{N(amount)} {choice.Label}"; - _confirmTransfer = (IltBankView.TransferVerb(ti, amount, note, to), $"Send {what} to {to}? This can't be undone."); - _bankMessage = string.Empty; - }); - } - - /// - /// The trade-note combo for a choice that counts notes; returns the note index in use (0 when - /// the choice isn't notes). A pick arrives as an event and lands in . - /// - private static int NoteCombo(UiWindow w, IltBankView b, IltBankChoice choice, string id, int index, Action set) - { - if (!choice.Notes || b.Notes.Count == 0) return 0; - var labels = new List(b.Notes.Count); - foreach (IltBankNote n in b.Notes) labels.Add($"{n.Label} ({N(n.Value)} pyreals)"); - index = Math.Clamp(index, 0, b.Notes.Count - 1); - w.Combo("Note", id, index, labels, set); - return index; - } - - private void DrawTransactions(UiWindow w, IltBankView b) - { - if (b.Transactions.Count == 0) return; - if (!w.CollapsingHeader($"Recent transfers ({b.Transactions.Count})", "b.txlog")) return; - int shown = 0; - foreach (IltBankTx t in b.Transactions) - { - if (shown++ >= MaxTransactionsShown) { w.TextDisabled($"...and {b.Transactions.Count - MaxTransactionsShown} more."); break; } - string dir = t.Type.Length > 0 ? t.Type : "?"; - w.Text($"{t.When} {dir} {N(t.Amount)} {t.Currency}{(t.Player.Length > 0 ? " - " + t.Player : "")}"); - } - } - - /// Hands a verb to RynthILT; says so when it was refused. - private void SendBank(string verb, string sending) - { - _bankMessage = _c.BankCommand(verb) ? sending : "RynthILT didn't take that (is it loaded, and are you logged in?)."; - } - - private static List Labels(IReadOnlyList choices) - { - var list = new List(choices.Count); - foreach (IltBankChoice c in choices) list.Add(c.Label); - return list; - } - - private static string N(long n) => n.ToString("N0", CultureInfo.InvariantCulture); -} diff --git a/Plugins/RynthCore.Plugin.RynthInventory/Views/InventoryView.cs b/Plugins/RynthCore.Plugin.RynthInventory/Views/InventoryView.cs index 2ca75ee..e712529 100644 --- a/Plugins/RynthCore.Plugin.RynthInventory/Views/InventoryView.cs +++ b/Plugins/RynthCore.Plugin.RynthInventory/Views/InventoryView.cs @@ -8,12 +8,13 @@ namespace RynthCore.Plugin.RynthInventory.Views; /// /// The Global Inventory window: a search page (every character on every server, filters, -/// totals, results, details), a characters page (snapshot ages, forget) and, with RynthILT, a -/// Banking page (Views\BankingTab.cs). Recorded on the pump thread, replayed by the engine. +/// totals, results, details) and a characters page (snapshot ages, forget). Recorded on the pump +/// thread, replayed by the engine. (A server's own pages are its server plugin's: the Banking page +/// that showed RynthILT's bank here is RynthILT's own Banking tab since 2026-10-21.) /// internal sealed partial class InventoryView { - public const int TabSearch = 0, TabCharacters = 1, TabBanking = 2; + public const int TabSearch = 0, TabCharacters = 1; private const int PageSize = 100; private const float RowIcon = 18f, DetailIcon = 32f, DetailsHeight = 190f; @@ -58,21 +59,10 @@ internal sealed partial class InventoryView w.SameLine(); int chars = _c.Index?.Characters.Count ?? 0; w.ToggleButton($"Characters ({chars})", "tab.chars", Tab == TabCharacters, () => Tab = TabCharacters, small: true); - if (BankingShown) - { - w.SameLine(); - w.ToggleButton("Banking", "tab.bank", Tab == TabBanking, () => Tab = TabBanking, small: true); - } w.SameLine(); w.TextDisabled(StatusLine()); w.Separator(); - // The bank comes from RynthILT, not the inventory files: it draws before they are read. - if (Tab == TabBanking) - { - DrawBanking(w); - return; - } if (_c.Index == null) { w.TextDisabled(_c.Loading ? "Reading the inventory files..." : "No inventory read yet."); diff --git a/Plugins/RynthCore.Plugin.RynthLeafDawn/RynthCore.Plugin.RynthLeafDawn.csproj b/Plugins/RynthCore.Plugin.RynthLeafDawn/RynthCore.Plugin.RynthLeafDawn.csproj deleted file mode 100644 index 7cba983..0000000 --- a/Plugins/RynthCore.Plugin.RynthLeafDawn/RynthCore.Plugin.RynthLeafDawn.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - - RynthCore.Plugin.RynthLeafDawn - 0.1.0 - leafdawn - LeafDawn - leafdawn.hopto.org - LeafDawn - LeafDawn only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthLeafDawn/ServerData.cs b/Plugins/RynthCore.Plugin.RynthLeafDawn/ServerData.cs deleted file mode 100644 index 78e22f2..0000000 --- a/Plugins/RynthCore.Plugin.RynthLeafDawn/ServerData.cs +++ /dev/null @@ -1,22 +0,0 @@ -// ServerData.cs - What is known about LeafDawn (RynthLeafDawn). Identity (id, hosts, world names) is in the csproj. -namespace RynthCore.Plugin.ServerPack; - -internal static class ServerData -{ - public static ServerPackInfo Create() => - new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) - { - Port = 9000, - Emulator = "ACE", - Ruleset = "PvE", - Status = "Stable", - Summary = "A PVE Server thats goal is to mimic end of game retail. With some custom content", - Facts = new[] - { - "End-of-retail with some custom content.", - "Not the same server as Leafdawning.", - }, - Discord = "https://discord.gg/c2QUBPwPZF", - Source = "public AC server list (acresources/serverslist), checked 2026-10-13", - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthLeafdawning/RynthCore.Plugin.RynthLeafdawning.csproj b/Plugins/RynthCore.Plugin.RynthLeafdawning/RynthCore.Plugin.RynthLeafdawning.csproj deleted file mode 100644 index 33d6188..0000000 --- a/Plugins/RynthCore.Plugin.RynthLeafdawning/RynthCore.Plugin.RynthLeafdawning.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - - RynthCore.Plugin.RynthLeafdawning - 0.1.0 - leafdawning - Leafdawning - leafdawning.duckdns.org - Leafdawning - Leafdawning only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthLeafdawning/ServerData.cs b/Plugins/RynthCore.Plugin.RynthLeafdawning/ServerData.cs deleted file mode 100644 index 7114a19..0000000 --- a/Plugins/RynthCore.Plugin.RynthLeafdawning/ServerData.cs +++ /dev/null @@ -1,24 +0,0 @@ -// ServerData.cs - What is known about Leafdawning (RynthLeafdawning). Identity (id, hosts, world names) is in the csproj. -namespace RynthCore.Plugin.ServerPack; - -internal static class ServerData -{ - public static ServerPackInfo Create() => - new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) - { - Port = 9000, - Emulator = "ACE", - Ruleset = "PvE", - Status = "Stable", - Summary = "A standard, no-frills PvE end-of-retail ACE Asheron's Call server. Runs on dedicated hardware with the ability " + - "to host a large number of players. Enforced 3 account limit.", - Facts = new[] - { - "Standard, no-frills end-of-retail.", - "Not the same server as LeafDawn.", - }, - AccountLimit = "3 accounts (enforced)", - Discord = "https://discord.gg/sQpDgAzSXB", - Source = "public AC server list (acresources/serverslist), checked 2026-10-13", - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthNet/Characters/AtlasNames.cs b/Plugins/RynthCore.Plugin.RynthNet/Characters/AtlasNames.cs new file mode 100644 index 0000000..c1f4ba4 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNet/Characters/AtlasNames.cs @@ -0,0 +1,81 @@ +// ============================================================================ +// RynthNet - Characters/AtlasNames.cs +// What the Characters window needs from RynthNav's Atlas (NavData\locations.json, +// the file RynthCore's own readers use): the landblocks with a place on the +// surface map (their indoor cells are buildings in the overworld, not a +// dungeon) and the dungeons' names by landblock. Read once, in the background, +// the first time the window is drawn; until then (or with no Atlas) every +// indoor landblock counts as a dungeon and is named by its number. Any thread. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text.Json; +using System.Threading.Tasks; + +namespace RynthCore.Plugin.RynthNet.Characters; + +internal static class AtlasNames +{ + private sealed record Data(HashSet MapLandblocks, Dictionary Dungeons); + + private static volatile Data _data = new(new HashSet(), new Dictionary()); + private static int _started; + + /// Starts the one background read (later calls do nothing). + public static void EnsureLoading(string path) + { + if (System.Threading.Interlocked.Exchange(ref _started, 1) != 0) return; + Task.Run(() => + { + try { if (File.Exists(path)) _data = Parse(File.ReadAllText(path)); } + catch { } + }); + } + + /// A surface building's landblock (a cell's top 16 bits). + public static bool IsMapLandblock(uint lb) => _data.MapLandblocks.Contains(lb & 0xFFFF); + + /// The dungeon's name, "" when the Atlas doesn't name it. + public static string DungeonName(uint lb) => _data.Dungeons.TryGetValue(lb & 0xFFFF, out string? n) ? n : ""; + + /// "Matron Hive East" for a named dungeon, else "LB 6146". + public static string DungeonLabel(uint lb) + { + string name = DungeonName(lb); + return name.Length > 0 ? name : "LB " + (lb & 0xFFFF).ToString("X4", CultureInfo.InvariantCulture); + } + + /// The Atlas's surface landblocks and dungeon names (RynthCore's RynthNavAtlas rules). Pure. + private static Data Parse(string json) + { + var lbs = new HashSet(); + var dungeons = new Dictionary(); + using JsonDocument doc = JsonDocument.Parse(json); + if (doc.RootElement.TryGetProperty("locations", out JsonElement arr) && arr.ValueKind == JsonValueKind.Array) + foreach (JsonElement e in arr.EnumerateArray()) + { + if (e.ValueKind != JsonValueKind.Object) continue; + string cell = Str(e, "cell"), type = Str(e, "type"), name = Str(e, "name"), lb = Str(e, "lb"); + bool onMap = e.TryGetProperty("ns", out JsonElement ns) && ns.ValueKind == JsonValueKind.Number + && e.TryGetProperty("ew", out JsonElement ew) && ew.ValueKind == JsonValueKind.Number; + if (onMap && cell.Length == 8 && uint.TryParse(cell.AsSpan(0, 4), NumberStyles.HexNumber, null, out uint l)) + lbs.Add(l); + if (type == "Dungeon" && name.Length > 0 && uint.TryParse(lb, NumberStyles.HexNumber, null, out uint d)) + dungeons.TryAdd(d, name); + } + return new Data(lbs, dungeons); + } + + /// For tests: the Atlas from text, at once. + internal static void LoadForTests(string json) + { + _data = Parse(json); + _started = 1; + } + + private static string Str(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : ""; +} diff --git a/Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersManifest.cs b/Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersManifest.cs new file mode 100644 index 0000000..3fcb4ce --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersManifest.cs @@ -0,0 +1,25 @@ +// ============================================================================ +// RynthNet - Characters/CharactersManifest.cs +// RynthNet's sections manifest (RynthPluginGetSectionsJson): the Characters +// window, which RynthCore hosts (plugin API v89: header, pop-out, bar button, +// remembered place) and RynthNet draws (RynthPluginRenderEmbed with Surface). +// Its title is the panel key players' saved places, /rc characters and hotkeys +// already use. An engine before v89 ignores "windows". Pure. +// ============================================================================ + +using System.Globalization; +using RynthCore.Plugin.Shared.RynthUi; + +namespace RynthCore.Plugin.RynthNet.Characters; + +internal static class CharactersManifest +{ + public const string Title = "Characters"; + public const string Surface = "window:characters"; + + /// The manifest JSON (built once). + public static readonly string Json = + "{\"version\":1,\"windows\":[{\"id\":\"characters\",\"title\":\"" + Title + "\",\"surface\":\"" + Surface + + "\",\"icon\":\"\\u" + ((int)RynthIcons.UsersThree[0]).ToString("X4", CultureInfo.InvariantCulture) + + "\",\"width\":420,\"height\":260,\"minWidth\":280,\"minHeight\":140,\"bar\":true,\"edgeToEdge\":true}]}"; +} diff --git a/Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersModel.cs b/Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersModel.cs new file mode 100644 index 0000000..b8742fa --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersModel.cs @@ -0,0 +1,310 @@ +// ============================================================================ +// RynthNet - Characters/CharactersModel.cs +// The Characters window's logic (moved from RynthCore's UI/Data, 2026-10-21: +// RynthNet draws the window itself now), pure so Tools/RynthNet.Tests can +// compile it in: parsing RynthNet's snapshot (RynthPluginGetSnapshotJson), +// where another character is relative to you (distance, compass point, or the +// dungeon / map coordinates and "elsewhere"), what it is doing, and the row +// order. RynthCore keeps a copy for its maps' other-characters layer until the +// world map moves to its plugin. +// +// Snapshot shape (RynthNet 0.1.x, Docs/RYNTHNET.md in RynthSuite): +// {version, online, offline?, node, char, world, login, tags, acceptRemote, +// clients:[{node, pid, char, world, login, tags, rtt, +// status:{hp,hpMax,st,stMax,mp,mpMax, cell,x,y,z, ns,ew, heading, +// portal, busy, vitae, id, cmode, bot:{macro, action, ...}} | null, +// age}]} +// Every field is optional: an older client's status lacks id/cmode (0.1.1), +// a client without RynthAi has no bot, one at character select has no status. +// +// Distances: outdoors (and in surface buildings) the landblock grid is one +// space, 192 m per landblock step. A dungeon is its own space: a distance is +// given only when both stand in the same landblock, or both in the +// overworld (SenseData's rule). Which indoor landblocks are overworld is the +// caller's call (isOverworldBlock): RynthNet's is the Atlas's surface landblocks +// (AtlasNames.cs). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.Json; + +namespace RynthCore.Plugin.RynthNet.Characters; + +/// One client from RynthNet's snapshot, as sent (nothing derived yet). +internal sealed class NetCharEntry +{ + public string Node = ""; + public int Pid; + public string Name = ""; + public string World = ""; + public bool LoggedIn; + public string[] Tags = Array.Empty(); + + /// A status object was present (the client has logged in and sent one). + public bool HasStatus; + /// Milliseconds since that status arrived (-1 = unknown). + public long AgeMs = -1; + + public bool HasVitals; + public uint Hp, HpMax, St, StMax, Mp, MpMax; + + public bool HasPose; + public uint Cell; + public float X, Y, Z; + + public bool HasCoords; + public double Ns, Ew; + + public bool Portal; + /// The character's object id (RynthNet 0.1.1+), 0 when not sent. + public uint Id; + /// AC combat mode (1 peace, 2 melee, 4 missile, 8 magic); 0 when not sent. + public int CombatMode; + + public bool HasBot; + public bool Macro; + public string Action = ""; +} + +internal sealed class NetCharSnapshot +{ + public static readonly NetCharSnapshot Empty = new(); + + public bool Online; + public string Offline = ""; + public string Version = ""; + public string MyName = ""; + public string MyWorld = ""; + public List Clients = new(); +} + +internal enum CharStateKind { None, Idle, Botting, Fighting, CombatMode, Dead, Portal, NoStatus, LoggedOut } + +/// Where another character is, relative to you. +internal readonly record struct CharPlace(bool Measured, float Distance, float Bearing, string Compass, string Location) +{ + public string DistanceText => Measured ? Distance.ToString("0", CultureInfo.InvariantCulture) + " yd" : ""; +} + +internal static class CharactersModel +{ + public const float LandblockSize = 192f; + + /// A status older than this is shown as stale (the client stopped ticking or sending). + public const long StaleMs = 5000; + + private static readonly string[] Compass8 = { "N", "NE", "E", "SE", "S", "SW", "W", "NW" }; + + // ── Parsing ───────────────────────────────────────────────────────── + + /// Parses one snapshot. Null for null/empty/invalid JSON or a non-object root. + public static NetCharSnapshot? Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return null; + try + { + using var doc = JsonDocument.Parse(json); + JsonElement r = doc.RootElement; + if (r.ValueKind != JsonValueKind.Object) return null; + var snap = new NetCharSnapshot + { + Online = Bool(r, "online"), + Offline = Str(r, "offline"), + Version = Str(r, "version"), + MyName = Str(r, "char"), + MyWorld = Str(r, "world"), + }; + if (r.TryGetProperty("clients", out JsonElement arr) && arr.ValueKind == JsonValueKind.Array) + foreach (JsonElement c in arr.EnumerateArray()) + if (c.ValueKind == JsonValueKind.Object) snap.Clients.Add(ParseClient(c)); + return snap; + } + catch (JsonException) + { + return null; + } + } + + private static NetCharEntry ParseClient(JsonElement c) + { + var e = new NetCharEntry + { + Node = Str(c, "node"), + Pid = (int)Num(c, "pid"), + Name = Str(c, "char").Trim(), + World = Str(c, "world"), + LoggedIn = Bool(c, "login"), + }; + if (c.TryGetProperty("tags", out JsonElement tags) && tags.ValueKind == JsonValueKind.Array) + { + var list = new List(); + foreach (JsonElement t in tags.EnumerateArray()) + if (t.ValueKind == JsonValueKind.String && t.GetString() is { Length: > 0 } s) list.Add(s); + e.Tags = list.ToArray(); + } + if (c.TryGetProperty("status", out JsonElement s0) && s0.ValueKind == JsonValueKind.Object) + { + e.HasStatus = true; + e.AgeMs = c.TryGetProperty("age", out JsonElement age) && age.ValueKind == JsonValueKind.Number ? (long)age.GetDouble() : -1; + if (Has(s0, "hp") && Has(s0, "hpMax")) + { + e.HasVitals = true; + e.Hp = U(s0, "hp"); e.HpMax = U(s0, "hpMax"); + e.St = U(s0, "st"); e.StMax = U(s0, "stMax"); + e.Mp = U(s0, "mp"); e.MpMax = U(s0, "mpMax"); + } + if (Has(s0, "cell")) + { + e.Cell = U(s0, "cell"); + e.X = (float)Num(s0, "x"); e.Y = (float)Num(s0, "y"); e.Z = (float)Num(s0, "z"); + e.HasPose = (e.Cell >> 16) != 0; + } + if (Has(s0, "ns") && Has(s0, "ew")) + { + e.HasCoords = true; + e.Ns = Num(s0, "ns"); e.Ew = Num(s0, "ew"); + } + e.Portal = Bool(s0, "portal"); + e.Id = U(s0, "id"); + e.CombatMode = (int)Num(s0, "cmode"); + if (s0.TryGetProperty("bot", out JsonElement bot) && bot.ValueKind == JsonValueKind.Object) + { + e.HasBot = true; + e.Macro = Bool(bot, "macro"); + e.Action = Str(bot, "action"); + } + } + return e; + } + + private static bool Has(JsonElement e, string name) => e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number; + + private static double Num(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number ? v.GetDouble() : 0; + + private static uint U(JsonElement e, string name) + { + double d = Num(e, name); + return d <= 0 ? 0 : d >= uint.MaxValue ? uint.MaxValue : (uint)d; + } + + private static bool Bool(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True; + + private static string Str(JsonElement e, string name) => + e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : ""; + + // ── Location ──────────────────────────────────────────────────────── + + public static bool IsOutdoorCell(uint cell) => (cell & 0xFFFF) < 0x100; + + /// Compass bearing (0 = north, clockwise) to the nearest of 8 points. + public static string Compass(float bearing) + { + float b = ((bearing % 360f) + 360f) % 360f; + return Compass8[(int)MathF.Round(b / 45f) & 7]; + } + + /// "42.1N 33.6E" from a cell and its local x/y (the client's own coordinate basis). + public static string Coords(uint cell, float x, float y) + { + int lbX = (int)((cell >> 24) & 0xFF), lbY = (int)((cell >> 16) & 0xFF); + double ew = (lbX * 8.0 + x / 24.0 - 1019.5) / 10.0; + double ns = (lbY * 8.0 + y / 24.0 - 1019.5) / 10.0; + return CoordsText(ns, ew); + } + + public static string CoordsText(double ns, double ew) => + Math.Abs(ns).ToString("0.0", CultureInfo.InvariantCulture) + (ns >= 0 ? "N " : "S ") + + Math.Abs(ew).ToString("0.0", CultureInfo.InvariantCulture) + (ew >= 0 ? "E" : "W"); + + /// + /// Where (, x, y, z) is from you at (, mx, my, mz). + /// : whether an indoor cell's landblock (cell >> 16) is part of + /// the overworld (a surface building) rather than a dungeon. : a + /// landblock's dungeon name, "" when unknown. Either may be null. + /// + public static CharPlace Locate(uint myCell, float mx, float my, float mz, + uint cell, float x, float y, float z, + Func? isOverworldBlock, Func? dungeonName) + { + uint lb = cell >> 16, myLb = myCell >> 16; + bool theyOver = IsOutdoorCell(cell) || (isOverworldBlock?.Invoke(lb) ?? false); + bool meOver = myLb != 0 && (IsOutdoorCell(myCell) || (isOverworldBlock?.Invoke(myLb) ?? false)); + string dn = theyOver ? "" : dungeonName?.Invoke(lb) ?? ""; + string where = theyOver ? Coords(cell, x, y) + : dn.Length > 0 ? dn + : "dungeon LB " + lb.ToString("X4", CultureInfo.InvariantCulture); + + bool measured = myLb != 0 && (lb == myLb || (theyOver && meOver)); + if (!measured) + return new CharPlace(false, float.PositiveInfinity, float.NaN, "", where); + + int dxb = (int)((cell >> 24) & 0xFF) - (int)((myCell >> 24) & 0xFF); + int dyb = (int)((cell >> 16) & 0xFF) - (int)((myCell >> 16) & 0xFF); + float dx = x + dxb * LandblockSize - mx, dy = y + dyb * LandblockSize - my, dz = z - mz; + float dist = MathF.Sqrt(dx * dx + dy * dy + dz * dz); + float flat = MathF.Sqrt(dx * dx + dy * dy); + if (flat < 0.5f) return new CharPlace(true, dist, float.NaN, "here", where); + float b = MathF.Atan2(dx, dy) * (180f / MathF.PI); + if (b < 0) b += 360f; + return new CharPlace(true, dist, b, Compass(b), where); + } + + // ── State ─────────────────────────────────────────────────────────── + + /// What the character is doing, for the state column. + public static (string Text, CharStateKind Kind) State(NetCharEntry e) + { + if (!e.LoggedIn || e.Name.Length == 0) return ("logged out", CharStateKind.LoggedOut); + if (!e.HasStatus) return ("no status yet", CharStateKind.NoStatus); + if (e.HasVitals && e.HpMax > 0 && e.Hp == 0) return ("dead", CharStateKind.Dead); + if (e.Portal) return ("portal space", CharStateKind.Portal); + if (e.HasBot && e.Macro) + { + string a = e.Action; + if (a.Equals("Combat", StringComparison.OrdinalIgnoreCase)) return ("botting: fighting", CharStateKind.Fighting); + if (a.Length == 0 || a.Equals("Default", StringComparison.OrdinalIgnoreCase)) return ("botting", CharStateKind.Botting); + return ("botting: " + a.ToLowerInvariant(), CharStateKind.Botting); + } + string stance = CombatModeName(e.CombatMode); + if (stance.Length > 0) return ("idle, " + stance, CharStateKind.CombatMode); + return (e.HasBot ? "idle (macro off)" : "idle", CharStateKind.Idle); + } + + /// "melee" / "missile" / "magic" for a combat stance, "" for peace or unknown. + public static string CombatModeName(int mode) => mode switch + { + 2 => "melee", + 4 => "missile", + 8 => "magic", + _ => "", + }; + + public static bool IsStale(NetCharEntry e) => e.LoggedIn && e.HasStatus && e.AgeMs > StaleMs; + + // ── Order ─────────────────────────────────────────────────────────── + + /// + /// Row order: a stable one (Tom, 2026-10-13: distance order reshuffled rows several times a + /// second for characters standing together). Logged-in characters alphabetically by name, + /// then clients without a character, by pid. Distance is a column, never the order. + /// + public static int CompareRows(NetCharEntry a, NetCharEntry b) + { + bool an = a.LoggedIn && a.Name.Length > 0, bn = b.LoggedIn && b.Name.Length > 0; + if (an != bn) return an ? -1 : 1; + int c = string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); + if (c != 0) return c; + c = string.Compare(a.World, b.World, StringComparison.OrdinalIgnoreCase); + return c != 0 ? c : a.Pid.CompareTo(b.Pid); + } + + /// "1234/1500". + public static string VitalText(uint cur, uint max) => + cur.ToString(CultureInfo.InvariantCulture) + "/" + max.ToString(CultureInfo.InvariantCulture); + + public static float Fraction(uint cur, uint max) => max == 0 ? 0f : Math.Clamp(cur / (float)max, 0f, 1f); +} diff --git a/Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersRows.cs b/Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersRows.cs new file mode 100644 index 0000000..40dee94 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersRows.cs @@ -0,0 +1,240 @@ +// ============================================================================ +// RynthNet - Characters/CharactersRows.cs +// The Characters window's rows, built on the plugin tick (twice a second while +// the window is drawn) from RynthNet's own snapshot and this client's pose, +// vitals and object table (through ICharacterGame), then published whole for +// the render thread to draw. Moved from RynthCore's UI/Data/CharactersData.cs +// (2026-10-21); the one difference is that a surface building is known from +// the Atlas only (the engine also used every outdoor object it could see). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; + +namespace RynthCore.Plugin.RynthNet.Characters; + +/// What the rows need from the game (RynthNet's host; a fake in Tools/RynthNet.Tests). Plugin tick. +internal interface ICharacterGame +{ + uint PlayerId { get; } + bool InWorld { get; } + bool Portaling { get; } + uint SelectedId { get; } + bool TryGetPose(out uint cell, out float x, out float y, out float z); + bool TryGetVitals(out uint hp, out uint hpMax, out uint st, out uint stMax, out uint mp, out uint mpMax); + /// The object is in this client's table (it can be selected). + bool TryGetName(uint id, out string name); + bool TryGetPosition(uint id, out uint cell, out float x, out float y, out float z); +} + +/// A vital bar: fill and "cur/max". +internal readonly record struct CharVital(float Fraction, string Text); + +/// One row, preformatted on the tick. +internal sealed class CharacterRow +{ + public string Name = ""; + /// The server's name when it differs from this client's ("" otherwise). + public string OtherWorld = ""; + public bool IsSelf; + public bool LoggedOut; + public uint Id; + /// The character is in this client's object table (a click selects it). + public bool InView; + + public bool HasVitals; + public CharVital Hp, St, Mp; + + public bool Measured; + public float Bearing = float.NaN; + public string DistanceText = ""; + public string Compass = ""; + public string Location = ""; + + public string StateText = ""; + public CharStateKind StateKind; + public bool Stale; + public string StaleText = ""; + public string Tooltip = ""; +} + +internal sealed class CharactersView +{ + public static readonly CharactersView Empty = new(Array.Empty(), "Waiting for RynthNet...", "", 0); + + public CharactersView(CharacterRow[] rows, string status, string myName, uint selectedId) + { + Rows = rows; + Status = status; + MyName = myName; + SelectedId = selectedId; + } + + /// This client first (when logged in), then the others in a stable order. + public CharacterRow[] Rows { get; } + /// The line above the rows: how many, or why there are none. + public string Status { get; } + public string MyName { get; } + /// The game's selection when the rows were built (its row is highlighted). + public uint SelectedId { get; } +} + +internal static class CharactersRows +{ + private static readonly Func IsOverworldBlock = AtlasNames.IsMapLandblock; + private static readonly Func DungeonName = AtlasNames.DungeonName; + + /// The rows for one snapshot. Plugin tick. + public static CharactersView Build(NetCharSnapshot snap, ICharacterGame game) + { + bool inWorld = game.InWorld && game.PlayerId != 0; + uint myCell = 0; + float mx = 0, my = 0, mz = 0; + bool havePose = inWorld && game.TryGetPose(out myCell, out mx, out my, out mz) && (myCell >> 16) != 0; + if (!havePose) { myCell = 0; mx = my = mz = 0; } + bool portaling = game.Portaling; + + var sorted = new List(snap.Clients); + sorted.Sort(CharactersModel.CompareRows); + + var rows = new List(sorted.Count + 1); + string myName = snap.MyName; + if (inWorld) + { + if (myName.Length == 0 && game.TryGetName(game.PlayerId, out string n)) myName = n; + rows.Add(SelfRow(game, myName, snap.MyWorld, havePose, myCell, mx, my, portaling)); + } + + int others = 0, stale = 0; + foreach (NetCharEntry e in sorted) + { + CharacterRow row = OtherRow(game, e, snap.MyWorld, havePose && !portaling, myCell, mx, my, mz); + rows.Add(row); + if (!row.LoggedOut) others++; + if (row.Stale) stale++; + } + + string status; + if (!snap.Online && snap.Version.Length > 0) + status = "RynthNet is offline" + (snap.Offline.Length > 0 ? ": " + snap.Offline : "."); + else if (sorted.Count == 0) + status = "No other RynthCore clients with RynthNet on this PC."; + else + status = others == 1 ? "1 other character" : others + " other characters"; + if (stale > 0) status += $" ({stale} not updating)"; + return new CharactersView(rows.ToArray(), status, myName, inWorld ? game.SelectedId : 0); + } + + private static CharacterRow SelfRow(ICharacterGame game, string name, string world, bool havePose, uint cell, float x, float y, bool portaling) + { + var row = new CharacterRow + { + Name = name.Length > 0 ? name : "You", + IsSelf = true, + Id = game.PlayerId, + StateText = "this client", + }; + if (game.TryGetVitals(out uint hp, out uint hpMax, out uint st, out uint stMax, out uint mp, out uint mpMax) && hpMax > 0) + { + row.HasVitals = true; + row.Hp = Vital(hp, hpMax); + row.St = Vital(st, stMax); + row.Mp = Vital(mp, mpMax); + } + if (portaling) row.Location = "portal space"; + else if (havePose) + { + uint lb = cell >> 16; + bool over = CharactersModel.IsOutdoorCell(cell) || IsOverworldBlock(lb); + row.Location = over ? CharactersModel.Coords(cell, x, y) : AtlasNames.DungeonLabel(lb); + } + row.Tooltip = row.Name + " (this client)" + (world.Length > 0 ? "\n" + world : ""); + return row; + } + + private static CharacterRow OtherRow(ICharacterGame game, NetCharEntry e, string myWorld, bool canMeasure, uint myCell, float mx, float my, float mz) + { + (string stateText, CharStateKind kind) = CharactersModel.State(e); + var row = new CharacterRow + { + Name = e.LoggedIn && e.Name.Length > 0 ? e.Name : "Not logged in (pid " + e.Pid.ToString(CultureInfo.InvariantCulture) + ")", + LoggedOut = kind == CharStateKind.LoggedOut, + Id = e.Id, + StateText = stateText, + StateKind = kind, + Stale = CharactersModel.IsStale(e), + }; + if (row.Stale) row.StaleText = "no update " + (e.AgeMs / 1000).ToString(CultureInfo.InvariantCulture) + " s"; + bool sameWorld = e.World.Length == 0 || myWorld.Length == 0 || string.Equals(e.World, myWorld, StringComparison.OrdinalIgnoreCase); + if (!sameWorld) row.OtherWorld = e.World; + + if (e.HasVitals && e.HpMax > 0) + { + row.HasVitals = true; + row.Hp = Vital(e.Hp, e.HpMax); + row.St = Vital(e.St, e.StMax); + row.Mp = Vital(e.Mp, e.MpMax); + } + + // Where: this client's own view of the character when it has one (fresher), else the status. + uint cell = e.Cell; + float x = e.X, y = e.Y, z = e.Z; + bool hasPose = e.HasPose; + if (sameWorld && e.Id != 0 && game.TryGetName(e.Id, out _)) + { + row.InView = true; + if (game.TryGetPosition(e.Id, out uint c2, out float x2, out float y2, out float z2) && (c2 >> 16) != 0) + { + cell = c2; x = x2; y = y2; z = z2; + hasPose = true; + } + } + + if (row.LoggedOut) row.Location = ""; + else if (!sameWorld) row.Location = "on " + e.World; + else if (e.Portal) row.Location = "portal space"; + else if (hasPose) + { + CharPlace p = canMeasure + ? CharactersModel.Locate(myCell, mx, my, mz, cell, x, y, z, IsOverworldBlock, DungeonName) + : CharactersModel.Locate(0, 0, 0, 0, cell, x, y, z, IsOverworldBlock, DungeonName); + row.Measured = p.Measured; + row.Bearing = p.Bearing; + row.DistanceText = p.Measured ? p.DistanceText : "elsewhere"; + row.Compass = p.Compass; + row.Location = p.Location; + } + else if (e.HasCoords) + { + row.Location = CharactersModel.CoordsText(e.Ns, e.Ew); + } + + row.Tooltip = Tooltip(e, row, cell, hasPose); + return row; + } + + private static CharVital Vital(uint cur, uint max) => new(CharactersModel.Fraction(cur, max), CharactersModel.VitalText(cur, max)); + + private static string Tooltip(NetCharEntry e, CharacterRow row, uint cell, bool hasPose) + { + var sb = new StringBuilder(200); + sb.Append(row.Name).Append('\n'); + if (e.World.Length > 0) sb.Append(e.World).Append('\n'); + if (e.Tags.Length > 0) sb.Append("tags: ").Append(string.Join(", ", e.Tags)).Append('\n'); + sb.Append(row.StateText); + if (e.HasBot && e.Action.Length > 0 && !e.Macro) sb.Append(" (last action: ").Append(e.Action).Append(')'); + sb.Append('\n'); + if (row.Measured) sb.Append(row.DistanceText).Append(' ').Append(row.Compass).Append(", "); + else if (hasPose && row.OtherWorld.Length == 0) sb.Append("Elsewhere: not in the same space as you (another dungeon or landblock), so no distance.\n"); + if (row.Location.Length > 0) sb.Append(row.Location); + if (hasPose) sb.Append(" (LB ").Append((cell >> 16).ToString("X4", CultureInfo.InvariantCulture)).Append(')'); + sb.Append('\n'); + if (e.AgeMs >= 0) sb.Append("status ").Append((e.AgeMs / 1000.0).ToString("0.0", CultureInfo.InvariantCulture)).Append(" s old\n"); + if (row.Id == 0) sb.Append("Its RynthNet is older than 0.1.1: no object id, so a click can't select it."); + else if (row.InView) sb.Append("Click to select. Right-click for commands."); + else sb.Append("Not in view: a click can't select it. Right-click for commands."); + return sb.ToString(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersWindow.cs b/Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersWindow.cs new file mode 100644 index 0000000..39db389 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNet/Characters/CharactersWindow.cs @@ -0,0 +1,372 @@ +// ============================================================================ +// RynthNet - Characters/CharactersWindow.cs +// The Characters window, drawn by RynthNet (2026-10-21; it was RynthCore's +// ImGui/Panels/CharactersFace.cs): RynthCore hosts the window (the manifest's +// "characters" window: header, pop-out, bar button, remembered place) and calls +// Draw through RynthPluginRenderEmbed. Each row: an arrow to the character +// (turning with you), name, server, what it is doing, a stale marker, the +// distance and compass point, the three vitals and where it is. Click selects +// it in game; right-click for /rn commands. Looks: Shared/RynthUi (the +// player's theme). AC's render thread: it reads the published rows and the +// pose, and queues everything it does for the plugin tick. +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.Shared; +using RynthCore.Plugin.Shared.RynthUi; +using RynthCore.PluginSdk; +using static RynthCore.Plugin.Shared.RynthUi.RynthUi; + +namespace RynthCore.Plugin.RynthNet.Characters; + +internal sealed class CharactersWindow +{ + private readonly Action _select; + private readonly Action _tell; + private readonly Action _followMeAll; + private readonly Func<(bool Ok, float Heading)> _heading; + + // The vitals colours of RynthAi's dashboard (fixed, whatever the theme). + private static readonly uint HpCol = Argb(0xFFD93333), StCol = Argb(0xFF40D973), MpCol = Argb(0xFF268CF2), + BarBg = Argb(0xFF0D161F), Purple = Argb(0xFFBF4DFF), White = Argb(0xFFFFFFFF); + + private const string HelpText = + "Your other characters: every RynthCore client on this PC running the RynthNet plugin.\n\n" + + "Each row shows health, stamina and mana, what the character is doing, and where it is. " + + "The distance and direction show when you are both outdoors (or in surface buildings), or in the same dungeon; " + + "otherwise the row says elsewhere and names the dungeon or gives map coordinates. Characters on another server " + + "only show their server.\n\n" + + "Rows stay in alphabetical order. A row that stops updating says so (its client may be frozen).\n\n" + + "Click a row to select that character in game (when this client can see it). Right-click for commands: " + + "follow me, stop following, start or stop the macro. They go through RynthNet, so the other client's " + + "remote command setting (/rn remote) decides whether they run.\n\n" + + "/rc characters opens and closes this window."; + + private float _k = 1f; + private float Px(float v) => v * _k; + + // The right-clicked row (copied: the rows can change while the popup is open). + private string _menuName = ""; + private uint _menuId; + private bool _menuInView, _menuOtherWorld, _menuSelf, _menuLoggedOut; + private bool _openMenu; + + public CharactersWindow(Action select, Action tell, Action followMeAll, Func<(bool, float)> heading) + { + _select = select; + _tell = tell; + _followMeAll = followMeAll; + _heading = heading; + } + + /// Draws the window body into the current ImGui window. Render thread. + public void Draw(CharactersView view) + { + _k = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f); + Vector2 origin = ImGui.GetCursorScreenPos(); + Vector2 size = ImGui.GetContentRegionAvail(); + if (size.X < 40 || size.Y < 30) return; + ImDrawListPtr frame = ImGui.GetWindowDrawList(); + frame.AddRectFilled(origin, origin + size, Background, 4); + using (PushFont(RynthUiFont.Ui10)) + { + ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4)); + ImGui.SetCursorScreenPos(origin + new Vector2(6, 6)); + ImGui.Indent(6); + float w = size.X - 12; + DrawTop(view, w); + + // The host's resize grip sits over the bottom-right corner: the rows end above it. + float bodyH = Math.Max(Px(30), origin.Y + size.Y - 6 - ImGui.GetCursorScreenPos().Y - Px(12)); + ImGui.PushStyleColor(ImGuiCol.ChildBg, Field); + ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0)); + ImGui.BeginChild("##chars_rows", new Vector2(w, bodyH)); + DrawRows(view); + ImGui.EndChild(); + ImGui.PopStyleVar(); + ImGui.PopStyleColor(); + + ImGui.Unindent(6); + ImGui.PopStyleVar(); + DrawMenu(view); + } + frame.AddRect(origin, origin + size, Border, 4); + } + + // ── Top line ──────────────────────────────────────────────────────── + + private void DrawTop(CharactersView view, float w) + { + Vector2 start = ImGui.GetCursorScreenPos(); + float h = Px(20), iconW = Px(22); + float fontH = ImGui.GetFontSize(); + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + float textW = Math.Max(10, w - 2 * iconW - Px(8)); + dl.PushClipRect(start, start + new Vector2(textW, h), true); + dl.AddText(new Vector2(start.X, start.Y + (h - fontH) * 0.5f), Mute, view.Status); + dl.PopClipRect(); + + float bx = start.X + w - 2 * iconW - Px(4); + bool canFollow = view.MyName.Length > 0; + if (IconButton("##chars_followall", RynthIcons.Footprints, new Vector2(bx, start.Y), new Vector2(iconW, h), Text, ButtonFill, + enabled: canFollow, font: RynthUiFont.Ui11)) + _followMeAll(); + ImGui.SetItemTooltip("Everyone follow me (/rn followme): every other client runs /ra follow ."); + IconButton("##chars_help", RynthIcons.Info, new Vector2(bx + iconW + Px(4), start.Y), new Vector2(iconW, h), Mute, ButtonFill, + font: RynthUiFont.Ui11); + if (ImGui.IsItemHovered()) + { + ImGui.BeginTooltip(); + ImGui.PushTextWrapPos(ImGui.GetFontSize() * 30); + ImGui.TextUnformatted(HelpText); + ImGui.PopTextWrapPos(); + ImGui.EndTooltip(); + } + ImGui.SetCursorScreenPos(new Vector2(start.X, start.Y + h + Px(4))); + ImGui.Dummy(Vector2.Zero); + } + + // ── Rows ──────────────────────────────────────────────────────────── + + private float RowH => Px(38); + + private void DrawRows(CharactersView view) + { + CharacterRow[] rows = view.Rows; + float bw = ImGui.GetContentRegionAvail().X; + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + if (rows.Length == 0) + { + Vector2 at = ImGui.GetCursorScreenPos() + new Vector2(Px(6), Px(6)); + dl.AddText(at, Faded(Mute), "Not in the world."); + return; + } + + (bool haveHeading, float heading) = _heading(); + float rowH = RowH; + Vector2 start = ImGui.GetCursorScreenPos(); + int hovered = -1; + + for (int i = 0; i < rows.Length; i++) + { + CharacterRow r = rows[i]; + var p = new Vector2(start.X, start.Y + i * rowH); + ImGui.SetCursorScreenPos(p); + ImGui.PushID(i); + bool clicked = ImGui.InvisibleButton("##row", new Vector2(bw, rowH), + ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight); + bool hot = ImGui.IsItemHovered(); + bool right = clicked && ImGui.IsMouseReleased(ImGuiMouseButton.Right); + ImGui.PopID(); + if (hot) hovered = i; + if (clicked && !right && r.InView && r.Id != 0 && !r.IsSelf) _select(r.Id); + if (right) OpenMenu(r); + + DrawRow(dl, r, p, bw, rowH, i, hot, r.Id != 0 && r.Id == view.SelectedId, heading, haveHeading); + } + + ImGui.SetCursorScreenPos(start); + ImGui.Dummy(new Vector2(bw, rows.Length * rowH)); + + if (hovered >= 0 && rows[hovered].Tooltip.Length > 0 && !ImGui.IsPopupOpen("##chars_menu")) + { + ImGui.BeginTooltip(); + ImGui.TextUnformatted(rows[hovered].Tooltip); + ImGui.EndTooltip(); + } + } + + private void DrawRow(ImDrawListPtr dl, CharacterRow r, Vector2 p, float bw, float rowH, int index, bool hot, bool isSel, + float heading, bool haveHeading) + { + uint bg = isSel ? Selected : hot ? Lighten(Field) : (index & 1) == 1 ? RowAlt : 0; + if (bg != 0) dl.AddRectFilled(p, p + new Vector2(bw, rowH), bg); + if (isSel) dl.AddRect(p, p + new Vector2(bw, rowH), Accent); + // This client's row is dimmed: it's here for comparison. + float dim = r.IsSelf || r.LoggedOut ? 0.55f : 1f; + + ImFontPtr bold = Font(RynthUiFont.UiBold11), f10 = Font(RynthUiFont.Ui10); + float arrowW = Px(20), pad = Px(4); + float line1 = p.Y + Px(3); + float x = p.X + arrowW; + float right = p.X + bw - pad; + + // Arrow / dot / ring. + var mid = new Vector2(p.X + arrowW * 0.5f, line1 + bold.FontSize * 0.5f + Px(1)); + uint arrowCol = Fade(StateColor(r), dim); + if (!r.IsSelf && r.Measured && haveHeading && !float.IsNaN(r.Bearing)) + DrawArrow(dl, mid, r.Bearing - heading, arrowCol, _k); + else if (r.IsSelf || r.Measured) + dl.AddCircleFilled(mid, Px(2.5f), arrowCol); + else + dl.AddCircle(mid, Px(3.5f), Faded(Mute), 12, Px(1.2f)); + + // Right side of line 1: distance + compass (or "elsewhere"). + string dist = r.IsSelf ? "" : r.Measured ? r.DistanceText + (r.Compass.Length > 0 ? " " + r.Compass : "") : r.DistanceText; + float distW = dist.Length > 0 ? ImGui.CalcTextSize(dist).X : 0; + if (dist.Length > 0) + dl.AddText(new Vector2(right - distW, line1 + (bold.FontSize - ImGui.GetFontSize()) * 0.5f), + Fade(r.Measured ? Text : Faded(Mute), dim), dist); + float limit = right - distW - (distW > 0 ? Px(8) : 0); + + // Name (+ server), then state and the stale marker. + float nameW = Math.Min(CalcW(bold, r.Name), Math.Max(Px(40), (limit - x) * 0.55f)); + Clip(dl, bold, r.Name, x, line1, nameW, Fade(r.IsSelf ? Mute : Text, dim)); + float sx = x + nameW + Px(6); + if (r.OtherWorld.Length > 0) + { + string wtext = "[" + r.OtherWorld + "]"; + float ww = Math.Min(CalcW(f10, wtext), Math.Max(0, limit - sx)); + Clip(dl, f10, wtext, sx, line1 + Px(1), ww, Fade(Highlight, dim)); + sx += ww + Px(6); + } + if (r.StateText.Length > 0 && sx < limit) + { + float tw = Math.Min(CalcW(f10, r.StateText), limit - sx); + Clip(dl, f10, r.StateText, sx, line1 + Px(1), tw, Fade(StateColor(r), dim)); + sx += tw + Px(6); + } + if (r.Stale && sx < limit) + Clip(dl, f10, RynthIcons.Warning + " " + r.StaleText, sx, line1 + Px(1), limit - sx, Highlight); + + // Line 2: bars, then the location. + float line2 = line1 + bold.FontSize + Px(4); + float barH = Px(13); + float locW = r.Location.Length > 0 ? Math.Min(CalcW(f10, r.Location), Math.Max(Px(70), bw * 0.32f)) : 0; + float barsW = right - x - (locW > 0 ? locW + Px(8) : 0); + if (barsW < Px(150)) { barsW = right - x; locW = 0; } // narrow: bars first, the tooltip has the place + if (r.HasVitals) + { + float gap = Px(3); + float one = (barsW - 2 * gap) / 3f; + Bar(dl, x, line2, one, barH, r.Hp, HpCol, f10, dim); + Bar(dl, x + one + gap, line2, one, barH, r.St, StCol, f10, dim); + Bar(dl, x + 2 * (one + gap), line2, one, barH, r.Mp, MpCol, f10, dim); + } + else if (!r.LoggedOut) + { + Clip(dl, f10, "no vitals yet", x, line2, barsW, Faded(Mute)); + } + if (locW > 0) + Clip(dl, f10, r.Location, right - locW, line2 + (barH - f10.FontSize) * 0.5f, locW, Fade(Mute, dim)); + } + + private void Bar(ImDrawListPtr dl, float x, float y, float w, float h, CharVital v, uint color, ImFontPtr font, float dim) + { + if (w <= 2) return; + var a = new Vector2(x, y); + var b = new Vector2(x + w, y + h); + float round = Px(3); + dl.AddRectFilled(a, b, BarBg, round); + if (v.Fraction > 0) dl.AddRectFilled(a, new Vector2(x + w * v.Fraction, b.Y), Fade(color, dim), round); + float tw = CalcW(font, v.Text); + float tx = x + Math.Max(Px(3), (w - tw) * 0.5f); + dl.PushClipRect(a, b, true); + dl.AddText(font, font.FontSize, new Vector2(tx, y + (h - font.FontSize) * 0.5f), Fade(White, dim), v.Text); + dl.PopClipRect(); + } + + private static uint StateColor(CharacterRow r) => r.StateKind switch + { + _ when r.IsSelf => Mute, + CharStateKind.Dead => Red, + CharStateKind.Fighting => Highlight, + CharStateKind.Botting => Green, + CharStateKind.Portal => Purple, + CharStateKind.CombatMode => Accent, + CharStateKind.NoStatus or CharStateKind.LoggedOut => Faded(Mute), + _ => Mute, + }; + + private static float CalcW(ImFontPtr font, string text) => + text.Length == 0 ? 0 : font.CalcTextSizeA(font.FontSize, float.MaxValue, 0f, text).X; + + private static void Clip(ImDrawListPtr dl, ImFontPtr font, string text, float x, float y, float width, uint color) + { + if (text.Length == 0 || width <= 0) return; + dl.PushClipRect(new Vector2(x, y - 2), new Vector2(x + width, y + font.FontSize + 4), true); + dl.AddText(font, font.FontSize, new Vector2(x, y), color, text); + dl.PopClipRect(); + } + + private static uint Fade(uint abgr, float k) + { + if (k >= 1f) return abgr; + uint a = (uint)Math.Clamp((int)(((abgr >> 24) & 0xFF) * k), 0, 255); + return (abgr & 0x00FFFFFF) | (a << 24); + } + + /// An arrow pointing clockwise from straight up (up = the way you face). + private static void DrawArrow(ImDrawListPtr dl, Vector2 c, float degrees, uint color, float k) + { + float rad = degrees * (MathF.PI / 180f); + float s = MathF.Sin(rad), co = MathF.Cos(rad); + Vector2 tip = Rot(c, 0, -6.5f * k, s, co), left = Rot(c, -4.5f * k, 5f * k, s, co), + notch = Rot(c, 0, 2.5f * k, s, co), rgt = Rot(c, 4.5f * k, 5f * k, s, co); + dl.AddTriangleFilled(tip, left, notch, color); + dl.AddTriangleFilled(tip, notch, rgt, color); + } + + private static Vector2 Rot(Vector2 c, float x, float y, float s, float co) => + new(c.X + x * co - y * s, c.Y + x * s + y * co); + + // ── Right-click menu ──────────────────────────────────────────────── + + private void OpenMenu(CharacterRow r) + { + _menuName = r.Name; + _menuId = r.Id; + _menuInView = r.InView; + _menuOtherWorld = r.OtherWorld.Length > 0; + _menuSelf = r.IsSelf; + _menuLoggedOut = r.LoggedOut; + _openMenu = true; + } + + private void DrawMenu(CharactersView view) + { + if (_openMenu) + { + _openMenu = false; + ImGui.OpenPopup("##chars_menu"); + } + ImGui.PushStyleColor(ImGuiCol.PopupBg, Background); + ImGui.PushStyleColor(ImGuiCol.Border, Accent); + ImGui.PushStyleColor(ImGuiCol.Text, Text); + ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(8), Px(6))); + bool open = ImGui.BeginPopup("##chars_menu"); + ImGui.PopStyleVar(); + ImGui.PopStyleColor(3); + if (!open) return; + try + { + string me = view.MyName; + bool canFollow = me.Length > 0; + if (!_menuSelf && !_menuLoggedOut) + { + SafeImGui.TextDisabled(_menuName); + if (ImGui.MenuItem("Select", "", false, _menuInView && _menuId != 0)) _select(_menuId); + ImGui.Separator(); + if (ImGui.MenuItem("Follow me", "", false, canFollow && !_menuOtherWorld)) _tell(_menuName, "/ra follow " + me); + SafeImGui.SetItemTooltip($"/rn tell {_menuName}, /ra follow {me}"); + if (ImGui.MenuItem("Stop following")) _tell(_menuName, "/ra follow off"); + SafeImGui.SetItemTooltip($"/rn tell {_menuName}, /ra follow off"); + ImGui.Separator(); + if (ImGui.MenuItem("Start macro")) _tell(_menuName, "/ra start"); + SafeImGui.SetItemTooltip($"/rn tell {_menuName}, /ra start"); + if (ImGui.MenuItem("Stop macro")) _tell(_menuName, "/ra stop"); + SafeImGui.SetItemTooltip($"/rn tell {_menuName}, /ra stop"); + ImGui.Separator(); + } + if (ImGui.MenuItem("Everyone: follow me", "", false, canFollow)) _followMeAll(); + ImGui.SetItemTooltip("/rn followme"); + ImGui.TextDisabled("The other client's /rn remote setting decides."); + } + finally + { + ImGui.EndPopup(); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNet/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthNet/PluginExports.cs index 7fcd491..f6970f3 100644 --- a/Plugins/RynthCore.Plugin.RynthNet/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthNet/PluginExports.cs @@ -24,6 +24,54 @@ public static unsafe class PluginExports catch { } try { ReleaseSnapshot(); } catch { } + try { ReleaseSections(); } + catch { } + } + + // The windows RynthNet draws (plugin API v89 hosts them; docs in RynthCore docs/PLUGIN_WINDOWS.md). + private static string? _sectionsJson; + private static IntPtr _sectionsPtr; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSectionsJson", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetSectionsJson() + { + try + { + if (Runtime.Plugin == null) return IntPtr.Zero; + string json = Characters.CharactersManifest.Json; + if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr; + _sectionsJson = json; + IntPtr fresh = Marshal.StringToCoTaskMemUTF8(json); + IntPtr old = Interlocked.Exchange(ref _sectionsPtr, fresh); + if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old); + return fresh; + } + catch { return IntPtr.Zero; } + } + + private static void ReleaseSections() + { + IntPtr old = Interlocked.Exchange(ref _sectionsPtr, IntPtr.Zero); + if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old); + _sectionsJson = null; + } + + // A window's body (AC's render thread): 1 drawn, 0 not this plugin's surface or not ready. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })] + public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight) + { + try + { + if (surface == null) return 0; + string name = Marshal.PtrToStringUTF8((IntPtr)surface) ?? string.Empty; + if (name.EndsWith(":popout", StringComparison.Ordinal)) name = name[..^":popout".Length]; + RynthNetPlugin? plugin = Runtime.Plugin; + if (plugin == null || !plugin.RenderEmbed(name, out float wantH)) return 0; + if (wantWidth != null) *wantWidth = width; + if (wantHeight != null) *wantHeight = wantH > 0 ? wantH : height; + return 1; + } + catch { return 0; } } [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] diff --git a/Plugins/RynthCore.Plugin.RynthNet/RynthCore.Plugin.RynthNet.csproj b/Plugins/RynthCore.Plugin.RynthNet/RynthCore.Plugin.RynthNet.csproj index 1ce02a2..ee9b920 100644 --- a/Plugins/RynthCore.Plugin.RynthNet/RynthCore.Plugin.RynthNet.csproj +++ b/Plugins/RynthCore.Plugin.RynthNet/RynthCore.Plugin.RynthNet.csproj @@ -42,5 +42,21 @@ + + + + + + + + + + + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthNet/RynthNetPlugin.Characters.cs b/Plugins/RynthCore.Plugin.RynthNet/RynthNetPlugin.Characters.cs new file mode 100644 index 0000000..47f3365 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNet/RynthNetPlugin.Characters.cs @@ -0,0 +1,110 @@ +// ============================================================================ +// RynthNet - RynthNetPlugin.Characters.cs +// The Characters window, RynthNet's own (2026-10-21; RynthCore drew it before): +// the sections manifest declares it ("windows", plugin API v89: RynthCore hosts +// it and gives it a bar button), RynthPluginRenderEmbed draws it +// (Characters/CharactersWindow.cs), and the tick rebuilds its rows twice a +// second while it is on screen (Characters/CharactersRows.cs). The window's +// clicks are queued here and run on the tick: selecting a character, and /rn +// tell / followme through the same queue as typed commands. +// ============================================================================ + +using System; +using System.Collections.Concurrent; +using System.IO; +using RynthCore.Install; +using RynthCore.Plugin.RynthNet.Characters; +using RynthCore.Plugin.Shared.RynthUi; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthNet; + +public sealed partial class RynthNetPlugin +{ + private const string CharactersSurface = CharactersManifest.Surface; + private const long CharactersRefreshMs = 500; + /// Rows are built only while the window was drawn this recently. + private const long CharactersShownMs = 2000; + + private CharactersWindow? _charsWindow; // render thread + private volatile CharactersView _charsView = CharactersView.Empty; + private long _charsDrawnMs = long.MinValue / 2; // render thread writes, tick reads + private long _nextCharsMs; + private string? _charsJson; + private NetCharSnapshot? _charsSnap; + private readonly ConcurrentQueue _uiActions = new(); + private HostGame? _game; + + /// RynthPluginRenderEmbed: draws (":popout" already off). Render thread. + internal bool RenderEmbed(string surface, out float wantHeight) + { + wantHeight = 0; + if (!surface.Equals(CharactersSurface, StringComparison.Ordinal)) return false; + System.Threading.Volatile.Write(ref _charsDrawnMs, Environment.TickCount64); + AtlasNames.EnsureLoading(Path.Combine(RynthInstallPaths.CoreDir, "NavData", "locations.json")); + _charsWindow ??= new CharactersWindow( + select: id => _uiActions.Enqueue(() => { if (id != 0) Host.SelectItem(id); }), + tell: (name, command) => _localCommands.Enqueue(("/rn tell " + name + ", " + command, false)), + followMeAll: () => _localCommands.Enqueue(("/rn followme", false)), + heading: CompassHeading); + _charsWindow.Draw(_charsView); + return true; + } + + /// Plugin tick: the window's queued clicks, and its rows while it is on screen. + private void TickCharacters() + { + while (_uiActions.TryDequeue(out Action? act)) + { + try { act(); } + catch (Exception ex) { Host.Log("[RynthNet] Characters: " + ex.Message); } + } + long now = Environment.TickCount64; + if (now - System.Threading.Volatile.Read(ref _charsDrawnMs) > CharactersShownMs || now < _nextCharsMs) return; + _nextCharsMs = now + CharactersRefreshMs; + string json = _snapshot; + if (!ReferenceEquals(json, _charsJson)) + { + _charsJson = json; + _charsSnap = CharactersModel.Parse(json); + } + _game ??= new HostGame(this); + _charsView = CharactersRows.Build(_charsSnap ?? NetCharSnapshot.Empty, _game); + } + + /// Your compass heading (0 = north, clockwise) from the pose's yaw quaternion. Render thread. + private (bool Ok, float Heading) CompassHeading() + { + if (!Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out float qw, out _, out _, out float qz) || cell == 0) + return (false, 0f); + double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI); + return (true, (float)((-yaw % 360.0 + 720.0) % 360.0)); + } + + /// The game through RynthNet's host (plugin tick). + private sealed class HostGame : ICharacterGame + { + private readonly RynthNetPlugin _p; + public HostGame(RynthNetPlugin p) => _p = p; + private RynthCoreHost Host => _p.Host; + + public uint PlayerId => Host.GetPlayerId(); + public bool InWorld => _p._loggedIn; + public bool Portaling => Host.HasIsPortaling && Host.IsPortaling(); + public uint SelectedId => Host.GetSelectedItemId(); + + public bool TryGetPose(out uint cell, out float x, out float y, out float z) => + Host.TryGetPlayerPose(out cell, out x, out y, out z, out _, out _, out _, out _); + + public bool TryGetVitals(out uint hp, out uint hpMax, out uint st, out uint stMax, out uint mp, out uint mpMax) => + Host.TryGetPlayerVitals(out hp, out hpMax, out st, out stMax, out mp, out mpMax); + + public bool TryGetName(uint id, out string name) => Host.TryGetObjectName(id, out name); + + public bool TryGetPosition(uint id, out uint cell, out float x, out float y, out float z) + { + cell = 0; x = y = z = 0; + return Host.HasGetObjectPosition && Host.TryGetObjectPosition(id, out cell, out x, out y, out z); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNet/RynthNetPlugin.cs b/Plugins/RynthCore.Plugin.RynthNet/RynthNetPlugin.cs index ca8ac96..68b08bf 100644 --- a/Plugins/RynthCore.Plugin.RynthNet/RynthNetPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthNet/RynthNetPlugin.cs @@ -58,6 +58,9 @@ public sealed partial class RynthNetPlugin : RynthPluginBase public override int Initialize() { + // The Characters window draws with ImGui.NET bound to the engine's cimgui, in the engine's look. + RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log("[RynthNet] " + msg)); + RynthCore.Plugin.Shared.RynthUi.RynthUi.Init(Host); _settings = RynthNetSettings.Load(out string? settingsError); _settingsStamp = RynthNetSettings.FileStamp(); if (settingsError != null) Host.Log("[RynthNet] " + settingsError); @@ -196,6 +199,7 @@ public sealed partial class RynthNetPlugin : RynthPluginBase _nextSnapshotMs = now + 500; _snapshot = BuildSnapshotJson(node, now); } + TickCharacters(); } internal string Snapshot => _snapshot; diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/DynamicStamps.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/DynamicStamps.cs deleted file mode 100644 index d504d52..0000000 --- a/Plugins/RynthCore.Plugin.RynthOracle/Data/DynamicStamps.cs +++ /dev/null @@ -1,170 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; - -namespace RynthCore.Plugin.RynthOracle.Data; - -/// -/// One Infinite Leaftide Dynamic Stamp (dynstamps.csv): an NPC hand-in that puts a -/// "Dynamic_N_..." quest flag on the character. List from the players' "ExtraDyn" sheet -/// (10.13.2026, one sheet per area, the wiki's Dynamic Stamps page); NPCs that give no stamp -/// are left out. A stamp is a one-time flag: having it in /myquests means it's done. -/// -internal sealed class DynamicStamp -{ - public string Area = ""; - /// Where in the area (a town, a dungeon, coordinates), or "". - public string Place = ""; - public string Npc = ""; - /// What the NPC gives back (the sheet's "X gives you Y"), or "". - public string Reward = ""; - /// The quest flag, lower case (as QuestFlagStore keys it). - public string Stamp = ""; - public string Note = ""; - - /// The NPC, else the place (a few sheet rows only name the spot). - public string Label => Npc.Length > 0 ? Npc : Place; - - /// - /// The flag this character has for the stamp, or null. The sheet has a few stamps copied - /// without their closing "!" or cut short: those also match with "!" added and, when at - /// least long, the one Dynamic flag on the character starting - /// with them. - /// - public string? MatchedFlag(QuestFlagStore flags) - { - if (flags.TryGet(Stamp, out _)) return Stamp; - if (Stamp.EndsWith('!')) return null; - if (flags.TryGet(Stamp + "!", out _)) return Stamp + "!"; - if (Stamp.Length < MinPrefixLength) return null; - string? only = null; - foreach (string key in flags.Flags.Keys) - { - if (!key.StartsWith(Stamp, StringComparison.OrdinalIgnoreCase)) continue; - if (only != null) return null; // more than one: can't tell which - only = key; - } - return only; - } - - public bool Have(QuestFlagStore flags) => MatchedFlag(flags) != null; - - // Sheet areas that are groupings, not places on the map. - private static readonly HashSet NotPlaces = new(StringComparer.OrdinalIgnoreCase) - { - "Looking Around", "Odd Stamps", "Odd Stamps 2", - }; - - /// - /// Where RynthNav should go for this stamp, best first (RynthNav takes the first that is on its - /// map): the coordinates in the note or the place, the place and its parts ("Mhoire Castle - - /// Great Hall" also tries "Mhoire Castle"), the NPC, then the area. Empty when there is nothing. - /// - public List NavCandidates() - { - var list = new List(); - void Add(string s) - { - s = s.Trim().Trim('.', ',', ';', ':').Trim(); - if (s.Length >= 4 && !char.IsDigit(s[0]) && !list.Contains(s, StringComparer.OrdinalIgnoreCase)) list.Add(s); - } - - foreach (string text in new[] { Note, Place }) - if (NavTargets.FirstCoords(text) is string c && !list.Contains(c)) list.Add(c); - - string place = NavTargets.WithoutCoords(Place); - place = System.Text.RegularExpressions.Regex.Replace(place, @"\b(at|in the|nearby)\b", " ", System.Text.RegularExpressions.RegexOptions.IgnoreCase); - place = System.Text.RegularExpressions.Regex.Replace(place, @"\s+", " ").Trim(); - Add(place); - foreach (string part in place.Split(new[] { " - ", " / ", "(", ")" }, StringSplitOptions.RemoveEmptyEntries)) - Add(part); - Add(Npc); - if (!NotPlaces.Contains(Area)) Add(Area); - return list; - } - - /// A truncated stamp shorter than this is matched exactly only (too many flags share a short stem). - public const int MinPrefixLength = 14; -} - -internal static class DynamicStampList -{ - /// Dynamic stamp quest flags start with this (lower case). - public const string FlagPrefix = "dynamic_"; - - public static List All { get; } = Load(); - - /// The areas in list order (Facility Hub, Looking Around, ...). - public static List Areas { get; } = BuildAreas(); - - /// - /// Dynamic stamps on this character that the list doesn't have (new or unlisted NPCs), so the - /// tab can show them and the count isn't only what the sheet knows. - /// - public static List Unlisted(QuestFlagStore flags) - { - var matched = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (DynamicStamp s in All) - if (s.MatchedFlag(flags) is string f) matched.Add(f); - var extra = new List(); - foreach (string key in flags.Flags.Keys) - if (key.StartsWith(FlagPrefix, StringComparison.OrdinalIgnoreCase) && !matched.Contains(key)) - extra.Add(key); - extra.Sort(StringComparer.OrdinalIgnoreCase); - return extra; - } - - private static List Load() - { - try - { - using StreamReader r = Csv.OpenEmbedded("dynstamps.csv"); - return Parse(r); - } - catch (Exception) - { - // A missing or unreadable list must not take the Quests page down with it. - return new List(); - } - } - - /// - /// Reads a dynstamps.csv (a header row, then one NPC hand-in a row). A row whose stamp isn't a - /// "dynamic_" flag, or repeats one already read, is skipped; a missing column reads as empty. - /// Internal for the tests. - /// - internal static List Parse(TextReader r) - { - var list = new List(); - Dictionary col = Csv.MapColumns(r.ReadLine() ?? ""); - int cArea = Csv.Column(col, "Area"), cPlace = Csv.Column(col, "Place"), cNpc = Csv.Column(col, "Npc"), - cReward = Csv.Column(col, "Reward"), cStamp = Csv.Column(col, "Stamp"), cNote = Csv.Column(col, "Note"); - var seen = new HashSet(StringComparer.OrdinalIgnoreCase); - while (r.ReadLine() is string line) - { - if (string.IsNullOrWhiteSpace(line)) continue; - string[] f = Csv.ParseLine(line); - string stamp = Csv.Field(f, cStamp).Trim().ToLowerInvariant(); - if (!stamp.StartsWith(FlagPrefix, StringComparison.Ordinal) || !seen.Add(stamp)) continue; - list.Add(new DynamicStamp - { - Area = Csv.Field(f, cArea), - Place = Csv.Field(f, cPlace), - Npc = Csv.Field(f, cNpc), - Reward = Csv.Field(f, cReward), - Stamp = stamp, - Note = Csv.Field(f, cNote), - }); - } - return list; - } - - private static List BuildAreas() - { - var areas = new List(); - foreach (DynamicStamp s in All) - if (!areas.Contains(s.Area)) areas.Add(s.Area); - return areas; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/IltServerProfile.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/IltServerProfile.cs deleted file mode 100644 index 38bc2ef..0000000 --- a/Plugins/RynthCore.Plugin.RynthOracle/Data/IltServerProfile.cs +++ /dev/null @@ -1,232 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text; -using System.Text.Json; -using RynthCore.Plugin.Shared; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.RynthOracle.Data; - -/// One Leaftide feature from RynthILT's profile: its state on this server and where it lives. -internal sealed record IltFeature(string Key, string Label, string Group, int State, string Where); - -/// -/// The ACECustom quest bonus list ("/qb list") as RynthILT last read it (the profile's "questBonus" -/// object). 0 = not loaded this session; -1 = unknown. -/// -internal sealed record IltQuestBonusList(bool Disabled, int Generation, long Count, string Status, - IReadOnlyList Completed, IReadOnlyList Incomplete); - -/// -/// What RynthILT reports about the Infinite Leaftide server (the "RynthILT.Server" profile JSON, -/// Plugins/Shared/RynthIltServerApi.cs): whether this is an ILT world, the Leaftide features with -/// their server state, and the fellowship rules. without RynthILT; every field is -/// read leniently so an older or newer RynthILT still parses. -/// -internal sealed class IltServerProfile -{ - /// No RynthILT (or nothing parsed): a retail fellowship and no features. - public static readonly IltServerProfile None = new(); - - /// RynthILT answered with a profile. - public bool Available { get; private init; } - public bool Ilt { get; private init; } - public string World { get; private init; } = ""; - public bool Forced { get; private init; } - public string Source { get; private init; } = ""; - /// Last server-options check (UTC); MinValue = never. - public DateTime CheckedUtc { get; private init; } = DateTime.MinValue; - public IReadOnlyList Features { get; private init; } = Array.Empty(); - - /// The server's fellowship size limit (retail 9 without RynthILT or off ILT). - public int FellowshipMax { get; private init; } = RynthIltServer.RetailFellowshipMax; - /// Fellowship feature states (RynthIltServer.State*): Zone Share, Fellowship Blackjack, luminance share. - public int ZoneShare { get; private init; } = RynthIltServer.StateUnknown; - public int Blackjack { get; private init; } = RynthIltServer.StateUnknown; - public int LuminanceShare { get; private init; } = RynthIltServer.StateUnknown; - - /// The /qb list (ILT worlds with RynthILT 0.2.3 or later); null = none offered. - public IltQuestBonusList? QuestBonus { get; private init; } - - /// The features in one group, in RynthILT's order. - public IEnumerable InGroup(string group) - { - foreach (IltFeature f in Features) - if (string.Equals(f.Group, group, StringComparison.OrdinalIgnoreCase)) yield return f; - } - - /// Parses the profile JSON; when it is empty or not JSON. - public static IltServerProfile Parse(string? json) - { - if (string.IsNullOrWhiteSpace(json)) return None; - try - { - using JsonDocument doc = JsonDocument.Parse(json); - JsonElement root = doc.RootElement; - if (root.ValueKind != JsonValueKind.Object) return None; - - var features = new List(); - if (root.TryGetProperty("features", out JsonElement fs) && fs.ValueKind == JsonValueKind.Array) - { - foreach (JsonElement f in fs.EnumerateArray()) - { - if (f.ValueKind != JsonValueKind.Object) continue; - string key = Str(f, "key"); - if (key.Length == 0) continue; - string label = Str(f, "label"); - features.Add(new IltFeature(key, label.Length > 0 ? label : key, Str(f, "group"), - Int(f, "state", RynthIltServer.StateUnknown), Str(f, "where"))); - } - } - - bool ilt = Bool(root, "ilt"); - int max = RynthIltServer.RetailFellowshipMax; - int zone = RynthIltServer.StateUnknown, bj = RynthIltServer.StateUnknown, lum = RynthIltServer.StateUnknown; - if (root.TryGetProperty("fellowship", out JsonElement fel) && fel.ValueKind == JsonValueKind.Object) - { - max = Int(fel, "maxMembers", max); - zone = Int(fel, "zoneShare", zone); - bj = Int(fel, "blackjack", bj); - lum = Int(fel, "luminanceShare", lum); - } - // A bogus size would let the tab claim room nobody has; stay within what the reader handles. - if (max < 1 || max > 64) max = RynthIltServer.RetailFellowshipMax; - - DateTime checkedUtc = DateTime.MinValue; - string when = Str(root, "checked"); - if (when.Length > 0 - && DateTime.TryParse(when, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t)) - checkedUtc = t; - - return new IltServerProfile - { - Available = true, - Ilt = ilt, - World = Str(root, "world"), - Forced = Bool(root, "forced"), - Source = Str(root, "source"), - CheckedUtc = checkedUtc, - Features = features, - FellowshipMax = max, - ZoneShare = zone, - Blackjack = bj, - LuminanceShare = lum, - QuestBonus = ParseQuestBonus(root), - }; - } - catch (JsonException) - { - return None; - } - } - - /// The "questBonus" object, or null when the profile has none. - private static IltQuestBonusList? ParseQuestBonus(JsonElement root) - { - if (!root.TryGetProperty("questBonus", out JsonElement q) || q.ValueKind != JsonValueKind.Object) return null; - long count = q.TryGetProperty("count", out JsonElement c) && c.ValueKind == JsonValueKind.Number && c.TryGetInt64(out long n) ? n : -1; - return new IltQuestBonusList(Bool(q, "disabled"), Int(q, "generation", 0), count, Str(q, "status"), - Strings(q, "completed"), Strings(q, "incomplete")); - } - - private static string[] Strings(JsonElement o, string name) - { - if (!o.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) return Array.Empty(); - var list = new List(a.GetArrayLength()); - foreach (JsonElement e in a.EnumerateArray()) - if (e.ValueKind == JsonValueKind.String && e.GetString() is { Length: > 0 } s) list.Add(s); - return list.ToArray(); - } - - /// "on", "off" or "checking" for a feature state. - public static string StateText(int state) => state switch - { - RynthIltServer.StateOn => "on", - RynthIltServer.StateOff => "off", - _ => "checking", - }; - - private static string Str(JsonElement o, string name) => - o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : ""; - - private static bool Bool(JsonElement o, string name) => - o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True; - - private static int Int(JsonElement o, string name, int fallback) => - o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : fallback; -} - -/// -/// Reads RynthILT's "RynthILT.Server" interface on the plugin pump. Looks the table up through the -/// host (re-checked while RynthILT is missing or after it unloads, Version 0) and copies the JSON -/// out every ; goes up when the profile changes. -/// -internal sealed unsafe class IltServerLink -{ - private const long PollMs = 2000; - private const long RequeryMs = 10_000; - // Room for the /qb list (hundreds of flags) on top of the features. - private const int MaxBuffer = 512 * 1024; - - private RynthIltServerApiV1* _table; - private long _nextPollAt, _nextQueryAt; - private byte[] _buffer = new byte[8192]; - private string _lastJson = ""; - - public IltServerProfile Profile { get; private set; } = IltServerProfile.None; - public int Revision { get; private set; } - - /// Forget the profile (logout); the next poll reads it again. - public void Clear() - { - _nextPollAt = 0; - SetJson(""); - } - - /// Pump thread. Cheap when not due. - public void Poll(RynthCoreHost host, long now) - { - if (now < _nextPollAt) return; - _nextPollAt = now + PollMs; - RynthIltServerApiV1* t = Table(host, now); - SetJson(t == null ? "" : Read(t)); - } - - /// The table, re-queried when it is missing or RynthILT has shut down (Version 0). - private RynthIltServerApiV1* Table(RynthCoreHost host, long now) - { - if (_table != null && _table->Version >= 1) return _table; - _table = null; - if (now < _nextQueryAt || !host.HasGetPluginInterface) return null; - _nextQueryAt = now + RequeryMs; - var p = (RynthIltServerApiV1*)host.GetPluginInterface(RynthIltServer.PluginName, RynthIltServerApiV1.InterfaceName, RynthIltServerApiV1.InterfaceVersion); - if (p != null && p->Version >= 1 && p->StructSize >= (uint)sizeof(RynthIltServerApiV1) && p->GetProfileJson != null) - _table = p; - return _table; - } - - /// Copies the JSON out, growing the buffer once when RynthILT says it didn't fit. - private string Read(RynthIltServerApiV1* t) - { - for (int attempt = 0; attempt < 2; attempt++) - { - int len; - fixed (byte* b = _buffer) len = t->GetProfileJson(b, _buffer.Length); - if (len <= 0) return ""; - if (len < _buffer.Length) return Encoding.UTF8.GetString(_buffer, 0, len); - if (len + 1 > MaxBuffer) return ""; - _buffer = new byte[len + 1024]; - } - return ""; - } - - /// Takes a profile JSON (internal: the tests feed one without RynthILT). - internal void SetJson(string json) - { - if (json == _lastJson) return; - _lastJson = json; - Profile = IltServerProfile.Parse(json); - Revision++; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestCatalog.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestCatalog.cs index 4323190..685faff 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestCatalog.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/QuestCatalog.cs @@ -2,8 +2,7 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Reflection; +using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthOracle.Data; @@ -11,7 +10,7 @@ namespace RynthCore.Plugin.RynthOracle.Data; internal sealed class Quest { public string Flag = ""; - /// "" for a retail quest; the server tag for a row from that server's pack. + /// "" for a retail quest; the pack's tag for a row from the active server's pack. public string Server = ""; public string Name = ""; public string Url = ""; @@ -72,15 +71,27 @@ internal sealed class Quest } } +/// +/// What the catalog merges on this server: its RynthCore id (the override file's name), the tag its +/// rows go under (the pack's own, else the server's name), the pack the server's plugin offers ("" = +/// none) and where that came from. +/// +internal sealed record QuestPackSource(string ServerId, string Tag, string Csv, string From) +{ + /// What the catalog was loaded for (the reader adds its pack revision: a changed pack loads again). + public string Key => $"{ServerId}|{Tag}|{From}|{Csv.Length}"; +} + /// /// The quest catalog: the base list (every retail quest: Oracle of Dereth's curated master -/// list, or a newer download of it) plus the current server's quest pack. +/// list, or a newer download of it) plus the active server's quest pack. /// -/// Packs: Resources\quests.<tag>.csv embedded as "RynthOracle.quests.<tag>.csv" (Conquest and -/// Levistras: Advis's server-specific rows; Aelrynth: generated from the world database by -/// Tools\RynthOracle.QuestPackGen). A file %APPDATA%\RynthCore\RynthOracle\packs\quests.<tag>.csv -/// replaces the embedded pack, so a regenerated pack can be tried without a rebuild. A new -/// server only needs a tag (ServerTags) and a pack file. +/// Packs are the server plugins' (since 2026-10-21): the plugin that owns the active server offers its +/// pack through "RynthServer.QuestPack" (Resources\quests.<server id>.csv in its project; e.g. +/// Advis's server-specific rows, or one generated from a world database by Tools\RynthOracle.QuestPackGen), +/// and RynthOracle merges whatever it offers, under the pack's tag, without knowing the server. A file +/// %APPDATA%\RynthCore\RynthOracle\packs\quests.<server id>.csv replaces the offered pack (or stands +/// in for a server whose plugin offers none), so a regenerated pack can be tried without a rebuild. /// /// Pack columns: the base list's (QuestFlag, Quest, Url, Info, Hint, Repeatable) plus optional /// MinDelta, MaxSolves, Source and NotOnServer. Merge: a pack row for a flag the base list has @@ -108,20 +119,44 @@ internal sealed class QuestCatalog public static string DownloadedPath => Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "RynthOracle", "quests.csv"); - public static string PackOverridePath(string tag) => Path.Combine( + /// The file that replaces a server's pack: packs\quests.<server id>.csv. + public static string PackOverridePath(string serverId) => Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "RynthOracle", "packs", - $"quests.{tag.ToLowerInvariant()}.csv"); + $"quests.{SafeFileName(serverId)}.csv"); - /// The servers with an embedded quest pack. - public static IEnumerable EmbeddedPacks() => - Assembly.GetExecutingAssembly().GetManifestResourceNames() - .Where(n => n.StartsWith("RynthOracle.quests.", StringComparison.Ordinal) && n.EndsWith(".csv", StringComparison.Ordinal) - && n.Length > "RynthOracle.quests..csv".Length) - .Select(n => n["RynthOracle.quests.".Length..^4]); - - /// Loads the base list (downloaded when valid, else bundled) and the pack for . - public void Load(string serverTag, Action? log) + /// A server id as a file name part (RynthCore ids are a-z, 0-9 and '-'; anything else becomes '_'). + private static string SafeFileName(string id) { + var sb = new System.Text.StringBuilder(id.Length); + foreach (char c in id.ToLowerInvariant()) sb.Append(c is >= 'a' and <= 'z' or >= '0' and <= '9' or '-' ? c : '_'); + return sb.ToString(); + } + + /// + /// What to merge for : nothing without an active server; else the pack its + /// plugin offers (, already checked to be the active server's), or none but + /// the server's id (an override file, or the master list's rows for it, can still apply). + /// + public static QuestPackSource? SourceFor(ServerIdentity server, ServerQuestPack? pack) + { + if (server.ServerId.Length == 0) return null; + string name = server.ServerName.Length > 0 ? server.ServerName : server.ServerId; + return pack != null + ? new QuestPackSource(server.ServerId, pack.Tag.Length > 0 ? pack.Tag : name, pack.Csv, pack.Plugin) + : new QuestPackSource(server.ServerId, name, "", ""); + } + + /// What the catalog was last loaded with (null = retail only). + public QuestPackSource? LastSource { get; private set; } + + /// Loads the lists again with the last source (a new download, the bundled list again). + public void Reload(Action? log) => Load(LastSource, log); + + /// Loads the base list (downloaded when valid, else bundled) and 's pack (null = retail only). + public void Load(QuestPackSource? source, Action? log) + { + LastSource = source; + string serverTag = source?.Tag ?? ""; List? baseRows = null; UsingBundled = true; if (File.Exists(DownloadedPath)) @@ -147,9 +182,9 @@ internal sealed class QuestCatalog List? packRows = null; PackServer = ""; PackSource = ""; - if (serverTag.Length > 0) + if (source != null && serverTag.Length > 0) { - string over = PackOverridePath(serverTag); + string over = PackOverridePath(source.ServerId); try { if (File.Exists(over)) @@ -157,32 +192,34 @@ internal sealed class QuestCatalog using var r = new StreamReader(over); packRows = ReadRows(r, serverTag, out string? why); if (packRows != null) PackSource = "file " + over; - else log?.Invoke($"[RynthOracle] {over} is unusable ({why}); using the bundled {serverTag} pack."); + else log?.Invoke($"[RynthOracle] {over} is unusable ({why}); using {(source.From.Length > 0 ? source.From + "'s" : "no")} {serverTag} pack."); } } catch (Exception ex) { log?.Invoke($"[RynthOracle] Couldn't read {over} ({ex.Message})."); } - if (packRows == null && EmbeddedPacks().Any(t => t.Equals(serverTag, StringComparison.OrdinalIgnoreCase))) + if (packRows == null && source.Csv.Length > 0) { - using StreamReader r = Csv.OpenEmbedded($"quests.{serverTag.ToLowerInvariant()}.csv"); - packRows = ReadRows(r, serverTag, out _); - if (packRows != null) PackSource = "bundled pack"; + using var r = new StringReader(source.Csv); + packRows = ReadRows(r, serverTag, out string? why); + if (packRows != null) PackSource = "from " + source.From; + else log?.Invoke($"[RynthOracle] {source.From}'s quest pack is unusable ({why}); retail quests only."); } if (packRows != null) PackServer = serverTag; } - Build(baseRows, packRows ?? new List(), serverTag); + Build(baseRows, packRows ?? new List(), serverTag, source?.ServerId ?? ""); } - private void Build(List baseRows, List packRows, string serverTag) + private void Build(List baseRows, List packRows, string serverTag, string serverId) { _quests.Clear(); _byFlag.Clear(); int retail = 0, server = 0, hidden = 0; - // Base rows tied to a server (a downloaded master list) are that server's pack rows. + // Base rows tied to a server (a downloaded master list) are that server's pack rows: its Server + // column names the pack's tag (or the server's id). var pack = new List(); foreach (Quest q in baseRows) { @@ -190,7 +227,8 @@ internal sealed class QuestCatalog { if (_byFlag.TryAdd(q.Flag, q)) { _quests.Add(q); retail++; } } - else if (serverTag.Length > 0 && q.Server.Equals(serverTag, StringComparison.OrdinalIgnoreCase)) + else if (serverTag.Length > 0 && (q.Server.Equals(serverTag, StringComparison.OrdinalIgnoreCase) + || serverId.Length > 0 && q.Server.Equals(serverId, StringComparison.OrdinalIgnoreCase))) { q.Server = serverTag; pack.Add(q); diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Data/ServerIdentity.cs b/Plugins/RynthCore.Plugin.RynthOracle/Data/ServerIdentity.cs index cc78c30..b0ae856 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Data/ServerIdentity.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Data/ServerIdentity.cs @@ -4,199 +4,85 @@ using RynthCore.PluginSdk; namespace RynthCore.Plugin.RynthOracle.Data; -/// The servers RynthOracle has server-specific features or data packs for. -internal static class ServerTags -{ - public const string Aelrynth = "Aelrynth"; - public const string Conquest = "Conquest"; - public const string Levistras = "Levistras"; - /// Infinite Leaftide (ACECustom). Its server rules come from RynthILT ("RynthILT.Server"). - public const string InfiniteLeaftide = "InfiniteLeaftide"; - - /// Tags with a quest pack (Resources\quests.<tag>.csv) or features. - public static readonly string[] Known = { Aelrynth, Conquest, Levistras, InfiniteLeaftide }; -} - /// -/// Which server this client is on, decided once per login and re-checked each second until -/// known. Server-specific features and data packs carry a tag () and -/// only load or show where says so; untagged (retail) ones work anywhere. +/// Which server this client is on, as RynthCore says (plugin API v86 GetServerStateJson, read by +/// ServerStateClient): the active server, with this character's overrides and the Diagnostics +/// page's pick applied, and the plugin that owns it. Re-read each second. /// -/// Sources, best first: -/// 0. Engine API v86 GetServerStateJson (ServerStateClient): RynthCore's active server, with -/// this character's overrides and the Diagnostics page's server pick applied (FromEngine). -/// 1. Engine API v75 GetServerInfo: the engine's own verdict for Aelrynth (connect host, -/// announced world name, Bank mod properties) and the world name the server announced -/// at login. Never the launcher profile name. -/// 2. Older engines: the world name (GetWorldName; the server's own once logged in, though -/// it falls back to the launcher profile name before that) and, for Aelrynth, the Bank -/// mod's player properties 9101-9103, which only Aelrynth sends. -/// Aelrynth's live config still names the world "Aeshnidae" (its earlier name); both count. -/// ConquestAC and Levistras are matched on their world names, as upstream does -/// (Decal's CharacterFilter.Server). Infinite Leaftide is matched on a world name containing -/// "Leaftide", or on RynthILT's own verdict (its world list or the character's override) when -/// RynthILT is loaded. +/// RynthOracle knows no server itself (since 2026-10-21): a server's own quests are its server +/// plugin's quest pack ("RynthServer.QuestPack", ServerQuestPackClient), which the catalog merges +/// under the pack's own tag, and a server's own pages are that plugin's. Before then RynthOracle +/// had its own server tags, detection and packs for three servers; they moved into those servers' +/// plugins. Without RynthCore's server list (an engine older than v86) no server is active here. /// internal sealed class ServerIdentity { - private const uint QuadRadianceEarned = 9101, QuadLuminanceBanked = 9102, QuadLuminanceDrawn = 9103; - - /// A known tag, or "" (a server without its own features: retail features only). - public string Tag { get; private set; } = ""; + /// RynthCore's id of the active server ("" = none: retail quests only). + public string ServerId { get; private set; } = ""; + /// Its name as RynthCore lists it ("" with none). + public string ServerName { get; private set; } = ""; + /// The plugin that owns it, the one asked for the quest pack ("" when none is loaded). + public string Plugin { get; private set; } = ""; public string WorldName { get; private set; } = ""; public string Source { get; private set; } = "not logged in"; - public bool Known => WorldName.Length > 0 || Tag.Length > 0; + public bool Known => WorldName.Length > 0 || ServerId.Length > 0; public int Revision { get; private set; } - public bool Is(string tag) => Tag.Length > 0 && string.Equals(Tag, tag, StringComparison.OrdinalIgnoreCase); + /// The active server's name for the player: its name, its id, or "no server". + public string DisplayName => ServerName.Length > 0 ? ServerName : ServerId.Length > 0 ? ServerId : "no server"; - /// Untagged features always; tagged ones only on their own server. - public bool Allows(string? tag) => string.IsNullOrEmpty(tag) || Is(tag); + public void Reset() => Set("", "", "", "", "not logged in"); - public void Reset() + /// RynthCore's server list (ServerStateClient); null on engines older than v86. + public void Refresh(RynthCoreHost host, EngineServerState? engine) { - Set("", "", "not logged in"); - } - - /// RynthILT's profile reports an ILT world (IltServerLink); false without RynthILT. - /// - /// RynthCore's server list (plugin API v86, ServerStateClient); null on older engines. When there, - /// it decides: it already applies this character's overrides and the Diagnostics page's pick. - /// - public void Refresh(RynthCoreHost host, uint playerId, bool rynthIltSaysIlt = false, EngineServerState? engine = null) - { - if (engine != null) - { - string fallbackWorld = host.TryGetWorldName(out string fw) ? fw.Trim() : ""; - FromEngine(engine, fallbackWorld, out string t, out string wn, out string src); - Set(t, wn, src); - return; - } - - string tag, world, source; - if (host.TryGetServerInfo(out bool aelrynth, out bool staging, out string announced)) - { - world = announced; - if (aelrynth) - { - tag = ServerTags.Aelrynth; - source = staging ? "engine: Aelrynth (staging)" : "engine: Aelrynth"; - } - else - { - // The engine's Aelrynth verdict is the authority (it already weighs the world name, - // and /rc server other overrides it for testing): never Aelrynth from the name here. - tag = TagForWorld(world); - if (tag == ServerTags.Aelrynth) tag = ""; - source = world.Length > 0 ? $"engine: the server calls itself \"{world}\"" : "engine: world name not announced yet"; - } - } - else - { - world = host.TryGetWorldName(out string w) ? w.Trim() : ""; - tag = TagForWorld(world); - source = world.Length > 0 ? $"world name \"{world}\" (older engine)" : "world name not known yet (older engine)"; - if (tag.Length == 0 && playerId != 0 && HasBankProperties(host, playerId)) - { - tag = ServerTags.Aelrynth; - source = "the Aelrynth Bank properties (older engine)"; - } - } - if (tag.Length == 0 && rynthIltSaysIlt) - { - tag = ServerTags.InfiniteLeaftide; - source = "RynthILT: an Infinite Leaftide world"; - } - Set(tag, world, source); + string fallbackWorld = host.HasGetWorldName && host.TryGetWorldName(out string fw) ? fw.Trim() : ""; + FromEngine(engine, fallbackWorld, out string id, out string name, out string plugin, out string world, out string source); + Set(id, name, plugin, world, source); } /// - /// The identity from RynthCore's server list. An active server decides the tag (its own, or "" - /// for a server RynthOracle has nothing for). With none active, the world name may still tag a - /// server the engine doesn't know (Conquest without RynthConquest loaded), but never one the - /// engine lists: that one is off on purpose (not detected, or this character's override). - /// Pure: the tests drive it. + /// The identity from RynthCore's server list: the active server decides (none active = no server, + /// whatever the world is called). Pure: the tests drive it. /// - internal static void FromEngine(EngineServerState engine, string fallbackWorld, out string tag, out string world, out string source) + internal static void FromEngine(EngineServerState? engine, string fallbackWorld, + out string id, out string name, out string plugin, out string world, out string source) { + if (engine == null) + { + id = name = plugin = ""; + world = (fallbackWorld ?? "").Trim(); + source = "RynthCore has no server list here (an engine older than API v86): retail quests only"; + return; + } world = engine.World.Length > 0 ? engine.World : (fallbackWorld ?? "").Trim(); - if (engine.HasActive) + if (!engine.HasActive) { - tag = TagForEngineId(engine.Active); - EngineServer? s = engine.Find(engine.Active); - string how = engine.Picked ? "picked by hand" - : s != null && s.Force.Equals("on", StringComparison.OrdinalIgnoreCase) ? "forced on for this character" - : s != null && s.Reason.Length > 0 ? s.Reason : "detected"; - string name = engine.ActiveName.Length > 0 ? engine.ActiveName : engine.Active; - source = $"RynthCore: {name} ({how})" + (tag.Length == 0 ? " - no RynthOracle pages for it" : ""); + id = name = plugin = ""; + source = "RynthCore: no server active (retail quests only)" + (engine.Picked ? ", picked by hand" : ""); return; } - - tag = TagForWorld(world); - string id = EngineIdForTag(tag); - if (tag.Length > 0 && id.Length > 0 && engine.Find(id) != null) - { - source = $"RynthCore: {tag} is off for this world (not detected, or overridden)"; - tag = ""; - return; - } - source = tag.Length > 0 - ? $"world name \"{world}\" (RynthCore has no {tag} server loaded)" - : "RynthCore: no server active (retail features only)"; + id = engine.Active; + name = engine.ActiveName.Length > 0 ? engine.ActiveName : engine.Active; + plugin = engine.ActivePlugin; + EngineServer? s = engine.Find(engine.Active); + string how = engine.Picked ? "picked by hand" + : s != null && s.Force.Equals("on", StringComparison.OrdinalIgnoreCase) ? "forced on for this character" + : s != null && s.Reason.Length > 0 ? s.Reason : "detected"; + source = $"RynthCore: {name} ({how})" + (plugin.Length > 0 ? $"; its plugin {plugin}" : "; no plugin loaded for it"); } - /// The tag for a RynthCore server id; "" for servers without RynthOracle features. - public static string TagForEngineId(string? id) => (id ?? "").Trim().ToLowerInvariant() switch + private void Set(string id, string name, string plugin, string world, string source) { - EngineServerState.IltId => ServerTags.InfiniteLeaftide, - EngineServerState.AelrynthId => ServerTags.Aelrynth, - "conquest" => ServerTags.Conquest, - "levistras" => ServerTags.Levistras, - _ => "", - }; - - /// The RynthCore server id for a tag; "" for none. - public static string EngineIdForTag(string? tag) => tag switch - { - ServerTags.InfiniteLeaftide => EngineServerState.IltId, - ServerTags.Aelrynth => EngineServerState.AelrynthId, - ServerTags.Conquest => "conquest", - ServerTags.Levistras => "levistras", - _ => "", - }; - - /// The tag for a world name; "" for servers without their own features. - public static string TagForWorld(string? world) - { - if (string.IsNullOrWhiteSpace(world)) return ""; - string w = world.Trim(); - if (w.StartsWith("Aelrynth", StringComparison.OrdinalIgnoreCase) || w.StartsWith("Aeshnidae", StringComparison.OrdinalIgnoreCase)) - return ServerTags.Aelrynth; - if (w.Equals(ServerTags.Conquest, StringComparison.OrdinalIgnoreCase) || w.Equals("ConquestAC", StringComparison.OrdinalIgnoreCase)) - return ServerTags.Conquest; - if (w.Equals(ServerTags.Levistras, StringComparison.OrdinalIgnoreCase)) - return ServerTags.Levistras; - // "InfiniteLeaftide", "Infinite Leaftide", staging copies: RynthILT's own world rule. - if (w.IndexOf("Leaftide", StringComparison.OrdinalIgnoreCase) >= 0) - return ServerTags.InfiniteLeaftide; - return ""; - } - - private static bool HasBankProperties(RynthCoreHost host, uint playerId) => - host.HasGetObjectQuadProperty - && (host.TryGetObjectQuadProperty(playerId, QuadRadianceEarned, out _) - || host.TryGetObjectQuadProperty(playerId, QuadLuminanceBanked, out _) - || host.TryGetObjectQuadProperty(playerId, QuadLuminanceDrawn, out _)); - - private void Set(string tag, string world, string source) - { - if (tag == Tag && world == WorldName && source == Source) return; - Tag = tag; + if (id == ServerId && name == ServerName && plugin == Plugin && world == WorldName && source == Source) return; + ServerId = id; + ServerName = name; + Plugin = plugin; WorldName = world; Source = source; Revision++; } - /// For tests: a fixed identity. - internal void Force(string tag, string world) => Set(tag, world, "forced"); + /// For tests: a fixed identity (an id, the world; name = id, no plugin unless given). + internal void Force(string id, string world, string plugin = "") => Set(id ?? "", id ?? "", plugin, world ?? "", "forced"); } diff --git a/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs b/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs index 494f0d0..e695036 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/OracleContext.cs @@ -20,24 +20,7 @@ internal sealed class OracleContext public readonly VoidTracker Void = new(); public readonly FellowshipTracker Fellowship = new(); public readonly ServerIdentity Server = new(); - /// RynthILT's server profile (Leaftide features, fellowship rules, the /qb list); None without RynthILT. - public readonly IltServerLink Ilt = new(); - /// RynthILT's "RynthILT.Data" (charms, pet breeding, the Temple guardians). - public readonly RynthCore.Plugin.Shared.RynthIltDataClient IltData = new(); - /// The charms RynthILT last reported (None without RynthILT); read while the Character tab shows. - public RynthCore.Plugin.Shared.IltCharmsView Charms = RynthCore.Plugin.Shared.IltCharmsView.None; - /// The last charm Toggle's outcome, shown under the charms list. - public string CharmMessage = ""; - /// RynthILT's pet breeding tracker (None without it); read while the Pet Breeding tab shows. - public RynthCore.Plugin.Shared.IltBreedingView Breeding = RynthCore.Plugin.Shared.IltBreedingView.None; - /// The last breeding button's outcome, shown under the tab's buttons. - public string BreedingMessage = ""; - /// RynthILT's Temple guardians (None without RynthILT 0.3.3+); read while the Quests tab shows on Infinite Leaftide. - public RynthCore.Plugin.Shared.IltGuardianView Guardian = RynthCore.Plugin.Shared.IltGuardianView.None; - /// Goes up each time changes, so the Quests list rebuilds its guardian rows. - public int GuardianRevision; - /// The last guardian button's outcome, shown under the guardian controls. - public string GuardianMessage = ""; + // A server's own screens are its server plugin's (2026-10-20, 2026-10-21): nothing here is one server's. /// RynthAi's session (the one session every tracker shows); read while the Character tab shows. public readonly RynthCore.Plugin.Shared.RynthAiSessionClient AiSession = new(); /// The last session RynthAi reported; SessionKnown false without RynthAi. @@ -46,6 +29,11 @@ internal sealed class OracleContext /// RynthCore's server list (API v86) and the active server owner's settings; State null on older engines. public readonly RynthCore.Plugin.Shared.ServerStateClient ServerState = new(); /// + /// The active server plugin's quest pack ("RynthServer.QuestPack"): whatever the plugin RynthCore names + /// as the active server's owner offers; none without one (retail quests only). + /// + public readonly RynthCore.Plugin.Shared.ServerQuestPackClient QuestPacks = new(); + /// /// The active server's Void DoT duration rule: its plugin's profile value "voidDotDurationScale" /// (RynthConquest publishes Conquest's), 1 on every other server or without the plugin. /// @@ -83,34 +71,9 @@ internal sealed class OracleContext /// Set by the plugin: runs a chat command through RynthCore's plugin dispatch (another plugin's window). public Func RunCommand = _ => false; - /// Set by the plugin: asks RynthILT to use a carried charm or Guardian Hand (its toggle id). - public Func ToggleCharm = _ => false; - - /// Set by the plugin: sends a verb to RynthILT's breeding tracker (RynthIltDataApi PetBreedingCommand). - public Func BreedingCommand = _ => false; - - /// Set by the plugin: sends a verb to RynthILT's guardians (RynthIltDataApi GuardianCommand). - public Func GuardianCommand = _ => false; - /// Set by the plugin: "<verb> <targets>" for RynthNav's /rnav (go, route, arrow); false when RynthNav isn't there. public Func SendNav = _ => false; - /// Set by the plugin: the name of a Parchment carried (null when none). Null here: the Quests tab doesn't look. - public Func? ParchmentFinder; - - /// - /// Set by the plugin: RynthAi is loaded and so can take the Quests tab's "/ub give" (the Give - /// Parchment button). False disables the button with a tooltip. - /// - public Func UbGiveAvailable = () => false; - /// - /// The loaded RynthAi answered a "/ub give" with "Unrecognized /ub command": it has no such verb, - /// so the Give Parchment button stays disabled (set by the plugin from the chat line). - /// - public bool UbGiveMissing; - /// When the Give Parchment button last sent "/ub give" (NowMs), so a rejection in chat can be tied to it. - public long UbGiveSentMs = long.MinValue / 2; - /// Set by the plugin: shows or hides the Quest Timers window. public Action SetQuestTimersWindow = _ => { }; /// Set by the plugin: whether the Quest Timers window is showing. @@ -118,18 +81,6 @@ internal sealed class OracleContext public Func Props => id => Character.Int(Host, id); - /// - /// A chat line seen just after the Give Parchment button sent "/ub give": RynthAi's "Unrecognized - /// /ub command" means this RynthAi has no such verb, so the button stays off. True when it did. - /// - public bool NoteChatLineForGive(string line, long nowMs) - { - if (nowMs - UbGiveSentMs >= 5000 || UbGiveMissing) return false; - if (line.IndexOf("Unrecognized /ub", StringComparison.OrdinalIgnoreCase) < 0) return false; - UbGiveMissing = true; - return true; - } - /// A line in the player's chat window only (nothing is sent to the server). public void Print(string text) { diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Resources/dynstamps.csv b/Plugins/RynthCore.Plugin.RynthOracle/Resources/dynstamps.csv deleted file mode 100644 index 6691ea9..0000000 --- a/Plugins/RynthCore.Plugin.RynthOracle/Resources/dynstamps.csv +++ /dev/null @@ -1,244 +0,0 @@ -Area,Place,Npc,Reward,Stamp,Note -"Facility Hub","Folthid Cellar","Raxanza Folthid","O-Yoroi Leggings","Dynamic_1_Aq2hMsFmW!","" -"Facility Hub","Folthid Cellar","Felscuda","Healing Rabbit Pie","Dynamic_1_&9jiyTB!","8.8S, 53.1E" -"Facility Hub","Folthid Cellar","Mi Krau-Li","examines your Parchment","Dynamic_1_WAuFukcRLoL5!","" -"Looking Around","","Le-Ai Rea","Blue Molly","Dynamic_1_XH!!nh#^NaRp!","75.9S 57.3E" -"Looking Around","Frost Haven","Robert","Greater Celdon Shadow Sleeves","Dynamic_1_HLq&!","" -"Looking Around","Frost Haven","Elijah","Homemade Stout","Dynamic_1_MpBeVDU!","" -"Looking Around","Frost Haven","Emma","Frost Slingshot","Dynamic_1_bEt6H5ECwGb2!","" -"Looking Around","Frost Haven","Chef Pleist","Stone Mace","Dynamic_1_HgaUKA#hxa!","" -"Looking Around","Frost Haven","The Mayor","Fried Egg","Dynamic_1_MRfxp5!g!","" -"Looking Around","Frost Haven","Numb","Perfect Coruscating Isparian Mace","Dynamic_1_z8LpGZpe4rq!","" -"Looking Around","Land Bridge Staging Complex","Director's Majordomo","Spitter Trochanter Metamorphi","Dynamic_1_FZYLYrAW1Zb!","" -"Looking Around","Frost Haven","Mossy Chamber","Broken Virindi","Dynamic_1_ANND","" -"Looking Around","Freebooter","Jusad the Collector","Renegade Atlatl of the Mountains","Dynamic_1_!mqkm9M!","" -"Looking Around","Lum Seer","Shade of Lady Adja","Frost Board with Nail","Dynamic_1_ps6iG^P!ndH!","" -"Looking Around","Frost Haven","Ka'hiri","Hearty Spiced Applesauce","Dynamic_1_s5MAzDcP9!","" -"Looking Around","Frost Haven","Liam of Gelid","Composite Crossbow with Handle","Dynamic_1_7cv3O^MTLLKzs&!","" -"Looking Around","84.1N, 44.1E","Aerlinthe Node Golem","Silifi of Crimson Stars","Dynamic_1_D6YxLUyUIW!","84.1N, 44.1E" -"Looking Around","62.0N, 18.0E","Esper Node Golem","Composite Bow with Handle","Dynamic_1_LE5V8SVHG!","62.0N, 18.0E" -"Looking Around","93.8N, 67.4W","Halaetan Node Golem","Slashing Longbow","Dynamic_1_QfLhcZJ64Hkold!","93.8N, 67.4W" -"Looking Around","64.8S, 59.3E","Linvak Node Golem","Greater Celdon Shadow Girth","Dynamic_1_V8&t5$!","64.8S, 59.3E" -"Looking Around","Ulgrim Island","Ulgrim the Unappreciated","Applesauce","Dynamic_1_x!zs79y!","" -"Looking Around","Fake Niffis Crate Quest","Chef Jonus","Fish","Dynamic_1_j&T!ZrQwKvo!","" -"Looking Around","Frost Haven","Larnia","Acid Hand Axe","Dynamic_1_88P$YBwEl!","" -"Looking Around","Tanada Chamber of Scroll / Fire","Tanada Han-Tu","Hearty Ice Cream","Dynamic_1_STjY86!0Iu8x!","" -"Looking Around","Frost Haven","Tanada Hido","Acid Mace","Dynamic_1_3ZhBEF!","" -"Looking Around","Frost Haven","Tanada Shouka","Pouch of Dried Meat","Dynamic_1_YgClBFy!","" -"Looking Around","Gerent's Compound at 87.2S, 17.5W","Representative of the Singularity","Fish","Dynamic_1_qkU0b^i!","87.2S, 17.5W" -"Odd Stamps","93.2N, 48.2W in the Shattered Outlands","Arialle du Bellenesse","Healing Holtburger","Dynamic_1_ADm5RsrDGCbT!","93.2N, 48.2W" -"Odd Stamps","Crater","Silencia's Magma Golem","Slicing Royal Atlatl","Dynamic_1_fR730X5VsPULE5!","" -"Odd Stamps","Colosseum","Master Arbitrator","Palenqual's Tewhate","Dynamic_1_XnFt&!","" -"Odd Stamps","","Colosseum Ticket Vendor","Silifi of Crimson Stars","Dynamic_1_luguukhgZg!","" -"Odd Stamps","Beach Fort","Suzuhara Sheshumi","Silifi of Crimson Stars","Dynamic_1_n5u2imCs!","" -"Odd Stamps","Obsidian Plains","Varetha","Major Smoldering Atlan Bow","Dynamic_1_P1&xxk5!","44.3S, 62.5W" -"Odd Stamps","Crystal Crag","Oorjit","Perfect Shimmering Isparian Bow","Dynamic_1_lPn&BaZ!","" -"Odd Stamps","","Jyotsana","Cragstone Farms Mac&Cheese","Dynamic_1_YCGJJ7cA!","" -"Odd Stamps","","Tokashi Ando","Perfect Dissolving Isparian Crossbow","Dynamic_1_R#HIf!","" -"Odd Stamps","Ries Woron's Story","Thrungus","Expired Stamina Draught","Dynamic_1_eMJVhyPzaa$aGn!","" -"Odd Stamps","Mite Maze","Roderick","Apple Pie","Dynamic_1_#C^p&w0gV$$!","" -"Odd Stamps","Sawato","Ssavish","Composite Bow with Handle","Dynamic_1_NMlDXfx2t!","" -"Odd Stamps","dryreach rescue","Dansha-Ki","Composite Bow with Handle","Dynamic_1_FnXoHWS&kaM!","" -"Odd Stamps","Seat of Knorr","Arikas, Warden of Knorr","Hearty Healing Rabbit Noodle","Dynamic_1_aWOWTc30f4","" -"Odd Stamps","Swamp Garden","Terese","Diforsa Bracers","Dynamic_1_PTy0kqqTLP1Dn^!","" -"Odd Stamps","Dark Isle","Tyrina of Arwic","Major Shadow Gauntlets","Dynamic_1_zJNxGBc!","84.7n 58.7e" -"Odd Stamps","Dark Isle","Francois di Terli","Habraeloi","Dynamic_1_3!Og!","" -"Odd Stamps 2","Aun Settlement 82.7N 21.2E.","Aun Tikakhe","Good Chilling Isparian Mace","Dynamic_1_hafO$cQvbkg!","82.7N 21.2E" -"Odd Stamps 2","","Aun Saritea","Health Tonic","Dynamic_1_7yW17JvMHKu!","" -"Odd Stamps 2","","Aun Aulakhe","Mana Rabbit Pie","Dynamic_1_5xE2TM!","" -"Odd Stamps 2","Lost Wish Cottages (Arwic) 42.6n 62.4e","Lartorus","Pants","Dynamic_1_$GB72K!","42.6n 62.4e" -"Odd Stamps 2","Catacombs of Opposition","Ripper","Gladiatorial Tunic","Dynamic_1_69Rjbany2pKD!","" -"Odd Stamps 2","","Rat Nose","Fine Atlan Staff","Dynamic_1_eBlku!","" -"Odd Stamps 2","","Nanoc, Basher of Bugs","Mana Potion","Dynamic_1_XCTiy!","" -"Odd Stamps 2","","Narg","Iron Rusted Mace","Dynamic_1_S!AhI!","" -"Odd Stamps 2","","Scout Luzumin Abigwei","Alduressa Helm","Dynamic_1_NFf5!","" -"Odd Stamps 2","","Teela","Orange Molly","Dynamic_1_Bl#Y!","" -"Odd Stamps 2","","Scout Tel al-Arat","Envoy's Heaume","Dynamic_1_AJ3Wm9Bk!","" -"Odd Stamps 2","","Pincer Danta","Olthoi Sollerets","Dynamic_1_VezOOBWbn43KU!!","" -"Odd Stamps 2","Vissidal","Merwart Pelagurg","Superior Smoldering Atlan Staff","Dynamic_1_DOIC1!","" -"Odd Stamps 2","Vissidal","Merwart Urglurg","Butter Knife of Slaying","Dynamic_1_&!iRR#RrhnGA!","" -"Odd Stamps 2","Vissidal","Dayla Bint Kazm","Hearty Healing Chicken Pie","Dynamic_1_nDAXG!","" -"Odd Stamps 2","Vissidal","Peng-Ya","Major Dissolving Isparian Crossbow","Dynamic_1_sx^9H^&Mnqp!","" -"Odd Stamps 2","Vissidal","Colista Fluress","Lesser Amuli Shadow Leggings","Dynamic_1_Ej!Zz!","" -"Odd Stamps 2","99.7S 96.7W","Surloshen Realaidain","Hammer of Lightning","Dynamic_1_tiiFC!","99.7S 96.7W" -"Odd Stamps 2","Silyiun - 89.1N 47.6W","Fiun Gaya","Enhanced Shadow Gauntlets","Dynamic_1_hev0!","89.1N 47.6W" -"Odd Stamps 2","Hermit - Thrungus Hole","Hermit","Scored Amuli Leggings","Dynamic_1_rDBG!","" -"Odd Stamps 2","93.2N 48.2W - Eastwatch","Commander Rylane di Cinghalle","Acid Crossbow","Dynamic_1_pZpx41&!","93.2N 48.2W" -"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Arbelests","Healing Carrot Soup","Dynamic_1_L3Hb3O!","32.0N, 43.2W" -"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Fists","Platemail Breastplate","Dynamic_1_xj&USOHNL9K&!","32.0N, 43.2W" -"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Bows","Tasty Stout","Dynamic_1_hw2LNdjT6!","32.0N, 43.2W" -"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Atlatls","Composite Crossbow with Handle","Dynamic_1_P6!!","32.0N, 43.2W" -"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Axes","Three Eyed Guppy","Dynamic_1_xX^IHjOo##J$8E!","32.0N, 43.2W" -"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Blades","Flaming Weeping Dagger","Dynamic_1_iFuvP!","32.0N, 43.2W" -"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Staves","Composite Crossbow","Dynamic_1_J$JV&VKf!","32.0N, 43.2W" -"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Orbs","Health Tincture","Dynamic_1_S&JMdWiBDy!","32.0N, 43.2W" -"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Maces","Wooden Scarecrow Guise","Dynamic_1_^pTx!","32.0N, 43.2W" -"Odd Stamps 2","32.0N, 43.2W - Virindi Crafters","Crafter of Knives","Scalemail Hauberk","Dynamic_1_6ZR$k^$Srwc3g!","32.0N, 43.2W" -"Odd Stamps 2","83.4S 97.2E - Ithaenc","Abbess Zik'Lir","Hearty Fish Noodle","Dynamic_1_jmCfm1p5a!","83.4S 97.2E" -"Odd Stamps 2","72.8N,25.0W - Stonehold nearby","Lord Pyrovor","Enhanced Shadow Greaves","Dynamic_1_Tw$7Zwmutan!","72.8N,25.0W" -"Odd Stamps 2","VoD Encampment","Guard Alfric","Bowl of Rice","Dynamic_1_LZkvsu4Ln2$h!","" -"Odd Stamps 2","VoD Encampment","Guard Taziq","Blackfire Shadow Sollerets","Dynamic_1_t9uxr!","" -"Odd Stamps 2","VoD Encampment","Guard Q'alia","Ancient Relic Gauntlets","Dynamic_1_m1KeUXELMuH!","" -"Odd Stamps 2","VoD Encampment","Guard Li","Frost Hatchet","Dynamic_1_XgrV$!","" -"Odd Stamps 2","77.7S 97.0E Ithaenc","Shah-hi","Katar","Dynamic_1_G3N9HSXlowLT$!","77.7S 97.0E" -"Odd Stamps 2","Releasing the Light - Reward Room","Calitoth","Fish","Dynamic_1_mu^91#T!","" -"Odd Stamps 2","VoD Encampment","Guardian of the Forbidden","Princely Runed Dart Flinger","Dynamic_1_#BELoT72Ib!","Small Creepy Statue" -"Odd Stamps 2","Shattered Outlands 94.0n 45.9w","Torgash","examines your Parchment","Dynamic_1_S","94.0n 45.9w" -"Odd Stamps 2","Hoshino Must Die last room","Spirit of Bist'elle","Enhanced Shadow Breastplate","Dynamic_1_b!","" -"Bandit Castle","","Karwin, the Lunatic","Chainmail Pauldrons","Dynamic_1_HIlMkY!","" -"Bandit Castle","","Kiriel Shadowborn","Healing Apple Pie","Dynamic_1_WBzVFJpFUzHkC!","" -"Bandit Castle","","Jourgensson","Hearty Healing Mushroom Pie","Dynamic_1_$W&Pl4!","" -"Bandit Castle","","Gillian the Poacher","Peppermint Ice Cream","Dynamic_1_5oLp!","" -"Bandit Castle","","Alison Dulane","Amuli Shadow Leggings","Dynamic_1_079u9!","" -"Bandit Castle","","Arianna the Adept","Expired Stamina Draught","Dynamic_1_hZIsyYE!!OmcQ!","" -"Bandit Castle","","Shanrek the Forger","Sparring Shirt","Dynamic_1_fbcmDRC!","" -"Bandit Castle","","Neela Nashua","Perfect Dissolving Isparian Spear","Dynamic_1_4tXQFu&&o!","" -"Bandit Castle","","Gwillim, the Apprentice","Lightning Flanged Mace","Dynamic_1_is#X6rBaprU!","" -"Bur","","Drogur","Frost Yari","Dynamic_1_KS8e32dtk7t!","" -"Bur","","Collector Golem","Upper Exoskeleton Metamorphi","Dynamic_1_4xdYA1QvaiDf^!","" -"Bur","","Kuurak","Hearty Healing Chicken Noodle","Dynamic_1_Zapx!","" -"Bur","","Furgal","Spitter Thorax Metamorphi","Dynamic_1_4rk&MTz!","" -"Bur","","Tibik","Gear Crossbow","Dynamic_1_!Ce^d!","" -"Bur","","Nimeruuk","Greater Celdon Shadow Sleeves","Dynamic_1_zIX1Sf6FJt!","" -"Bur","","Kurket","Acidic Rejuvenation","Dynamic_1_snVaz#0Ze3R#4M!","" -"Bur","","Brogosh","Lugian Morning Star","Dynamic_1_$9YdvC2jYTxWZ!","" -"Bur","","Mohor","Quality Isparian Crossbow","Dynamic_1_qpXiWqwBTN4!","" -"Bur","","Kushuk","Silifi of Crimson Stars","Dynamic_1_3ISBG!","" -"Bur","","Borsh","Health Tonic","Dynamic_1_Jh4!","" -"Bur","","Kuuru","Electric Compound Bow","Dynamic_1_vNktko1!","" -"Bur","","Torgluuk, High Shaman of Kor-Gursha","Stout","Dynamic_1_2yxpXSMY!","" -"Bur","","Scout Leader Tmauruk","Hood","Dynamic_1_fEiU!","" -"Bur","","Gruuk'lar","Rynthid Tentacle Dagger","Dynamic_1_xFipmT1!","" -"Gear Knight","Inner Sea Gearknight Invasion","Lieutenant Micham","Dabus","Dynamic_1_CQxkFJvoJrVx!","" -"Gear Knight","Inner Sea Gearknight Invasion","Sir Oakley","Composite Crossbow with Handle","Dynamic_1_lh9wOaXR0!","" -"Gear Knight","Inner Sea Gearknight Invasion","Lieutenant Faen","Blunt Bow","Dynamic_1_Vz#gp!","" -"Gear Knight","Inner Sea Gearknight Invasion","Sir Stavitor","Red Tea","Dynamic_1_ogt05i!","" -"Gear Knight","Inner Sea Gearknight Invasion","Dame Alistra","Superb Flaming Isparian Claw","Dynamic_1_y!","" -"Gear Knight","Direland Gearknight Invasion","Sir Yanov","Major Shadow Greaves","Dynamic_1_BlAckAuHU#!","" -"Gear Knight","Direland Gearknight Invasion","Sir Durnstad","Silifi of Crimson Stars","Dynamic_1_#Dfd!","" -"Gear Knight","Direland Gearknight Invasion","Squire Tylaen","Good Coruscating Isparian Atlatl","Dynamic_1_i1Cxg8Bt!","" -"Gear Knight","Direland Gearknight Invasion","Dame Trielle","Frost Yari","Dynamic_1_h^MdsKZ$6SSD!","" -"Gear Knight","Direland Gearknight Invasion","T'ing Douzen","Panaq","Dynamic_1_p0BEy$e!","" -"Gear Knight","Atamarr Tasks Dungeon","Bronze Gauntlet Knight-Commander","Frost Greataxe","Dynamic_1_REv&biyDw!","" -"Gear Knight","Direland Gearknight Invasion","Copper Cog Craftsmaster","Greater Amuli Leggings of Frost","Dynamic_1_4uls5J!","" -"Wai Jhou","","Kreavon","Skeleton Fish","Dynamic_1_KrPl9N5!","" -"Wai Jhou","","Aun Teverea","Singularity Crossbow","Dynamic_1_Y9wg!RfKHoyL!","" -"Wai Jhou","","Nona","Fish","Dynamic_1_JrzQr8U!","" -"Wai Jhou","","Zho Heishan","Bandit Dagger","Dynamic_1_Abm8qK2!","" -"Wai Jhou","","Sarkin Killcrane","Shadow Tassets","Dynamic_1_mb7NAtZEdBaz!","" -"Wai Jhou","","Riordin Nightbane","Hafted Serpent Spear","Dynamic_1_cCzQdsl5JxLC!","" -"Wai Jhou","","Lacarra Avanthi","Shou-jen Shozoku Trousers","Dynamic_1_ip&NsyQ!","" -"Wai Jhou","","Xanda Har","Gold Fish","Dynamic_1_1CiKW8^x^$!","" -"Rynthid","","Lohrn","Shreth Hide Shoes","Dynamic_1_cS!mivYZ^b!cAA!","" -"Rynthid","","Rhys","Plate Leggings","Dynamic_1_A!!","" -"Rynthid","","Morgethais","Silifi of Crimson Stars","Dynamic_1_wDTf#!","" -"Rynthid","","Geilla","Audetaunga's Korua of the Mountains","Dynamic_1_&dNG5U4!","" -"Rynthid","","Rinne Gorber","Brilliant Celdon Leggings","Dynamic_1_ln!Lx!","" -"Rynthid","","Aun Ol'tra","Small Beer","Dynamic_1_&^3Hve4JXH^!","" -"Rynthid","","Ranulf","Prismatic Celdon Sleeves","Dynamic_1_8n2l!","" -"Rynthid","","Sylvanus","Ursuin Hide Coat","Dynamic_1_veaD!","" -"Rynthid","","Marcus","Fish","Dynamic_1_bpNCu!rsf45Fk!","" -"Rynthid","","Ilte Krongal","Hearty Mana Rabbit Noodle","Dynamic_1_AusVgDl!","" -"Rynthid","","The Bringer of Light","Peppermint Hot Chocolate","Dynamic_1_LrpV!62!","" -"Paradox Camp","Paradox Olthoi Camp","Ethan Wintermaine","Superb Flaming Isparian Bow","Dynamic_1_PPtO6!7dB!","" -"Paradox Camp","","Adrien Swiftblade","Oak Stormwood Crossbow","Dynamic_1_R^1Uv!J8k!","" -"Paradox Camp","","Alicia Swiftblade","Badlands Siraluun Dress","Dynamic_1_G0Rn1lOZKj7C!","" -"Paradox Camp","","Tomihino","Dart Flinger","Dynamic_1_!$cc!","" -"Paradox Camp","North Olthoi Burrow","Peda's Assistant","examines your Parchment","Dynamic_1_3ddaHUzi!","" -"Paradox Camp","North Olthoi Burrow","Peda","examines your Parchment","Dynamic_1_1R9O85L$b!","" -"Paradox Camp","North Olthoi Burrow","Crusher","examines your Parchment","Dynamic_1_a&Z2!","" -"Paradox Camp","North Olthoi Burrow","Deena","examines your Parchment","Dynamic_1_cIZV2uDB6B!","" -"Paradox Camp","North Olthoi Burrow","Mac","examines your Parchment","Dynamic_1_5x^G2$X9!","" -"Paradox Camp","North Olthoi Burrow","Swift-Eye","examines your Parchment","Dynamic_1_o$yT7al7ZTxv!","" -"Paradox Camp","North Olthoi Burrow","Sasha","examines your Parchment","Dynamic_1_CvzZIz!","" -"Paradox Camp","North Olthoi Burrow","Dead-Eye","examines your Parchment","Dynamic_1_fP9y!","" -"Paradox Camp","North Olthoi Burrow","Lash","examines your Parchment","Dynamic_1_AniHdl4wtIuF0!","" -"Paradox Camp","North Olthoi Burrow","Long-Shot","examines your Parchment","Dynamic_1_jJ^yEFc#m^M!","" -"Graveyard","","Renata","Singularity Spear","Dynamic_1_1fDZO3!","" -"Graveyard","","Yoite","Composite Bow with Handle","Dynamic_1_OG6jdId!","" -"Graveyard","","Gadi","Scored Celdon Girth","Dynamic_1_ELgh#!","" -"Graveyard","","Aethelswith","Leather Helm","Dynamic_1_cF!","" -"Graveyard","","Mhoire Soldier","Superb Isparian Bow","Dynamic_1_VgB#WcZOIA!","North Soldier - Opposite side of bunker" -"Graveyard","","Mhoire Soldier","Hafted Gromnie Banner with Crest","Dynamic_1_z$DX!","South Soldier - Opposite side of bunker" -"Graveyard","","Apep-tek the Tolerant","Spectacular Lager","Dynamic_1_Y55^MqgC!","Above ground, outside bunker 65.3w 44.0w" -"Graveyard","","Laylana","Stiletto","Dynamic_1_&SRgbH!","Above ground, outside bunker 65.2s 44.3w" -"Graveyard","","Lo Shoen","Amateur Explorer Pants","Dynamic_1_102!pkgn8wAYSe!","Floating Platform - Level 50 req" -"Graveyard","","Slubbley","Healing Cake","Dynamic_1_mDaEh7!","" -"Graveyard","","Jailer","Good Shimmering Isparian Bow","Dynamic_1_2Hm6DL!","NE bunker aboveground 64.9s 44.1w" -"Graveyard","","Kousu Temo","Fried Mushroom Rice Dough","Dynamic_1_QUXbn6!","EW Initiation guy, 64.2s 44.0w" -"Graveyard","","Candrus Steady-Hand","Academy Mana Potion","Dynamic_1_BKq6N6nXoR!","CH Initiation guy, 65.8s 45.3w" -"Graveyard","","Ancient Stones","Bandit Flaming Jambiya","Dynamic_1_xL!g4ZoCuv!H","Pile of stones at 66.5s 44.7w" -"Graveyard","Mhoire Castle - Great Hall","Ancient Throne","Taiaha","Dynamic_1_&y4ettwcivZ5Nm!","" -"Graveyard","Mhoire Castle - Great Hall","Shade of Antemy","Left Peg Leg","Dynamic_1_CphV&!","" -"Graveyard","Mhoire Castle - Great Hall","Shade of Fordroth","Perfect Chilling Isparian Atlatl","Dynamic_1_M0u7js^$E!","" -"Graveyard","Mhoire Castle - Great Hall","Shade of Terelev","Silifi of Crimson Stars","Dynamic_1_XPvw!","" -"Graveyard","Mhoire Castle - Great Hall","Guliant","Celdon Girth of Acid","Dynamic_1_aCEEdQil42!","" -"Neftet","","T'ing Setsuko","Flaming Broad Sword","Dynamic_1_JfmjJmY0O8r!","" -"Neftet","","Nephthys","Red Tea","Dynamic_1_mnJCjm5QR$s&!","" -"Neftet","","Fahneph","Gear Crossbow","Dynamic_1_owGS9WGJ1Q!","" -"Neftet","","Nekshla","Mana Pumpkin Pie","Dynamic_1_AAQ1#!","" -"Neftet","","Sir Hassim bin Tamarek","Enhanced Shadow Greaves","Dynamic_1_r7zID$U!","" -"Neftet","","Sir Adarl","Bobo's Stout","Dynamic_1_SoBgM6JPckOY9!","" -"Neftet","","Sir Ibreh bin Kassim","Expired Mana Tincture","Dynamic_1_aVMuY!","" -"Neftet","","Sir Daeglan","Quality Coruscating Isparian Crossbow","Dynamic_1_n!","" -"Neftet","","Bemeth the Gatherer","Lesser Koujia Breastplate of Acid","Dynamic_1_bda1WYoI!","" -"Neftet","","Hammah al Rundik","Olthoi Greaves","Dynamic_1_9v^POv6ADt3r!","" -"Neftet","22.2S 8.7E","Kaltus","Composite Bow with Handle","Dynamic_1_xWYS3fqIjPN!","22.2S 8.7E Not Dangerous run" -"Frozen Valley","","Sir Donovan","Pickled Egg","Dynamic_1_ypu2L!","" -"Frozen Valley","","Sir Learth","Royal Cabbage","Dynamic_1_xpAJDzm$!","" -"Frozen Valley","","Lady Daenerah","Acid Spadone","Dynamic_1_$SDp1uWx8wq$!","" -"Frozen Valley","","Gregoria, Gurog Destroyer","Chocolate Gromnie","Dynamic_1_!vr&1c1Ug1XI!","" -"Frozen Valley","","Hunter","Hearty Healing Chicken Pie","Dynamic_1_Sy!9l0FAJFI!","" -"Frozen Valley","","Leilah","Lightning Silifi","Dynamic_1_uyoL!","" -"Frozen Valley","","Halvor","Noble Quarterstaff","Dynamic_1_LfLac!","" -"Frozen Valley","","Kumiko","Expired Health Potion","Dynamic_1_TB!q!","" -"Frozen Valley","","Archmage Ichihiri","Arbalest","Dynamic_1_HzvCs4B2!","" -"Hoshino Tent","","Sergeant Trebuus","Soldier Pincer Metamorphi","Dynamic_1_GQIb1mF!","" -"Hoshino Tent","","Sergeant Freng","Lightning War Axe","Dynamic_1_wVJm&#Lpz7AQ#F","" -"Hoshino Tent","","Aun Kirtal","Arena Bow","Dynamic_1_V9ffGx!","" -"Hoshino Tent","","Lieutenant Aurin","Enhanced Smoldering Atlan Sword","Dynamic_1_4qlVcAWbM!","" -"Hoshino Tent","","Lord Eorlinde","Major Shadow Gauntlets","Dynamic_1_zkzTna!","" -"Hoshino Tent","","Griffon","Mana Elixir","Dynamic_1_b4^F&M1^uG!","" -"Hoshino Tent","","Hanamoto Aki'ko","Lightning Nekode","Dynamic_1_3Qlg!","" -"Hoshino Tent","","Corporal Irashi","Lesser Koujia Shadow Leggings","Dynamic_1_2DBoreKEH!","" -"Hoshino Tent","","Lieutenant Takamaki","Silifi of Crimson Stars","Dynamic_1_#hzL!","" -"Hoshino Tent","","Lieutenant Roothe","Fried Rabbit","Dynamic_1_XuH!z7l!","" -"Viridian Rise","","Brellegia","Greater Celdon Breastplate of Acid","Dynamic_1_mCyu9F!","Requires Viridian Rise Recall Gem" -"Viridian Rise","","Summercrown","Tachi","Dynamic_1_R8H6nh!","" -"Viridian Rise","","Aangesilus","Slashing Compound Bow","Dynamic_1_2LJyvGJL!","" -"Viridian Rise","","Dridge","Greater Amuli Leggings of Flame","Dynamic_1_LP3Ee7tH!","" -"Viridian Rise","","Kervim'telek","Ursuin Hide Coat","Dynamic_1_E5$S!","" -"Viridian Rise","","Swift","Fried Chicken","Dynamic_1_hYVV!","" -"Ayan","","Aludi al-Jaladh","Seasoned Explorer Gauntlets","Dynamic_1_7$I7bC!","" -"Ayan","","Aun Javhalrea, the Game Warden","Frost Ono","Dynamic_1_UdRA9W!","" -"Ayan","","Aun Khekierea","Rich Mocha","Dynamic_1_Yt1uiSkCgK!","" -"Ayan","","Aun Aukherea","Chocolate Cookie","Dynamic_1_G$iqi763E!","" -"Ayan","","Shuthoth","Silifi of Crimson Stars","Dynamic_1_CkuPj0IwP!","" -"Ayan","","Yuan Hanzu","Acid Hatchet","Dynamic_1_t^CiJAt2TBz17!","" -"Ayan","","Joku Shunja","Dho Life Apprentice Robe","Dynamic_1_&X4EDhy!","" -"Ayan","","Aaminah","Upgraded Marksman's Robe","Dynamic_1_YlHC^cbS!","" -"Ayan","","Anfram Mellow","Ulgrim's Bunny Slippers","Dynamic_1_$MJj0ytiSy0CKN!","" -"Ayan","","Alishia bint Aldan","Lightning Hatchet","Dynamic_1_87z&&Ok2o&jo!","" -"Ayan","","Vierana du Canamorra","Fine Shadow Atlan Mace","Dynamic_1_qtZdY0C!ae!","" -"Ayan","","Qurakh al-Taal","Hearty Mana Beef Stew","Dynamic_1_Ug2snTqb44!","" -"Ayan","","Laedron the Geomancer","Fine Stinging Atlan Spear","Dynamic_1_2lXQdqHWxPU!","" -"Ayan","","Rohula bint Ludun","Arena Staff","Dynamic_1_SjjPqyCHNigY!","" -"Ayan","","Guard Winterborn","Silifi of Crimson Stars","Dynamic_1_!fzudXFZV0Je3!","" -"Ayan","","Ennio di Cinghalle","Perfect Chilling Isparian Claw","Dynamic_1_fYP!","" -"Ayan","","Lydda","Pathwarden Scale Hauberk","Dynamic_1_neYBz15!","" -"Ayan","","Gaston Shadowbound","Major Shadow Tassets","Dynamic_1_jdMT!","" -"Ayan","","Harkwull the Discreet","Quality Flaming Isparian Crossbow","Dynamic_1_Bq7Brhg!","" -"Ayan","","Tanami Kei","Souldrinker","Dynamic_1_en!","" -"Ayan","","Lamorda Loschi","Major Shadow Sollerets","Dynamic_1_2xn4LwsUdh!","" -"Ayan","","Soju Bo-Ki","Composite Crossbow with Handle","Dynamic_1_ADDKG!","" -"Ayan","","Hoshar ibn Jalaq","High Balance Testing Coat","Dynamic_1_bZ4bc!","" -"Ayan","","Guard Bey","Tasty Stout","Dynamic_1_&!4f5YlXZ!","" -"Ayan","","Ishaq the Philosopher","Enhanced Skeletal Atlatl","Dynamic_1_H3UNETkRXTX!","" -"Candeth Keep","","Morathe gives you","Superb Isparian Atlatl","Dynamic_1_g9M7bV3z3#S!","" -"Candeth Keep","","Aun Autuorea gives you","Singularity Katar","Dynamic_1_5kEI0!","" -"Candeth Keep","","Talira Dain","Composite Bow","Dynamic_1_5i1z1Mb!","No text about being given item, it just shows up in backpack" -"Candeth Keep","","Dalius Kendmar gives you","Undead Guise","Dynamic_1_YFrw!","" -"Candeth Keep","","Grania the Bold gives you","Composite Crossbow with Handle","Dynamic_1_DaevbVP!","" -"Candeth Keep","","Yukara Miko the Collector","Acid Longbow","Dynamic_1_F1r^qTQ!","" -"Candeth Keep","","Ryukai Hiro","Good Olthoi Pauldrons","Dynamic_1_HeucrAy6c!","" -"Candeth Keep","","Garaena the Emissary","Seasoned Explorer Arbalest","Dynamic_1_es^0FY!","Aerlinthe Portal NPC" diff --git a/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj b/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj index 450dfd0..821e3bb 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj +++ b/Plugins/RynthCore.Plugin.RynthOracle/RynthCore.Plugin.RynthOracle.csproj @@ -23,7 +23,7 @@ 66 - Quests (with the Legendary, marker, Dynamic Stamp and Temple guardian trackers), character and titles. + Quests (with the Legendary and exploration marker trackers, and the active server plugin's quest pack), character and titles. @@ -34,11 +34,8 @@ - - - - - + @@ -46,8 +43,6 @@ - - @@ -55,10 +50,6 @@ - - - @@ -68,6 +59,9 @@ + + + diff --git a/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs b/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs index 541ea02..b71b5d4 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/RynthOraclePlugin.cs @@ -41,18 +41,14 @@ public sealed class RynthOraclePlugin : RynthPluginBase private long _loginMs; private long _nextCharacterReadMs; private long _nextCharacterExtrasMs; - private string _charmsJson = ""; - private long _nextBreedingMs; - private string _breedingJson = ""; - private long _nextGuardianMs; - private string _guardianJson = ""; private bool _voidAutoDecided; private bool _dailyCheckStarted; - private int _seenFlagRevision = -1, _seenCatalogRevision = -1, _seenVoidRevision = -1, _seenIltRevision = -1; + private int _seenFlagRevision = -1, _seenCatalogRevision = -1, _seenVoidRevision = -1; // RynthCore's server list (ServerStateClient.Revision) last applied to the server identity. private int _seenServerStateRevision = -1; private bool _noUiLogged; - private string? _catalogTag; // the server tag the catalog and server data were loaded for + private string? _catalogKey; // what the catalog was loaded for (QuestPackSource.Key; "" = retail only) + private int _seenPackRevision = -1; // the active server plugin's quest pack (ServerQuestPackClient.Revision) private int _titleCount = -2; private uint _titleCurrent; @@ -66,10 +62,6 @@ public sealed class RynthOraclePlugin : RynthPluginBase _c.ReloadQuestList = ReloadQuestList; _c.Send = cmd => _c.InWorld && Host.InvokeChatParser(cmd); _c.RunCommand = cmd => _c.InWorld && Host.InvokeChatParser(cmd); - _c.ToggleCharm = ToggleCharm; - _c.BreedingCommand = BreedingCommand; - _c.GuardianCommand = GuardianCommand; - _c.UbGiveAvailable = UbGiveAvailable; _c.SendNav = line => Host.HasSendPluginCommand && Host.SendPluginCommand("RynthNav", "rnav", line); _ui.Log = msg => Host.Log(msg); @@ -126,14 +118,15 @@ public sealed class RynthOraclePlugin : RynthPluginBase _c.Flags.Clear(); _c.Void.Clear(); _c.Server.Reset(); - _c.Ilt.Clear(); - _c.Ilt.Poll(Host, Environment.TickCount64); _c.ServerState.Clear(); _c.ServerState.Poll(Host, Environment.TickCount64, force: true); _seenServerStateRevision = _c.ServerState.Revision; _c.VoidDotScale = VoidScaleFrom(_c.ServerState.ProfileJson); - _c.Server.Refresh(Host, Host.GetPlayerId(), _c.Ilt.Profile.Ilt, _c.ServerState.State); - _catalogTag = null; + _c.Server.Refresh(Host, _c.ServerState.State); + _c.QuestPacks.Clear(); + _c.QuestPacks.Poll(Host, Shared.ServerQuestPackClient.OwnerOf(_c.ServerState.State), Environment.TickCount64, force: true); + _seenPackRevision = _c.QuestPacks.Revision; + _catalogKey = null; ApplyServer(); _titleCount = -2; _c.TitlesKnown = false; @@ -171,45 +164,24 @@ public sealed class RynthOraclePlugin : RynthPluginBase _c.Void.Clear(); _c.Server.Reset(); _c.VoidDotScale = 1.0; - _c.Ilt.Clear(); _c.ServerState.Clear(); + _c.QuestPacks.Clear(); _c.TitlesKnown = false; _c.EarnedTitles.Clear(); ClearCharacterExtras(); } - /// Forgets the Character tab's charms and session and the ILT readers' data (login, logout): the next character's come fresh. + /// Forgets the Character tab's session (login, logout): the next character's comes fresh. private void ClearCharacterExtras() { - _c.Charms = Shared.IltCharmsView.None; - _charmsJson = ""; - _c.CharmMessage = ""; - _c.Breeding = Shared.IltBreedingView.None; - _breedingJson = ""; - _c.BreedingMessage = ""; - _c.Guardian = Shared.IltGuardianView.None; - _guardianJson = ""; - _c.GuardianRevision++; - _c.GuardianMessage = ""; - _c.UbGiveMissing = false; _c.Session = default; _c.SessionKnown = false; _c.AiSession.Reset(); } - /// The Character tab's Toggle: RynthILT checks the id is one of the player's charms and uses it. - private bool ToggleCharm(uint id) - { - bool ok = _c.InWorld && _c.IltData.ToggleCharm(Host, Environment.TickCount64, id); - _c.CharmMessage = ok ? "Toggled; the status updates in a moment." : "RynthILT didn't take that (not carried any more, or RynthILT isn't loaded)."; - _nextCharacterExtrasMs = Environment.TickCount64 + 1000; // re-read soon so the new state shows - if (_main != null) _main.NeedsPass = true; - return ok; - } - /// - /// While the Character tab is on screen: RynthILT's charms JSON and RynthAi's session, every - /// . Nothing is read with the window closed or on another tab. + /// While the Character tab is on screen: RynthAi's session, every . + /// Nothing is read with the window closed or on another tab. /// private void ReadCharacterExtras(long now) { @@ -217,13 +189,6 @@ public sealed class RynthOraclePlugin : RynthPluginBase if (now < _nextCharacterExtrasMs) return; _nextCharacterExtrasMs = now + CharacterExtrasReadMs; - string json = _c.IltData.ReadCharms(Host, now); - if (!string.Equals(json, _charmsJson, StringComparison.Ordinal)) - { - _charmsJson = json; - _c.Charms = Shared.IltCharmsView.Parse(json); - _main.NeedsPass = true; - } bool known = _c.AiSession.TryGet(Host, now, out Shared.SessionStatsV1 s); if (known != _c.SessionKnown || known && (s.Xp != _c.Session.Xp || s.Lum != _c.Session.Lum || s.Kills != _c.Session.Kills)) _main.NeedsPass = true; @@ -231,76 +196,11 @@ public sealed class RynthOraclePlugin : RynthPluginBase _c.Session = known ? s : default; } - /// The Pet Breeding tab's buttons: a verb for RynthILT's tracker, then a quick re-read. - private bool BreedingCommand(string verb) - { - long now = Environment.TickCount64; - bool ok = _c.InWorld && _c.IltData.PetBreedingCommand(Host, now, verb); - _c.BreedingMessage = ok ? "Sent to RynthILT; the tab updates in a moment." : "RynthILT didn't take that (not loaded, or older than 0.3.1)."; - _nextBreedingMs = now + 800; - if (_main != null) _main.NeedsPass = true; - return ok; - } - - /// - /// While the Pet Breeding tab is on screen: RynthILT's breeding JSON every - /// (reading it keeps RynthILT's tracker scanning). Nothing is read with the window closed or on another tab. - /// - private void ReadBreeding(long now) - { - if (_main == null || _mainView == null || !_main.Visible || _mainView.Tab != OracleView.TabBreeding) return; - if (now < _nextBreedingMs) return; - _nextBreedingMs = now + CharacterExtrasReadMs; - string json = _c.IltData.ReadPetBreeding(Host, now); - if (string.Equals(json, _breedingJson, StringComparison.Ordinal)) return; - _breedingJson = json; - _c.Breeding = Shared.IltBreedingView.Parse(json); - _main.NeedsPass = true; - } - - /// The Quests tab's guardian controls: a verb for RynthILT's guardians, then a quick re-read. - private bool GuardianCommand(string verb) - { - long now = Environment.TickCount64; - bool ok = _c.InWorld && _c.IltData.GuardianCommand(Host, now, verb); - _c.GuardianMessage = ok ? "" : "RynthILT didn't take that (not loaded, or older than 0.3.3)."; - _nextGuardianMs = now + 400; - if (_main != null) _main.NeedsPass = true; - return ok; - } - - /// - /// While the Quests tab is on screen on Infinite Leaftide: RynthILT's Temple guardian JSON every - /// (the guardian rows, switches and last answer). Nothing is - /// read with the window closed, on another tab, or on another server. - /// - private void ReadGuardian(long now) - { - if (_main == null || _mainView == null || !_main.Visible || _mainView.Tab != OracleView.TabQuests) return; - if (!_c.Server.Is(ServerTags.InfiniteLeaftide)) return; - if (now < _nextGuardianMs) return; - _nextGuardianMs = now + CharacterExtrasReadMs; - string json = _c.IltData.ReadGuardian(Host, now); - if (string.Equals(json, _guardianJson, StringComparison.Ordinal)) return; - _guardianJson = json; - _c.Guardian = Shared.IltGuardianView.Parse(json); - _c.GuardianRevision++; - _main.NeedsPass = true; - } - - /// - /// The Give Parchment button's gate: the "/ub give" verb lives in RynthAi, so RynthAi must answer - /// on its hub interface, and must not have rejected the verb already. - /// - private bool UbGiveAvailable() - => _c.InWorld && !_c.UbGiveMissing && Host.HasInvokeChatParser && _c.AiSession.IsLoaded(Host, Environment.TickCount64); - - /// Opens the Quests tab on the trackers: one kind (/ro legendary, /ro dynamic ...) or all of them (null). + /// Opens the Quests tab on the trackers: one kind (/ro legendary, /ro markers) or all of them (null). private void ShowTrackers(QuestKind? kind) { _mainView?.ShowTrackers(kind); if (_main != null) { _main.Visible = true; _main.NeedsPass = true; } - _nextGuardianMs = 0; // read at once } /// Shows the main window on a tab (another plugin's link, or a /ro tab command). @@ -309,28 +209,33 @@ public sealed class RynthOraclePlugin : RynthPluginBase if (_mainView != null) _mainView.Tab = tab; if (_main != null) { _main.Visible = true; _main.NeedsPass = true; } if (tab == OracleView.TabCharacter) _nextCharacterExtrasMs = 0; // read at once - if (tab == OracleView.TabBreeding) _nextBreedingMs = 0; - if (tab == OracleView.TabQuests) _nextGuardianMs = 0; } /// - /// Loads what depends on the server: the quest catalog with the server's pack, and fresh - /// server-specific data. Runs at login and again whenever the server tag changes (it can be - /// known only a moment after login). + /// Loads what depends on the server: the quest catalog with the active server's pack (the one its + /// plugin offers through "RynthServer.QuestPack"; none on a server without one). Runs at login and + /// again whenever the server or its pack changes (either can arrive a moment after login). /// private void ApplyServer() { - string tag = _c.Server.Tag; - if (_catalogTag == tag) return; - _catalogTag = tag; - try { _c.Catalog.Load(tag, msg => Host.Log(msg)); } + Shared.ServerQuestPack? pack = Shared.ServerQuestPackClient.ForActive(_c.ServerState.State, _c.QuestPacks.Pack); + QuestPackSource? source = QuestCatalog.SourceFor(_c.Server, pack); + // The pack client's revision goes up whenever the offered pack changes (same size or not). + string key = source == null ? "" : source.Key + "|" + _c.QuestPacks.Revision; + if (_catalogKey == key) return; + _catalogKey = key; + try { _c.Catalog.Load(source, msg => Host.Log(msg)); } catch (Exception ex) { Host.Log($"[RynthOracle] Couldn't load the quest list: {ex.Message}"); } _c.Catalog.SyncDiscoveries(_c.Flags); - string pack = _c.Catalog.PackServer.Length > 0 ? $" + {_c.Catalog.ServerCount} {_c.Catalog.PackServer}" : ""; - Host.Log($"[RynthOracle] Server: {(tag.Length > 0 ? tag : "no server-specific features")} ({_c.Server.Source}); {_c.Catalog.RetailCount} retail quests{pack}."); + Host.Log($"[RynthOracle] Server: {_c.Server.DisplayName} ({_c.Server.Source}); {_c.Catalog.RetailCount} retail quests{PackText()}."); if (_main != null) _main.NeedsPass = true; } + /// " + 546 Conquest (from RynthConquest)", or "" without a pack. + private string PackText() => _c.Catalog.PackServer.Length > 0 + ? $" + {_c.Catalog.ServerCount} {_c.Catalog.PackServer} ({_c.Catalog.PackSource})" + : ""; + public override void Shutdown() { _skills?.Shutdown(); @@ -347,9 +252,6 @@ public sealed class RynthOraclePlugin : RynthPluginBase long now = Environment.TickCount64; string line = text.TrimEnd('\r', '\n'); - // RynthAi's reply to a "/ub give" it doesn't have: the Give Parchment button turns itself off. - if (_c.NoteChatLineForGive(line, now) && _main != null) _main.NeedsPass = true; - MyQuestsLine kind = _c.Flags.OnChatLine(line, now); if (kind != MyQuestsLine.None) { @@ -428,11 +330,8 @@ public sealed class RynthOraclePlugin : RynthPluginBase break; case "character": case "char": - case "charms": - case "charm": - // The Character tab: the character overview, RynthAi's session and, on Infinite Leaftide, - // RynthILT's charms (the Mini Remote's Charms tab stays as well). - // RynthAi, RynthILT and RynthCore's menus link here; it shows, never toggles off. + // The Character tab: the character overview and RynthAi's session. + // RynthAi, the server plugins and RynthCore's menus link here; it shows, never toggles off. ShowTab(OracleView.TabCharacter); break; case "legendary": @@ -447,33 +346,10 @@ public sealed class RynthOraclePlugin : RynthPluginBase ShowTrackers(QuestKind.Marker); break; case "trackers": - // Every tracker this server has: Legendary, markers, and on Infinite Leaftide stamps and guardians. + // Every tracker: the Legendary Key quests and the exploration markers. A server's own + // trackers and tabs are its server plugin's pages (since 2026-10-21). ShowTrackers(null); break; - case "dynamic": - case "dyn": - case "dyno": - case "stamps": - case "guardian": - case "guardians": - // Infinite Leaftide's trackers: Dynamic Stamps and RynthILT's Temple guardians. - bool guardians = arg is "guardian" or "guardians"; - if (!_c.Server.Is(ServerTags.InfiniteLeaftide)) - { - _c.Print((guardians ? "The Temple guardians are" : "Dynamic stamps are") - + " an Infinite Leaftide quest line; this server isn't recognised as Infinite Leaftide."); - ShowTrackers(null); - } - else ShowTrackers(guardians ? QuestKind.Guardian : QuestKind.Dynamic); - break; - case "breeding": - case "breed": - case "pets": - // The Pet Breeding tab (Infinite Leaftide only; the Mini Remote's Pets > Breeding is the same tracker). - if (!_c.Server.Is(ServerTags.InfiniteLeaftide)) - _c.Print("Pet breeding is an Infinite Leaftide feature; this server isn't recognised as Infinite Leaftide."); - ShowTab(OracleView.TabBreeding); - break; case "skills": case "skill": // The Skills tab: RynthCore's skills panel (raise and train) inside this window. @@ -490,31 +366,27 @@ public sealed class RynthOraclePlugin : RynthPluginBase ShowTab(OracleView.TabProgress); break; case "status": - string pack = _c.Catalog.PackServer.Length > 0 ? $" + {_c.Catalog.ServerCount} {_c.Catalog.PackServer}" : ""; string titles = _c.TitlesKnown ? $", {_c.EarnedTitles.Count} titles held" : ""; - _c.Print($"Server: {(_c.Server.Tag.Length > 0 ? _c.Server.Tag : "no server-specific features")} ({_c.Server.Source}). " - + $"{_c.Flags.Flags.Count} quest flags read, {_c.Catalog.RetailCount} retail quests{pack}, {_c.Void.Dots.Count} Void spells tracked{titles}."); + _c.Print($"Server: {_c.Server.DisplayName} ({_c.Server.Source}). " + + $"{_c.Flags.Flags.Count} quest flags read, {_c.Catalog.RetailCount} retail quests{PackText()}, {_c.Void.Dots.Count} Void spells tracked{titles}."); break; case "about": - case "features": - // The About tab (settings, the server RynthCore says this is, RynthILT's server features). + // The About tab (settings, the server RynthCore says this is, the quest list). _c.Print("Based on Oracle of Dereth by Advis Eveldan - thank you! github.com/advis61/OracleOfDereth (MIT)"); ShowTab(OracleView.TabAbout); break; default: - _c.Print("Commands: /ro (window), /ro character (Character tab: status, session, charms), " + _c.Print("Commands: /ro (window), /ro character (Character tab: status, session), " + "/ro skills|attributes|progress (those tabs), /ro void (Void window), " - + "/ro timers (Quest Timers window), /ro fellowship (Fellowship tab), /ro breeding (Pet Breeding tab, Infinite Leaftide), " + + "/ro timers (Quest Timers window), /ro fellowship (Fellowship tab), " + "/ro trackers (Quests tab, trackers only), /ro legendary (John's 30 key quests), /ro markers, " - + "/ro dynamic and /ro guardians (Infinite Leaftide: NPC stamps, Temple guardians), " + "/ro quests (read quest flags), /ro status, " - + "/ro about (About tab: settings, server features)"); + + "/ro about (About tab: settings, server, quest list). A server's own pages are its server plugin's (/rserver)."); break; } - if (arg is "" or "void" or "timers" or "timer" or "fellowship" or "fellow" or "fship" or "character" or "char" or "charms" or "charm" + if (arg is "" or "void" or "timers" or "timer" or "fellowship" or "fellow" or "fship" or "character" or "char" or "skills" or "skill" or "attributes" or "attrs" or "attribute" or "vitals" or "progress" or "progression" - or "breeding" or "breed" or "pets" or "legendary" or "legend" or "john" or "markers" or "marker" or "trackers" - or "dynamic" or "dyn" or "dyno" or "stamps" or "guardian" or "guardians" or "about" or "features" && !Host.HasUi && !_noUiLogged) + or "legendary" or "legend" or "john" or "markers" or "marker" or "trackers" or "about" && !Host.HasUi && !_noUiLogged) { _noUiLogged = true; _c.Print("This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). /ro status still works."); @@ -563,8 +435,9 @@ public sealed class RynthOraclePlugin : RynthPluginBase } /// - /// Reloads the quest list and the server's pack from their files (a downloaded list, or a pack - /// dropped into %APPDATA%\RynthCore\RynthOracle\packs) and asks RynthCore which server this is. + /// Reloads the quest list and the server's pack (a downloaded list, a pack dropped into + /// %APPDATA%\RynthCore\RynthOracle\packs, the server plugin's pack asked for again) and asks + /// RynthCore which server this is. /// private void ReloadQuestList() { @@ -572,11 +445,10 @@ public sealed class RynthOraclePlugin : RynthPluginBase _c.ServerState.Poll(Host, now, force: true); _seenServerStateRevision = _c.ServerState.Revision; _c.VoidDotScale = VoidScaleFrom(_c.ServerState.ProfileJson); - _c.Ilt.Poll(Host, now); - _c.Server.Refresh(Host, _c.Character.PlayerId != 0 ? _c.Character.PlayerId : Host.GetPlayerId(), _c.Ilt.Profile.Ilt, _c.ServerState.State); - try { _c.Catalog.Load(_c.Server.Tag, msg => Host.Log(msg)); } - catch (Exception ex) { Host.Log($"[RynthOracle] Couldn't load the quest list: {ex.Message}"); } - _c.Catalog.SyncDiscoveries(_c.Flags); + _c.Server.Refresh(Host, _c.ServerState.State); + _c.QuestPacks.Poll(Host, Shared.ServerQuestPackClient.OwnerOf(_c.ServerState.State), now, force: true); + _seenPackRevision = _c.QuestPacks.Revision; + _catalogKey = null; // the files may have changed: load again even for the same pack ApplyServer(); if (_main != null) _main.NeedsPass = true; } @@ -651,7 +523,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase Host.Log("[RynthOracle] " + result); if (updated) { - _c.Catalog.Load(_c.Server.Tag, msg => Host.Log(msg)); + _c.Catalog.Reload(msg => Host.Log(msg)); _c.Catalog.SyncDiscoveries(_c.Flags); } if (_main != null) _main.NeedsPass = true; @@ -659,25 +531,22 @@ public sealed class RynthOraclePlugin : RynthPluginBase if (!_c.InWorld) return; - // RynthILT's profile (every 2 s): which features the server has, the /qb list. - _c.Ilt.Poll(Host, now); - if (_c.Ilt.Revision != _seenIltRevision) - { - _seenIltRevision = _c.Ilt.Revision; - if (_main != null) _main.NeedsPass = true; - } - ReadCharacterExtras(now); - ReadBreeding(now); - ReadGuardian(now); // RynthCore's server list (every 2 s): a new pick or override applies now, not at the next character read. _c.ServerState.Poll(Host, now); - if (_c.ServerState.Revision != _seenServerStateRevision) + bool serverChanged = _c.ServerState.Revision != _seenServerStateRevision; + if (serverChanged) { _seenServerStateRevision = _c.ServerState.Revision; _c.VoidDotScale = VoidScaleFrom(_c.ServerState.ProfileJson); - _c.Server.Refresh(Host, _c.Character.PlayerId != 0 ? _c.Character.PlayerId : Host.GetPlayerId(), _c.Ilt.Profile.Ilt, _c.ServerState.State); + _c.Server.Refresh(Host, _c.ServerState.State); + } + // The active server plugin's quest pack (every 2 s; the CSV is read only when it changed). + _c.QuestPacks.Poll(Host, Shared.ServerQuestPackClient.OwnerOf(_c.ServerState.State), now, force: serverChanged); + if (serverChanged || _c.QuestPacks.Revision != _seenPackRevision) + { + _seenPackRevision = _c.QuestPacks.Revision; ApplyServer(); if (_main != null) _main.NeedsPass = true; } @@ -703,7 +572,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase _nextCharacterReadMs = now + CharacterReadMs; _c.Character.Read(Host); _c.Void.RemoveExpired(now); - _c.Server.Refresh(Host, _c.Character.PlayerId, _c.Ilt.Profile.Ilt, _c.ServerState.State); + _c.Server.Refresh(Host, _c.ServerState.State); ApplyServer(); LoadQuestBook(now); AnnounceTimers(); diff --git a/Plugins/RynthCore.Plugin.RynthOracle/THIRD_PARTY_NOTICES.md b/Plugins/RynthCore.Plugin.RynthOracle/THIRD_PARTY_NOTICES.md index 9a1d499..2be77a7 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/THIRD_PARTY_NOTICES.md +++ b/Plugins/RynthCore.Plugin.RynthOracle/THIRD_PARTY_NOTICES.md @@ -10,9 +10,10 @@ contributions from aunrela and porranlc (one commit each). Thank you, Advis! LICENSE file and names no copyright line, so the standard MIT text is reproduced below with the author and the years of the repository's history. -Not from upstream: `quests.aelrynth.csv` is generated from Aelrynth's own world database by -`Tools\RynthOracle.QuestPackGen`; where a quest is also in Advis's list, that list's name and notes -are kept (the pack only adds Aelrynth's timers and who sets the flag). +Server quest packs are the server plugins' since 2026-10-21 (each with its own notice): the +master list's Conquest and Levistras rows are in RynthConquest and RynthLevistras, and the pack +generated from Aelrynth's world database by `Tools\RynthOracle.QuestPackGen` is in RynthAelrynth. +RynthOracle merges whichever pack the active server's plugin offers. What came from upstream: @@ -20,8 +21,8 @@ What came from upstream: in `Resources\` (`quests.csv`, `augmentations.csv`, `augquests.csv`, `society.csv`, `titles.csv`, `markers.csv`), copied unchanged, except that the master quest list is split by its own Server column into `quests.csv` (every retail - quest), `quests.conquest.csv` and `quests.levistras.csv` (each server's own rows, loaded - only on that server); the lines themselves are untouched. `quests.csv` is Oracle of Dereth's curator-maintained master quest list; + quest) and each server's own rows (now in that server's plugin, see above); the lines + themselves are untouched. `quests.csv` is Oracle of Dereth's curator-maintained master quest list; its README says the Quest Flags list "was assembled with AI assistance and may contain errors". The curator is the same author (every commit that updates it is Advis Eveldan's); the file carries no licence of its own, so it is treated as part of the MIT-licensed repository. diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs index fa013b4..f10461a 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/AboutTab.cs @@ -29,9 +29,11 @@ internal sealed partial class OracleView w.SeparatorText("Server"); ServerIdentity sv = _c.Server; - w.Text(sv.Tag.Length == 0 ? "No server-specific pages here (retail features only)." - : sv.Is(ServerTags.InfiniteLeaftide) ? $"{sv.Tag}: its own pages are on (stamps and guardians on the Quests tab, Pet Breeding)." - : $"{sv.Tag}: its own pages and quest pack are on."); + QuestCatalog pc = _c.Catalog; + w.Text(sv.ServerId.Length == 0 ? "No server active (retail quests only)." + : pc.PackServer.Length > 0 ? $"{sv.DisplayName}: its quest pack is on ({pc.ServerCount} {pc.PackServer} quests, {pc.PackSource})." + : $"{sv.DisplayName}: no quest pack ({(sv.Plugin.Length > 0 ? sv.Plugin + " offers none" : "no server plugin loaded for it")}; retail quests only)."); + w.TextDisabled("A server's quest pack comes from its server plugin, and its own pages are that plugin's: the Mini Remote's Server section, or /rserver."); w.TextDisabled($"How it was decided: {sv.Source}"); // RynthCore's server list (API v86) and the active server's settings from the plugin that owns it. RynthCore.Plugin.Shared.ServerStateClient st = _c.ServerState; @@ -46,11 +48,9 @@ internal sealed partial class OracleView w.TextDisabled($"{es.ActivePlugin} hasn't sent its server settings (an older plugin?)."); w.TextDisabled("Change the server: RynthCore Options > Diagnostics > Server, or /rc server pick |auto."); } - else if (_c.Host.Version >= 75 && _c.Host.Version < 85) - w.TextDisabled($"This engine is API v{_c.Host.Version}; v86 lets RynthOracle follow RynthCore's server pick and overrides."); - if (_c.Host.Version < 75) w.TextDisabled($"This engine is API v{_c.Host.Version}; v75 adds a surer server check and the titles you hold."); - - DrawServerFeatures(w); + else if (_c.Host.Version > 0 && _c.Host.Version < 86) + w.TextDisabled($"This engine is API v{_c.Host.Version}; server quest packs need v86 (RynthCore's server list)."); + if (_c.Host.Version > 0 && _c.Host.Version < 75) w.TextDisabled($"This engine is API v{_c.Host.Version}; v75 adds the titles you hold."); w.SeparatorText("Quest list"); QuestCatalog cat = _c.Catalog; @@ -70,77 +70,18 @@ internal sealed partial class OracleView w.SeparatorText("Commands"); w.BulletText("/ro open or close this window"); - w.BulletText("/ro character the Character tab (status, session, charms)"); + w.BulletText("/ro character the Character tab (status, session)"); w.BulletText("/ro skills the Skills tab (raise and train); /ro attributes, /ro progress likewise"); w.BulletText("/ro timers open or close the Quest Timers window"); w.BulletText("/ro fellowship the Fellowship tab"); - w.BulletText("/ro trackers the Quests tab, trackers only (Legendary, markers, and on ILT stamps and guardians)"); + w.BulletText("/ro trackers the Quests tab, trackers only (Legendary, markers)"); w.BulletText("/ro legendary John's Legendary Key quests: have, missing, repeat timers"); w.BulletText("/ro markers the 100 exploration markers: found and still to find"); - if (_c.Server.Is(Data.ServerTags.InfiniteLeaftide)) - { - w.BulletText("/ro dynamic Infinite Leaftide Dynamic Stamps: NPC stamps you have and are missing"); - w.BulletText("/ro guardians the Temple guardians: riddle answers, auto hand-in, buy if missing, turn-ins"); - w.BulletText("/ro breeding the Pet Breeding tab (when the server has pet breeding)"); - } - w.BulletText("/ro about this tab (settings, server, server features)"); + w.BulletText("/ro about this tab (settings, server, quest list)"); w.BulletText("/ro void open or close the Void window"); w.BulletText("/ro quests read your quest flags now"); w.BulletText("/ro help list the commands in chat"); - w.TextDisabled("A server quest pack can be replaced without a rebuild: put quests..csv in %APPDATA%\\RynthCore\\RynthOracle\\packs."); - } - - /// - /// "Server features": the Leaftide feature list RynthILT keeps (sent in its "RynthILT.Server" - /// profile), drawn group by group in RynthILT's order with each feature's state and where it - /// lives. Nothing here is hard-coded: a newer RynthILT adds features without an Oracle update. - /// - private void DrawServerFeatures(UiWindow w) - { - IltServerProfile p = _c.Ilt.Profile; - if (!p.Available) - { - if (_c.Server.Is(ServerTags.InfiniteLeaftide)) - { - w.SeparatorText("Server features"); - w.TextDisabled("Load RynthILT to list the Infinite Leaftide features here."); - } - return; - } - if (p.Features.Count == 0) return; - - w.SeparatorText("Server features"); - string checkedText = p.CheckedUtc == DateTime.MinValue ? "not checked yet" : $"checked {p.CheckedUtc.ToLocalTime():yyyy-MM-dd HH:mm}"; - w.TextDisabled(p.Ilt - ? $"From RynthILT ({(p.World.Length > 0 ? p.World : "this world")}, {checkedText}{(p.Forced ? ", forced on" : "")})." - : "From RynthILT: this isn't an Infinite Leaftide world, so no Leaftide feature is claimed."); - - // Groups in the order RynthILT lists them; one table per group. - var groups = new System.Collections.Generic.List(); - foreach (IltFeature f in p.Features) - if (!groups.Exists(g => string.Equals(g, f.Group, StringComparison.OrdinalIgnoreCase))) groups.Add(f.Group); - - int on = 0; - foreach (IltFeature f in p.Features) if (f.State == RynthCore.Plugin.Shared.RynthIltServer.StateOn) on++; - w.TextDisabled($"{on} of {p.Features.Count} on."); - - foreach (string group in groups) - { - if (!w.CollapsingHeader(group.Length > 0 ? group : "Other", "o.feat.h." + group)) continue; - foreach (IltFeature f in p.InGroup(group)) - { - uint color = f.State switch - { - RynthCore.Plugin.Shared.RynthIltServer.StateOn => UiColors.Green, - RynthCore.Plugin.Shared.RynthIltServer.StateOff => UiColors.Red, - _ => UiColors.Yellow, - }; - w.TextColored(color, $"[{IltServerProfile.StateText(f.State)}]"); - w.SameLine(); - w.Text(f.Label); - if (f.Where.Length > 0) w.Tooltip("Where: " + f.Where); - } - } + w.TextDisabled("A server quest pack can be replaced without a rebuild: put quests..csv in %APPDATA%\\RynthCore\\RynthOracle\\packs."); } private void StartQuestListCheck() @@ -155,7 +96,7 @@ internal sealed partial class OracleView { try { File.Delete(QuestCatalog.DownloadedPath); } catch (Exception ex) { _c.UpdaterMessage = "Couldn't remove the downloaded list: " + ex.Message; return; } - _c.Catalog.Load(_c.Server.Tag, null); + _c.Catalog.Reload(null); _c.Catalog.SyncDiscoveries(_c.Flags); _c.UpdaterMessage = "Using the bundled quest list."; } diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/CharacterTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/CharacterTab.cs index d8eca34..8929f0f 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/CharacterTab.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/CharacterTab.cs @@ -9,8 +9,8 @@ namespace RynthCore.Plugin.RynthOracle.Views; /// /// Character: level and experience, luminance, the status summary (upstream's Status HUD: buff, /// house, beer, page and rare timers, key skills, aetheria surges), RynthAi's session (the generic -/// part of the Mini Remote's old Character tab, moved here 2026-10-13), on Infinite Leaftide RynthILT's -/// charms (a second place for them: the Mini Remote's Charms tab stays) and the full buff list. +/// part of the Mini Remote's old Character tab, moved here 2026-10-13) and the full buff list. A +/// server's own character extras are its server plugin's (the charms list left on 2026-10-21). /// internal sealed partial class OracleView { @@ -57,7 +57,6 @@ internal sealed partial class OracleView Field(w, "Summoning", SkillText(c.Summoning), 300f, 400f); DrawSession(w); - DrawCharms(w); var list = new List(c.Enchantments); list.Sort((a, b) => a.Remaining.CompareTo(b.Remaining)); @@ -106,97 +105,6 @@ internal sealed partial class OracleView private static string RateText(double perHour) => perHour > 0 ? TimeText.Number((long)Math.Round(perHour)) : "0"; - /// - /// "Charms": RynthILT's Infinite Leaftide charm list (the Mini Remote's Charms tab shows the same - /// one), with a Toggle for each carried charm and Guardian Hand. Nothing is listed here: RynthILT - /// sends the list, so a charm it learns about shows up without an Oracle update. - /// - private void DrawCharms(UiWindow w) - { - Shared.IltCharmsView v = _c.Charms; - if (!v.Loaded) - { - if (_c.Server.Is(ServerTags.InfiniteLeaftide)) - { - w.SeparatorText("Charms"); - w.TextDisabled("Load RynthILT to list your Infinite Leaftide charms here."); - } - return; - } - if (!v.Available) return; // not an ILT world: no charms - - w.SeparatorText("Charms"); - w.TextDisabled($"{v.Acquired} acquired, {v.Active} on (from RynthILT{(v.World.Length > 0 ? ", " + v.World : "")})."); - if (_c.CharmMessage.Length > 0) w.TextDisabled(_c.CharmMessage); - - if (w.CollapsingHeader($"Charms ({v.Charms.Count})", "c.charms", defaultOpen: true)) - { - if (v.Charms.Count == 0) w.TextDisabled("RynthILT hasn't listed any charms yet."); - for (int i = 0; i < v.Charms.Count; i++) - { - Shared.IltCharmRow r = v.Charms[i]; - CharmState(w, r.Active); - w.SameLine(50f); - if (r.Carried) w.Text(Cut(r.Name, 30)); - else w.TextDisabled(Cut(r.Name, 30)); - if (r.Effect.Length > 0) w.Tooltip(r.Effect); - w.SameLine(270f); - w.TextDisabled(r.MaxTier > 0 ? $"T{r.Tier}/{r.MaxTier}" : r.Tier > 0 ? $"T{r.Tier}" : "-"); - w.SameLine(330f); - w.TextDisabled(AcquiredText(r)); - if (r.Server == "off") - { - w.SameLine(430f); - w.TextColored(UiColors.Red, "server off"); - } - if (r.Carried && r.ToggleId != 0) - { - w.SameLine(510f); - uint id = r.ToggleId; - w.SmallButton("Toggle", "c.charm." + i, () => _c.ToggleCharm(id)); - } - } - } - - if (v.Hands.Count > 0 && w.CollapsingHeader($"Guardian Hands ({v.Hands.Count})", "c.hands", defaultOpen: true)) - { - for (int i = 0; i < v.Hands.Count; i++) - { - Shared.IltHandRow h = v.Hands[i]; - CharmState(w, h.Active); - w.SameLine(50f); - w.Text(Cut(h.Name, 30)); - if (h.Server == "off") - { - w.SameLine(430f); - w.TextColored(UiColors.Red, "server off"); - } - w.SameLine(510f); - uint id = h.Id; - w.SmallButton("Toggle", "c.hand." + i, () => _c.ToggleCharm(id)); - } - } - } - - /// ON in green, OFF in red, "?" in grey (status not read yet). - private static void CharmState(UiWindow w, string active) - { - switch (active) - { - case "on": w.TextColored(UiColors.Green, "ON"); break; - case "off": w.TextColored(UiColors.Red, "OFF"); break; - default: w.TextColored(UiColors.Grey, "?"); break; - } - } - - /// Carried (with the count), stored (seen on this character before) or not acquired. - internal static string AcquiredText(Shared.IltCharmRow r) => r.Acquired switch - { - "carried" => r.Count > 1 ? $"carried x{r.Count}" : "carried", - "seen" => r.LastSeen.Length > 0 ? "seen " + r.LastSeen : "seen", - _ => "not acquired", - }; - /// /// The buff timer: the soonest-ending long (over 15 minutes) buff that isn't a beer, a debuff /// or one of the not-really-buffs, with how many there are (upstream's rule). diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/DynamicStampsTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/DynamicStampsTab.cs deleted file mode 100644 index be3bd52..0000000 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/DynamicStampsTab.cs +++ /dev/null @@ -1,214 +0,0 @@ -using System; -using System.Collections.Generic; -using RynthCore.Plugin.RynthOracle.Data; -using RynthCore.Plugin.RynthOracle.Ui; - -namespace RynthCore.Plugin.RynthOracle.Views; - -/// -/// Dynamic Stamps (Infinite Leaftide only): the NPC hand-ins that put a "Dynamic_N_..." flag on -/// the character, read from /myquests. They are rows of the Quests tab's merged list (QuestsTab.cs: -/// DYN rows, the Show filter's area picker). What is here is the opened stamp's box (RynthNav, the -/// Parchment hand-in, chat), the read after a hand-in, and the RynthNav sender every row kind -/// shares. The list follows the players' "ExtraDyn" sheet (dynstamps.csv). -/// -/// Give Parchment sends RynthAi's "/ub give 1 <parchment> to <npc>". That verb belongs to -/// RynthAi, so the button is disabled (with a tooltip saying why) when RynthAi isn't loaded or has -/// answered "Unrecognized /ub command" to it. -/// -internal sealed partial class OracleView -{ - // The stamp clicked last: the box below the list offers RynthNav's auto nav to it. - private DynamicStamp? _dynNav; - private bool _dynNavDone; - private string _dynNavStatus = ""; - // The Parchment waiting for Yes: handing it over is the one thing here that can't be taken back. - private string _giveConfirm = ""; - - /// - /// The destination box (the click's pop-up): the stamp, where RynthNav will take you, and Go (plan - /// and walk the route: portals, recalls and dungeon entrances included), Arrow, Chat and Close. - /// - private void DrawDynamicNavBox(UiWindow w) - { - DynamicStamp? s = _dynNav; - if (s == null) return; - List targets = s.NavCandidates(); - w.SeparatorText("Navigate to " + Cut(s.Label, 40)); - w.TextDisabled(targets.Count == 0 - ? "No place, coordinates or area to go to for this stamp." - : "Where: " + Cut(string.Join(" or ", targets), 90)); - if (targets.Count > 0) - { - w.Button("Go (auto nav)", "dy.nav.go", () => SendNav("go", s)); - w.Tooltip("RynthNav plans the route (walking, portals, recalls, the dungeon's entrance) and walks it."); - w.SameLine(); - w.Button("Arrow", "dy.nav.arrow", () => SendNav("arrow", s)); - w.Tooltip("Only point RynthNav's arrow at it."); - w.SameLine(); - } - w.Button("Chat", "dy.nav.chat", () => PrintStamp(s, _dynNavDone)); - w.SameLine(); - w.Button("Close", "dy.nav.close", () => { _dynNav = null; _dynNavStatus = ""; _selKey = ""; _giveConfirm = ""; }); - - // The hand-in: a Parchment from your packs to the stamp's NPC (RynthAi's /ub give). - if (s.Npc.Length > 0) - { - string? parchment = CarriedParchment(); - if (parchment != null) - { - string? why = GiveUnavailableReason(); - if (why == null && _giveConfirm == parchment) - { - // Asked first: the Parchment leaves the pack and doesn't come back. - w.TextColored(UiColors.Red, $"Give one {Cut(parchment, 30)} to {Cut(s.Npc, 30)}? It leaves your pack for good."); - w.SmallButton("Yes, give it", "dy.nav.give.yes", () => { _giveConfirm = ""; GiveParchment(s, parchment); }); - w.SameLine(); - w.SmallButton("Cancel", "dy.nav.give.no", () => _giveConfirm = ""); - } - else if (why == null) - { - w.Button("Give " + Cut(parchment, 24), "dy.nav.give", () => _giveConfirm = parchment); - w.Tooltip($"Hands one {parchment} to {s.Npc} (it asks first). Stand near them (or Go first): AC walks you the last bit."); - } - else - { - // Greyed text in place of the button, so it can't be clicked into a command nobody answers. - w.TextDisabled("[Give " + Cut(parchment, 24) + "]"); - w.Tooltip(why); - } - } - else - w.TextDisabled("No Parchment in your packs to give " + Cut(s.Npc, 30) + "."); - } - if (_dynNavStatus.Length > 0) w.TextDisabled(_dynNavStatus); - } - - // A /myquests read this long after a Parchment hand-in (the walk there and the NPC's answer), so - // the new stamp shows as had; 0 = none due. - private const long HandInRefreshMs = 8000; - private long _dynRefreshAt; - - /// The read after a hand-in, when it is due: now, or when the server's once-a-minute wait ends. - private void RefreshAfterHandIn(QuestFlagStore flags) - { - if (_dynRefreshAt == 0 || _c.NowMs < _dynRefreshAt) return; - if (flags.Loading) return; - int wait = flags.ThrottleSecondsLeft(_c.NowMs); - if (wait > 0) { _dynRefreshAt = _c.NowMs + wait * 1000L; return; } - _dynRefreshAt = 0; - _c.RequestQuests(); - } - - // Packs scanned for a Parchment at most this often (the box draws every frame). - private const long ParchmentScanMs = 1500; - private long _parchmentScanAt; - private string? _parchmentName; - - /// - /// The name of a Parchment you carry (the main pack and its side packs), or null. Any item - /// whose name has "Parchment" in it; read again every . - /// - private string? CarriedParchment() - { - if (_c.ParchmentFinder != null) return _c.ParchmentFinder(); - if (_c.NowMs - _parchmentScanAt < ParchmentScanMs && _parchmentScanAt != 0) return _parchmentName; - _parchmentScanAt = _c.NowMs == 0 ? 1 : _c.NowMs; - _parchmentName = null; - RynthCore.PluginSdk.RynthCoreHost host = _c.Host; // a struct: an empty one (the offline tests) reports nothing carried - uint me = _c.Character.PlayerId; - if (!_c.InWorld || me == 0 || !host.HasGetContainerContents) return null; - var buf = new uint[512]; - var packs = new List { me }; - for (int p = 0; p < packs.Count && p < 16; p++) - { - int n = Math.Min(host.GetContainerContents(packs[p], buf), buf.Length); - for (int i = 0; i < n; i++) - { - uint id = buf[i]; - if (!host.TryGetObjectName(id, out string name)) continue; - if (name.IndexOf("Parchment", StringComparison.OrdinalIgnoreCase) >= 0) { _parchmentName = name; return name; } - // A side pack in the main pack: look inside it too (only one level deep, as AC packs go). - if (p == 0) packs.Add(id); - } - } - return null; - } - - /// Why Give Parchment can't be used now (for its tooltip); null when it can. - private string? GiveUnavailableReason() - { - if (_c.UbGiveMissing) - return "The loaded RynthAi has no \"/ub give\" (it answered \"Unrecognized /ub command\"). Update RynthAi, or hand the Parchment over yourself."; - if (!_c.UbGiveAvailable()) - return "Needs RynthAi: the hand-in is RynthAi's \"/ub give\". It isn't loaded (or you aren't logged in), so give the Parchment to the NPC yourself."; - return null; - } - - /// A name made safe to put inside a chat command: no control characters. - private static string ForCommand(string name) - { - var sb = new System.Text.StringBuilder(name.Length); - foreach (char ch in name) if (ch >= ' ' && ch != '\u007f') sb.Append(ch); - return sb.ToString().Trim(); - } - - /// "/ub give 1 <parchment> to <npc>": RynthAi finds the NPC by name and hands it over. - private void GiveParchment(DynamicStamp s, string parchment) - { - if (!_c.InWorld) { _dynNavStatus = "Log in first."; return; } - string? why = GiveUnavailableReason(); - if (why != null) { _dynNavStatus = why; return; } - _c.UbGiveSentMs = _c.NowMs; // a "Unrecognized /ub command" in the next moments turns the button off - bool sent = _c.RunCommand($"/ub give 1 {ForCommand(parchment)} to {ForCommand(s.Npc)}"); - _parchmentScanAt = 0; // read the packs again after the give - // The stamp is a quest flag: read /myquests again once the NPC has had time to answer. - if (sent) _dynRefreshAt = _c.NowMs + HandInRefreshMs; - _dynNavStatus = sent - ? $"Giving {parchment} to {s.Npc} (RynthAi does the give; it says so in chat if {s.Npc} isn't in sight)." - : "Could not send the give."; - } - - /// Clicking a row: select it and ask RynthNav for the route (shown in chat and its overlay). - private void SelectDynamicStamp(DynamicStamp s, bool done) - { - _dynNav = s; - _dynNavDone = done; - _dynNavStatus = ""; - _giveConfirm = ""; - if (s.NavCandidates().Count > 0) SendNav("route", s); - } - - /// "/rnav <verb> a || b || c" to RynthNav (it takes the first candidate on its map). - private void SendNav(string verb, DynamicStamp s) - { - List targets = s.NavCandidates(); - if (targets.Count == 0) return; - _dynNavStatus = SendRynthNav(verb, targets); - } - - /// - /// "/rnav <verb> a || b || c" to RynthNav (go walks the route, route plans it in chat, arrow - /// points at it; RynthNav takes the first candidate on its map). What to tell the player. - /// Shared by every row kind of the Quests tab. - /// - private string SendRynthNav(string verb, IReadOnlyList targets) - { - if (targets.Count == 0) return ""; - if (!_c.InWorld) return "Log in first."; - bool sent = _c.SendNav(verb + " " + string.Join(" || ", targets)); - return !sent ? "RynthNav isn't loaded (it plans and walks the route)." - : verb == "go" ? "RynthNav is planning the route and walking it (its chat lines say how)." - : verb == "arrow" ? "RynthNav's arrow points at it." - : "RynthNav's route is in chat. Go walks it."; - } - - /// Chat: the NPC, its stamp and whether this character has it, where, the reward and - /// any coordinates (RynthChat makes those a RynthNav arrow link). - private void PrintStamp(DynamicStamp s, bool done) - { - string where = s.Place.Length > 0 ? $"{s.Area}, {s.Place}" : s.Area; - string details = $"{where}" + (s.Reward.Length > 0 ? $" - gives {s.Reward}" : "") + (s.Note.Length > 0 ? $" - {s.Note}" : ""); - PrintEntry(s.Label, s.Stamp, done ? "have" : "missing", details, ""); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/OracleView.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/OracleView.cs index 9f216cc..9b36180 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/OracleView.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/OracleView.cs @@ -13,16 +13,17 @@ internal sealed partial class OracleView TabSkills = "Skills", TabAttributes = "Attributes", TabProgress = "Progress", TabAugs = "Augs", TabSociety = "Society", TabTitles = "Titles", TabVoid = "Void", TabFellowship = "Fellowship", - TabBreeding = "Pet Breeding", TabAbout = "About"; - // The Markers tab (and the Legendary and Dynamic Stamps trackers and RynthILT's Temple guardians) - // are rows of the Quests tab: QuestsTab.cs, ShowTrackers, /ro markers. A saved tab name of the old - // Markers tab falls back to Quests (see Tab). + TabAbout = "About"; + // The Markers tab (and the Legendary tracker) are rows of the Quests tab: QuestsTab.cs, + // ShowTrackers, /ro markers. A saved tab name of an old tab falls back to Quests (see Tab). + // A server's own pages are its server plugin's: Conquest's and Aelrynth's since 2026-10-20, + // Infinite Leaftide's (Pet Breeding, the stamps and guardians) since 2026-10-21. /// - /// A tab: shown where any of its server tags matches the server; no tags = everywhere (retail). - /// Refresh is the page's Refresh button (Views\RefreshBar.cs); Help its tooltip. + /// A tab (every one is shown on every server). Refresh is the page's Refresh button + /// (Views\RefreshBar.cs); Help its tooltip. /// - private sealed record TabDef(string Name, string[] Servers, Action Draw, bool LiveTimers, + private sealed record TabDef(string Name, Action Draw, bool LiveTimers, Func Refresh, Func Help); private readonly OracleContext _c; @@ -35,60 +36,37 @@ internal sealed partial class OracleView public OracleView(OracleContext c) { _c = c; - string[] any = Array.Empty(); _tabs = new TabDef[] { - new(TabQuests, any, DrawQuests, true, () => RefreshQuests(), + new(TabQuests, DrawQuests, true, () => RefreshQuests(), () => "Sends /myquests to the server and reads the reply."), - new(TabCharacter, any, DrawCharacter, true, RefreshCharacter, + new(TabCharacter, DrawCharacter, true, RefreshCharacter, () => "Re-reads your level, experience, buffs and skills from the game now (and RynthAi's session)."), // Skills / Attributes / Progress: RynthCore draws its Skills panel body under the tab // strip (SkillsEmbed). The engine's panel reads the game itself, so there is no Refresh row. - new(TabSkills, any, DrawEmbedded, false, RefreshCharacter, + new(TabSkills, DrawEmbedded, false, RefreshCharacter, () => "RynthCore's skills panel: raise and train skills."), - new(TabAttributes, any, DrawEmbedded, false, RefreshCharacter, + new(TabAttributes, DrawEmbedded, false, RefreshCharacter, () => "RynthCore's skills panel: attributes and vitals."), - new(TabProgress, any, DrawEmbedded, false, RefreshCharacter, - () => "RynthCore's skills panel: progression planners (Infinite Leaftide)."), - new(TabAugs, any, DrawAugs, true, RefreshCharacterAndQuests, + new(TabProgress, DrawEmbedded, false, RefreshCharacter, + () => "RynthCore's skills panel: progression planners (where the server has them)."), + new(TabAugs, DrawAugs, true, RefreshCharacterAndQuests, () => "Re-reads your character from the game and sends /myquests for the gem timers."), - new(TabSociety, any, DrawSociety, true, RefreshCharacterAndQuests, + new(TabSociety, DrawSociety, true, RefreshCharacterAndQuests, () => "Re-reads your society standing from the game and sends /myquests for today's ribbons and quest timers."), - new(TabTitles, any, DrawTitles, false, RefreshTitles, + new(TabTitles, DrawTitles, false, RefreshTitles, () => "Re-reads the titles you hold from the game."), - new(TabVoid, any, DrawVoid, true, RefreshVoid, + new(TabVoid, DrawVoid, true, RefreshVoid, () => "Re-reads your buffs from the game and drops the spell timers that ran out."), - new(TabFellowship, any, DrawFellowship, false, RefreshFellowship, + new(TabFellowship, DrawFellowship, false, RefreshFellowship, () => "Re-reads the fellowship and its members from the game."), - // A server's own pages are its server plugin's since 2026-10-20: Conquest's (bank, augs, - // boards, ...) RynthConquest's, Aelrynth's leaderboards and Trials RynthAelrynth's. - // Infinite Leaftide only, and only while the server has pet breeding (BreedingOffered). - new(TabBreeding, new[] { Data.ServerTags.InfiniteLeaftide }, DrawBreeding, false, RefreshBreeding, - () => "Asks RynthILT to appraise every essence again (charges, rest timers, bond, growth)."), - new(TabAbout, any, DrawAbout, false, RefreshAbout, + new(TabAbout, DrawAbout, false, RefreshAbout, () => "Loads the quest list and server pack from their files again and asks RynthCore which server this is."), }; } - private bool Visible(TabDef t) - { - if (t.Name == TabBreeding && !BreedingOffered()) return false; - if (t.Servers.Length == 0) return true; - foreach (string s in t.Servers) if (_c.Server.Is(s)) return true; - return false; - } - - /// - /// The Pet Breeding tab is offered on an Infinite Leaftide world unless RynthILT's profile says - /// the server has pet breeding switched off (a feature it doesn't know yet counts as on). - /// - internal bool BreedingOffered() - { - if (!_c.Server.Is(Data.ServerTags.InfiniteLeaftide)) return false; - foreach (Data.IltFeature f in _c.Ilt.Profile.Features) - if (f.Key == "pet_breeding") return f.State != RynthCore.Plugin.Shared.RynthIltServer.StateOff; - return true; - } + /// Every tab shows on every server (a server's own pages are its server plugin's). + private static bool Visible(TabDef t) => true; /// The selected tab's name; a tab not available on this server falls back to Quests. public string Tab diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/PetBreedingTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/PetBreedingTab.cs deleted file mode 100644 index 9b67599..0000000 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/PetBreedingTab.cs +++ /dev/null @@ -1,202 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using RynthCore.Plugin.RynthOracle.Ui; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.RynthOracle.Views; - -/// -/// "Pet Breeding" (Infinite Leaftide, and only where the server has pet breeding on): RynthILT's -/// breeding tracker, the same one as RynthAi's Mini Remote Pets > Breeding tab (which stays). RynthILT -/// reads the essences, learns the server's rules and runs the actions; this tab draws its JSON -/// ("RynthILT.Data" GetPetBreedingJson) and sends its verbs back. Dance and supply uses ask here -/// first (RynthILT doesn't ask again). The page's Refresh button is the Refresh row every page has. -/// -internal sealed partial class OracleView -{ - /// Essence rows drawn at most (each is about eight ops; the window's op budget is shared). - private const int BreedingMaxRows = 40; - - /// The breeding verb waiting for Yes / No, with its question ("" = none). - private string _breedConfirmVerb = "", _breedConfirmText = ""; - /// The essence the supplies are used on (index into the essence list). - private int _breedTarget; - - private void DrawBreeding(UiWindow w) - { - IltBreedingView v = _c.Breeding; - w.SeparatorText("Pet Breeding"); - if (!v.Loaded) - { - w.TextDisabled(_c.IltData.Connected && !_c.IltData.PetBreedingSupported - ? "This RynthILT is older than 0.3.1 and has no breeding tracker; update RynthILT." - : "Load RynthILT (0.3.1 or later) to track pet breeding here. Reading..."); - return; - } - - uint col = v.Enabled == "off" ? UiColors.Red : v.Enabled == "on" ? UiColors.Green : UiColors.Yellow; - w.TextColored(col, v.Enabled switch - { - "off" => "Pet breeding is off on this server.", - "on" => $"Pet breeding: on. Breeding room: {v.Room}.", - _ => "Pet breeding: not confirmed yet (Diagnostics in the breeding room checks).", - }); - if (v.Bond == "off") w.TextColored(UiColors.Yellow, "Pet bond is off here, so bond can't reach the breeding minimum."); - - w.SmallButton("Diagnostics", "br.debug", () => _c.BreedingCommand(IltBreedingView.DebugVerb())); - w.Tooltip("@breed-debug: whether you're in the breeding room, your pet, partners nearby."); - w.SameLine(); - w.SmallButton("Dance", "br.dance", () => AskBreeding(IltBreedingView.DanceVerb(), - "Dance now? If your partner dances in time with both pets summoned in the same room, the breed happens.")); - w.Tooltip("@dance: both owners must dance within a few seconds."); - w.SameLine(); - w.SmallButton("Mini Remote", "br.remote", () => _c.RunCommand("/ra hub open breeding")); - w.Tooltip("RynthAi's Mini Remote, Pets > Breeding (the same tracker, with the pair planner)."); - - if (_breedConfirmVerb.Length > 0) - { - w.TextColored(UiColors.Gold, _breedConfirmText); - string verb = _breedConfirmVerb; - w.SmallButton("Yes", "br.yes", () => { _breedConfirmVerb = ""; _c.BreedingCommand(verb); }); - w.SameLine(); - w.SmallButton("No", "br.no", () => _breedConfirmVerb = ""); - } - if (v.Message.Length > 0) w.TextDisabled(v.Message); - else if (_c.BreedingMessage.Length > 0) w.TextDisabled(_c.BreedingMessage); - if (v.FreeSlots == 0) w.TextColored(UiColors.Yellow, "Your main pack is full: as the dam's owner you couldn't receive the baby."); - - DrawBreedEssences(w, v); - DrawBreedPairs(w, v); - DrawBreedSupplies(w, v); - DrawBreedRules(w, v); - DrawBreedEvents(w, v); - } - - /// Holds a verb until the player clicks Yes. - private void AskBreeding(string verb, string question) - { - _breedConfirmVerb = verb; - _breedConfirmText = question; - } - - private void DrawBreedEssences(UiWindow w, IltBreedingView v) - { - int ready = 0; - foreach (IltBreedEssenceRow e in v.Essences) if (e.Ready) ready++; - if (!w.CollapsingHeader($"Essences ({ready} ready of {v.Essences.Count})", "br.ess", defaultOpen: true)) return; - if (v.Essences.Count == 0) { w.TextDisabled("No combat pet essences in your pack."); return; } - for (int i = 0; i < v.Essences.Count && i < BreedingMaxRows; i++) - { - IltBreedEssenceRow e = v.Essences[i]; - w.TextColored(e.Ready ? UiColors.Green : e.Problems.Count > 0 && e.ReadyIn > 0 ? UiColors.Yellow : UiColors.Grey, Cut(e.Status, 22)); - w.SameLine(170f); - w.Text(Cut(e.Name, 32)); - w.Tooltip(BreedTooltip(e)); - w.SameLine(410f); - w.TextDisabled($"{(e.Male ? "M" : "F")} T{(e.Tier > 0 ? e.Tier.ToString(CultureInfo.InvariantCulture) : "?")} B{e.Bond} " - + $"Mut {e.Mutations}{(e.PotencyMutations > 0 ? "+" + e.PotencyMutations + "p" : "")}"); - } - if (v.Essences.Count > BreedingMaxRows) w.TextDisabled($"... and {v.Essences.Count - BreedingMaxRows} more (see the Mini Remote)."); - } - - private static string BreedTooltip(IltBreedEssenceRow e) - { - var lines = new List { $"{e.Name}: {(e.Male ? "stud" : "dam")}, tier {e.Tier}, bond {e.Bond}" }; - if (e.Male) lines.Add($"Charges {e.Charges}/{e.ChargesMax}"); - if (e.Juvenile) lines.Add($"Growing: {e.Stage}, {Math.Max(0, e.KillsRequired - e.Kills)} kills to Adult"); - if (e.Boosters.Count > 0) lines.Add("Boosters: " + string.Join(", ", e.Boosters)); - foreach (string p in e.Problems) lines.Add("- " + p); - return string.Join("\n", lines); - } - - private static void DrawBreedPairs(UiWindow w, IltBreedingView v) - { - if (v.Pairs.Count == 0) return; - if (!w.CollapsingHeader($"Ready pairs ({v.Pairs.Count})", "br.pairs", defaultOpen: true)) return; - w.TextDisabled("Stat mutation odds; fewer inherited mutations keep the odds up. Each owner dances with their own pet."); - for (int i = 0; i < v.Pairs.Count; i++) - { - IltBreedPairRow p = v.Pairs[i]; - w.Text($"{Cut(p.Stud, 26)} x {Cut(p.Dam, 26)}"); - w.SameLine(400f); - w.TextDisabled($"{Pct(p.ChanceWorst)}-{Pct(p.ChanceBest)}, inherits {p.InheritMin}-{p.InheritMax}"); - } - } - - private void DrawBreedSupplies(UiWindow w, IltBreedingView v) - { - long carried = 0; - foreach (IltBreedSupplyRow s in v.Supplies) carried += s.Count; - if (!w.CollapsingHeader($"Supplies ({carried} carried)", "br.sup", defaultOpen: false)) return; - w.TextDisabled("Ivo sells these at the Seedy Motel. Boosters are spent by the essence's next breed."); - - IltBreedEssenceRow? target = null; - if (v.Essences.Count > 0) - { - var names = new List(v.Essences.Count); - foreach (IltBreedEssenceRow e in v.Essences) names.Add(Cut(e.Name, 34)); - int index = Math.Clamp(_breedTarget, 0, v.Essences.Count - 1); - w.Combo("Use on", "br.target", index, names, i => _breedTarget = i); - target = v.Essences[index]; - } - - for (int i = 0; i < v.Supplies.Count; i++) - { - IltBreedSupplyRow s = v.Supplies[i]; - w.TextColored(s.Count > 0 ? UiColors.Green : UiColors.Grey, $"{s.Count,3} {s.Name}"); - w.Tooltip(s.Price > 0 ? $"{s.Effect}\nIvo's price: {Price(s.Price)} pyreals" : s.Effect); - if (!s.Apply || s.Count <= 0 || target == null) continue; - w.SameLine(330f); - if (System.Linq.Enumerable.Contains(s.Targets, target.Id)) - { - string verb = IltBreedingView.ApplyVerb(s.Key, target.Id); - string q = $"Use {s.Name} on {target.Name}? {s.Effect}"; - w.SmallButton("Use", "br.use." + i, () => AskBreeding(verb, q)); - } - else w.TextDisabled("-"); - } - } - - private static void DrawBreedRules(UiWindow w, IltBreedingView v) - { - if (!w.CollapsingHeader("Server rules", "br.rules", defaultOpen: false)) return; - w.TextDisabled("Values this server showed win over the ILT profile, which wins over ACE's defaults."); - foreach (IltBreedRuleRow r in v.Rules) - { - w.Text(r.Label); - if (r.Help.Length > 0) w.Tooltip(r.Help); - w.SameLine(230f); - w.Text(r.Value); - w.SameLine(310f); - w.TextColored(r.Source == "seen on server" ? UiColors.Green : UiColors.Grey, r.Source); - } - if (v.Debug is { } d) - { - w.Separator(); - w.TextDisabled($"Last diagnostics ({d.When} UTC):"); - if (d.Location.Length > 0) w.BulletText("You: " + d.Location); - if (d.Match.Length > 0) w.BulletText(d.Match == "valid" ? "In the breeding room" : "Not in the breeding room"); - if (d.Pet.Length > 0) w.BulletText("Pet: " + d.Pet + (d.Sex.Length > 0 ? " (" + d.Sex + ")" : "")); - if (d.Partners >= 0) w.BulletText($"Partners nearby: {d.Partners}"); - } - } - - private static void DrawBreedEvents(UiWindow w, IltBreedingView v) - { - if (!w.CollapsingHeader($"Recent events ({v.Events.Count})", "br.events", defaultOpen: false)) return; - if (v.Events.Count == 0) w.TextDisabled("Nothing yet: rituals, births, growth and charges land here."); - foreach (IltBreedEventRow e in v.Events) - { - w.TextDisabled(e.When); - w.SameLine(130f); - w.TextWrapped(e.Text); - } - } - - private static string Pct(double v) => (v * 100).ToString("0.#", CultureInfo.InvariantCulture) + "%"; - - private static string Price(long p) => p >= 1_000_000 - ? (p / 1_000_000.0).ToString("0.##", CultureInfo.InvariantCulture) + "M" - : p.ToString("N0", CultureInfo.InvariantCulture); -} diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestsTab.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestsTab.cs index 09bfe76..6ffca9c 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestsTab.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/QuestsTab.cs @@ -2,7 +2,8 @@ // Tracking, kill tasks, rewards and the quest bonus list merged in from RynthAi's Mini Remote // Quests tab and UtilityBelt ILT's quest tracker (2026-10-13). The Legendary, Markers and Dynamic // Stamps tabs and RynthILT's Temple guardians merged in as tracker rows (SilentKelpie's PR 12, -// RynthOracle 0.6.0, ported by hand onto this lineage). +// RynthOracle 0.6.0, ported by hand onto this lineage). The Dynamic Stamps, the Temple guardians and the +// /qb list are one server's (Infinite Leaftide's) and moved to that server's plugin, RynthILT, on 2026-10-21. using System; using System.Collections.Generic; using RynthCore.Plugin.RynthOracle.Data; @@ -12,31 +13,27 @@ using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthOracle.Views; /// -/// What a row of the merged Quests list is. Every kind but Quest is a tracker: Legendary Key quests -/// and exploration markers everywhere, Dynamic Stamps and the Temple guardians on Infinite Leaftide. +/// What a row of the merged Quests list is. Every kind but Quest is a tracker: the Legendary Key +/// quests and the exploration markers (retail, every server). /// -internal enum QuestKind { Quest, Legendary, Marker, Dynamic, Guardian } +internal enum QuestKind { Quest, Legendary, Marker } /// -/// Quests: every flag the character holds, cross-referenced with the master quest list, plus the -/// trackers (Legendary Key quests, exploration markers, Dynamic Stamps, Temple guardians), in one -/// searchable, sortable, paged list. Each kind shows only on the servers it belongs to, and -/// "Trackers only" narrows the list to the trackers with their status above it. The * column tracks -/// a quest in the Quest Timers window (a favourite); clicking a row opens it below the list: a -/// quest's notes and rewards editor, a tracker's details, and RynthNav's Go / Route / Arrow for any -/// coordinates in its notes. A click on a quest or a marker also prints its texts in chat. On -/// Infinite Leaftide the quest bonus list (/qb, read by RynthILT) follows. +/// Quests: every flag the character holds, cross-referenced with the master quest list (and the +/// active server plugin's quest pack), plus the trackers (Legendary Key quests, exploration markers), +/// in one searchable, sortable, paged list. "Trackers only" narrows the list to the trackers with +/// their status above it. The * column tracks a quest in the Quest Timers window (a favourite); +/// clicking a row opens it below the list: a quest's notes and rewards editor, a tracker's details, +/// and RynthNav's Go / Route / Arrow for any coordinates in its notes. A click on a quest or a marker +/// also prints its texts in chat. /// internal sealed partial class OracleView { private const int QuestPageSize = 40; - private const int QbShownMax = 150; // per /qb list on one pass (the rest: narrow with Search) private const float QuestListHeightWithPanel = 300f; private static readonly string[] QuestSorts = { "Flag", "Name", "Done first", "Not done first", "Ready soonest", "Most solves" }; /// The kinds' names in order (the Show filter). - private static readonly string[] KindNames = { "Quests", "Legendary", "Markers", "Dynamic Stamps", "Guardians" }; - /// The guardians' last answer is offered for this long (RynthILT's Mini Remote line does the same). - private const long GuardianAnswerShownSec = 600; + private static readonly string[] KindNames = { "Quests", "Legendary", "Markers" }; // The reward editor's fields, in QuestReward order (two percentages, then counts). private static readonly string[] RewardLabels = @@ -50,13 +47,12 @@ internal sealed partial class OracleView private QuestKind? _qKind; private int _questSort; private int _questPage; - private int _dynArea; // 0 = all areas, else DynamicStampList.Areas[n - 1] (Show: Dynamic Stamps) private readonly List _questRows = new(); private string _questKey = ""; private long _questBuiltMs; - // The row opened below the list: a quest (_questSel), a Dynamic Stamp (_dynNav) or another tracker (_selKey). + // The row opened below the list: a quest (_questSel) or a tracker (_selKey). private QuestKind _selKind; private string _selKey = ""; private string _questSel = ""; @@ -67,10 +63,10 @@ internal sealed partial class OracleView private sealed class QuestRow { public QuestKind Kind; - /// Unique across kinds: the quest flag, or "lg:", "mk:", "dy:", "gd:" and the tracker's own key. + /// Unique across kinds: the quest flag, or "lg:", "mk:" and the tracker's own key. public string Key = ""; public string Label = ""; - /// The tracker's group: a Legendary area, a marker's location, a stamp's area, a guardian's NPC. + /// The tracker's group: a Legendary area or a marker's location. public string Group = ""; /// Its place in its own list (the default order of tracker rows). public int Order; @@ -78,32 +74,18 @@ internal sealed partial class OracleView public Quest? Q; public LegendaryQuest? L; public Marker? M; - public DynamicStamp? D; - public IltGuardianRow? G; } - /// - /// The kinds this server shows: quests, Legendary quests and markers everywhere; Dynamic Stamps - /// and the Temple guardians only on Infinite Leaftide. Internal for the tests. - /// - internal List AvailableKinds() - { - var kinds = new List { QuestKind.Quest, QuestKind.Legendary, QuestKind.Marker }; - if (_c.Server.Is(ServerTags.InfiniteLeaftide)) - { - kinds.Add(QuestKind.Dynamic); - kinds.Add(QuestKind.Guardian); - } - return kinds; - } + /// The kinds the list shows: quests, Legendary quests and markers, on every server. Internal for the tests. + internal List AvailableKinds() => new() { QuestKind.Quest, QuestKind.Legendary, QuestKind.Marker }; /// A kind is listed: this server has it, the Show filter allows it, and Trackers only doesn't hide it. private bool KindListed(QuestKind k, List kinds) => kinds.Contains(k) && (_qKind == null || _qKind == k) && !(_qTrackers && k == QuestKind.Quest); /// - /// Opens the Quests tab on the trackers: one kind (/ro legendary, /ro dynamic, /ro markers, - /// /ro guardians) or all of them (null). The old tabs' commands land here. + /// Opens the Quests tab on the trackers: one kind (/ro legendary, /ro markers) or all of them + /// (null). The old tabs' commands land here. /// public void ShowTrackers(QuestKind? kind) { @@ -116,7 +98,6 @@ internal sealed partial class OracleView private void DrawQuests(UiWindow w) { QuestFlagStore flags = _c.Flags; - RefreshAfterHandIn(flags); if (flags.ServerDisabled) w.TextColored(UiColors.Red, "This server has /myquests turned off, so quest flags can't be read."); else if (flags.Loading) @@ -138,15 +119,14 @@ internal sealed partial class OracleView ? $"{cat.RetailCount} retail quests + {cat.ServerCount} {cat.PackServer} quests" : $"{cat.RetailCount} retail quests"); - // A Show filter left on a kind this server doesn't have (another server's character): all kinds. + // A Show filter left on a kind the list doesn't have: all kinds. List kinds = AvailableKinds(); if (_qKind is QuestKind chosen && !kinds.Contains(chosen)) _qKind = null; - bool ilt = kinds.Contains(QuestKind.Dynamic); w.InputText("Search", "q.search", _questSearch, 64, s => { _questSearch = s; _questPage = 0; }); - w.Tooltip("Words to find in a row: a quest's flag or name; a tracker's NPC, place, area, reward or notes. Also filters the quest bonus list."); + w.Tooltip("Words to find in a row: a quest's flag or name; a tracker's place, area or notes."); w.Checkbox("Done", "q.done", _qDone, v => { _qDone = v; _questPage = 0; }); - w.Tooltip("Done quests; Legendary quests and stamps you have, markers found, guardians on cooldown."); + w.Tooltip("Done quests; Legendary quests you have, markers found."); w.SameLine(); w.Checkbox("Not done", "q.notdone", _qNotDone, v => { _qNotDone = v; _questPage = 0; }); w.SameLine(); @@ -174,9 +154,7 @@ internal sealed partial class OracleView if (v && _qKind == QuestKind.Quest) _qKind = null; _questPage = 0; }); - w.Tooltip("Only the trackers, with their status above the list: Legendary Key quests, exploration markers" - + (ilt ? ", Dynamic Stamps and the Temple guardians." : ".") - + (ilt ? "" : "\nDynamic Stamps and the Temple guardians show on Infinite Leaftide.")); + w.Tooltip("Only the trackers, with their status above the list: Legendary Key quests and exploration markers."); w.SameLine(); var kindItems = new List(kinds.Count + 1) { "Everything" }; foreach (QuestKind k in kinds) kindItems.Add(KindNames[(int)k]); @@ -187,14 +165,7 @@ internal sealed partial class OracleView if (_qKind == QuestKind.Quest) _qTrackers = false; _questPage = 0; }); - w.Tooltip("One kind of row, or everything this server has."); - if (_qKind == QuestKind.Dynamic) - { - w.SameLine(); - var areaItems = new List(DynamicStampList.Areas.Count + 1) { "All areas" }; - areaItems.AddRange(DynamicStampList.Areas); - w.Combo("##dyarea", "dy.area", Math.Clamp(_dynArea, 0, areaItems.Count - 1), areaItems, v => { _dynArea = v; _questPage = 0; }); - } + w.Tooltip("One kind of row, or everything."); w.Combo("Sort", "q.sort", _questSort, QuestSorts, i => { _questSort = Math.Clamp(i, 0, QuestSorts.Length - 1); _questPage = 0; }); if (_qTrackers || _qKind is QuestKind k2 && k2 != QuestKind.Quest) DrawTrackerSummary(w, kinds); @@ -204,12 +175,11 @@ internal sealed partial class OracleView w.SameLine(160f); _questPage = Pager(w, "q.page", _questPage, rows.Count, QuestPageSize, p => _questPage = p); - // A fixed-height list when something follows it (the opened row, the /qb list); else it fills the page. - IltQuestBonusList? qb = ilt && !_qTrackers ? _c.Ilt.Profile.QuestBonus : null; + // A fixed-height list when the opened row follows it; else it fills the page. bool selected = HasSelection(); - w.BeginChild("q.list", 0f, selected || qb != null ? QuestListHeightWithPanel : 0f, border: true); + w.BeginChild("q.list", 0f, selected ? QuestListHeightWithPanel : 0f, border: true); w.TextDisabled("*"); - w.Tooltip("Track: list the quest in the Quest Timers window. Trackers show their kind here instead (LEG, MRK, DYN, GRD)."); + w.Tooltip("Track: list the quest in the Quest Timers window. Trackers show their kind here instead (LEG, MRK)."); w.SameLine(28f); w.TextDisabled("Done"); w.SameLine(72f); @@ -221,7 +191,7 @@ internal sealed partial class OracleView w.SameLine(530f); w.TextDisabled("Rewards"); w.Tooltip("What you recorded for a quest (click it to edit): %XP, %Lum, Coins, Trinkets, Medallions, Yellow/Red/Blue powder, MMDs (D), at Level.\n" - + "Trackers: a Legendary quest's luminance, a marker's location, a stamp's area, a guardian's next turn-in."); + + "Trackers: a Legendary quest's luminance, a marker's location."); DateTime now = _c.UtcNow; bool canTrack = _c.Book.Loaded; @@ -233,7 +203,6 @@ internal sealed partial class OracleView w.EndChild(); if (selected) DrawSelection(w); - if (qb != null) DrawQuestBonus(w, qb); } /// One list row: a quest (track, done, timer, solves, rewards) or a tracker (kind, status, its own columns). @@ -269,13 +238,7 @@ internal sealed partial class OracleView } // A tracker: its kind tag where the * is, then its mark, label and columns. - w.TextColored(UiColors.Gold, r.Kind switch - { - QuestKind.Legendary => "LEG", - QuestKind.Marker => "MRK", - QuestKind.Dynamic => "DYN", - _ => "GRD", - }); + w.TextColored(UiColors.Gold, r.Kind == QuestKind.Legendary ? "LEG" : "MRK"); w.SameLine(28f); TrackerMark(w, r); w.SameLine(72f); @@ -299,22 +262,8 @@ internal sealed partial class OracleView } break; } - case QuestKind.Guardian: - { - IltGuardianRow g = r.G!; - w.SameLine(370f); - w.TextColored(g.Ready ? UiColors.Green : g.Status == "Unknown" ? UiColors.Grey : UiColors.Yellow, Cut(g.Status, 14)); - w.SameLine(470f); - w.Text("#" + g.Count); - if (g.Eta.Length > 0) - { - w.SameLine(530f); - w.TextDisabled(Cut(g.Eta, 18)); - } - break; - } default: - // Markers and stamps: where they are. + // Markers: where they are. if (r.Group.Length > 0) { w.SameLine(530f); @@ -324,42 +273,21 @@ internal sealed partial class OracleView } } - /// A tracker's done column: have / need, found / --, or a guardian's ready / wait. + /// A tracker's done column: have / need (Legendary) or found / -- (markers). private static void TrackerMark(UiWindow w, QuestRow r) { - switch (r.Kind) - { - case QuestKind.Marker: - DoneMark(w, r.Done); - break; - case QuestKind.Guardian: - // Done = turned in and on cooldown; not done = a turn-in is ready (or unknown). - w.TextColored(r.Done ? UiColors.Yellow : UiColors.Green, r.Done ? "wait" : "ready"); - break; - default: - w.TextColored(r.Done ? UiColors.Green : UiColors.Red, r.Done ? "have" : "need"); - break; - } + if (r.Kind == QuestKind.Marker) DoneMark(w, r.Done); + else w.TextColored(r.Done ? UiColors.Green : UiColors.Red, r.Done ? "have" : "need"); } - /// A tracker row's hover text: its notes, hint or where it comes from. + /// A tracker row's hover text: its notes or hint. private static string TrackerTooltip(QuestRow r) => r.Kind switch { QuestKind.Legendary => r.L!.Note.Length > 0 ? $"{r.Group}: {r.L.Note}" : r.Group, QuestKind.Marker => r.M!.Hint, - QuestKind.Dynamic => string.Join(" - ", Parts(r.D!.Area, r.D.Place, r.D.Reward.Length > 0 ? "gives " + r.D.Reward : "", r.D.Note)), - QuestKind.Guardian => $"{r.G!.Npc}: {(r.G.Exact ? "from /myquests (exact)" : "from /qb wait stamps (count and timer are estimates)")}", _ => "", }; - /// The non-empty strings, in order. - private static List Parts(params string[] items) - { - var list = new List(items.Length); - foreach (string s in items) if (!string.IsNullOrWhiteSpace(s)) list.Add(s); - return list; - } - /// The timer column: "ready" (green once done), a countdown, "N left" (yellow) or done (grey). private static void TimerText(UiWindow w, Quest q, QuestFlagStore flags, DateTime now, bool done) { @@ -377,8 +305,7 @@ internal sealed partial class OracleView /// /// The trackers' status (what each old tab showed at its top), for the kinds the Show filter - /// lists: John's Legendary counter, markers found and the next one, stamps had, and the Temple - /// guardians' switches, last answer and hand-in. + /// lists: John's Legendary counter, and the markers found and the next one. /// private void DrawTrackerSummary(UiWindow w, List kinds) { @@ -426,69 +353,6 @@ internal sealed partial class OracleView w.Tooltip("Opens it below the list (directions, RynthNav) and prints the directions in chat."); } } - - if (Shows(QuestKind.Dynamic)) - { - List all = DynamicStampList.All; - int have = 0; - foreach (DynamicStamp s in all) if (s.Have(flags)) have++; - int unlisted = DynamicStampList.Unlisted(flags).Count; - w.ProgressBar(all.Count == 0 ? 0f : (float)have / all.Count, -1f, 0f, - $"{have} / {all.Count} listed Dynamic stamps" + (unlisted > 0 ? $" (+{unlisted} not in the list)" : "")); - w.Tooltip("Dynamic stamps are one-time quest flags (Dynamic_1_...) from handing items to NPCs on Infinite Leaftide.\n" - + "List: the players' ExtraDyn sheet. Click a stamp for RynthNav's route to it and the Parchment hand-in." - + (unlisted > 0 ? "\nStamps not in the sheet show as quests with Not in list." : "")); - } - - if (Shows(QuestKind.Guardian)) DrawGuardianControls(w); - } - - /// - /// The Temple guardians' controls (RynthILT's Guardian window): chat detection, auto hand-in and - /// buy-if-missing, which run inside RynthILT; the last answer with Hand in / Stop; and a refresh. - /// - private void DrawGuardianControls(UiWindow w) - { - IltGuardianView g = _c.Guardian; - if (!g.Loaded) - { - w.TextDisabled(_c.IltData.Connected - ? "Temple guardians: this RynthILT is older than 0.3.3 (no guardian data for Oracle)." - : "Temple guardians: RynthILT isn't loaded (it runs the riddles, hand-ins and turn-in tracker)."); - return; - } - int ready = 0; - foreach (IltGuardianRow r in g.Rows) if (r.Ready) ready++; - w.TextColored(UiColors.Gold, "Temple guardians"); - w.SameLine(); - w.TextDisabled($"{ready} of {g.Rows.Count} attribute turn-ins ready" - + (g.SyncedUtc == DateTime.MinValue ? ", /qb not read this session" : $", /qb read {g.SyncedUtc.ToLocalTime():HH:mm}")); - w.SameLine(); - w.SmallButton("Refresh", "gd.refresh", () => _c.GuardianCommand(IltGuardianView.RefreshVerb())); - w.Tooltip("RynthILT re-reads /myquests and /qb list for the turn-ins (the server allows each once a minute)."); - - w.Checkbox("Detect from chat", "gd.chat", g.Chat, v => _c.GuardianCommand(IltGuardianView.SwitchVerb("chat", v))); - w.Tooltip("Translate the guardians' tells as they arrive and show the answer here."); - w.SameLine(); - w.Checkbox("Auto hand-in", "gd.auto", g.Auto, v => _c.GuardianCommand(IltGuardianView.SwitchVerb("auto", v))); - w.Tooltip("After a chat answer, RynthILT gives one of the item to the guardian automatically."); - w.SameLine(); - w.Checkbox("Buy if missing", "gd.buy", g.Buy, v => _c.GuardianCommand(IltGuardianView.SwitchVerb("buy", v))); - w.Tooltip("Temple guardian: when you carry none, RynthILT buys one from the open or nearest vendor first."); - - bool recent = g.Answer.Length > 0 && g.AnswerAgeSec >= 0 && g.AnswerAgeSec < GuardianAnswerShownSec; - if (recent || g.Running) - { - w.TextColored(UiColors.Green, g.Answer); - if (g.Heard.Length > 0) w.Tooltip("Heard: " + Cut(g.Heard, 300)); - w.SameLine(); - w.TextDisabled("-> " + g.Npc); - w.SameLine(); - if (g.Running) w.SmallButton("Stop", "gd.stop", () => _c.GuardianCommand(IltGuardianView.StopVerb())); - else w.SmallButton("Hand in", "gd.handin", () => _c.GuardianCommand(IltGuardianView.HandInVerb())); - } - else w.TextDisabled("No guardian answer yet."); - w.TextDisabled("Hand-in: " + g.Status + (_c.GuardianMessage.Length > 0 ? " - " + _c.GuardianMessage : "")); } // ── The opened row ────────────────────────────────────────────────────── @@ -497,22 +361,19 @@ internal sealed partial class OracleView private bool HasSelection() => _selKind switch { QuestKind.Quest => _questSel.Length > 0, - QuestKind.Dynamic => _dynNav != null, _ => _selKey.Length > 0, }; private bool IsSelected(QuestRow r) => r.Kind switch { QuestKind.Quest => _selKind == QuestKind.Quest && r.Q!.Flag == _questSel, - QuestKind.Dynamic => _selKind == QuestKind.Dynamic && ReferenceEquals(r.D, _dynNav), _ => _selKind == r.Kind && _selKey == r.Key, }; /// /// Clicking a row opens it below the list (a second click closes it). As before, a click on a /// quest prints its texts in chat (the info and hint, the wiki link and the flag's history) and - /// a click on a marker prints its directions. A Dynamic Stamp also asks RynthNav for the route - /// at once, as its tab did. + /// a click on a marker prints its directions. /// private void SelectRow(QuestRow r) { @@ -521,7 +382,6 @@ internal sealed partial class OracleView bool same = IsSelected(r); _questSel = ""; - _dynNav = null; _selKey = ""; _questStopIdx = 0; _questNavStatus = ""; @@ -532,10 +392,6 @@ internal sealed partial class OracleView case QuestKind.Quest: OpenQuest(r.Q!); break; - case QuestKind.Dynamic: - _selKey = r.Key; - SelectDynamicStamp(r.D!, r.Done); - break; default: _selKey = r.Key; break; @@ -550,7 +406,7 @@ internal sealed partial class OracleView LoadRewardEdit(q.Flag); } - /// The opened row's panel: a quest, a Dynamic Stamp's nav box, a Legendary quest, a marker or a guardian. + /// The opened row's panel: a quest, a Legendary quest or a marker. private void DrawSelection(UiWindow w) { switch (_selKind) @@ -558,9 +414,6 @@ internal sealed partial class OracleView case QuestKind.Quest: DrawSelectedQuest(w); break; - case QuestKind.Dynamic: - DrawDynamicNavBox(w); - break; case QuestKind.Legendary: LegendaryQuest? l = LegendaryList.All.Find(x => "lg:" + x.Name == _selKey); if (l != null) DrawSelectedLegendary(w, l); @@ -569,12 +422,6 @@ internal sealed partial class OracleView Marker? m = MarkerList.All.Find(x => "mk:" + x.Number == _selKey); if (m != null) DrawSelectedMarker(w, m); break; - case QuestKind.Guardian: - IltGuardianRow? g = null; - foreach (IltGuardianRow r in _c.Guardian.Rows) - if ("gd:" + r.Attribute == _selKey) { g = r; break; } - DrawSelectedGuardian(w, g); - break; } } @@ -628,32 +475,6 @@ internal sealed partial class OracleView w.Button("Close", "m.sel.close", () => _selKey = ""); } - private void DrawSelectedGuardian(UiWindow w, IltGuardianRow? g) - { - if (g != null) - { - w.SeparatorText("Temple guardian: " + g.Attribute); - w.TextDisabled("NPC"); - w.SameLine(90f); - w.Text(g.Npc); - w.TextDisabled("Turn-ins"); - w.SameLine(90f); - w.Text(g.Count.ToString()); - w.TextDisabled("Status"); - w.SameLine(90f); - w.TextColored(g.Ready ? UiColors.Green : g.Status == "Unknown" ? UiColors.Grey : UiColors.Yellow, g.Status); - if (g.Eta.Length > 0) - { - w.SameLine(260f); - w.TextDisabled("Next: " + g.Eta); - } - w.TextDisabled(g.Exact ? "From /myquests (exact)." : $"From /qb wait stamps: the count and timer are estimates (cooldown taken as {_c.Guardian.CooldownHours} h)."); - } - else w.SeparatorText("Temple guardians"); - DrawGuardianControls(w); - w.Button("Close", "gd.sel.close", () => _selKey = ""); - } - // ── Go to: the coordinates in the opened row's text, through RynthNav ── private string _questStopsFor = ""; @@ -674,7 +495,7 @@ internal sealed partial class OracleView /// /// Go to: one place is shown with Go / Route / Arrow; several get a picker first (picking one - /// plans its route, as clicking a Dynamic Stamp does). Nothing without any. + /// plans its route). Nothing without any. /// private void DrawGoTo(UiWindow w, List stops) { @@ -706,6 +527,22 @@ internal sealed partial class OracleView if (_questNavStatus.Length > 0) w.TextDisabled(_questNavStatus); } + /// + /// "/rnav <verb> a || b || c" to RynthNav (go walks the route, route plans it in chat, arrow + /// points at it; RynthNav takes the first candidate on its map). What to tell the player. + /// Shared by every row kind of the Quests tab. + /// + private string SendRynthNav(string verb, IReadOnlyList targets) + { + if (targets.Count == 0) return ""; + if (!_c.InWorld) return "Log in first."; + bool sent = _c.SendNav(verb + " " + string.Join(" || ", targets)); + return !sent ? "RynthNav isn't loaded (it plans and walks the route)." + : verb == "go" ? "RynthNav is planning the route and walking it (its chat lines say how)." + : verb == "arrow" ? "RynthNav's arrow points at it." + : "RynthNav's route is in chat. Go walks it."; + } + // ── The opened quest and its rewards ────────────────────────────────── /// Fills the editor from what is recorded (blank fields for zero). @@ -810,42 +647,6 @@ internal sealed partial class OracleView _rewardMsg = r.IsEmpty ? "Cleared." : "Saved: " + r.ShortSummary(); } - // ── Quest bonus (/qb, Infinite Leaftide through RynthILT) ────────────── - - private void DrawQuestBonus(UiWindow w, IltQuestBonusList qb) - { - string count = qb.Count >= 0 ? $" - count {TimeText.Number(qb.Count)}" : ""; - if (!w.CollapsingHeader($"Quest bonus (/qb){count}", "q.qb")) return; - if (qb.Disabled) - { - w.TextDisabled("/qb is turned off on this server."); - return; - } - w.Button("Load /qb list", "q.qb.load", () => - { - if (!_c.Send("/ilt qb")) _c.Print("Log in first."); - }); - w.Tooltip("RynthILT asks the server for your quest bonus list (the server allows once a minute)."); - w.SameLine(); - w.TextDisabled(qb.Generation == 0 && qb.Status == "not loaded" ? "Not loaded yet this session." : qb.Status); - - string[] terms = _questSearch.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - QbList(w, "Incomplete", "q.qb.todo", qb.Incomplete, terms, UiColors.Yellow); - QbList(w, "Completed", "q.qb.done", qb.Completed, terms, UiColors.Green); - } - - private static void QbList(UiWindow w, string label, string id, IReadOnlyList items, string[] terms, uint color) - { - var shown = new List(); - foreach (string s in items) - if (MatchesAll(s, terms)) shown.Add(s); - string counts = terms.Length > 0 ? $"{shown.Count} of {items.Count}" : items.Count.ToString(); - if (!w.CollapsingHeader($"{label} ({counts})", id)) return; - for (int i = 0; i < shown.Count && i < QbShownMax; i++) w.TextColored(color, shown[i]); - if (shown.Count > QbShownMax) w.TextDisabled($"... and {shown.Count - QbShownMax} more. Narrow them with Search."); - if (shown.Count == 0) w.TextDisabled(items.Count == 0 ? "None." : "None match the search."); - } - /// Every search word is in (any case); no words = everything matches. private static bool MatchesAll(string hay, string[] terms) { @@ -863,8 +664,8 @@ internal sealed partial class OracleView private List QuestRows(List kinds) { string key = $"{_questSearch}|{_qDone}{_qNotDone}{_qRepeatable}{_qOneTime}{_qNew}{_qServer}{_qTracked}{_qKill}|{_questSort}" - + $"|{_qTrackers}|{_qKind}|{_dynArea}|{string.Join(",", kinds)}" - + $"|{_c.Flags.Revision}|{_c.Catalog.Revision}|{(_qTracked ? _c.Book.Revision : 0)}|{_c.GuardianRevision}"; + + $"|{_qTrackers}|{_qKind}|{string.Join(",", kinds)}" + + $"|{_c.Flags.Revision}|{_c.Catalog.Revision}|{(_qTracked ? _c.Book.Revision : 0)}"; bool timeSorted = _questSort == 4; if (key == _questKey && (!timeSorted || _c.NowMs - _questBuiltMs < 5000)) return _questRows; _questKey = key; @@ -874,17 +675,10 @@ internal sealed partial class OracleView string[] terms = _questSearch.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); _questRows.Clear(); - // The Dynamic stamps the list matched: shown as stamp rows, not again as unknown quest flags. - var stampFlags = new HashSet(StringComparer.OrdinalIgnoreCase); - if (kinds.Contains(QuestKind.Dynamic)) - foreach (DynamicStamp s in DynamicStampList.All) - if (s.MatchedFlag(flags) is string f) stampFlags.Add(f); - if (KindListed(QuestKind.Quest, kinds)) { foreach (Quest q in _c.Catalog.Quests) { - if (q.IsNew && stampFlags.Contains(q.Flag)) continue; if (_qNew && !q.IsNew) continue; if (_qServer && q.Server.Length == 0) continue; if (_qTracked && !_c.Book.IsTracked(q.Flag)) continue; @@ -915,23 +709,6 @@ internal sealed partial class OracleView QuestRow r = MarkerRow(MarkerList.All[i], flags, i); if (KeepTracker(r, repeatable: false, tracked: false, $"{r.Label} {r.M!.Location} {r.M.Hint}", terms)) _questRows.Add(r); } - - if (KindListed(QuestKind.Dynamic, kinds)) - for (int i = 0; i < DynamicStampList.All.Count; i++) - { - DynamicStamp s = DynamicStampList.All[i]; - if (_dynArea > 0 && (_dynArea > DynamicStampList.Areas.Count || DynamicStampList.Areas[_dynArea - 1] != s.Area)) continue; - var r = new QuestRow { Kind = QuestKind.Dynamic, Key = "dy:" + s.Stamp, Label = s.Label, Group = s.Area, Order = i, Done = s.Have(flags), D = s }; - if (KeepTracker(r, repeatable: false, tracked: false, $"{s.Npc} {s.Place} {s.Reward} {s.Area} {s.Stamp} {s.Note}", terms)) _questRows.Add(r); - } - - if (KindListed(QuestKind.Guardian, kinds)) - for (int i = 0; i < _c.Guardian.Rows.Count; i++) - { - IltGuardianRow g = _c.Guardian.Rows[i]; - var r = new QuestRow { Kind = QuestKind.Guardian, Key = "gd:" + g.Attribute, Label = g.Attribute + " (" + g.Npc + ")", Group = g.Npc, Order = i, Done = !g.Ready, G = g }; - if (KeepTracker(r, repeatable: true, tracked: false, $"{g.Attribute} {g.Npc} {g.Status}", terms)) _questRows.Add(r); - } } DateTime now = _c.UtcNow; @@ -980,7 +757,7 @@ internal sealed partial class OracleView return MatchesAll(hay, terms); } - /// Ready soonest: held repeatable quests and Legendary quests by time left, ready guardians first; the rest after. + /// Ready soonest: held repeatable quests and Legendary quests by time left; the rest after. private static double RowReadyKey(QuestRow r, QuestFlagStore flags, DateTime now) { switch (r.Kind) @@ -990,20 +767,13 @@ internal sealed partial class OracleView case QuestKind.Legendary: TimeSpan? left = r.L!.TimeLeft(flags, now); return left == null ? double.MaxValue : Math.Max(0, left.Value.TotalSeconds); - case QuestKind.Guardian: - return r.G!.Ready ? 0 : double.MaxValue; default: return double.MaxValue; } } - /// Most solves: a repeatable quest's solves, a guardian's turn-ins. - private static int RowSolves(QuestRow r, QuestFlagStore flags) => r.Kind switch - { - QuestKind.Quest => Solves(r.Q!, flags), - QuestKind.Guardian => r.G!.Count, - _ => 0, - }; + /// Most solves: a repeatable quest's solves. + private static int RowSolves(QuestRow r, QuestFlagStore flags) => r.Kind == QuestKind.Quest ? Solves(r.Q!, flags) : 0; /// Held repeatables by time left (ready ones first); everything else after them. private static double ReadyKey(Quest q, QuestFlagStore flags, DateTime now) => diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Views/RefreshBar.cs b/Plugins/RynthCore.Plugin.RynthOracle/Views/RefreshBar.cs index f7ef119..335690d 100644 --- a/Plugins/RynthCore.Plugin.RynthOracle/Views/RefreshBar.cs +++ b/Plugins/RynthCore.Plugin.RynthOracle/Views/RefreshBar.cs @@ -124,16 +124,6 @@ internal sealed partial class OracleView return new RefreshResult("Re-read your buffs and dropped the spell timers that ran out. Timers on targets are learned from your casts."); } - /// The Pet Breeding tab: RynthILT appraises every essence again; the line waits for the new snapshot. - private RefreshResult RefreshBreeding() - { - if (CoolingDown("breeding")) return new RefreshResult(TooSoon); - object before = _c.Breeding; - if (!_c.BreedingCommand(RynthCore.Plugin.Shared.IltBreedingView.RefreshVerb())) - return new RefreshResult("RynthILT didn't take that (not loaded, or older than 0.3.1)."); - return new RefreshResult("Asked RynthILT to appraise your essences again.", () => !ReferenceEquals(_c.Breeding, before)); - } - private RefreshResult RefreshFellowship() { _c.Fellowship.Invalidate(); diff --git a/Plugins/RynthCore.Plugin.RynthPortalStorm/RynthCore.Plugin.RynthPortalStorm.csproj b/Plugins/RynthCore.Plugin.RynthPortalStorm/RynthCore.Plugin.RynthPortalStorm.csproj deleted file mode 100644 index e4e0182..0000000 --- a/Plugins/RynthCore.Plugin.RynthPortalStorm/RynthCore.Plugin.RynthPortalStorm.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - - RynthCore.Plugin.RynthPortalStorm - 0.1.0 - portalstorm - PortalStorm - ac.portalstorm.us.com - PortalStorm|Portal Storm - PortalStorm only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthPortalStorm/ServerData.cs b/Plugins/RynthCore.Plugin.RynthPortalStorm/ServerData.cs deleted file mode 100644 index 164b6ce..0000000 --- a/Plugins/RynthCore.Plugin.RynthPortalStorm/ServerData.cs +++ /dev/null @@ -1,26 +0,0 @@ -// ServerData.cs - What is known about PortalStorm (RynthPortalStorm). Identity (id, hosts, world names) is in the csproj. -namespace RynthCore.Plugin.ServerPack; - -internal static class ServerData -{ - public static ServerPackInfo Create() => - new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) - { - // Not the usual 9000. - Port = 9020, - Emulator = "ACE", - Ruleset = "PvE", - Status = "Stable", - Summary = "15 Tiers, 10 Enlightenments, Infinite Lum Augs, Optional Hard Mode, Custom Skills, Years of custom content.", - Facts = new[] - { - "15 loot tiers.", - "10 enlightenments and infinite luminance augmentations.", - "Optional hard mode.", - "Custom skills and years of custom content.", - "Connects on port 9020, not 9000.", - }, - Discord = "https://discord.gg/YeX6mupcf", - Source = "public AC server list (acresources/serverslist), checked 2026-10-13", - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthReefcull/RynthCore.Plugin.RynthReefcull.csproj b/Plugins/RynthCore.Plugin.RynthReefcull/RynthCore.Plugin.RynthReefcull.csproj deleted file mode 100644 index 0c7e1ef..0000000 --- a/Plugins/RynthCore.Plugin.RynthReefcull/RynthCore.Plugin.RynthReefcull.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - - RynthCore.Plugin.RynthReefcull - 0.1.0 - reefcull - Reefcull - reefcull.gdleac.com - Reefcull - Reefcull only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthReefcull/ServerData.cs b/Plugins/RynthCore.Plugin.RynthReefcull/ServerData.cs deleted file mode 100644 index 16ad01a..0000000 --- a/Plugins/RynthCore.Plugin.RynthReefcull/ServerData.cs +++ /dev/null @@ -1,21 +0,0 @@ -// ServerData.cs - What is known about Reefcull (RynthReefcull). Identity (id, hosts, world names) is in the csproj. -namespace RynthCore.Plugin.ServerPack; - -internal static class ServerData -{ - public static ServerPackInfo Create() => - new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) - { - Port = 9000, - Emulator = "GDLE", - Ruleset = "PvE", - Status = "Stable", - Summary = "A PVE Server thats goal is to mimic end of game retail.", - Facts = new[] - { - "End-of-retail experience on GDLE (not ACE): set the launcher's emulator to Gdle.", - }, - Discord = "https://discord.gg/3ngsm6e", - Source = "public AC server list (acresources/serverslist), checked 2026-10-13", - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthSundering/RynthCore.Plugin.RynthSundering.csproj b/Plugins/RynthCore.Plugin.RynthSundering/RynthCore.Plugin.RynthSundering.csproj deleted file mode 100644 index e6a833d..0000000 --- a/Plugins/RynthCore.Plugin.RynthSundering/RynthCore.Plugin.RynthSundering.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - - RynthCore.Plugin.RynthSundering - 0.1.0 - sundering - Sundering - ace.sunderingac.com - Sundering|The Sundering - Sundering only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthSundering/ServerData.cs b/Plugins/RynthCore.Plugin.RynthSundering/ServerData.cs deleted file mode 100644 index 4396287..0000000 --- a/Plugins/RynthCore.Plugin.RynthSundering/ServerData.cs +++ /dev/null @@ -1,25 +0,0 @@ -// ServerData.cs - What is known about Sundering (RynthSundering). Identity (id, hosts, world names) is in the csproj. -namespace RynthCore.Plugin.ServerPack; - -internal static class ServerData -{ - public static ServerPackInfo Create() => - new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) - { - Port = 9000, - Emulator = "ACE", - Ruleset = "PvE", - Status = "Stable", - Summary = "The Sundering is a 3 active character limit, PVE server targeting an End of Retail feel with convenience " + - "modifications, custom content, and pre-planned weekend/weekday bonuses.", - Facts = new[] - { - "End-of-retail feel with convenience changes and custom content.", - "Planned weekend and weekday bonuses.", - }, - AccountLimit = "3 active characters", - Discord = "https://discord.gg/XgHpcVbmJA", - Website = "https://sunderingac.com", - Source = "public AC server list (acresources/serverslist), checked 2026-10-13", - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthThistlecrown/RynthCore.Plugin.RynthThistlecrown.csproj b/Plugins/RynthCore.Plugin.RynthThistlecrown/RynthCore.Plugin.RynthThistlecrown.csproj deleted file mode 100644 index 1bbcd5f..0000000 --- a/Plugins/RynthCore.Plugin.RynthThistlecrown/RynthCore.Plugin.RynthThistlecrown.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - - RynthCore.Plugin.RynthThistlecrown - 0.1.0 - thistlecrown - Thistlecrown - thistlecrown.ddns.net - Thistlecrown - Thistlecrown only: the server card (rules, account limits, botting policy, links, account setup) in the Mini Remote. - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthThistlecrown/ServerData.cs b/Plugins/RynthCore.Plugin.RynthThistlecrown/ServerData.cs deleted file mode 100644 index 13a10f7..0000000 --- a/Plugins/RynthCore.Plugin.RynthThistlecrown/ServerData.cs +++ /dev/null @@ -1,19 +0,0 @@ -// ServerData.cs - What is known about Thistlecrown (RynthThistlecrown). Identity (id, hosts, world names) is in the csproj. -namespace RynthCore.Plugin.ServerPack; - -internal static class ServerData -{ - public static ServerPackInfo Create() => - new(RynthPluginInfo.ServerId, RynthPluginInfo.ServerName, RynthPluginInfo.ServerHosts, RynthPluginInfo.ServerWorldNames) - { - Port = 9000, - Emulator = "ACE", - Ruleset = "PvE", - Status = "Stable", - Summary = "Everyone welcome! 3 account limit. Recreation of TD.", - Facts = new[] { "A recreation of the retail Thistledown (TD) server." }, - AccountLimit = "3 accounts", - Discord = "https://discord.gg/uhZ3hn7", - Source = "public AC server list (acresources/serverslist), checked 2026-10-13", - }; -} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthThreads/PluginExports.cs deleted file mode 100644 index 44f0fc7..0000000 --- a/Plugins/RynthCore.Plugin.RynthThreads/PluginExports.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using RynthCore.PluginCore; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.RynthThreads; - -/// -/// C ABI exports. Nothing may throw out of an [UnmanagedCallersOnly] method (it would take -/// acclient.exe down): every export goes through RynthPluginRuntime, which catches and logs. -/// The window goes through the engine's script windows (host calls from the plugin's own tick), -/// so there is no render callback. -/// -public static unsafe class PluginExports -{ - private static readonly RynthPluginRuntime Runtime = new(); - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })] - private static int Init(RynthCoreApiNative* api) => Runtime.Init(api); - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void Shutdown() => Runtime.Shutdown(); - - // UTF-8 literals live in the module's read-only data: nothing to allocate or free. - [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetName() => LiteralPointer("RynthThreads"u8); - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetVersion() => LiteralPointer("0.1.0"u8); - - private static IntPtr LiteralPointer(ReadOnlySpan literal) - { - fixed (byte* p = literal) - return (IntPtr)p; - } - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void Tick() => Runtime.OnTick(); - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void OnLoginComplete() => Runtime.OnLoginComplete(); - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void OnLogout() => Runtime.OnLogout(); - - // The Fragment Press lines (read only; nothing is eaten). - [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) - => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag); - - // "/rthreads ..." commands. - [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag); -} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/RynthCore.Plugin.RynthThreads.csproj b/Plugins/RynthCore.Plugin.RynthThreads/RynthCore.Plugin.RynthThreads.csproj deleted file mode 100644 index 27c9213..0000000 --- a/Plugins/RynthCore.Plugin.RynthThreads/RynthCore.Plugin.RynthThreads.csproj +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - net10.0-windows - x86 - win-x86 - Library - true - enable - true - Shared - true - Size - false - RynthCore.Plugin.RynthThreads - RynthCore.Plugin.RynthThreads - x86 - - 66 - DreamWeave only: records Fragment Press results and shows the odds of each modifier per component. - - - - - - - - diff --git a/Plugins/RynthCore.Plugin.RynthThreads/RynthThreadsPlugin.cs b/Plugins/RynthCore.Plugin.RynthThreads/RynthThreadsPlugin.cs deleted file mode 100644 index 12ae818..0000000 --- a/Plugins/RynthCore.Plugin.RynthThreads/RynthThreadsPlugin.cs +++ /dev/null @@ -1,334 +0,0 @@ -// RynthThreadsPlugin.cs - DreamWeave's "Threads" gem crafting: records every Fragment Press result -// from chat and shows the odds of each modifier with each component (DreamWeave components give a -// chance of each modifier, not a fixed one). -// -// Active only on DreamWeave (the world name contains "DreamWeave"); anywhere else it reads nothing, -// shows no window and only answers /rthreads to say so. Presses go to one file shared by every -// character and client on the PC (Threads/PressStore.cs); the window shows what the inference -// (Threads/PressInference.cs) makes of all of them. -// -// Threads: OnTick, OnChatWindowText and login/logout run on the plugin pump. OnChatBarEnter may run -// on AC's main thread, so it only queues the command. -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text; -using RynthCore.Plugin.RynthThreads.Threads; -using RynthCore.Plugin.RynthThreads.Ui; -using RynthCore.Plugin.RynthThreads.Views; -using RynthCore.PluginCore; - -namespace RynthCore.Plugin.RynthThreads; - -public sealed class RynthThreadsPlugin : RynthPluginBase -{ - public const string Version = "0.1.0"; - private const string Command = "/rthreads"; - private const long IdentityRetryMs = 1_000; - /// Wait this long after login for the character's name before recording without it. - private const long NameWaitMs = 30_000; - /// How often the shared file is checked for other clients' presses. - private const long PollMs = 2_000; - private const long PassIntervalMs = 5_000; - - private readonly PressParser _parser = new(); - private readonly UiHost _ui = new(); - private readonly ConcurrentQueue _commands = new(); - private PressStore? _store; - private UiWindow? _window; - private ThreadsPanel? _panel; - private ThreadsReport? _report; - private int _reportVersion = -1; - - private bool _inWorld; - private bool _checked; // the world is known (DreamWeave or not) - private bool _active; // on DreamWeave: reading chat, showing the window - private long _loginAtMs; - private long _nextIdentityTryMs; - private long _nextPollMs; - private string _world = string.Empty; - private string _character = string.Empty; - private bool _noUiLogged; - - public override int Initialize() - { - _ui.Log = msg => Host.Log(msg); - _panel = new ThreadsPanel - { - Report = CurrentReport, - Presses = () => _store?.Presses ?? (IReadOnlyList)Array.Empty(), - Export = Export, - Notice = Notice, - }; - _window = _ui.Add(new UiWindow("RynthThreads/Main", "RynthThreads") - { - DefaultWidth = 440f, DefaultHeight = 480f, MinWidth = 320f, MinHeight = 220f, - }); - Host.Log($"[RynthThreads] {Version} initialized (DreamWeave only). {Command} shows or hides the window; {Command} stats|export."); - return 0; - } - - /// True for DreamWeave's world name (any case, any decoration around it). - internal static bool IsDreamWeave(string? world) => - !string.IsNullOrEmpty(world) && world.IndexOf("DreamWeave", StringComparison.OrdinalIgnoreCase) >= 0; - - // The engine calls this on a real login and on a freshly (re)loaded plugin already in game. - public override void OnLoginComplete() - { - _inWorld = true; - _checked = false; - _active = false; - _character = string.Empty; - _loginAtMs = Environment.TickCount64; - _nextIdentityTryMs = _loginAtMs; - } - - public override void OnLogout() - { - SaveFinished(_parser.Flush("logout")); - _inWorld = false; - _checked = false; - _active = false; - if (_window != null) { _window.Visible = false; _window.NeedsPass = true; } - _ui.SubmitEmpty(Host); - } - - // Plugin unload (hot reload, update, client closing): keep a half-read press. - public override void Shutdown() - { - SaveFinished(_parser.Flush("logout")); - _store?.FlushPending(); - _ui.SubmitEmpty(Host); - } - - public override void OnChatWindowText(string? text, int chatType, ref int eat) - { - if (!_active || string.IsNullOrEmpty(text)) return; - List? done = _parser.Feed(text, Environment.TickCount64); - if (done == null) return; - foreach (Press p in done) SaveFinished(p); - } - - // May run on AC's thread: classify and queue only. - public override void OnChatBarEnter(string? text, ref int eat) - { - if (string.IsNullOrWhiteSpace(text)) return; - string t = text.Trim(); - if (!t.StartsWith(Command, StringComparison.OrdinalIgnoreCase) - || (t.Length > Command.Length && !char.IsWhiteSpace(t[Command.Length]))) - return; - eat = 1; - _commands.Enqueue(t.Substring(Command.Length).Trim()); - } - - public override void OnTick() - { - long now = Environment.TickCount64; - while (_commands.TryDequeue(out string? cmd)) RunCommand(cmd); - if (_inWorld && !_checked && now >= _nextIdentityTryMs) TryIdentify(now); - if (!_active || _store == null) return; - - SaveFinished(_parser.Tick(now)); - if (now >= _nextPollMs) - { - _nextPollMs = now + PollMs; - _store.FlushPending(); - if (_store.Poll() > 0 && _window != null) _window.NeedsPass = true; - } - - if (!Host.HasUi || _window == null || _panel == null) return; - _ui.Poll(Host); - Record(_window, now); - _ui.Submit(Host, now); - } - - /// Learns the world (and the character's name) after login; starts on DreamWeave. - private void TryIdentify(long now) - { - _nextIdentityTryMs = now + IdentityRetryMs; - if (!Host.HasGetWorldName || !Host.TryGetWorldName(out string world) || string.IsNullOrWhiteSpace(world)) return; - - uint me = Host.GetPlayerId(); - string name = string.Empty; - bool named = me != 0 && Host.HasGetObjectName && Host.TryGetObjectName(me, out name) && !string.IsNullOrWhiteSpace(name); - if (!named && now - _loginAtMs < NameWaitMs && IsDreamWeave(world)) return; - - _world = world.Trim(); - _character = named ? name.Trim() : string.Empty; - _checked = true; - _active = IsDreamWeave(_world); - if (!_active) - { - Host.Log($"[RynthThreads] {_world} isn't DreamWeave: idle."); - return; - } - _store ??= new PressStore(PressStore.DefaultFolder); - _store.Poll(); - _nextPollMs = now + PollMs; - if (_window != null) _window.NeedsPass = true; - Host.Log($"[RynthThreads] recording Fragment Press results for {(_character.Length > 0 ? _character : "this character")} on {_world}; " - + $"{_store.Presses.Count} presses so far in {_store.FilePath}"); - } - - // ── Presses ───────────────────────────────────────────────────────────── - - private void SaveFinished(Press? p) - { - if (p == null || _store == null) return; - p.Server = _world; - p.Character = _character; - string? error = _store.Record(p); - if (_window != null) _window.NeedsPass = true; - - string level = p.FragmentLevel?.ToString(CultureInfo.InvariantCulture) ?? "?"; - string what = p.Complete - ? $"{p.Modifiers.Count} modifier{(p.Modifiers.Count == 1 ? "" : "s")}" - : "incomplete"; - Print($"Saved press {_store.Presses.Count}: {p.Fragment} (Level {level}), {p.ComponentsText} - {what}."); - if (error != null) - { - Host.Log($"[RynthThreads] couldn't write {_store.FilePath} yet: {error}"); - Print("The press file is busy; it will be written in a moment."); - } - } - - private ThreadsReport CurrentReport() - { - if (_store == null) return new ThreadsReport(); - if (_report == null || _reportVersion != _store.Version) - { - _report = PressInference.Build(_store.Presses); - _reportVersion = _store.Version; - } - return _report; - } - - private string Notice() - { - if (_store == null) return string.Empty; - var parts = new List(); - if (_store.PendingCount > 0) parts.Add($"{_store.PendingCount} press(es) waiting to be written"); - if (_store.BadLines > 0) parts.Add($"{_store.BadLines} unreadable line(s) in the file skipped"); - return string.Join("; ", parts); - } - - private void Export() - { - if (_store == null) return; - try - { - string path = _store.ExportCsv(DateTime.Now); - Print($"Exported {_store.Presses.Count} presses to {path}"); - } - catch (Exception ex) - { - Print($"Export failed: {ex.Message}"); - } - } - - // ── Commands ──────────────────────────────────────────────────────────── - - private void RunCommand(string arg) - { - string word = arg.Split(' ', StringSplitOptions.RemoveEmptyEntries) is { Length: > 0 } w ? w[0].ToLowerInvariant() : string.Empty; - if (word is "help" or "?") - { - Print($"DreamWeave only: records Fragment Press results and shows the odds of each modifier per component. {Command} shows or hides the window; {Command} stats; {Command} export."); - return; - } - if (!_inWorld) { Print("Log in first."); return; } - if (!_checked) { Print("Still finding out which server this is; try again in a moment."); return; } - if (!_active) - { - Print($"RynthThreads is for DreamWeave only (this is {_world})."); - return; - } - switch (word) - { - case "": - if (_window == null) return; - _window.Visible = !_window.Visible; - _window.NeedsPass = true; - if (_window.Visible && !Host.HasUi && !_noUiLogged) - { - _noUiLogged = true; - Print($"This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). Presses are still recorded: {Command} stats."); - } - break; - case "stats": - foreach (string line in StatsLines(CurrentReport(), _store!.FilePath)) Print(line); - break; - case "export": - Export(); - break; - default: - Print($"{Command} [stats | export | help]"); - break; - } - } - - /// - /// The short /rthreads stats summary: totals, then one line per component (at most 6) and No - /// components with its top 5 modifiers by rate ("Guarded 75%", "+" when more likely with it). - /// The Affinity group is left out: every gem has one. - /// - internal static List StatsLines(ThreadsReport r, string file) - { - var lines = new List - { - $"{r.Total} press{(r.Total == 1 ? "" : "es")} ({r.Usable} complete, {r.Incomplete} incomplete) by {r.Characters} character{(r.Characters == 1 ? "" : "s")}; {r.Modifiers.Count} modifiers seen.", - }; - var groups = new List(r.Components); - if (r.NoComponents != null) groups.Add(r.NoComponents); - int shown = 0; - foreach (GroupReport g in groups) - { - if (shown++ == 6) { lines.Add($"... and {groups.Count - 6} more (see the window)."); break; } - var sb = new StringBuilder(); - sb.Append(g.Name).Append(" (").Append(g.Presses).Append("): "); - int n = 0; - foreach (Odds o in g.Odds) - { - if (o.IsGroup) continue; - if (n == 5) break; - if (n++ > 0) sb.Append(", "); - sb.Append(o.Modifier).Append(' ') - .Append(Math.Round(o.Rate * 100).ToString("0", CultureInfo.InvariantCulture)).Append('%'); - if (o.MoreLikely) sb.Append('+'); - } - lines.Add(sb.ToString()); - } - if (groups.Any(g => g.Odds.Any(o => o.MoreLikely))) lines.Add("+ = more likely with it than without."); - if (r.Total == 0) lines.Add("Press a Raw Fragment at a Fragment Press to start."); - lines.Add("File: " + file); - return lines; - } - - private void Print(string text) - { - if (!Host.HasWriteToChat || !Host.WriteToChat("[RynthThreads] " + text, 1)) - Host.Log("[RynthThreads] " + text); - } - - /// A pass when one is wanted, or now and then while visible. - private void Record(UiWindow w, long now) - { - bool due = w.NeedsPass || (w.Visible && now >= w.NextPassMs); - if (!due) return; - w.NeedsPass = false; - w.NextPassMs = now + PassIntervalMs; - w.Begin(); - try - { - _panel!.Draw(w); - } - catch (Exception ex) - { - w.TextWrapped($"Something went wrong drawing this window: {ex.GetType().Name}: {ex.Message}"); - Host.Log($"[RynthThreads] {w.Key} pass failed: {ex}"); - } - w.End(); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/Threads/Press.cs b/Plugins/RynthCore.Plugin.RynthThreads/Threads/Press.cs deleted file mode 100644 index 1689e42..0000000 --- a/Plugins/RynthCore.Plugin.RynthThreads/Threads/Press.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace RynthCore.Plugin.RynthThreads.Threads; - -/// One number in a modifier's description, with the form it was written in. -internal readonly struct ModNumber -{ - /// "x1.38" multiplier. - public const string Mult = "mult"; - /// "12%". - public const string Pct = "pct"; - /// "+29" (or "-5"): a signed amount, e.g. a rating. - public const string Plus = "plus"; - /// A plain number. - public const string Num = "num"; - - public readonly double Value; - public readonly string Kind; - /// As written ("x1.38", "12%", "+29", "75"). - public readonly string Text; - - public ModNumber(double value, string kind, string text) - { - Value = value; - Kind = kind; - Text = text; - } -} - -/// One "Name - description" line of the gem's block. -internal sealed class GemModifier -{ - public string Name = string.Empty; - public string Description = string.Empty; - public List Numbers = new(); -} - -/// -/// One press at a Fragment Press, as the server told it in chat. Everything the server says is -/// kept as said (numbers raw): "Level 190, 4 entries." goes into ResultLevel and Entries without -/// guessing what entries are. -/// -internal sealed class Press -{ - /// Random id, so a press read back from the shared file isn't counted twice. - public string Id = string.Empty; - public DateTime TimeUtc; - public string Server = string.Empty; - public string Character = string.Empty; - - /// "Raw Fragment" from "Using the Raw Fragment (Level 185) with the Fragment Press". - public string Fragment = string.Empty; - public int? FragmentLevel; - /// "Fragment Press". - public string Tool = string.Empty; - - /// The "Pressed. ..." line ("Pressed. It holds."), or "" when none came. - public string Outcome = string.Empty; - /// A "Components selected: ..." (or "No components ...") line came. - public bool ComponentsSeen; - /// Sorted, case-insensitively. - public List Components = new(); - /// The "... drawn at random." line, or "". - public string RandomNote = string.Empty; - public List Modifiers = new(); - public int? ResultLevel; - public int? Entries; - - /// Ended on its "Level N, M entries." line. False: timed out, or another "Using ..." line came first. - public bool Complete; - /// Why it ended: "done", "timeout", "next use", "logout". - public string End = string.Empty; - - /// The press's own lines, in order. - public List Raw = new(); - /// Lines that came while the press was open but didn't fit it (other players' chat, or text not known yet). - public List Extra = new(); - - /// The press says "It holds." (the only success text seen so far). - public bool Held => Outcome.IndexOf("holds", StringComparison.OrdinalIgnoreCase) >= 0; - - /// Used by the inference: a finished press with its whole gem block. - public bool Usable => Complete && Modifiers.Count > 0; - - public bool HasComponent(string name) - { - foreach (string c in Components) - if (string.Equals(c, name, StringComparison.OrdinalIgnoreCase)) return true; - return false; - } - - public bool HasModifier(string name) - { - foreach (GemModifier m in Modifiers) - if (string.Equals(m.Name, name, StringComparison.OrdinalIgnoreCase)) return true; - return false; - } - - public GemModifier? FindModifier(string name) - { - foreach (GemModifier m in Modifiers) - if (string.Equals(m.Name, name, StringComparison.OrdinalIgnoreCase)) return m; - return null; - } - - public string ComponentsText => Components.Count == 0 ? "no components" : string.Join(", ", Components); - - public static string NewId() => Guid.NewGuid().ToString("N").Substring(0, 16); -} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressInference.cs b/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressInference.cs deleted file mode 100644 index 85239aa..0000000 --- a/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressInference.cs +++ /dev/null @@ -1,458 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text; - -namespace RynthCore.Plugin.RynthThreads.Threads; - -/// -/// One modifier's rate in a set of presses (a component's, a combination's, ...), with its rate -/// in the other presses for comparison. -/// -internal sealed class Odds -{ - /// The modifier's name, or for any "<Material> Affinity". - public string Modifier = string.Empty; - /// Presses in the set that had it, of . - public int Hits, N; - /// False for the All presses row: nothing to compare with. - public bool Compared; - /// The other presses (without the component, ...) that had it, of ; 0 = no data. - public int OtherHits, OtherN; - /// One-sided Fisher exact p: chance of a rate this much higher here if the set made no difference. - public double P = 1; - /// Clearly higher here than in the other presses (Fisher p < 0.05 or the 95% intervals apart). - public bool MoreLikely; - /// Its numbers in these presses ("x1.38 to x1.52"). - public string Values = string.Empty; - /// For the Affinity group: presses per material, most first. - public List<(string Material, int Hits)> Split = new(); - - public double Rate => N == 0 ? 0 : (double)Hits / N; - public double? OtherRate => OtherN == 0 ? null : (double)OtherHits / OtherN; - public bool IsGroup => Modifier == PressInference.AffinityGroup; -} - -internal enum GroupKind { All, Component, Combination, NoComponents } - -/// (fragment level, result level, entries) and how many presses gave it. -internal readonly record struct ResultCount(int? FragmentLevel, int? ResultLevel, int? Entries, int Count); - -/// A set of presses: All presses, one component's, one exact combination's, or those with no component. -internal sealed class GroupReport -{ - public string Name = string.Empty; - public GroupKind Kind; - /// The components (one for a component row, several for a combination, none otherwise). - public List Members = new(); - public int Presses; - public double AvgModifiers; - public int MinModifiers, MaxModifiers; - /// Most common first. - public List Results = new(); - /// Every modifier seen in these presses, likeliest first. - public List Odds = new(); - - /// What the comparison column is: "without", "other presses", "with components", or "". - public string OtherLabel => Kind switch - { - GroupKind.Component => "without", - GroupKind.Combination => "other presses", - GroupKind.NoComponents => "with components", - _ => string.Empty, - }; - - public Odds? Find(string modifier) => - Odds.FirstOrDefault(o => o.Modifier.Equals(modifier, StringComparison.OrdinalIgnoreCase)); -} - -internal sealed class ModifierReport -{ - /// The modifier's name, or . - public string Name = string.Empty; - public bool IsGroup; - public string Example = string.Empty; - /// "reward" (loot, salvage), "harder" (monster health, damage, numbers) or "" when the text doesn't say plainly. - public string Tag = string.Empty; - /// Its rate over all usable presses. - public Odds Overall = new(); - /// Its rate in presses with no components (against presses with some); null when there are none. - public Odds? NoComponents; - /// Its rate with each component and combination (0% included), likeliest first. - public List<(GroupReport Group, Odds Odds)> ByGroup = new(); - public string Values = string.Empty; - /// (fragment level, presses, values), lowest level first; level null = unknown. - public List<(int? Level, int Count, string Values)> ByLevel = new(); - - public int Seen => Overall.Hits; -} - -internal sealed class ThreadsReport -{ - public int Total, Usable, Incomplete, Characters; - /// Every usable press (the baseline); null when there are none. - public GroupReport? All; - public List Components = new(); - /// Exact combinations of two or more components. - public List Combinations = new(); - /// Presses with no components (the plain random draw); null when there are none. - public GroupReport? NoComponents; - public List Modifiers = new(); - - public GroupReport? Component(string name) => - Components.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); - - public GroupReport? Combination(string name) => - Combinations.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); - - public ModifierReport? Modifier(string name) => - Modifiers.FirstOrDefault(m => m.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); -} - -/// -/// The odds of each modifier from the recorded presses. On DreamWeave a component gives a chance of -/// each modifier, not a fixed one, so for every set of presses (All presses, each component, each -/// exact combination of components, no components) this counts how often each modifier came: -/// hits/N, with a 95% Wilson interval, against its rate in the presses outside the set. -/// -/// Only finished presses with their gem block count (Press.Usable); a finished press without a -/// "Components selected" line counts as one with no components. Every gem carries one -/// "<Material> Affinity": those are counted together as the Affinity group, with the split by -/// material. -/// -/// "More likely with X": the rate with X is above the rate without and either the one-sided Fisher -/// exact p is under 0.05 or the two 95% intervals don't overlap. "Always ... so far" only for 100% -/// over at least 10 presses. -/// -internal static class PressInference -{ - public const string AffinityGroup = "Affinity"; - private const string AffinitySuffix = " Affinity"; - private const double Z = 1.96; - /// Intervals are shown below this many presses. - public const int IntervalBelow = 50; - public const int AlwaysAtLeast = 10; - - public static ThreadsReport Build(IReadOnlyList all) - { - var report = new ThreadsReport { Total = all.Count }; - var used = new List(); - var characters = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (Press p in all) - { - if (p.Character.Length > 0) characters.Add(p.Character); - if (!p.Complete) report.Incomplete++; - if (p.Usable) used.Add(p); - } - report.Usable = used.Count; - report.Characters = characters.Count; - if (used.Count == 0) return report; - - List components = Distinct(used.SelectMany(p => p.Components)); - List keys = Distinct(used.SelectMany(Keys)); - - report.All = Group("All presses", GroupKind.All, new List(), used, used); - - foreach (string c in components) - report.Components.Add(Group(c, GroupKind.Component, new List { c }, used, used.Where(p => p.HasComponent(c)).ToList())); - SortGroups(report.Components); - - foreach (var g in used.Where(p => p.Components.Count > 1).GroupBy(ComboKey, StringComparer.OrdinalIgnoreCase)) - { - List members = g.First().Components.OrderBy(x => x, StringComparer.OrdinalIgnoreCase).ToList(); - report.Combinations.Add(Group(string.Join(" + ", members), GroupKind.Combination, members, used, g.ToList())); - } - SortGroups(report.Combinations); - - List plain = used.Where(p => p.Components.Count == 0).ToList(); - if (plain.Count > 0) - report.NoComponents = Group("No components", GroupKind.NoComponents, new List(), used, plain); - - foreach (string k in keys) - { - List with = used.Where(p => Has(p, k)).ToList(); - var mr = new ModifierReport - { - Name = k, - IsGroup = k == AffinityGroup, - Example = Find(with[^1], k)!.Description, - Overall = Count(k, used, null), - Values = Values(with, k), - }; - mr.Tag = Tag(mr.Example); - if (report.NoComponents != null) mr.NoComponents = Count(k, plain, used.Where(p => p.Components.Count > 0).ToList()); - foreach (GroupReport gr in report.Components.Concat(report.Combinations)) - mr.ByGroup.Add((gr, gr.Find(k) ?? Count(k, Members(used, gr), Others(used, gr)))); - mr.ByGroup.Sort((a, b) => - { - int byOdds = CompareOdds(a.Odds, b.Odds); - return byOdds != 0 ? byOdds : string.Compare(a.Group.Name, b.Group.Name, StringComparison.OrdinalIgnoreCase); - }); - foreach (var g in with.GroupBy(p => p.FragmentLevel).OrderBy(g => g.Key ?? int.MaxValue)) - mr.ByLevel.Add((g.Key, g.Count(), Values(g, k))); - report.Modifiers.Add(mr); - } - report.Modifiers.Sort((a, b) => b.Seen != a.Seen ? b.Seen.CompareTo(a.Seen) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); - return report; - } - - // ── Groups ────────────────────────────────────────────────────────────── - - private static GroupReport Group(string name, GroupKind kind, List members, List used, List set) - { - var g = new GroupReport { Name = name, Kind = kind, Members = members, Presses = set.Count }; - if (set.Count == 0) return g; - g.AvgModifiers = set.Average(p => (double)p.Modifiers.Count); - g.MinModifiers = set.Min(p => p.Modifiers.Count); - g.MaxModifiers = set.Max(p => p.Modifiers.Count); - g.Results = set.GroupBy(p => (p.FragmentLevel, p.ResultLevel, p.Entries)) - .Select(x => new ResultCount(x.Key.FragmentLevel, x.Key.ResultLevel, x.Key.Entries, x.Count())) - .OrderByDescending(r => r.Count).ThenBy(r => r.ResultLevel ?? int.MaxValue).ThenBy(r => r.Entries ?? int.MaxValue) - .ToList(); - List? others = kind == GroupKind.All ? null : Others(used, g, set); - foreach (string k in Distinct(set.SelectMany(Keys))) - g.Odds.Add(Count(k, set, others)); - g.Odds.Sort(CompareOdds); - return g; - } - - private static void SortGroups(List groups) => - groups.Sort((a, b) => b.Presses != a.Presses ? b.Presses.CompareTo(a.Presses) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); - - /// The presses a component or combination row covers. - private static List Members(List used, GroupReport g) => g.Kind switch - { - GroupKind.Component => used.Where(p => p.HasComponent(g.Members[0])).ToList(), - GroupKind.Combination => used.Where(p => ComboKey(p).Equals(ComboKey(g.Members), StringComparison.OrdinalIgnoreCase)).ToList(), - GroupKind.NoComponents => used.Where(p => p.Components.Count == 0).ToList(), - _ => used, - }; - - /// The presses a row is compared with: without the component, not this combination, with components. - private static List Others(List used, GroupReport g, List? set = null) - { - var inSet = new HashSet(set ?? Members(used, g)); - return used.Where(p => !inSet.Contains(p)).ToList(); - } - - private static string ComboKey(Press p) => ComboKey(p.Components); - - private static string ComboKey(IEnumerable components) => - string.Join("\n", components.Select(c => c.ToLowerInvariant()).OrderBy(c => c, StringComparer.Ordinal)); - - /// Likeliest first; then more presses; then by name. - private static int CompareOdds(Odds a, Odds b) - { - if (a.Rate != b.Rate) return b.Rate.CompareTo(a.Rate); - if (a.Hits != b.Hits) return b.Hits.CompareTo(a.Hits); - return string.Compare(a.Modifier, b.Modifier, StringComparison.OrdinalIgnoreCase); - } - - /// Modifier in , against (null = no comparison). - internal static Odds Count(string k, List set, List? others) - { - var o = new Odds { Modifier = k, N = set.Count, Compared = others != null }; - foreach (Press p in set) - if (Has(p, k)) o.Hits++; - if (others != null) - { - o.OtherN = others.Count; - foreach (Press p in others) - if (Has(p, k)) o.OtherHits++; - if (o.OtherN > 0 && o.N > 0) - { - o.P = FisherGreater(o.Hits, o.N, o.OtherHits, o.OtherN); - bool apart = Wilson(o.Hits, o.N).Low > Wilson(o.OtherHits, o.OtherN).High; - o.MoreLikely = o.Rate > o.OtherRate!.Value && (o.P < 0.05 || apart); - } - } - o.Values = Values(set, k); - if (k == AffinityGroup) - { - var split = new Dictionary(StringComparer.OrdinalIgnoreCase); - var names = new List(); - foreach (Press p in set) - foreach (string mat in p.Modifiers.Select(m => Material(m.Name)).OfType().Distinct(StringComparer.OrdinalIgnoreCase)) - { - if (!split.ContainsKey(mat)) { split[mat] = 0; names.Add(mat); } - split[mat]++; - } - o.Split = names.Select(n => (n, split[n])) - .OrderByDescending(x => x.Item2).ThenBy(x => x.n, StringComparer.OrdinalIgnoreCase).ToList(); - } - return o; - } - - // ── Modifier keys (the Affinity group) ────────────────────────────────── - - /// "Amethyst" for "Amethyst Affinity", else null. - internal static string? Material(string modifier) => - modifier.Length > AffinitySuffix.Length && modifier.EndsWith(AffinitySuffix, StringComparison.OrdinalIgnoreCase) - ? modifier.Substring(0, modifier.Length - AffinitySuffix.Length).Trim() - : null; - - /// The name the counts use: for any affinity, else the modifier's own. - internal static string Key(string modifier) => Material(modifier) != null ? AffinityGroup : modifier; - - private static IEnumerable Keys(Press p) => p.Modifiers.Select(m => Key(m.Name)); - - private static bool Has(Press p, string k) => Find(p, k) != null; - - private static GemModifier? Find(Press p, string k) - { - if (k != AffinityGroup) return p.FindModifier(k); - foreach (GemModifier m in p.Modifiers) - if (Material(m.Name) != null) return m; - return null; - } - - /// "Affinity (any)" for the group, else the name. - internal static string Display(string k) => k == AffinityGroup ? "Affinity (any)" : k; - - // ── Statistics ────────────────────────────────────────────────────────── - - /// 95% Wilson score interval for of . - internal static (double Low, double High) Wilson(int hits, int n) - { - if (n <= 0) return (0, 1); - double p = (double)hits / n, z2 = Z * Z; - double denom = 1 + z2 / n; - double centre = (p + z2 / (2 * n)) / denom; - double half = Z * Math.Sqrt(p * (1 - p) / n + z2 / (4.0 * n * n)) / denom; - return (Math.Max(0, centre - half), Math.Min(1, centre + half)); - } - - /// - /// One-sided Fisher exact test: the chance of or more hits in a set of - /// when + hits are spread at random - /// over the + presses. - /// - internal static double FisherGreater(int a, int n, int c, int m) - { - int total = n + m, hits = a + c; - if (total == 0) return 1; - double logAll = LogChoose(total, n), sum = 0; - for (int x = a; x <= Math.Min(n, hits); x++) - { - if (hits - x > m) continue; - sum += Math.Exp(LogChoose(hits, x) + LogChoose(total - hits, n - x) - logAll); - } - return Math.Min(1, sum); - } - - private static double LogChoose(int n, int k) - { - if (k < 0 || k > n) return double.NegativeInfinity; - double r = 0; - for (int i = 1; i <= k; i++) r += Math.Log(n - k + i) - Math.Log(i); - return r; - } - - // ── Text ──────────────────────────────────────────────────────────────── - - private static string Pct(double v) => Math.Round(v * 100).ToString("0", CultureInfo.InvariantCulture); - - /// "75% (3/4, 30-95%)"; the interval only below presses. - internal static string OddsText(Odds o) - { - if (o.N == 0) return "no data"; - if (o.N >= IntervalBelow) return $"{Pct(o.Rate)}% ({o.Hits}/{o.N})"; - var (lo, hi) = Wilson(o.Hits, o.N); - return $"{Pct(o.Rate)}% ({o.Hits}/{o.N}, {Pct(lo)}-{Pct(hi)}%)"; - } - - /// "without: 20% (1/5)", "without: no data", or "" when not compared. - internal static string OtherText(Odds o, string label) - { - if (!o.Compared || label.Length == 0) return string.Empty; - return o.OtherN == 0 ? label + ": no data" : $"{label}: {Pct(o.OtherRate!.Value)}% ({o.OtherHits}/{o.OtherN})"; - } - - /// "more likely with Lead Scarab", "always with Lead Scarab so far" (100% over 10+), or "". - internal static string LikelyText(Odds o, GroupReport g) - { - if (!o.MoreLikely) return string.Empty; - string who = g.Kind == GroupKind.NoComponents ? "no components" : g.Name; - return o.Hits == o.N && o.N >= AlwaysAtLeast ? $"always with {who} so far" : $"more likely with {who}"; - } - - /// "Amethyst 1, Iron 1" for the Affinity group's split, else "". - internal static string SplitText(Odds o) => - string.Join(", ", o.Split.Select(s => $"{s.Material} {s.Hits}")); - - /// "5.25 modifiers per press (5-6)". - internal static string ModifiersText(GroupReport g) - { - string avg = g.AvgModifiers.ToString("0.##", CultureInfo.InvariantCulture); - string range = g.MinModifiers == g.MaxModifiers ? "" : $" ({g.MinModifiers}-{g.MaxModifiers})"; - return $"{avg} modifiers per press{range}"; - } - - /// "L185 -> 175, 3 entries: 4" per result, most common first. - internal static string ResultsText(GroupReport g) => - string.Join("; ", g.Results.Select(r => - $"L{N(r.FragmentLevel)} -> {N(r.ResultLevel)}, {N(r.Entries)} entries: {r.Count}")); - - private static string N(int? v) => v?.ToString(CultureInfo.InvariantCulture) ?? "?"; - - private static List Distinct(IEnumerable names) - { - var list = new List(); - var seen = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (string n in names) - if (n.Length > 0 && seen.Add(n)) list.Add(n); - list.Sort(StringComparer.OrdinalIgnoreCase); - return list; - } - - /// - /// The modifier's numbers across presses, position by position: "x1.38 to x1.52, 12%". Empty - /// when it has none. - /// - internal static string Values(IEnumerable presses, string k) - { - var ranges = new List<(string Kind, double Min, double Max)>(); - foreach (Press p in presses) - { - GemModifier? gm = Find(p, k); - if (gm == null) continue; - for (int i = 0; i < gm.Numbers.Count; i++) - { - ModNumber n = gm.Numbers[i]; - if (i >= ranges.Count) ranges.Add((n.Kind, n.Value, n.Value)); - else ranges[i] = (ranges[i].Kind, Math.Min(ranges[i].Min, n.Value), Math.Max(ranges[i].Max, n.Value)); - } - } - var sb = new StringBuilder(); - foreach (var (kind, min, max) in ranges) - { - if (sb.Length > 0) sb.Append(", "); - sb.Append(Format(kind, min)); - if (max != min) sb.Append(" to ").Append(Format(kind, max)); - } - return sb.ToString(); - } - - internal static string Format(string kind, double v) - { - string s = v.ToString("0.##", CultureInfo.InvariantCulture); - return kind switch - { - ModNumber.Mult => "x" + s, - ModNumber.Pct => s + "%", - ModNumber.Plus => v >= 0 ? "+" + s : s, - _ => s, - }; - } - - /// "reward" or "harder" when the description says so plainly, else "". - internal static string Tag(string description) - { - string d = description.ToLowerInvariant(); - bool reward = d.Contains("loot") || d.Contains("salvage") || d.Contains("drop"); - bool harder = d.Contains("monsters have") || d.Contains("more monsters") || d.Contains("monsters attack") - || d.Contains("boss attacks") || d.Contains("hitting harder"); - return reward == harder ? string.Empty : reward ? "reward" : "harder"; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressParser.cs b/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressParser.cs deleted file mode 100644 index bc99d6c..0000000 --- a/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressParser.cs +++ /dev/null @@ -1,250 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; - -namespace RynthCore.Plugin.RynthThreads.Threads; - -/// -/// Reads Fragment Press results out of chat, one line at a time. A press starts at -/// "Using the Raw Fragment (Level 185) with the Fragment Press" -/// and collects, in any order and with other chat in between: -/// "Pressed. It holds." the outcome (any "Pressed..." line) -/// "Components selected: A, B" (or "No components ...") -/// "Remaining slots drawn at random." (any "... drawn at random" line) -/// "The gem carries:" then one " Name - description" line per modifier -/// and ends at "Level 190, 4 entries." (complete). A press that never gets there is still saved, -/// marked incomplete: after without a line of its own, when another -/// "Using ..." line comes, or at logout. Lines that don't fit are kept in the press's Extra list -/// (other players' chat lands there too). Never throws on odd text. -/// -internal sealed class PressParser -{ - /// A press's lines arrive within the same second; this long without one ends it. - public const long TimeoutMs = 15_000; - private const int MaxLineLength = 400; - private const int MaxRawLines = 80; - private const int MaxExtraLines = 40; - private const int MaxModifiers = 40; - - private static readonly RegexOptions Opt = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase; - private static readonly Regex UseRx = new(@"^Using (?:the |an? )?(?.+?) with (?:the |an? )?(?[^.]*\bPress)\b", Opt); - private static readonly Regex LevelInName = new(@"^(?.*?)\s*\(\s*Level\s+(?\d+)\s*\)\s*$", Opt); - private static readonly Regex ComponentsRx = new(@"^Components?(?: selected)?\s*:\s*(?.*)$", Opt); - private static readonly Regex NoComponentsRx = new(@"^No components\b", Opt); - private static readonly Regex CarriesRx = new(@"^The [^:]{1,40} carries\s*:?\s*$", Opt); - private static readonly Regex EndRx = new(@"^Level\s+(?\d+)\s*(?:,\s*(?\d+)\s+entr(?:y|ies))?\s*\.?\s*$", Opt); - // "Name - description": a short name of letters, spaces, apostrophes and hyphens. - private static readonly Regex ModifierRx = new(@"^(?[A-Za-z][A-Za-z' \-]{0,47}?)\s+[-–—]\s+(?.+)$", Opt); - private static readonly Regex NumberRx = new( - @"(?[x×]\s?\d+(?:\.\d+)?)|(?[+\-]\d+(?:\.\d+)?)(?!\d|\.\d|\s?%)|(?[+\-]?\d+(?:\.\d+)?\s?%)|(?\d+(?:\.\d+)?))", - RegexOptions.CultureInvariant); - - private enum State { Idle, Open, Carries } - - private State _state = State.Idle; - private Press? _press; - private long _lastOwnLineMs; - - /// A press is being read. - public bool Busy => _press != null; - - /// - /// Feeds one chat message (it may hold several lines). Returns the presses it finished, or - /// null. is a monotonic clock (Environment.TickCount64). - /// - public List? Feed(string? text, long nowMs) - { - if (string.IsNullOrEmpty(text)) return null; - List? done = null; - foreach (string piece in text.Split('\n')) - { - string line = piece.TrimEnd('\r', ' ', '\t'); - if (line.Trim().Length == 0) continue; - if (line.Length > MaxLineLength) line = line.Substring(0, MaxLineLength); - try - { - Press? finished = FeedLine(line, nowMs); - if (finished != null) (done ??= new List()).Add(finished); - } - catch - { - // Odd text must never stop chat; the line is just not used. - } - } - return done; - } - - /// Ends a press that has gone quiet. Returns it (incomplete), or null. - public Press? Tick(long nowMs) - { - if (_press == null || nowMs - _lastOwnLineMs < TimeoutMs) return null; - return Finish("timeout"); - } - - /// Ends whatever is open (logout, unload). Returns it (incomplete), or null. - public Press? Flush(string reason) => _press == null ? null : Finish(reason); - - private Press? FeedLine(string line, long nowMs) - { - string t = line.Trim(); - Press? previous = null; - - if (t.StartsWith("Using ", StringComparison.OrdinalIgnoreCase)) - { - Match use = UseRx.Match(t); - if (_press != null) previous = Finish("next use"); - if (!use.Success) return previous; - Start(use, line, nowMs); - return previous; - } - if (_press == null) return null; - - if (_state == State.Carries) - { - Match mod = ModifierRx.Match(t); - // Modifier lines are indented; an unindented one must still look exactly like "Name - text". - bool indented = line.Length > 0 && char.IsWhiteSpace(line[0]); - if (mod.Success && (indented || !LooksLikeChat(t))) - { - if (_press.Modifiers.Count < MaxModifiers) _press.Modifiers.Add(MakeModifier(mod)); - Own(line, nowMs); - return null; - } - } - - Match end = EndRx.Match(t); - if (end.Success) - { - _press.ResultLevel = Int(end.Groups["lvl"].Value); - if (end.Groups["entries"].Success) _press.Entries = Int(end.Groups["entries"].Value); - Own(line, nowMs); - return Finish("done", complete: true); - } - if (t.StartsWith("Pressed", StringComparison.OrdinalIgnoreCase) && _press.Outcome.Length == 0) - { - _press.Outcome = t; - Own(line, nowMs); - return null; - } - Match comps = ComponentsRx.Match(t); - if (comps.Success && !_press.ComponentsSeen) - { - _press.ComponentsSeen = true; - _press.Components = SplitComponents(comps.Groups["list"].Value); - Own(line, nowMs); - return null; - } - if (NoComponentsRx.IsMatch(t) && !_press.ComponentsSeen) - { - _press.ComponentsSeen = true; - Own(line, nowMs); - return null; - } - if (t.IndexOf("drawn at random", StringComparison.OrdinalIgnoreCase) >= 0 && _press.RandomNote.Length == 0) - { - _press.RandomNote = t; - Own(line, nowMs); - return null; - } - if (CarriesRx.IsMatch(t)) - { - _state = State.Carries; - Own(line, nowMs); - return null; - } - - // Not ours (or not known yet): keep it beside the press, don't let it extend the timeout. - if (_press.Extra.Count < MaxExtraLines) _press.Extra.Add(line); - return null; - } - - private void Start(Match use, string line, long nowMs) - { - string item = use.Groups["item"].Value.Trim(); - var p = new Press - { - Id = Press.NewId(), - TimeUtc = DateTime.UtcNow, - Tool = use.Groups["tool"].Value.Trim(), - Fragment = item, - }; - Match lv = LevelInName.Match(item); - if (lv.Success) - { - p.Fragment = lv.Groups["name"].Value.Trim(); - p.FragmentLevel = Int(lv.Groups["lvl"].Value); - } - _press = p; - _state = State.Open; - Own(line, nowMs); - } - - private void Own(string line, long nowMs) - { - if (_press!.Raw.Count < MaxRawLines) _press.Raw.Add(line); - _lastOwnLineMs = nowMs; - } - - private Press Finish(string reason, bool complete = false) - { - Press p = _press!; - p.Complete = complete; - p.End = reason; - _press = null; - _state = State.Idle; - return p; - } - - /// Chat from players and channels ("Bob says, ...", "[Trade] ...", "You tell ..."). - private static bool LooksLikeChat(string t) => - t.StartsWith("[", StringComparison.Ordinal) || t.Contains(" says, ") || t.Contains(" tells you") - || t.StartsWith("You ", StringComparison.Ordinal) || t.Contains('"'); - - internal static List SplitComponents(string list) - { - var result = new List(); - string s = list.Trim().TrimEnd('.'); - if (s.Length == 0 || s.Equals("none", StringComparison.OrdinalIgnoreCase)) return result; - foreach (string part in s.Replace(" and ", ",", StringComparison.OrdinalIgnoreCase).Split(',')) - { - string c = part.Trim(); - if (c.Length > 0 && !result.Exists(x => x.Equals(c, StringComparison.OrdinalIgnoreCase))) result.Add(c); - } - result.Sort(StringComparer.OrdinalIgnoreCase); - return result; - } - - private static GemModifier MakeModifier(Match m) - { - string desc = m.Groups["desc"].Value.Trim(); - return new GemModifier - { - Name = m.Groups["name"].Value.Trim(), - Description = desc, - Numbers = Numbers(desc), - }; - } - - /// Every number in a description with its form: x1.38, 12%, +29 (or -5), 75. - internal static List Numbers(string text) - { - var list = new List(); - foreach (Match m in NumberRx.Matches(text)) - { - string kind; - string raw; - if (m.Groups["mult"].Success) { kind = ModNumber.Mult; raw = m.Groups["mult"].Value; } - else if (m.Groups["plus"].Success) { kind = ModNumber.Plus; raw = m.Groups["plus"].Value; } - else if (m.Groups["pct"].Success) { kind = ModNumber.Pct; raw = m.Groups["pct"].Value; } - else { kind = ModNumber.Num; raw = m.Groups["num"].Value; } - string digits = raw.TrimStart('x', '×', '+').TrimEnd('%').Trim(); - if (double.TryParse(digits, NumberStyles.Float, CultureInfo.InvariantCulture, out double v)) - list.Add(new ModNumber(v, kind, raw.Replace(" ", string.Empty))); - } - return list; - } - - private static int? Int(string s) => - int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v) ? v : null; -} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressStore.cs b/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressStore.cs deleted file mode 100644 index 1a016c6..0000000 --- a/Plugins/RynthCore.Plugin.RynthThreads/Threads/PressStore.cs +++ /dev/null @@ -1,346 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Text; -using System.Text.Json; -using System.Threading; - -namespace RynthCore.Plugin.RynthThreads.Threads; - -/// -/// Every press, one JSON object per line, in one file shared by all characters and clients on the -/// PC (%LOCALAPPDATA%\RynthCore\RynthThreads\presses.jsonl). Appends open the file for writing -/// alone, so two clients never mix their lines: a writer that finds it busy tries again a few -/// times, and a press that still can't be written waits for . -/// Reading follows the file's growth (), so other clients' presses show up. -/// Written by hand with Utf8JsonWriter and read with JsonDocument: plugin types never go through -/// System.Text.Json's serializer (its cache would keep an old plugin alive across a hot reload). -/// -internal sealed class PressStore -{ - public const string FileName = "presses.jsonl"; - private const int AppendTries = 4; - private const int AppendWaitMs = 15; - private const int MaxPending = 200; - - private readonly List _presses = new(); - private readonly HashSet _ids = new(StringComparer.Ordinal); - private readonly List _pending = new(); - private long _readOffset; - - public readonly string Folder; - public string FilePath => Path.Combine(Folder, FileName); - - /// Every press read or recorded, oldest first. - public IReadOnlyList Presses => _presses; - /// Presses recorded here that couldn't be written yet. - public int PendingCount => _pending.Count; - /// Lines in the file that couldn't be read (kept in the file, skipped here). - public int BadLines { get; private set; } - /// Bumped whenever changes. - public int Version { get; private set; } - - public PressStore(string folder) => Folder = folder; - - /// %LOCALAPPDATA%\RynthCore\RynthThreads. - public static string DefaultFolder => Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "RynthThreads"); - - // ── Writing ───────────────────────────────────────────────────────────── - - /// - /// Keeps the press and appends it to the file. Returns null when written, else why not (it - /// stays pending and tries again). - /// - public string? Record(Press p) - { - if (p.Id.Length == 0) p.Id = Press.NewId(); - Add(p); - string? error = TryAppend(ToJson(p)); - if (error != null && _pending.Count < MaxPending) _pending.Add(p); - return error; - } - - /// Writes presses that found the file busy before. Returns how many are still waiting. - public int FlushPending() - { - while (_pending.Count > 0) - { - if (TryAppend(ToJson(_pending[0])) != null) break; - _pending.RemoveAt(0); - } - return _pending.Count; - } - - /// Appends one line, retrying briefly while another writer holds the file. - internal string? TryAppend(string json) - { - byte[] bytes = Encoding.UTF8.GetBytes(json + "\n"); - string? last = null; - for (int attempt = 0; attempt < AppendTries; attempt++) - { - try - { - Directory.CreateDirectory(Folder); - // FileShare.Read: readers may look, no other writer gets in until this line is down. - using var fs = new FileStream(FilePath, FileMode.Append, FileAccess.Write, FileShare.Read); - fs.Write(bytes, 0, bytes.Length); - return null; - } - catch (IOException ex) - { - last = ex.Message; - } - catch (UnauthorizedAccessException ex) - { - return ex.Message; - } - if (attempt < AppendTries - 1) Thread.Sleep(AppendWaitMs * (attempt + 1)); // at most 90 ms on the pump - } - return last ?? "the file is busy"; - } - - // ── Reading ───────────────────────────────────────────────────────────── - - /// Reads what was added to the file since the last read (everything the first time). Returns the number of new presses. - public int Poll() - { - string path = FilePath; - long length; - try - { - var info = new FileInfo(path); - if (!info.Exists) return 0; - length = info.Length; - } - catch { return 0; } - - if (length < _readOffset) _readOffset = 0; // replaced or cut short: read it all again (ids keep it from doubling) - if (length == _readOffset) return 0; - - byte[] data; - try - { - using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); - fs.Seek(_readOffset, SeekOrigin.Begin); - data = new byte[length - _readOffset]; - int got = 0; - while (got < data.Length) - { - int n = fs.Read(data, got, data.Length - got); - if (n <= 0) break; - got += n; - } - if (got < data.Length) Array.Resize(ref data, got); - } - catch { return 0; } - - // Only whole lines; a line still being written is read next time. - int lastNewline = Array.LastIndexOf(data, (byte)'\n'); - if (lastNewline < 0) return 0; - _readOffset += lastNewline + 1; - - int added = 0; - foreach (string line in Encoding.UTF8.GetString(data, 0, lastNewline).Split('\n')) - { - string l = line.Trim(); - if (l.Length == 0) continue; - Press? p = FromJson(l); - if (p == null) { BadLines++; continue; } - if (Add(p)) added++; - } - return added; - } - - private bool Add(Press p) - { - if (p.Id.Length > 0 && !_ids.Add(p.Id)) return false; - // Kept in time order (other clients' lines can land out of order). - int at = _presses.Count; - while (at > 0 && _presses[at - 1].TimeUtc > p.TimeUtc) at--; - _presses.Insert(at, p); - Version++; - return true; - } - - // ── JSON ──────────────────────────────────────────────────────────────── - - internal static string ToJson(Press p) - { - using var ms = new MemoryStream(); - using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = false })) - { - w.WriteStartObject(); - w.WriteNumber("v", 1); - w.WriteString("id", p.Id); - w.WriteString("time", p.TimeUtc.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture)); - w.WriteString("server", p.Server); - w.WriteString("character", p.Character); - w.WriteString("fragment", p.Fragment); - WriteInt(w, "fragmentLevel", p.FragmentLevel); - w.WriteString("tool", p.Tool); - w.WriteString("outcome", p.Outcome); - w.WriteBoolean("componentsSeen", p.ComponentsSeen); - w.WriteStartArray("components"); - foreach (string c in p.Components) w.WriteStringValue(c); - w.WriteEndArray(); - w.WriteString("random", p.RandomNote); - w.WriteStartArray("modifiers"); - foreach (GemModifier m in p.Modifiers) - { - w.WriteStartObject(); - w.WriteString("name", m.Name); - w.WriteString("description", m.Description); - w.WriteStartArray("numbers"); - foreach (ModNumber n in m.Numbers) - { - w.WriteStartObject(); - w.WriteNumber("value", n.Value); - w.WriteString("kind", n.Kind); - w.WriteString("text", n.Text); - w.WriteEndObject(); - } - w.WriteEndArray(); - w.WriteEndObject(); - } - w.WriteEndArray(); - WriteInt(w, "resultLevel", p.ResultLevel); - WriteInt(w, "entries", p.Entries); - w.WriteBoolean("complete", p.Complete); - w.WriteString("end", p.End); - WriteStrings(w, "raw", p.Raw); - WriteStrings(w, "extra", p.Extra); - w.WriteEndObject(); - } - return Encoding.UTF8.GetString(ms.ToArray()); - } - - private static void WriteInt(Utf8JsonWriter w, string name, int? v) - { - if (v.HasValue) w.WriteNumber(name, v.Value); - else w.WriteNull(name); - } - - private static void WriteStrings(Utf8JsonWriter w, string name, List list) - { - w.WriteStartArray(name); - foreach (string s in list) w.WriteStringValue(s); - w.WriteEndArray(); - } - - /// One line back into a press, or null when it isn't one. Unknown fields are ignored, missing ones left empty. - internal static Press? FromJson(string line) - { - try - { - using JsonDocument doc = JsonDocument.Parse(line); - JsonElement r = doc.RootElement; - if (r.ValueKind != JsonValueKind.Object) return null; - var p = new Press - { - Id = Str(r, "id"), - Server = Str(r, "server"), - Character = Str(r, "character"), - Fragment = Str(r, "fragment"), - FragmentLevel = IntOrNull(r, "fragmentLevel"), - Tool = Str(r, "tool"), - Outcome = Str(r, "outcome"), - ComponentsSeen = Bool(r, "componentsSeen"), - Components = Strings(r, "components"), - RandomNote = Str(r, "random"), - ResultLevel = IntOrNull(r, "resultLevel"), - Entries = IntOrNull(r, "entries"), - Complete = Bool(r, "complete"), - End = Str(r, "end"), - Raw = Strings(r, "raw"), - Extra = Strings(r, "extra"), - }; - p.Components.Sort(StringComparer.OrdinalIgnoreCase); - if (DateTime.TryParse(Str(r, "time"), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime t)) - p.TimeUtc = t.ToUniversalTime(); - if (r.TryGetProperty("modifiers", out JsonElement mods) && mods.ValueKind == JsonValueKind.Array) - { - foreach (JsonElement m in mods.EnumerateArray()) - { - if (m.ValueKind != JsonValueKind.Object) continue; - var gm = new GemModifier { Name = Str(m, "name"), Description = Str(m, "description") }; - if (gm.Name.Length == 0) continue; - if (m.TryGetProperty("numbers", out JsonElement nums) && nums.ValueKind == JsonValueKind.Array) - foreach (JsonElement n in nums.EnumerateArray()) - if (n.ValueKind == JsonValueKind.Object && n.TryGetProperty("value", out JsonElement v) && v.TryGetDouble(out double d)) - gm.Numbers.Add(new ModNumber(d, Str(n, "kind"), Str(n, "text"))); - p.Modifiers.Add(gm); - } - } - return p; - } - catch - { - return null; - } - } - - private static string Str(JsonElement o, string name) => - o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty; - - private static bool Bool(JsonElement o, string name) => - o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True; - - private static int? IntOrNull(JsonElement o, string name) => - o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : null; - - private static List Strings(JsonElement o, string name) - { - var list = new List(); - if (o.TryGetProperty(name, out JsonElement a) && a.ValueKind == JsonValueKind.Array) - foreach (JsonElement e in a.EnumerateArray()) - if (e.ValueKind == JsonValueKind.String) list.Add(e.GetString() ?? string.Empty); - return list; - } - - // ── CSV ───────────────────────────────────────────────────────────────── - - /// Writes every press as CSV into this folder (presses-yyyyMMdd-HHmmss.csv). Returns the path. - public string ExportCsv(DateTime localNow) - { - Directory.CreateDirectory(Folder); - string path = Path.Combine(Folder, "presses-" + localNow.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture) + ".csv"); - File.WriteAllText(path, Csv(_presses), new UTF8Encoding(true)); - return path; - } - - internal static string Csv(IEnumerable presses) - { - var sb = new StringBuilder(); - sb.Append("time_utc,server,character,fragment,fragment_level,outcome,components,result_level,entries,complete,modifier_count,modifiers\r\n"); - foreach (Press p in presses) - { - var mods = new List(); - foreach (GemModifier m in p.Modifiers) mods.Add(m.Name + ": " + m.Description); - Cell(sb, p.TimeUtc.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)); sb.Append(','); - Cell(sb, p.Server); sb.Append(','); - Cell(sb, p.Character); sb.Append(','); - Cell(sb, p.Fragment); sb.Append(','); - Cell(sb, p.FragmentLevel?.ToString(CultureInfo.InvariantCulture) ?? string.Empty); sb.Append(','); - Cell(sb, p.Outcome); sb.Append(','); - Cell(sb, string.Join("; ", p.Components)); sb.Append(','); - Cell(sb, p.ResultLevel?.ToString(CultureInfo.InvariantCulture) ?? string.Empty); sb.Append(','); - Cell(sb, p.Entries?.ToString(CultureInfo.InvariantCulture) ?? string.Empty); sb.Append(','); - Cell(sb, p.Complete ? "yes" : "no (" + p.End + ")"); sb.Append(','); - Cell(sb, p.Modifiers.Count.ToString(CultureInfo.InvariantCulture)); sb.Append(','); - Cell(sb, string.Join(" | ", mods)); - sb.Append("\r\n"); - } - return sb.ToString(); - } - - private static void Cell(StringBuilder sb, string s) - { - // A spreadsheet would run a cell starting with = + - @ as a formula: start it with ' instead. - if (s.Length > 0 && s[0] is '=' or '+' or '-' or '@') s = "'" + s; - bool quote = s.IndexOfAny(new[] { ',', '"', '\n', '\r' }) >= 0; - if (!quote) { sb.Append(s); return; } - sb.Append('"').Append(s.Replace("\"", "\"\"")).Append('"'); - } -} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiFormat.cs b/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiFormat.cs deleted file mode 100644 index d54717a..0000000 --- a/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiFormat.cs +++ /dev/null @@ -1,130 +0,0 @@ -using System; - -namespace RynthCore.Plugin.RynthThreads.Ui; - -/// -/// Display-list format 1 for the engine's script windows (RynthSuite -/// Docs/RYNTHLUA_WINDOWS_DESIGN.md §4.2-4.3; the engine's DisplayListParser.cs is the source of -/// truth). Little-endian. Only the ops these windows draw are listed. -/// -internal static class UiFormat -{ - public const uint Magic = 0x31575352; // 'RSW1' - public const ushort FormatVersion = 1; - public const uint BodyUnchanged = 0xFFFFFFFF; - public const int MaxString = 4096; - public const int MaxStr8 = 128; - public const int MaxOps = 1500; // engine limit per window - public const int MaxBodyBytes = 64 * 1024; // engine limit per window - public const byte OpHasBlock = 1; - - // Ops - public const byte OpEnd = 0x00; - public const byte OpText = 0x01; - public const byte OpTextColored = 0x02; - public const byte OpTextWrapped = 0x03; - public const byte OpTextDisabled = 0x04; - public const byte OpBulletText = 0x05; - public const byte OpSeparatorText = 0x06; - public const byte OpSeparator = 0x10; - public const byte OpSameLine = 0x11; - public const byte OpSpacing = 0x13; - public const byte OpDummy = 0x14; - public const byte OpIndent = 0x15; - public const byte OpUnindent = 0x16; - public const byte OpButton = 0x20; - public const byte OpCheckbox = 0x21; - public const byte OpSliderInt = 0x22; - public const byte OpInputText = 0x24; - public const byte OpCombo = 0x25; - public const byte OpSelectable = 0x26; - public const byte OpProgressBar = 0x27; - public const byte OpImage = 0x28; // op level 2 (engines from 2026-09-30) - public const byte OpPushID = 0x30; - public const byte OpPopID = 0x31; - public const byte OpPushStyleColor = 0x32; - public const byte OpPopStyleColor = 0x33; - public const byte OpSetItemTooltip = 0x38; - public const byte OpChild = 0x40; - public const byte OpCollapsingHeader = 0x41; - - // Window flags - public const uint FlagVisible = 1u << 0; - public const uint FlagShowInBar = 1u << 1; - /// With ShowInBar: a bar button of its own instead of a Scripts menu line (engines from - /// 2026-10-11; older ones ignore it and list the window in the Scripts menu). - public const uint FlagBarButton = 1u << 11; - public const uint FlagNoScrollbar = 1u << 5; - - // Image icon kinds (op level 2) - public const byte IconKindIcon = 0; // a 0x06 texture id - public const byte IconKindObject = 1; // a live object's icon with underlay and overlay - - // Selectable flags - public const uint SelectableAllowDoubleClick = 4; - - // Event types - public const ushort EvClicked = 1; - public const ushort EvBool = 2; - public const ushort EvInt = 3; - public const ushort EvText = 5; - public const ushort EvOpen = 6; - public const ushort EvVisibility = 8; - public const ushort EvError = 10; - - // ImGuiCol ids the engine accepts in PushStyleColor (ImGui.NET 1.91.6.1) - public const int ColText = 0; - public const int ColButton = 21; - public const int ColButtonHovered = 22; - public const int ColHeader = 24; - - // InputText flags - public const uint InputAutoSelectAll = 4096; - /// The text box reports Enter (its event carries submitted = true). - public const uint InputEnterReturnsTrue = 32; - - // CollapsingHeader flags - public const uint TreeDefaultOpen = 32; - - public static uint Fnv1a(ReadOnlySpan bytes, uint hash = 2166136261) - { - foreach (byte b in bytes) - { - hash ^= b; - hash *= 16777619; - } - return hash; - } - - /// The length of cut to at most bytes without splitting a character. - public static int CutUtf8(ReadOnlySpan s, int max) - { - if (s.Length <= max) return s.Length; - int n = Math.Max(0, max); - while (n > 0 && (s[n] & 0xC0) == 0x80) n--; - return n; - } - - /// An ImGui U32 colour (0xAABBGGRR) from RGB bytes. - public static uint Rgb(byte r, byte g, byte b, byte a = 255) => - ((uint)a << 24) | ((uint)b << 16) | ((uint)g << 8) | r; -} - -/// Colours RynthThreads uses (copied from RynthSort) (0xAABBGGRR). -internal static class UiColors -{ - public static readonly uint Green = UiFormat.Rgb(110, 210, 110); - public static readonly uint Red = UiFormat.Rgb(225, 95, 95); - public static readonly uint Yellow = UiFormat.Rgb(235, 205, 90); - public static readonly uint Grey = UiFormat.Rgb(150, 150, 150); - public static readonly uint Gold = UiFormat.Rgb(230, 180, 60); - /// Upstream's "destruction" highlight: deep pink brightened by half (255, 30, 220). - public static readonly uint Destruction = UiFormat.Rgb(255, 30, 220); - public static readonly uint TabActive = UiFormat.Rgb(60, 110, 170); - public static readonly uint TabActiveHover = UiFormat.Rgb(75, 130, 195); - public static readonly uint OtherServer = UiFormat.Rgb(150, 185, 235); - public static readonly uint Stale = UiFormat.Rgb(225, 150, 80); - public static readonly uint White = UiFormat.Rgb(255, 255, 255); - /// The Lua script's amber (paused, full packs): 1.0, 0.75, 0.25. - public static readonly uint Amber = UiFormat.Rgb(255, 191, 64); -} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiHost.cs b/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiHost.cs deleted file mode 100644 index f660d49..0000000 --- a/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiHost.cs +++ /dev/null @@ -1,202 +0,0 @@ -using System; -using System.Buffers.Binary; -using System.Collections.Generic; -using System.Text; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.RynthThreads.Ui; - -/// -/// The plugin's side of the engine's script windows (API v71): polls the engine's events into -/// the windows' handlers and submits the window set when something changed. Plugin pump thread -/// only (inside the plugin's own tick), as the engine requires. -/// -internal sealed class UiHost -{ - private readonly List _windows = new(); - private readonly Dictionary _byHash = new(); - private byte[] _events = new byte[8192]; - private byte[] _submit = new byte[64 * 1024]; - private uint _lastSeq; - private bool _submittedSomething; - private long _retryAtMs; - private long _lastErrorLogMs; - - public Action? Log; - - public IReadOnlyList Windows => _windows; - - public UiWindow Add(UiWindow w) - { - _windows.Add(w); - _byHash[w.Hash] = w; - return w; - } - - /// Drains the engine's queued events into the windows' handlers. - public void Poll(RynthCoreHost host) - { - if (!host.HasUi || !_submittedSomething) return; - for (int round = 0; round < 8; round++) - { - int n = host.UiPollEvents(_events, out int remaining); - if (n > 0) Apply(_events.AsSpan(0, n)); - if (remaining == 0) break; - if (n == 0) Array.Resize(ref _events, _events.Length * 2); // one event didn't fit - } - } - - private void Apply(ReadOnlySpan data) - { - int pos = 0; - while (data.Length - pos >= 16) - { - ushort type = BinaryPrimitives.ReadUInt16LittleEndian(data[pos..]); - int size = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 2)..]); - if (size < 16 || size > data.Length - pos) break; - uint seq = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 4)..]); - uint window = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 8)..]); - uint key = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 12)..]); - ReadOnlySpan p = data.Slice(pos + 16, size - 16); - pos += size; - if (seq > _lastSeq) _lastSeq = seq; - - _byHash.TryGetValue(window, out UiWindow? w); - switch (type) - { - case UiFormat.EvClicked when w != null && p.Length >= 2: - int count = BinaryPrimitives.ReadUInt16LittleEndian(p); - for (int i = 0; i < Math.Min(count, 4); i++) w.Dispatch(key, new UiEvent(type)); - break; - case UiFormat.EvBool when w != null && p.Length >= 1: - w.Dispatch(key, new UiEvent(type, b: p[0] != 0)); - break; - case UiFormat.EvInt when w != null && p.Length >= 4: - w.Dispatch(key, new UiEvent(type, i: BinaryPrimitives.ReadInt32LittleEndian(p))); - break; - case UiFormat.EvText when w != null && p.Length >= 3: - { - int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p[1..]), p.Length - 3); - w.Dispatch(key, new UiEvent(type, text: Encoding.UTF8.GetString(p.Slice(3, n)), submitted: p[0] != 0)); - break; - } - case UiFormat.EvOpen when w != null && p.Length >= 1: - w.Dispatch(key, new UiEvent(type, b: p[0] != 0)); - break; - case UiFormat.EvVisibility when w != null && p.Length >= 1: - // The player closed it (X) or opened it (bar menu / command): theirs wins. - w.Visible = p[0] != 0; - w.NeedsPass = true; - break; - case UiFormat.EvError when p.Length >= 2: - { - int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p), p.Length - 2); - Log?.Invoke("[RynthThreads] window error: " + Encoding.UTF8.GetString(p.Slice(2, n))); - break; - } - } - } - } - - /// Sends the window set when any window's list or header changed. - public void Submit(RynthCoreHost host, long nowMs) - { - if (!host.HasUi || nowMs < _retryAtMs) return; - bool changed = !_submittedSomething && _windows.Count > 0; - foreach (UiWindow w in _windows) - if (w.BodyDirty || w.HeaderDirty) { changed = true; break; } - if (!changed) return; - - int pos = Write(); - int rc = host.UiSubmit(_submit.AsSpan(0, pos)); - if (rc == 0) - { - foreach (UiWindow w in _windows) w.MarkSubmitted(w.BodyDirty); - _submittedSomething = true; - } - else - { - // Nothing was applied; the engine keeps the previous lists. Try again in a second. - _retryAtMs = nowMs + 1000; - if (nowMs - _lastErrorLogMs > 10_000) - { - _lastErrorLogMs = nowMs; - Log?.Invoke($"[RynthThreads] the engine refused the window list ({rc})."); - } - } - } - - /// Removes every window from the engine (logout, shutdown). Their placement is kept by the engine. - public void SubmitEmpty(RynthCoreHost host) - { - if (!host.HasUi || !_submittedSomething) return; - Span b = stackalloc byte[16]; - BinaryPrimitives.WriteUInt32LittleEndian(b, UiFormat.Magic); - BinaryPrimitives.WriteUInt16LittleEndian(b[4..], UiFormat.FormatVersion); - BinaryPrimitives.WriteUInt16LittleEndian(b[6..], 0); - BinaryPrimitives.WriteUInt32LittleEndian(b[8..], _lastSeq); - BinaryPrimitives.WriteUInt32LittleEndian(b[12..], 16); - if (host.UiSubmit(b) == 0) - { - _submittedSomething = false; - foreach (UiWindow w in _windows) w.ForgetSubmitted(); - } - } - - private int Write() - { - int size = 16; - foreach (UiWindow w in _windows) size += 2 * (1 + UiFormat.MaxStr8) + 4 + 32 + 8 + (w.BodyDirty ? w.Body.Length : 0); - if (_submit.Length < size) _submit = new byte[Math.Max(size, _submit.Length * 2)]; - Span b = _submit; - - BinaryPrimitives.WriteUInt32LittleEndian(b, UiFormat.Magic); - BinaryPrimitives.WriteUInt16LittleEndian(b[4..], UiFormat.FormatVersion); - BinaryPrimitives.WriteUInt16LittleEndian(b[6..], (ushort)_windows.Count); - // Every event polled so far has been applied (handlers run as they arrive). - BinaryPrimitives.WriteUInt32LittleEndian(b[8..], _lastSeq); - int pos = 16; - foreach (UiWindow w in _windows) - { - pos = Str8(b, pos, w.KeyUtf8); - pos = Str8(b, pos, Encoding.UTF8.GetBytes(w.Title ?? string.Empty)); - BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], w.Flags); pos += 4; - pos = F32(b, pos, w.DefaultWidth); - pos = F32(b, pos, w.DefaultHeight); - pos = F32(b, pos, w.MinWidth); - pos = F32(b, pos, w.MinHeight); - pos = F32(b, pos, float.NaN); // RequestSize: none - pos = F32(b, pos, float.NaN); - pos = F32(b, pos, float.NaN); // RequestPos: none - pos = F32(b, pos, float.NaN); - BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], w.ListSeq); pos += 4; - if (w.BodyDirty) - { - ReadOnlySpan body = w.Body; - BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], (uint)body.Length); pos += 4; - body.CopyTo(b[pos..]); - pos += body.Length; - } - else - { - BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], UiFormat.BodyUnchanged); pos += 4; - } - } - BinaryPrimitives.WriteUInt32LittleEndian(b[12..], (uint)pos); - return pos; - } - - private static int Str8(Span b, int pos, ReadOnlySpan s) - { - int n = UiFormat.CutUtf8(s, UiFormat.MaxStr8); - b[pos] = (byte)n; - s[..n].CopyTo(b[(pos + 1)..]); - return pos + 1 + n; - } - - private static int F32(Span b, int pos, float v) - { - BinaryPrimitives.WriteSingleLittleEndian(b[pos..], v); - return pos + 4; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiWindow.cs b/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiWindow.cs deleted file mode 100644 index bbbdea9..0000000 --- a/Plugins/RynthCore.Plugin.RynthThreads/Ui/UiWindow.cs +++ /dev/null @@ -1,515 +0,0 @@ -using System; -using System.Buffers.Binary; -using System.Collections.Generic; -using System.Text; - -namespace RynthCore.Plugin.RynthThreads.Ui; - -/// One input from the engine for a widget (a click, a new value, an open state). -internal readonly struct UiEvent -{ - public readonly ushort Type; - public readonly bool Bool; - public readonly int Int; - public readonly string Text; - public readonly bool Submitted; - - public UiEvent(ushort type, bool b = false, int i = 0, string? text = null, bool submitted = false) - { - Type = type; - Bool = b; - Int = i; - Text = text ?? string.Empty; - Submitted = submitted; - } -} - -/// -/// One script window (engine API v71) and its recorder. A render pass records ImGui-style calls -/// into a display list; every widget's handler (click, value change) is kept by its widget key -/// until the next pass, so an event from the engine runs the code that drew that widget. -/// -/// Widget keys are FNV-1a(id, window hash): RynthThreads names every widget itself, so it needs -/// no ID stack. ImGui sees "label###id": its ID comes from the id alone, so labels can change. -/// The engine echoes the key in events and keys its per-widget local values by it. -/// -internal sealed class UiWindow -{ - public readonly string Key; - public readonly byte[] KeyUtf8; - public readonly uint Hash; - - public string Title; - public bool Visible; - public bool ShowInBar = true; - /// With ShowInBar: the window has its own button on the RynthCore bar (title as the - /// tooltip) rather than a line in the Scripts menu. - public bool BarButton = true; - public float DefaultWidth, DefaultHeight, MinWidth, MinHeight; - - /// A pass is wanted at the next chance (input arrived, it was just shown, data changed). - public bool NeedsPass = true; - public long NextPassMs; - - // The list as recorded by the last pass, and what the engine last accepted. - private byte[] _body = new byte[16 * 1024]; - private int _len; - private int _ops; - private bool _cut; - private byte[] _sentBody = Array.Empty(); - private int _sentLen = -1; - public uint ListSeq { get; private set; } - internal bool BodyDirty; - - // Header as last accepted by the engine. - private string? _sentTitle; - private uint _sentFlags; - private float _sentDw = float.NaN, _sentDh, _sentMw, _sentMh; - - private Dictionary> _handlers = new(); - private Dictionary> _next = new(); - private readonly Dictionary _openStates = new(); - - // Child blocks: where each open block's u32 length sits, or -1 when the block was dropped. - private readonly int[] _blocks = new int[16]; - private int _blockDepth; - private byte[] _tmp = new byte[512]; - - public UiWindow(string key, string title) - { - Key = key; - KeyUtf8 = Encoding.UTF8.GetBytes(key); - Hash = UiFormat.Fnv1a(KeyUtf8); - Title = title; - } - - public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0) - | (ShowInBar && BarButton ? UiFormat.FlagBarButton : 0); - - public bool HeaderDirty => - _sentTitle != Title || _sentFlags != Flags || _sentDw != DefaultWidth || _sentDh != DefaultHeight - || _sentMw != MinWidth || _sentMh != MinHeight; - - public ReadOnlySpan Body => _body.AsSpan(0, _len); - - // ── Pass ──────────────────────────────────────────────────────────────── - - public void Begin() - { - _len = 0; - _ops = 0; - _cut = false; - _blockDepth = 0; - _next.Clear(); - } - - /// Ends the pass: closes open blocks, writes End, and notes whether the list changed. - public void End() - { - while (_blockDepth > 0) EndChild(); - if (_cut) - { - // Room was kept for this line (see Room). - int p = BeginOp(UiFormat.OpTextDisabled); - Str("(more than fits in one window; narrow the list)"); - EndOp(p); - } - Ensure(4); - _body[_len++] = UiFormat.OpEnd; - _body[_len++] = 0; - _body[_len++] = 0; - _body[_len++] = 0; - - (_handlers, _next) = (_next, _handlers); - bool differs = _sentLen != _len || !_body.AsSpan(0, _len).SequenceEqual(_sentBody.AsSpan(0, _sentLen)); - if (differs && !BodyDirty) ListSeq++; - BodyDirty = differs; - } - - /// The engine accepted the last submit: remember what it now has. - internal void MarkSubmitted(bool bodySent) - { - if (bodySent) - { - if (_sentBody.Length < _len) _sentBody = new byte[_body.Length]; - _body.AsSpan(0, _len).CopyTo(_sentBody); - _sentLen = _len; - BodyDirty = false; - } - _sentTitle = Title; - _sentFlags = Flags; - _sentDw = DefaultWidth; _sentDh = DefaultHeight; _sentMw = MinWidth; _sentMh = MinHeight; - } - - /// The engine dropped every window (logout, empty submit): send everything again next time. - internal void ForgetSubmitted() - { - _sentLen = -1; - _sentTitle = null; - BodyDirty = _len > 0; - } - - internal void Dispatch(uint widgetKey, in UiEvent e) - { - if (_handlers.TryGetValue(widgetKey, out Action? h)) - h(e); - NeedsPass = true; - } - - // ── Widgets ───────────────────────────────────────────────────────────── - - public uint KeyOf(string id) - { - int max = Encoding.UTF8.GetMaxByteCount(id.Length); - if (_tmp.Length < max) _tmp = new byte[Math.Max(max, _tmp.Length * 2)]; - int n = Encoding.UTF8.GetBytes(id, _tmp); - return UiFormat.Fnv1a(_tmp.AsSpan(0, n), Hash); - } - - public void Text(string text) => WriteText(UiFormat.OpText, text); - public void TextDisabled(string text) => WriteText(UiFormat.OpTextDisabled, text); - public void TextWrapped(string text) => WriteText(UiFormat.OpTextWrapped, text); - public void BulletText(string text) => WriteText(UiFormat.OpBulletText, text); - public void SeparatorText(string text) => WriteText(UiFormat.OpSeparatorText, text); - - public void TextColored(uint abgr, string text) - { - if (!Room()) return; - int p = BeginOp(UiFormat.OpTextColored); - U32(abgr); - Str(text); - EndOp(p); - } - - public void Separator() - { - if (!Room()) return; - EndOp(BeginOp(UiFormat.OpSeparator)); - } - - public void Spacing() - { - if (!Room()) return; - EndOp(BeginOp(UiFormat.OpSpacing)); - } - - /// Next item on the same line, logical units from the content start (0 = right after). - public void SameLine(float x = 0f, float spacing = -1f) - { - if (!Room()) return; - int p = BeginOp(UiFormat.OpSameLine); - F32(x); - F32(spacing); - EndOp(p); - } - - public void Dummy(float w, float h) - { - if (!Room()) return; - int p = BeginOp(UiFormat.OpDummy); - F32(w); - F32(h); - EndOp(p); - } - - /// Moves the following items right by logical units, until . - public void Indent(float w) - { - if (!Room()) return; - int p = BeginOp(UiFormat.OpIndent); - F32(w); - EndOp(p); - } - - public void Unindent(float w) - { - if (!Room()) return; - int p = BeginOp(UiFormat.OpUnindent); - F32(w); - EndOp(p); - } - - public void Button(string label, string id, Action onClick, float w = 0f, float h = 0f, bool small = false) - { - if (!Room()) return; - uint key = KeyOf(id); - int p = BeginOp(UiFormat.OpButton); - U32(key); - Str(label + "###" + id); - F32(w); - F32(h); - U8(small ? (byte)1 : (byte)0); - EndOp(p); - _next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); }; - } - - public void SmallButton(string label, string id, Action onClick) => Button(label, id, onClick, small: true); - - /// A button drawn highlighted when (tabs, toggles). - public void ToggleButton(string label, string id, bool active, Action onClick, bool small = false) - { - if (active) - { - PushStyleColor(UiFormat.ColButton, UiColors.TabActive); - PushStyleColor(UiFormat.ColButtonHovered, UiColors.TabActiveHover); - } - Button(label, id, onClick, small: small); - if (active) PopStyleColor(2); - } - - public void Checkbox(string label, string id, bool value, Action set) - { - if (!Room()) return; - uint key = KeyOf(id); - int p = BeginOp(UiFormat.OpCheckbox); - U32(key); - Str(label + "###" + id); - U8(value ? (byte)1 : (byte)0); - EndOp(p); - _next[key] = e => { if (e.Type == UiFormat.EvBool) set(e.Bool); }; - } - - /// An integer slider from to (clamped by the engine). - public void SliderInt(string label, string id, int value, int min, int max, Action set, string format = "%d") - { - if (!Room()) return; - uint key = KeyOf(id); - int p = BeginOp(UiFormat.OpSliderInt); - U32(key); - Str(label + "###" + id); - I32(value); - I32(min); - I32(max); - Str(format); - EndOp(p); - _next[key] = e => { if (e.Type == UiFormat.EvInt) set(Math.Clamp(e.Int, min, max)); }; - } - - /// A text box; gets every edit (submitted = Enter was pressed). - public void InputText(string label, string id, string value, int maxLen, Action set, uint flags = 0) => - InputText(label, id, value, maxLen, (text, _) => set(text), flags); - - /// A text box; gets every edit and whether Enter was pressed. - public void InputText(string label, string id, string value, int maxLen, Action set, uint flags = 0) - { - if (!Room()) return; - maxLen = Math.Clamp(maxLen, 1, UiFormat.MaxString); - uint key = KeyOf(id); - int p = BeginOp(UiFormat.OpInputText); - U32(key); - Str(label + "###" + id); - Str(value ?? string.Empty, maxLen); - U16((ushort)maxLen); - U32(flags); - EndOp(p); - _next[key] = e => { if (e.Type == UiFormat.EvText) set(e.Text, e.Submitted); }; - } - - public void Combo(string label, string id, int index, IReadOnlyList items, Action set) - { - if (!Room()) return; - uint key = KeyOf(id); - int count = Math.Min(items.Count, 512); - int p = BeginOp(UiFormat.OpCombo); - U32(key); - Str(label + "###" + id); - I32(index); - U16((ushort)count); - for (int i = 0; i < count; i++) Str(items[i]); - EndOp(p); - _next[key] = e => { if (e.Type == UiFormat.EvInt) set(e.Int); }; - } - - public void Selectable(string label, string id, bool selected, Action onClick, float w = 0f, float h = 0f) - { - if (!Room()) return; - uint key = KeyOf(id); - int p = BeginOp(UiFormat.OpSelectable); - U32(key); - Str(label + "###" + id); - U8(selected ? (byte)1 : (byte)0); - U32(0); - F32(w); - F32(h); - EndOp(p); - _next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); }; - } - - public void ProgressBar(float fraction, float w, float h, string overlay) - { - if (!Room()) return; - int p = BeginOp(UiFormat.OpProgressBar); - F32(float.IsFinite(fraction) ? Math.Clamp(fraction, 0f, 1f) : 0f); - F32(w); - F32(h); - Str(overlay ?? string.Empty); - EndOp(p); - } - - /// - /// An icon (op level 2): = a 0x06 - /// texture id, = a live object. Engines without op level - /// 2 skip it (the caller checks first so the layout doesn't shift). - /// - public void Image(byte kind, uint id, float w, float h) - { - if (!Room()) return; - int p = BeginOp(UiFormat.OpImage); - U8(kind); - U32(id); - F32(w); - F32(h); - F32(0f); F32(0f); // uv0 - F32(1f); F32(1f); // uv1 - U32(0xFFFFFFFFu); // tint: as is - U32(0u); // border: none - EndOp(p); - } - - /// Tooltip for the item just drawn. - public void Tooltip(string text) - { - if (!Room() || string.IsNullOrEmpty(text)) return; - int p = BeginOp(UiFormat.OpSetItemTooltip); - Str(text); - EndOp(p); - } - - public void PushStyleColor(int colId, uint abgr) - { - if (!Room()) return; - int p = BeginOp(UiFormat.OpPushStyleColor); - U16((ushort)colId); - U32(abgr); - EndOp(p); - } - - /// Pops are dropped when the list is cut short; the engine pops leftovers at the scope's end. - public void PopStyleColor(int count = 1) - { - if (!Room()) return; - int p = BeginOp(UiFormat.OpPopStyleColor); - U8((byte)Math.Clamp(count, 1, 255)); - EndOp(p); - } - - /// - /// A collapsing header; returns whether to record its contents. The open state is the - /// player's (kept from the engine's Open events), so a header stays as they left it. - /// - public bool CollapsingHeader(string label, string id, bool defaultOpen = false) - { - uint key = KeyOf(id); - bool open = _openStates.TryGetValue(key, out bool o) ? o : defaultOpen; - if (!Room()) return false; - int p = BeginOp(UiFormat.OpCollapsingHeader); - U32(key); - Str(label + "###" + id); - U32(defaultOpen ? UiFormat.TreeDefaultOpen : 0); - U8(open ? (byte)1 : (byte)0); - EndOp(p); - _next[key] = e => { if (e.Type == UiFormat.EvOpen) _openStates[key] = e.Bool; }; - return open; - } - - /// A scrolling region; h 0 = fill the rest of the window. Must be closed with . - public void BeginChild(string id, float w = 0f, float h = 0f, bool border = true) - { - if (_blockDepth >= _blocks.Length) throw new InvalidOperationException("child regions nested too deep"); - if (!Room()) - { - _blocks[_blockDepth++] = -1; - return; - } - uint key = KeyOf(id); - int p = BeginOp(UiFormat.OpChild, UiFormat.OpHasBlock); - U32(key); - Str(id); - F32(w); - F32(h); - U8(border ? (byte)1 : (byte)0); - U32(0); - EndOp(p); - _blocks[_blockDepth++] = _len; - U32(0); // BlockLength, patched by EndChild - } - - public void EndChild() - { - if (_blockDepth == 0) return; - int at = _blocks[--_blockDepth]; - if (at < 0) return; - BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(at), (uint)(_len - (at + 4))); - } - - // ── Writing ───────────────────────────────────────────────────────────── - - /// - /// Whether another op fits. Room is kept for the closing "list cut short" line and the End - /// op, so the list never goes over the engine's limits (it refuses an over-limit list whole). - /// - private bool Room() - { - if (_cut) return false; - if (_ops < UiFormat.MaxOps - 8 && _len < UiFormat.MaxBodyBytes - 4096) return true; - _cut = true; - return false; - } - - private void WriteText(byte code, string text) - { - if (!Room()) return; - int p = BeginOp(code); - Str(text); - EndOp(p); - } - - private int BeginOp(byte code, byte opFlags = 0) - { - _ops++; - Ensure(4); - _body[_len++] = code; - _body[_len++] = opFlags; - _len += 2; // PayloadLength, patched by EndOp - return _len; - } - - private void EndOp(int payloadStart) - { - int length = _len - payloadStart; - BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(payloadStart - 2), (ushort)Math.Min(length, ushort.MaxValue)); - } - - private void Ensure(int extra) - { - if (_len + extra <= _body.Length) return; - int size = _body.Length; - while (size < _len + extra) size *= 2; - Array.Resize(ref _body, size); - } - - private void U8(byte v) { Ensure(1); _body[_len++] = v; } - private void U16(ushort v) { Ensure(2); BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(_len), v); _len += 2; } - private void U32(uint v) { Ensure(4); BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(_len), v); _len += 4; } - private void I32(int v) { Ensure(4); BinaryPrimitives.WriteInt32LittleEndian(_body.AsSpan(_len), v); _len += 4; } - - private void F32(float v) - { - Ensure(4); - BinaryPrimitives.WriteSingleLittleEndian(_body.AsSpan(_len), float.IsFinite(v) ? v : 0f); - _len += 4; - } - - /// str: u16 length + UTF-8, cut to on a character boundary. - private void Str(string s, int maxBytes = UiFormat.MaxString) - { - s ??= string.Empty; - ReadOnlySpan src = s.Length > maxBytes ? s.AsSpan(0, maxBytes) : s.AsSpan(); - Ensure(2 + Encoding.UTF8.GetMaxByteCount(src.Length)); - int at = _len + 2; - Span dst = _body.AsSpan(at); - int n = UiFormat.CutUtf8(dst[..Encoding.UTF8.GetBytes(src, dst)], maxBytes); - BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(_len), (ushort)n); - _len = at + n; - } -} diff --git a/Plugins/RynthCore.Plugin.RynthThreads/Views/ThreadsPanel.cs b/Plugins/RynthCore.Plugin.RynthThreads/Views/ThreadsPanel.cs deleted file mode 100644 index c9a5d13..0000000 --- a/Plugins/RynthCore.Plugin.RynthThreads/Views/ThreadsPanel.cs +++ /dev/null @@ -1,186 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using RynthCore.Plugin.RynthThreads.Threads; -using RynthCore.Plugin.RynthThreads.Ui; - -namespace RynthCore.Plugin.RynthThreads.Views; - -/// -/// The RynthThreads window: a summary line and Export, then three tabs. Components: All presses -/// (the baseline), each component, each exact combination and No components, each opening to the -/// rate of every modifier seen in its presses (hits/presses, a 95% range while few, the rate -/// without it), modifiers per press and the results. Modifiers: each one's overall rate, its rate -/// with each component, its values by fragment level. Presses: the newest first, each opening to -/// its modifiers and raw chat lines. -/// Recorded on the pump thread, replayed by the engine. -/// -internal sealed class ThreadsPanel -{ - private enum Tab { Components, Modifiers, Presses } - - private const int MaxPressesShown = 60; - private Tab _tab = Tab.Components; - - public Func Report = () => new ThreadsReport(); - public Func> Presses = () => Array.Empty(); - public Action Export = () => { }; - /// Extra status (pending writes, unreadable lines), or "". - public Func Notice = () => string.Empty; - - public void Draw(UiWindow w) - { - ThreadsReport r = Report(); - w.Text($"{r.Total} press{(r.Total == 1 ? "" : "es")}, {r.Usable} complete" + (r.Incomplete > 0 ? $", {r.Incomplete} incomplete" : "") - + $" ({r.Characters} character{(r.Characters == 1 ? "" : "s")})"); - w.SameLine(); - w.SmallButton("Export CSV", "export", Export); - w.Tooltip("Writes every press to a CSV file next to presses.jsonl (the folder is named in chat)"); - string notice = Notice(); - if (notice.Length > 0) w.TextColored(UiColors.Amber, notice); - - w.ToggleButton("Components", "tab.c", _tab == Tab.Components, () => _tab = Tab.Components, small: true); - w.SameLine(); - w.ToggleButton("Modifiers", "tab.m", _tab == Tab.Modifiers, () => _tab = Tab.Modifiers, small: true); - w.SameLine(); - w.ToggleButton("Presses", "tab.p", _tab == Tab.Presses, () => _tab = Tab.Presses, small: true); - w.Separator(); - - w.BeginChild("body", 0f, 0f, border: false); - if (r.Total == 0) - w.TextWrapped("No presses yet. Press a Raw Fragment at a Fragment Press: the result is read from chat and saved for every character on this PC."); - else if (_tab == Tab.Components) DrawComponents(w, r); - else if (_tab == Tab.Modifiers) DrawModifiers(w, r); - else DrawPresses(w); - w.EndChild(); - } - - // ── Components ────────────────────────────────────────────────────────── - - private static void DrawComponents(UiWindow w, ThreadsReport r) - { - w.TextWrapped("Each component gives a chance of each modifier. Rates are how often it came: hits/presses, " - + "with a 95% range while presses are few, and the rate without the component to compare."); - if (r.All is { } all) DrawGroup(w, all, "c:(all)"); - if (r.Components.Count == 0) - w.TextDisabled("No complete press with a component yet."); - foreach (GroupReport c in r.Components) DrawGroup(w, c, "c:" + c.Name); - foreach (GroupReport c in r.Combinations) DrawGroup(w, c, "k:" + c.Name); - if (r.NoComponents is { } nc) DrawGroup(w, nc, "c:(none)"); - } - - private static void DrawGroup(UiWindow w, GroupReport g, string id) - { - if (!w.CollapsingHeader($"{g.Name} ({g.Presses} press{(g.Presses == 1 ? "" : "es")})", id)) return; - w.Indent(8f); - if (g.Kind == GroupKind.All) w.TextDisabled("Every complete press: the baseline."); - else if (g.Kind == GroupKind.Combination) w.TextDisabled("Presses with exactly these components."); - else if (g.Kind == GroupKind.NoComponents) w.TextDisabled("The plain random draw: no component used."); - w.TextDisabled(PressInference.ModifiersText(g)); - w.TextDisabled("Results: " + PressInference.ResultsText(g)); - foreach (Odds o in g.Odds) DrawOdds(w, PressInference.Display(o.Modifier), o, g); - w.Unindent(8f); - } - - /// "Guarded 75% (3/4, 30-95%); without: no data; x1.83 to x1.91", green when more likely. - private static void DrawOdds(UiWindow w, string label, Odds o, GroupReport g) - { - var parts = new List { $"{label} {PressInference.OddsText(o)}" }; - string other = PressInference.OtherText(o, g.OtherLabel); - if (other.Length > 0) parts.Add(other); - if (o.Values.Length > 0) parts.Add(o.Values); - string likely = PressInference.LikelyText(o, g); - if (likely.Length > 0) parts.Add(likely); - string line = string.Join("; ", parts); - if (likely.Length > 0) - { - w.PushStyleColor(UiFormat.ColText, UiColors.Green); - w.BulletText(line); - w.PopStyleColor(); - } - else w.BulletText(line); - if (o.IsGroup && o.Split.Count > 0) w.TextDisabled(" " + PressInference.SplitText(o)); - } - - // ── Modifiers ─────────────────────────────────────────────────────────── - - private static void DrawModifiers(UiWindow w, ThreadsReport r) - { - if (r.Modifiers.Count == 0) w.TextDisabled("No complete press yet."); - foreach (ModifierReport m in r.Modifiers) - { - string tag = m.Tag.Length > 0 ? " [" + m.Tag + "]" : ""; - if (!w.CollapsingHeader($"{PressInference.Display(m.Name)} {PressInference.OddsText(m.Overall)}{tag}", "m:" + m.Name)) continue; - w.Indent(8f); - w.TextWrapped(m.Example); - w.Text("All presses: " + PressInference.OddsText(m.Overall)); - if (m.NoComponents is { } nc && r.NoComponents is { } ncg) DrawOdds(w, "No components", nc, ncg); - if (m.ByGroup.Count > 0) - { - w.SeparatorText("By component"); - foreach (var (g, o) in m.ByGroup) DrawOdds(w, g.Name, o, g); - } - if (m.IsGroup && m.Overall.Split.Count > 0) - { - w.SeparatorText("By material"); - foreach (var (mat, hits) in m.Overall.Split) - w.BulletText($"{mat}: {PressInference.OddsText(new Odds { Hits = hits, N = m.Overall.N })}"); - } - if (m.Values.Length > 0) w.Text("Values: " + m.Values); - if (m.ByLevel.Count > 1 || (m.ByLevel.Count == 1 && m.ByLevel[0].Level != null)) - { - w.SeparatorText("By fragment level"); - foreach (var (level, count, values) in m.ByLevel) - w.BulletText($"{(level?.ToString(CultureInfo.InvariantCulture) ?? "?")}: {(values.Length > 0 ? values : "-")} ({count} press{(count == 1 ? "" : "es")})"); - } - w.Unindent(8f); - } - } - - // ── Presses ───────────────────────────────────────────────────────────── - - private void DrawPresses(UiWindow w) - { - IReadOnlyList presses = Presses(); - int shown = 0; - for (int i = presses.Count - 1; i >= 0 && shown < MaxPressesShown; i--, shown++) - { - Press p = presses[i]; - if (!w.CollapsingHeader(PressTitle(p), "p:" + p.Id)) continue; - w.Indent(8f); - w.TextDisabled($"{p.Character} on {p.Server}, {p.TimeUtc.ToLocalTime():yyyy-MM-dd HH:mm:ss}"); - if (p.Outcome.Length > 0) w.Text(p.Outcome); - w.Text("Components: " + (p.ComponentsSeen ? p.ComponentsText : "(no line)")); - foreach (GemModifier m in p.Modifiers) w.BulletText(m.Name + " - " + m.Description); - if (p.ResultLevel != null || p.Entries != null) - w.Text($"Level {p.ResultLevel?.ToString(CultureInfo.InvariantCulture) ?? "?"}, {p.Entries?.ToString(CultureInfo.InvariantCulture) ?? "?"} entries"); - if (!p.Complete) w.TextColored(UiColors.Amber, "Incomplete: " + EndText(p.End)); - w.SeparatorText("Chat lines"); - foreach (string line in p.Raw) w.TextDisabled(line); - if (p.Extra.Count > 0) - { - w.SeparatorText("Other lines while it was open"); - foreach (string line in p.Extra) w.TextDisabled(line); - } - w.Unindent(8f); - } - if (presses.Count > MaxPressesShown) - w.TextDisabled($"The newest {MaxPressesShown} of {presses.Count}; Export CSV has them all."); - } - - internal static string PressTitle(Press p) - { - string lvl = p.FragmentLevel?.ToString(CultureInfo.InvariantCulture) ?? "?"; - string to = p.ResultLevel != null ? " -> " + p.ResultLevel.Value.ToString(CultureInfo.InvariantCulture) : ""; - string state = p.Complete ? $"{p.Modifiers.Count} modifiers" : "incomplete"; - return $"{p.TimeUtc.ToLocalTime():MM-dd HH:mm} L{lvl}{to} {p.ComponentsText} ({state})"; - } - - private static string EndText(string end) => end switch - { - "timeout" => "the press's lines stopped before its Level line", - "next use" => "another item was used before its Level line", - "logout" => "logged out before its Level line", - _ => end, - }; -} diff --git a/Plugins/Shared/EngineServerState.cs b/Plugins/Shared/EngineServerState.cs index d478d65..364f6f5 100644 --- a/Plugins/Shared/EngineServerState.cs +++ b/Plugins/Shared/EngineServerState.cs @@ -25,10 +25,6 @@ internal sealed record EngineServer(string Id, string Name, bool Active, bool De /// The engine's server list at one moment (GetServerStateJson, schema 1). internal sealed class EngineServerState { - /// Engine server ids with a meaning across RynthSuite. - public const string IltId = "ilt"; - public const string AelrynthId = "aelrynth"; - public int Revision { get; private init; } /// The connect host the client was launched with ("" when not known). public string Host { get; private init; } = string.Empty; @@ -60,45 +56,6 @@ internal sealed class EngineServerState /// True when is the active server. public bool IsActive(string id) => Active.Equals(id, StringComparison.OrdinalIgnoreCase) && Active.Length > 0; - /// - /// Whether this world is one of (a user's server list, "InfiniteLeaftide, - /// Conquest"): names compare case- and space-insensitively against server ids, names and the world. - /// Without the engine ( null) the world name decides. With it, an active - /// server decides ("ilt" counts as any Leaftide name); with none active the world name still counts, - /// unless it names a server the engine lists, which is then off on purpose (not detected, or this - /// character's override). - /// - public static bool MatchesNameList(EngineServerState? engine, string? world, IReadOnlyList names) - { - bool Named(string? s) - { - string n = Norm(s); - if (n.Length == 0) return false; - foreach (string name in names) - if (Norm(name) == n) return true; - return false; - } - bool anyLeaftide = false; - foreach (string name in names) - if (Norm(name).Contains("leaftide", StringComparison.Ordinal)) anyLeaftide = true; - - if (engine == null) return Named(world); - if (engine.HasActive) - return Named(engine.Active) || Named(engine.ActiveName) || (anyLeaftide && engine.IsActive(IltId)); - if (!Named(world)) return false; - string w = Norm(world); - foreach (EngineServer s in engine.Servers) - { - if (Norm(s.Id) == w || Norm(s.Name) == w) return false; - // ILT's world names ("InfiniteLeaftide") are the engine's own ILT detection. - if (s.Id.Equals(IltId, StringComparison.OrdinalIgnoreCase) && w.Contains("leaftide", StringComparison.Ordinal)) return false; - } - return true; - } - - /// Lower case without spaces, so "Infinite Leaftide" equals "InfiniteLeaftide". - private static string Norm(string? s) => (s ?? string.Empty).Replace(" ", string.Empty).Trim().ToLowerInvariant(); - /// /// Parses GetServerStateJson output. Null for empty or unusable text, or another schema's. /// Missing fields read as empty; nothing throws. @@ -159,7 +116,7 @@ internal sealed class EngineServerState /// owns the server), read leniently: a field the owner doesn't send stays "". /// internal sealed record ServerProfileView(string Id, string Name, string Plugin, string Ruleset, string Emulator, - string Botting, string BottingNote, string AccountLimit, bool Ilt, int FeaturesOn) + string Botting, string BottingNote, string AccountLimit) { /// Null for empty or unusable text. public static ServerProfileView? Parse(string? json) @@ -170,16 +127,11 @@ internal sealed record ServerProfileView(string Id, string Name, string Plugin, using JsonDocument doc = JsonDocument.Parse(json); JsonElement root = doc.RootElement; if (root.ValueKind != JsonValueKind.Object) return null; - // RynthILT's profile: its feature list, state 1 = on. - int on = 0; - if (root.TryGetProperty("features", out JsonElement features) && features.ValueKind == JsonValueKind.Array) - foreach (JsonElement f in features.EnumerateArray()) - if (f.ValueKind == JsonValueKind.Object && EngineServerState.Int(f, "state") == 1) on++; return new ServerProfileView( EngineServerState.Str(root, "id"), EngineServerState.Str(root, "name"), EngineServerState.Str(root, "plugin"), EngineServerState.Str(root, "ruleset"), EngineServerState.Str(root, "emulator"), EngineServerState.Str(root, "botting"), EngineServerState.Str(root, "bottingNote"), - EngineServerState.Str(root, "accountLimit"), EngineServerState.Bool(root, "ilt"), on); + EngineServerState.Str(root, "accountLimit")); } catch (JsonException) { @@ -220,7 +172,6 @@ internal sealed record ServerProfileView(string Id, string Name, string Plugin, parts.Add(Ruleset.Length > 0 && Emulator.Length > 0 ? Ruleset + ", " + Emulator : Ruleset + Emulator); if (Botting.Length > 0) parts.Add("botting " + Botting + (BottingNote.Length > 0 ? " - " + BottingNote : string.Empty)); if (AccountLimit.Length > 0) parts.Add("accounts: " + AccountLimit); - if (Ilt || FeaturesOn > 0) parts.Add((Ilt ? "ILT world" : "not ILT") + ", " + FeaturesOn + " Leaftide features on"); return parts.Count == 0 ? "no details" : string.Join("; ", parts); } } diff --git a/Plugins/Shared/PetCaptureLines.cs b/Plugins/Shared/PetCaptureLines.cs deleted file mode 100644 index 72777e7..0000000 --- a/Plugins/Shared/PetCaptureLines.cs +++ /dev/null @@ -1,29 +0,0 @@ -// PetCaptureLines.cs - The chat lines that mean an ACECustom siphon-lens capture worked. -// -// RynthILT's (linked source): its siphon auto-capture (IltPetAutomation, RynthAi's Pets tab's until -// 2026-10-20) reads them to time the next lens (success -> short cooldown), and its Vaulted Dungeons -// keeper counts a capture as a kill for its "Kill Client" timer (a hunter who captures instead of -// killing is not idle). They are the MonsterCapture success replies; nothing new is guessed here. -using System; - -namespace RynthCore.Plugin.Shared; - -internal static class PetCaptureLines -{ - /// Substrings of the success replies (matched case-insensitively). - private static readonly string[] Success = - { - "successfully siphoned the essence", - "The echo resonates perfectly", - "The essence is captured", - }; - - /// True when is a capture-success reply. - public static bool IsSuccess(string? text) - { - if (string.IsNullOrEmpty(text)) return false; - foreach (string part in Success) - if (text.IndexOf(part, StringComparison.OrdinalIgnoreCase) >= 0) return true; - return false; - } -} diff --git a/Plugins/Shared/RynthAiHubApi.cs b/Plugins/Shared/RynthAiHubApi.cs index 062a90c..a609787 100644 --- a/Plugins/Shared/RynthAiHubApi.cs +++ b/Plugins/Shared/RynthAiHubApi.cs @@ -10,7 +10,7 @@ // rules' wield counters (the T11 counters RynthILT reads from /aug). // Compiled into both plugins (linked source), so the layout can't drift. // -// Rules: as RynthILT.Hub (Shared/RynthIltHubApi.cs): append-only, UTF-8 strings, +// Rules: as RynthServer.Hub (Shared/RynthServerHubApi.cs): append-only, UTF-8 strings, // each function says its thread, no exception crosses, the table lives as long as // the RynthAi copy (never freed; Version 0 after Shutdown), callers re-query. // RynthILT works without RynthAi: every feature that needs it says so. @@ -192,7 +192,7 @@ public unsafe struct RynthAiHubApiV1 /// /// VaultedDungeonsEnabled(): obsolete since 2026-10-20, kept because the table is append-only. The /// Vaulted Dungeons master switch is RynthILT's own setting now (RynthILT 0.4+ reads its state, and - /// RynthAi mirrors it for the engine through RynthILT.Hub GetSetting / SetSetting). RynthAi answers + /// RynthAi mirrors it for the engine through RynthServer.Hub GetSetting / SetSetting). RynthAi answers /// the value its profile still carries (what RynthILT copied once), so an older RynthILT keeps /// working; 0 before login and after shutdown. Any thread. /// diff --git a/Plugins/Shared/RynthIltDataApi.cs b/Plugins/Shared/RynthIltDataApi.cs deleted file mode 100644 index 84601ee..0000000 --- a/Plugins/Shared/RynthIltDataApi.cs +++ /dev/null @@ -1,722 +0,0 @@ -// ============================================================================ -// RynthSuite - Plugins/Shared/RynthIltDataApi.cs -// The "RynthILT.Data" interface: the Infinite Leaftide data RynthILT's Mini Remote Charms -// and Banking tabs show, for other plugins to draw (RynthOracle's Character tab charms, -// Pet Breeding tab and Quests tab guardians, and RynthInventory's Global Inventory "Banking" tab -// read it; the Mini Remote's own tabs keep working beside them): -// - the registry charms and Guardian Hands (GetCharmsJson, ToggleCharm); -// - the bank balances of every character RynthILT has seen on this server, and -// deposits, withdrawals, transfers and balance reads (GetBankJson, BankCommand); -// - version 2: the pet breeding tracker (GetPetBreedingJson, PetBreedingCommand). -// Separate from "RynthServer.Profile" (the server's settings) and "RynthILT.Hub" (RynthAi's -// exact-version table) so neither has to change for this. -// Compiled into RynthILT and its readers (linked source), so the layout can't drift. -// -// Rules (as the other shared interfaces): -// - Append-only: new functions go at the end, and Version goes up. -// - Strings are UTF-8, NUL-terminated. The JSON itself is plain ASCII. -// - Every function returns safely (no exception crosses the boundary). -// - The table is allocated once per loaded copy of RynthILT and never freed; shutdown -// sets Version to 0, and a reader re-queries (host GetPluginInterface) when it sees that. -// - Reading a JSON says "someone is looking": RynthILT rebuilds that snapshot on its pump -// (every couple of seconds) only while it is being read, so an idle reader costs nothing. -// -// GetCharmsJson payload (IltCharms.BuildReaderJson; read leniently): -// { "available": true, "world": "InfiniteLeaftide", "total": 28, "acquiredCount": 5, "activeCount": 3, -// "charms": [ { "name": "Mana Barrier", "effect": "...", "acquired": "carried"|"seen"|"no", -// "count": 1, "tier": 3, "maxTier": 5, "active": "on"|"off"|"unknown", -// "server": "on"|"off"|"unknown", "lastSeen": "2026-10-13", "toggleId": 1234567 } ], -// "hands": [ { "id": 1234568, "name": "Guardian Hand", "active": "on"|"off"|"unknown", -// "server": "on"|"off"|"unknown" } ] } -// "hands" are the Guardian Hands carried now (not a registry charm); "id" is their Toggle id. -// -// GetBankJson payload (IltBankExport.Build; read leniently): -// { "available": true, "enabled": 1, "world": "InfiniteLeaftide", "character": "Name", -// "characters": [ { "name": "Name", "current": true, "pyreals": 0, "luminance": 0, -// "legendaryKeys": 0, "mythicalKeys": 0, "enlightenedCoins": 0, -// "weaklyEnlightenedCoins": 0, "prestigeCoins": 0, "updated": "2026-10-13T21:25:37Z" } ], -// "deposits": ["Everything", ...], "withdrawals": [ { "label": "Pyreals", "notes": false } ], -// "transfers": [ { "label": "Pyreals", "notes": false } ], "notes": [ { "label": "MMD", "value": 250000 } ], -// "result": "Deposited ...", "transactions": [ { "when": "...", "type": "Sent", "amount": 1, -// "currency": "Pyreals", "player": "Who" } ] } -// "enabled": 1 the server has /bank, 0 it doesn't, -1 not known yet. -// -// BankCommand verbs (ASCII, space separated; the reply lands in "result"): -// refresh quiet /bank balance read -// deposit -// withdraw (amount = note count for trade notes) -// transfer -// The reader confirms a transfer with the player before sending it (RynthILT doesn't ask again). -// -// Version 2 (RynthILT 0.3.1) appends GetPetBreedingJson and PetBreedingCommand: the data of the -// pet breeding tracker RynthILT draws in the Mini Remote's Pets > Breeding sub-tab (RynthOracle's -// Pet Breeding tab reads it too). Readers still query version 1 and accept a version-1 table, so charms -// and the bank keep working with an older RynthILT; they use the breeding functions only when -// the table says Version >= 2 and is that big (HasPetBreeding). -// -// GetPetBreedingJson payload (IltPetBreeding.BuildJson; read leniently): -// { "available": true, "world": "...", "enabled": "on"|"off"|"unknown", "maturity": "...", "bond": "...", -// "room": "landblock 0x0106 variant 2", "freeSlots": 12, "message": "...", -// "essences": [ { "id": 1234, "name": "...", "sex": "M"|"F", "tier": 150, "bond": 120, "ready": true, -// "status": "Ready (9/10)", "readyIn": 0, "charges": 9, "chargesMax": 10, "juvenile": false, -// "stage": "Adult", "kills": 300, "killsRequired": 300, "mutations": 2, "potencyMutations": 1, -// "problems": ["..."], "boosters": ["..."] } ], -// "pairs": [ { "stud": "...", "dam": "...", "chanceBest": 0.05, "chanceWorst": 0.04, "inheritMin": 0, "inheritMax": 2 } ], -// "supplies": [ { "key": "incense2", "name": "...", "effect": "...", "count": 1, "price": 2500000, "apply": true, -// "targets": [1234] } ], -// "rules": [ { "label": "...", "value": "10", "source": "seen on server", "help": "..." } ], -// "events": [ { "when": "2026-10-15 20:15", "kind": "birth", "text": "..." } ], newest first -// "debug": { "when": "...", "enabled": "on", "location": "...", "match": "valid"|"invalid"|"", "pet": "...", -// "sex": "...", "partners": 1 } } -// PetBreedingCommand verbs (ASCII): refresh | debug | dance | apply -// The reader confirms "apply" and "dance" with the player first (RynthILT doesn't ask again). -// -// Version 3 (RynthILT 0.2.20) appends GetGuardianJson and GuardianCommand (the Temple guardians -// on RynthOracle's Quests tab). Readers use them only when Version >= 3 and the table is that big -// (HasGuardian); a version-2 table still answers charms, the bank and breeding (V2Size). -// -// GetGuardianJson payload (IltGuardian.BuildJson; read leniently): -// { "available": true, "world": "...", "chat": true, "auto": false, "buy": true, "cooldownHours": 20, -// "answer": "Pyreal", "npc": "Guardian of ...", "answerAgeSec": 42 (-1 none yet), "heard": "...", -// "running": false, "status": "idle", "synced": "2026-10-18T19:05:00Z" ("" /qb not read), -// "rows": [ { "attribute": "Strength", "npc": "...", "count": 3, "status": "Ready", "eta": "", -// "ready": true, "exact": true } ] } exact = from /myquests (else /qb estimates) -// GuardianCommand verbs (ASCII): handin | stop | refresh | chat on|off | auto on|off | buy on|off -// Auto hand-in and buying a missing Temple item run inside RynthILT whatever the reader shows. -// ============================================================================ - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Runtime.InteropServices; -using System.Text; -using System.Text.Json; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.Shared; - -[StructLayout(LayoutKind.Sequential)] -public unsafe struct RynthIltDataApiV1 -{ - public const string InterfaceName = "RynthILT.Data"; - public const uint InterfaceVersion = 3; - - /// The size of a version-1 table (everything before GetPetBreedingJson) on this platform. - public static uint V1Size - { - get - { - RynthIltDataApiV1 t = default; - return (uint)((byte*)&t.GetPetBreedingJson - (byte*)&t); - } - } - - /// The size of a version-2 table (everything before GetGuardianJson) on this platform. - public static uint V2Size - { - get - { - RynthIltDataApiV1 t = default; - return (uint)((byte*)&t.GetGuardianJson - (byte*)&t); - } - } - - public uint Version; // InterfaceVersion of the table RynthILT filled; 0 once it has shut down - public uint StructSize; // sizeof(RynthIltDataApiV1) as RynthILT built it - - /// - /// GetCharmsJson(buffer, capacity): the charms JSON (UTF-8, NUL-terminated) when it fits; returns - /// its length without the NUL (capacity or more = too small, nothing written; 0 = nothing to report). - /// - public delegate* unmanaged[Cdecl] GetCharmsJson; - - /// GetBankJson(buffer, capacity): the bank JSON, same contract as GetCharmsJson. - public delegate* unmanaged[Cdecl] GetBankJson; - - /// - /// ToggleCharm(objectId): uses the carried charm with that id (a "toggleId" from the charms JSON). - /// RynthILT checks it is one of the player's charms before using it. 1 = queued, 0 = refused. - /// - public delegate* unmanaged[Cdecl] ToggleCharm; - - /// BankCommand(utf8 verb line): queues a bank verb (header above). 1 = queued, 0 = refused. - public delegate* unmanaged[Cdecl] BankCommand; - - // ── Version 2 ─────────────────────────────────────────────────────────── - - /// GetPetBreedingJson(buffer, capacity): the pet breeding JSON, same contract as GetCharmsJson. - public delegate* unmanaged[Cdecl] GetPetBreedingJson; - - /// PetBreedingCommand(utf8 verb line): queues a breeding verb (header above). 1 = queued, 0 = refused. - public delegate* unmanaged[Cdecl] PetBreedingCommand; - - // ── Version 3 ─────────────────────────────────────────────────────────── - - /// GetGuardianJson(buffer, capacity): the Temple guardian JSON, same contract as GetCharmsJson. - public delegate* unmanaged[Cdecl] GetGuardianJson; - - /// GuardianCommand(utf8 verb line): queues a guardian verb (header above). 1 = queued, 0 = refused. - public delegate* unmanaged[Cdecl] GuardianCommand; -} - -/// -/// A reader of "RynthILT.Data". Looks the table up through the host, -/// re-queried while RynthILT is missing or after it unloads (Version 0), and copies a JSON out on -/// request. Pump thread only. -/// -public sealed unsafe class RynthIltDataClient -{ - private const long RequeryMs = 10_000; - private const int MaxBuffer = 256 * 1024; - private const string PluginName = "RynthILT"; - - private RynthIltDataApiV1* _table; - private long _nextQueryAt; - private byte[] _buffer = new byte[8192]; - - /// RynthILT answered with the table (last lookup). - public bool Connected => _table != null && _table->Version >= 1; - - /// The charms JSON now ("" without RynthILT). - public string ReadCharms(RynthCoreHost host, long now) - { - RynthIltDataApiV1* t = Table(host, now); - return t == null || t->GetCharmsJson == null ? "" : Read(t->GetCharmsJson); - } - - /// The bank JSON now ("" without RynthILT). - public string ReadBank(RynthCoreHost host, long now) - { - RynthIltDataApiV1* t = Table(host, now); - return t == null || t->GetBankJson == null ? "" : Read(t->GetBankJson); - } - - /// The pet breeding JSON now ("" without a RynthILT that has the tracker). - public string ReadPetBreeding(RynthCoreHost host, long now) - { - RynthIltDataApiV1* t = Table(host, now); - return !HasPetBreeding(t) || t->GetPetBreedingJson == null ? "" : Read(t->GetPetBreedingJson); - } - - /// The loaded RynthILT has the breeding tracker (table version 2 or later). - public bool PetBreedingSupported => HasPetBreeding(_table); - - /// Queues a breeding verb line (see the header). False without RynthILT or when it refused. - public bool PetBreedingCommand(RynthCoreHost host, long now, string verbLine) - { - RynthIltDataApiV1* t = Table(host, now); - if (!HasPetBreeding(t) || t->PetBreedingCommand == null || string.IsNullOrWhiteSpace(verbLine)) return false; - byte[] bytes = Encoding.UTF8.GetBytes(verbLine + "\0"); - try - { - fixed (byte* p = bytes) return t->PetBreedingCommand(p) == 1; - } - catch { return false; } - } - - private static bool HasPetBreeding(RynthIltDataApiV1* t) - => t != null && t->Version >= 2 && t->StructSize >= RynthIltDataApiV1.V2Size; - - /// The Temple guardian JSON now ("" without a RynthILT that has it, version 3). - public string ReadGuardian(RynthCoreHost host, long now) - { - RynthIltDataApiV1* t = Table(host, now); - return !HasGuardian(t) || t->GetGuardianJson == null ? "" : Read(t->GetGuardianJson); - } - - /// The loaded RynthILT has the guardian functions (table version 3 or later). - public bool GuardianSupported => HasGuardian(_table); - - /// Queues a guardian verb line (see the header). False without RynthILT or when it refused. - public bool GuardianCommand(RynthCoreHost host, long now, string verbLine) - { - RynthIltDataApiV1* t = Table(host, now); - if (!HasGuardian(t) || t->GuardianCommand == null || string.IsNullOrWhiteSpace(verbLine)) return false; - byte[] bytes = Encoding.UTF8.GetBytes(verbLine + "\0"); - try - { - fixed (byte* p = bytes) return t->GuardianCommand(p) == 1; - } - catch { return false; } - } - - private static bool HasGuardian(RynthIltDataApiV1* t) - => t != null && t->Version >= 3 && t->StructSize >= (uint)sizeof(RynthIltDataApiV1); - - /// Asks RynthILT to use a carried charm. False without RynthILT or when it refused. - public bool ToggleCharm(RynthCoreHost host, long now, uint objectId) - { - RynthIltDataApiV1* t = Table(host, now); - if (t == null || t->ToggleCharm == null || objectId == 0) return false; - try { return t->ToggleCharm(objectId) == 1; } - catch { return false; } - } - - /// Queues a bank verb line (see the header). False without RynthILT or when it refused. - public bool BankCommand(RynthCoreHost host, long now, string verbLine) - { - RynthIltDataApiV1* t = Table(host, now); - if (t == null || t->BankCommand == null || string.IsNullOrWhiteSpace(verbLine)) return false; - byte[] bytes = Encoding.UTF8.GetBytes(verbLine + "\0"); - try - { - fixed (byte* p = bytes) return t->BankCommand(p) == 1; - } - catch { return false; } - } - - /// The table, re-queried when it is missing or RynthILT has shut down (Version 0). - private RynthIltDataApiV1* Table(RynthCoreHost host, long now) - { - if (_table != null && _table->Version >= 1) return _table; - _table = null; - if (now < _nextQueryAt || !host.HasGetPluginInterface) return null; - _nextQueryAt = now + RequeryMs; - // Version 1 is asked for and a version-1-sized table taken, so an older RynthILT still answers. - var p = (RynthIltDataApiV1*)host.GetPluginInterface(PluginName, RynthIltDataApiV1.InterfaceName, 1); - if (p != null && p->Version >= 1 && p->StructSize >= RynthIltDataApiV1.V1Size) - _table = p; - return _table; - } - - /// Copies a JSON out, growing the buffer once when RynthILT says it didn't fit. - private string Read(delegate* unmanaged[Cdecl] get) - { - for (int attempt = 0; attempt < 2; attempt++) - { - int len; - try - { - fixed (byte* b = _buffer) len = get(b, _buffer.Length); - } - catch { return ""; } - if (len <= 0) return ""; - if (len < _buffer.Length) return Encoding.UTF8.GetString(_buffer, 0, len); - if (len + 1 > MaxBuffer) return ""; - _buffer = new byte[len + 1024]; - } - return ""; - } -} - -/// One registry charm from the charms JSON. -public sealed record IltCharmRow(string Name, string Effect, string Acquired, int Count, int Tier, int MaxTier, - string Active, string Server, string LastSeen, uint ToggleId) -{ - /// Carried now (in the pack or equipped). - public bool Carried => Acquired == "carried"; -} - -/// A Guardian Hand carried now: its object id (the Toggle's id), name, status and the server's switch. -public sealed record IltHandRow(uint Id, string Name, string Active, string Server); - -/// The charms JSON parsed. without RynthILT; every field read leniently. -public sealed class IltCharmsView -{ - public static readonly IltCharmsView None = new(); - - /// RynthILT answered. - public bool Loaded { get; private init; } - /// An Infinite Leaftide world (charms exist). - public bool Available { get; private init; } - public string World { get; private init; } = ""; - public int Acquired { get; private init; } - public int Active { get; private init; } - public IReadOnlyList Charms { get; private init; } = Array.Empty(); - /// The Guardian Hands carried now (none from an older RynthILT). - public IReadOnlyList Hands { get; private init; } = Array.Empty(); - - public static IltCharmsView Parse(string? json) - { - if (string.IsNullOrWhiteSpace(json)) return None; - try - { - using JsonDocument doc = JsonDocument.Parse(json); - JsonElement root = doc.RootElement; - if (root.ValueKind != JsonValueKind.Object) return None; - var rows = new List(); - if (root.TryGetProperty("charms", out JsonElement cs) && cs.ValueKind == JsonValueKind.Array) - { - foreach (JsonElement c in cs.EnumerateArray()) - { - if (c.ValueKind != JsonValueKind.Object) continue; - string name = IltJson.Str(c, "name"); - if (name.Length == 0) continue; - rows.Add(new IltCharmRow(name, IltJson.Str(c, "effect"), IltJson.Str(c, "acquired", "no"), - (int)IltJson.Long(c, "count"), (int)IltJson.Long(c, "tier"), (int)IltJson.Long(c, "maxTier"), - IltJson.Str(c, "active", "unknown"), IltJson.Str(c, "server", "unknown"), IltJson.Str(c, "lastSeen"), - (uint)Math.Clamp(IltJson.Long(c, "toggleId"), 0, uint.MaxValue))); - } - } - var hands = new List(); - foreach (JsonElement h in IltJson.Array(root, "hands")) - { - uint id = (uint)Math.Clamp(IltJson.Long(h, "id"), 0, uint.MaxValue); - if (id == 0) continue; // no id = nothing a Toggle could use - hands.Add(new IltHandRow(id, IltJson.Str(h, "name", "Guardian Hand"), IltJson.Str(h, "active", "unknown"), - IltJson.Str(h, "server", "unknown"))); - } - return new IltCharmsView - { - Loaded = true, - Available = IltJson.Bool(root, "available"), - World = IltJson.Str(root, "world"), - Acquired = (int)IltJson.Long(root, "acquiredCount"), - Active = (int)IltJson.Long(root, "activeCount"), - Charms = rows, - Hands = hands, - }; - } - catch (JsonException) { return None; } - } -} - -/// One character's saved bank balances from the bank JSON. -public sealed record IltBankRow(string Name, bool Current, long Pyreals, long Luminance, long LegendaryKeys, long MythicalKeys, - long EnlightenedCoins, long WeaklyEnlightenedCoins, long PrestigeCoins, DateTime UpdatedUtc); - -/// A bank form choice: its label and whether the amount is a trade-note count. -public sealed record IltBankChoice(string Label, bool Notes); - -/// A trade-note denomination: label and pyreal value. -public sealed record IltBankNote(string Label, long Value); - -/// One logged transfer. -public sealed record IltBankTx(string When, string Type, long Amount, string Currency, string Player); - -/// The bank JSON parsed. without RynthILT; every field read leniently. -public sealed class IltBankView -{ - public static readonly IltBankView None = new(); - - /// RynthILT answered. - public bool Loaded { get; private init; } - /// An Infinite Leaftide world (bank commands exist). - public bool Available { get; private init; } - /// 1 the server has /bank, 0 not, -1 not known yet. - public int Enabled { get; private init; } = -1; - public string World { get; private init; } = ""; - public string Character { get; private init; } = ""; - public string Result { get; private init; } = ""; - public IReadOnlyList Characters { get; private init; } = Array.Empty(); - public IReadOnlyList Deposits { get; private init; } = Array.Empty(); - public IReadOnlyList Withdrawals { get; private init; } = Array.Empty(); - public IReadOnlyList Transfers { get; private init; } = Array.Empty(); - public IReadOnlyList Notes { get; private init; } = Array.Empty(); - public IReadOnlyList Transactions { get; private init; } = Array.Empty(); - - public static IltBankView Parse(string? json) - { - if (string.IsNullOrWhiteSpace(json)) return None; - try - { - using JsonDocument doc = JsonDocument.Parse(json); - JsonElement root = doc.RootElement; - if (root.ValueKind != JsonValueKind.Object) return None; - - var chars = new List(); - foreach (JsonElement c in IltJson.Array(root, "characters")) - { - string name = IltJson.Str(c, "name"); - if (name.Length == 0) continue; - DateTime updated = DateTime.MinValue; - string when = IltJson.Str(c, "updated"); - if (when.Length > 0 - && DateTime.TryParse(when, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t)) - updated = t; - chars.Add(new IltBankRow(name, IltJson.Bool(c, "current"), IltJson.Long(c, "pyreals"), IltJson.Long(c, "luminance"), - IltJson.Long(c, "legendaryKeys"), IltJson.Long(c, "mythicalKeys"), IltJson.Long(c, "enlightenedCoins"), - IltJson.Long(c, "weaklyEnlightenedCoins"), IltJson.Long(c, "prestigeCoins"), updated)); - } - - var deposits = new List(); - if (root.TryGetProperty("deposits", out JsonElement ds) && ds.ValueKind == JsonValueKind.Array) - foreach (JsonElement d in ds.EnumerateArray()) - if (d.ValueKind == JsonValueKind.String) deposits.Add(d.GetString() ?? ""); - - var notes = new List(); - foreach (JsonElement n in IltJson.Array(root, "notes")) - notes.Add(new IltBankNote(IltJson.Str(n, "label"), IltJson.Long(n, "value"))); - - var tx = new List(); - foreach (JsonElement x in IltJson.Array(root, "transactions")) - tx.Add(new IltBankTx(IltJson.Str(x, "when"), IltJson.Str(x, "type"), IltJson.Long(x, "amount"), - IltJson.Str(x, "currency"), IltJson.Str(x, "player"))); - - return new IltBankView - { - Loaded = true, - Available = IltJson.Bool(root, "available"), - Enabled = (int)Math.Clamp(IltJson.Long(root, "enabled", -1), -1, 1), - World = IltJson.Str(root, "world"), - Character = IltJson.Str(root, "character"), - Result = IltJson.Str(root, "result"), - Characters = chars, - Deposits = deposits, - Withdrawals = Choices(root, "withdrawals"), - Transfers = Choices(root, "transfers"), - Notes = notes, - Transactions = tx, - }; - } - catch (JsonException) { return None; } - } - - private static List Choices(JsonElement root, string name) - { - var list = new List(); - foreach (JsonElement c in IltJson.Array(root, name)) - list.Add(new IltBankChoice(IltJson.Str(c, "label"), IltJson.Bool(c, "notes"))); - return list; - } - - /// The bank verb lines (header of this file); pure so the tests check them. - public static string RefreshVerb() => "refresh"; - public static string DepositVerb(int index) => "deposit " + index.ToString(CultureInfo.InvariantCulture); - public static string WithdrawVerb(int index, long amount, int note) - => string.Join(' ', "withdraw", index.ToString(CultureInfo.InvariantCulture), amount.ToString(CultureInfo.InvariantCulture), - note.ToString(CultureInfo.InvariantCulture)); - public static string TransferVerb(int currency, long amount, int note, string recipient) - => string.Join(' ', "transfer", currency.ToString(CultureInfo.InvariantCulture), amount.ToString(CultureInfo.InvariantCulture), - note.ToString(CultureInfo.InvariantCulture), (recipient ?? "").Trim()); -} - -/// One carried combat essence from the pet breeding JSON. -public sealed record IltBreedEssenceRow(int Id, string Name, bool Male, int Tier, int Bond, bool Ready, string Status, long ReadyIn, - int Charges, int ChargesMax, bool Juvenile, string Stage, int Kills, int KillsRequired, - int Mutations, int PotencyMutations, IReadOnlyList Problems, IReadOnlyList Boosters); - -/// A ready stud + dam pairing and its stat mutation odds (0..1). -public sealed record IltBreedPairRow(string Stud, string Dam, double ChanceBest, double ChanceWorst, int InheritMin, int InheritMax); - -/// A breeding supply: count carried, Ivo's price, and the essence ids the server would take it on now. -public sealed record IltBreedSupplyRow(string Key, string Name, string Effect, long Count, long Price, bool Apply, IReadOnlyList Targets); - -/// One breeding rule: its value and where it came from ("seen on server", "ILT profile", "ACE default"). -public sealed record IltBreedRuleRow(string Label, string Value, string Source, string Help); - -/// One breeding event (newest first in the view). -public sealed record IltBreedEventRow(string When, string Kind, string Text); - -/// The last "@breed-debug" reply: when, the switch, where you were, the room check, your pet, partners nearby. -public sealed record IltBreedDebugRow(string When, string Enabled, string Location, string Match, string Pet, string Sex, int Partners); - -/// The pet breeding JSON parsed. without RynthILT; every field read leniently. -public sealed class IltBreedingView -{ - public static readonly IltBreedingView None = new(); - - /// RynthILT answered. - public bool Loaded { get; private init; } - public bool Available { get; private init; } - public string World { get; private init; } = ""; - /// "on", "off" or "unknown": the server's pet breeding switch as RynthILT knows it. - public string Enabled { get; private init; } = "unknown"; - public string Maturity { get; private init; } = "unknown"; - public string Bond { get; private init; } = "unknown"; - public string Room { get; private init; } = ""; - /// Free main-pack slots (-1 unknown). - public int FreeSlots { get; private init; } = -1; - public string Message { get; private init; } = ""; - public IReadOnlyList Essences { get; private init; } = Array.Empty(); - public IReadOnlyList Pairs { get; private init; } = Array.Empty(); - public IReadOnlyList Supplies { get; private init; } = Array.Empty(); - public IReadOnlyList Rules { get; private init; } = Array.Empty(); - public IReadOnlyList Events { get; private init; } = Array.Empty(); - public IltBreedDebugRow? Debug { get; private init; } - - public static IltBreedingView Parse(string? json) - { - if (string.IsNullOrWhiteSpace(json)) return None; - try - { - using JsonDocument doc = JsonDocument.Parse(json); - JsonElement root = doc.RootElement; - if (root.ValueKind != JsonValueKind.Object) return None; - - var essences = new List(); - foreach (JsonElement e in IltJson.Array(root, "essences")) - { - string name = IltJson.Str(e, "name"); - if (name.Length == 0) continue; - essences.Add(new IltBreedEssenceRow((int)IltJson.Long(e, "id"), name, IltJson.Str(e, "sex") == "M", - (int)IltJson.Long(e, "tier"), (int)IltJson.Long(e, "bond"), IltJson.Bool(e, "ready"), IltJson.Str(e, "status"), - IltJson.Long(e, "readyIn"), (int)IltJson.Long(e, "charges"), (int)IltJson.Long(e, "chargesMax"), - IltJson.Bool(e, "juvenile"), IltJson.Str(e, "stage"), (int)IltJson.Long(e, "kills"), (int)IltJson.Long(e, "killsRequired"), - (int)IltJson.Long(e, "mutations"), (int)IltJson.Long(e, "potencyMutations"), - IltJson.Strings(e, "problems"), IltJson.Strings(e, "boosters"))); - } - - var pairs = new List(); - foreach (JsonElement p in IltJson.Array(root, "pairs")) - pairs.Add(new IltBreedPairRow(IltJson.Str(p, "stud"), IltJson.Str(p, "dam"), IltJson.Double(p, "chanceBest"), - IltJson.Double(p, "chanceWorst"), (int)IltJson.Long(p, "inheritMin"), (int)IltJson.Long(p, "inheritMax"))); - - var supplies = new List(); - foreach (JsonElement s in IltJson.Array(root, "supplies")) - { - var targets = new List(); - if (s.TryGetProperty("targets", out JsonElement ts) && ts.ValueKind == JsonValueKind.Array) - foreach (JsonElement t in ts.EnumerateArray()) - if (t.ValueKind == JsonValueKind.Number && t.TryGetInt32(out int id)) targets.Add(id); - supplies.Add(new IltBreedSupplyRow(IltJson.Str(s, "key"), IltJson.Str(s, "name"), IltJson.Str(s, "effect"), - IltJson.Long(s, "count"), IltJson.Long(s, "price"), IltJson.Bool(s, "apply"), targets)); - } - - var rules = new List(); - foreach (JsonElement r in IltJson.Array(root, "rules")) - rules.Add(new IltBreedRuleRow(IltJson.Str(r, "label"), IltJson.Str(r, "value"), IltJson.Str(r, "source"), IltJson.Str(r, "help"))); - - var events = new List(); - foreach (JsonElement ev in IltJson.Array(root, "events")) - events.Add(new IltBreedEventRow(IltJson.Str(ev, "when"), IltJson.Str(ev, "kind"), IltJson.Str(ev, "text"))); - - IltBreedDebugRow? debug = null; - if (root.TryGetProperty("debug", out JsonElement d) && d.ValueKind == JsonValueKind.Object) - debug = new IltBreedDebugRow(IltJson.Str(d, "when"), IltJson.Str(d, "enabled", "unknown"), IltJson.Str(d, "location"), - IltJson.Str(d, "match"), IltJson.Str(d, "pet"), IltJson.Str(d, "sex"), (int)IltJson.Long(d, "partners", -1)); - - return new IltBreedingView - { - Loaded = true, - Available = IltJson.Bool(root, "available"), - World = IltJson.Str(root, "world"), - Enabled = IltJson.Str(root, "enabled", "unknown"), - Maturity = IltJson.Str(root, "maturity", "unknown"), - Bond = IltJson.Str(root, "bond", "unknown"), - Room = IltJson.Str(root, "room"), - FreeSlots = (int)IltJson.Long(root, "freeSlots", -1), - Message = IltJson.Str(root, "message"), - Essences = essences, - Pairs = pairs, - Supplies = supplies, - Rules = rules, - Events = events, - Debug = debug, - }; - } - catch (JsonException) { return None; } - } - - /// The breeding verb lines (header of this file); pure so the tests check them. - public static string RefreshVerb() => "refresh"; - public static string DebugVerb() => "debug"; - public static string DanceVerb() => "dance"; - public static string ApplyVerb(string supplyKey, int essenceId) - => string.Join(' ', "apply", (supplyKey ?? "").Trim(), essenceId.ToString(CultureInfo.InvariantCulture)); -} - -/// One Temple attribute turn-in from the guardian JSON. -public sealed record IltGuardianRow(string Attribute, string Npc, int Count, string Status, string Eta, bool Ready, bool Exact); - -/// The Temple guardian JSON parsed. without RynthILT; every field read leniently. -public sealed class IltGuardianView -{ - public static readonly IltGuardianView None = new(); - - /// RynthILT answered. - public bool Loaded { get; private init; } - public bool Available { get; private init; } - public string World { get; private init; } = ""; - /// Translate the guardians' tells as they arrive. - public bool Chat { get; private init; } - /// Give the answer item to the guardian automatically after a chat answer. - public bool Auto { get; private init; } - /// Buy a missing Temple item from the nearest vendor first. - public bool Buy { get; private init; } - public int CooldownHours { get; private init; } - public string Answer { get; private init; } = ""; - public string Npc { get; private init; } = ""; - /// Seconds since the last answer (-1 none yet). - public long AnswerAgeSec { get; private init; } = -1; - public string Heard { get; private init; } = ""; - /// A hand-in is running. - public bool Running { get; private init; } - public string Status { get; private init; } = ""; - /// When /qb was last read (MinValue never). - public DateTime SyncedUtc { get; private init; } = DateTime.MinValue; - public IReadOnlyList Rows { get; private init; } = Array.Empty(); - - public static IltGuardianView Parse(string? json) - { - if (string.IsNullOrWhiteSpace(json)) return None; - try - { - using JsonDocument doc = JsonDocument.Parse(json); - JsonElement root = doc.RootElement; - if (root.ValueKind != JsonValueKind.Object) return None; - var rows = new List(); - foreach (JsonElement r in IltJson.Array(root, "rows")) - { - string attr = IltJson.Str(r, "attribute"); - if (attr.Length == 0) continue; - rows.Add(new IltGuardianRow(attr, IltJson.Str(r, "npc"), (int)IltJson.Long(r, "count"), IltJson.Str(r, "status"), - IltJson.Str(r, "eta"), IltJson.Bool(r, "ready"), IltJson.Bool(r, "exact"))); - } - DateTime synced = DateTime.MinValue; - string when = IltJson.Str(root, "synced"); - if (when.Length > 0 - && DateTime.TryParse(when, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t)) - synced = t; - return new IltGuardianView - { - Loaded = true, - Available = IltJson.Bool(root, "available"), - World = IltJson.Str(root, "world"), - Chat = IltJson.Bool(root, "chat"), - Auto = IltJson.Bool(root, "auto"), - Buy = IltJson.Bool(root, "buy"), - CooldownHours = (int)IltJson.Long(root, "cooldownHours"), - Answer = IltJson.Str(root, "answer"), - Npc = IltJson.Str(root, "npc"), - AnswerAgeSec = IltJson.Long(root, "answerAgeSec", -1), - Heard = IltJson.Str(root, "heard"), - Running = IltJson.Bool(root, "running"), - Status = IltJson.Str(root, "status"), - SyncedUtc = synced, - Rows = rows, - }; - } - catch (JsonException) { return None; } - } - - /// The guardian verb lines (header of this file); pure so the tests check them. - public static string HandInVerb() => "handin"; - public static string StopVerb() => "stop"; - public static string RefreshVerb() => "refresh"; - /// "chat on", "auto off", "buy on": is chat, auto or buy. - public static string SwitchVerb(string name, bool on) => (name ?? "").Trim().ToLowerInvariant() + (on ? " on" : " off"); -} - -/// Lenient JSON field reads shared by the views above. -internal static class IltJson -{ - public static string Str(JsonElement o, string name, string fallback = "") => - o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? fallback : fallback; - - public static bool Bool(JsonElement o, string name) => - o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True; - - public static long Long(JsonElement o, string name, long fallback = 0) => - o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long l) ? l : fallback; - - public static double Double(JsonElement o, string name, double fallback = 0) => - o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out double d) ? d : fallback; - - /// The string items of an array field (other kinds skipped). - public static List Strings(JsonElement o, string name) - { - var list = new List(); - if (!o.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) return list; - foreach (JsonElement e in a.EnumerateArray()) - if (e.ValueKind == JsonValueKind.String) list.Add(e.GetString() ?? ""); - return list; - } - - public static IEnumerable Array(JsonElement o, string name) - { - if (!o.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) yield break; - foreach (JsonElement e in a.EnumerateArray()) - if (e.ValueKind == JsonValueKind.Object) yield return e; - } -} diff --git a/Plugins/Shared/RynthIltHubApi.cs b/Plugins/Shared/RynthIltHubApi.cs deleted file mode 100644 index cdd3e9a..0000000 --- a/Plugins/Shared/RynthIltHubApi.cs +++ /dev/null @@ -1,231 +0,0 @@ -// ============================================================================ -// RynthSuite - Plugins/Shared/RynthIltHubApi.cs -// The "RynthILT.Hub" interface: a server plugin's features as RynthAi's Mini -// Remote shows them (RynthILT's Infinite Leaftide ones; any server plugin may serve -// the same layout as "RynthServer.Hub", which RynthAi asks the active server's owner -// for first). The Mini Remote stays RynthAi's (its window, tab bar, Remote, Pets and -// Crafting tabs) and knows no server's content: the plugin supplies its tabs and the -// Pets tab's sub-tabs, its sections drawn inside RynthAi's surfaces (Remote, Pets, -// Options, menu), its feature bits, texts and mirrored settings, its "/ra" verbs and -// the pet summon-from-empty gate. Field names say ILT for history; the meaning is -// "the plugin's server" (IsIltWorld, GetForceIlt). -// Compiled into both plugins (linked source), so the layout can't drift. -// -// Rules (as the RynthAi.* interfaces, Shared/RynthAiScriptApi.cs): -// - Append-only: new functions go at the end, and Version goes up. -// - Strings are UTF-8, NUL-terminated. -// - Threads: each function says where it may be called. The render-thread ones -// draw into the caller's current ImGui window and context (the engine's cimgui, -// shared by both plugins). -// - Every function returns safely (no exception crosses the boundary), and returns -// 0 / "unknown" once RynthILT has shut down. -// - The table is allocated once per loaded copy of RynthILT and never freed: its -// functions stay callable from the render thread while plugins shut down (a -// plugin DLL is never unloaded, see the engine's PluginManager.PluginsUnloaded). -// Shutdown sets Version to 0; a caller re-queries (host GetPluginInterface) -// when it sees that, after a plugin reload, or every few seconds. -// ============================================================================ - -using System.Runtime.InteropServices; - -namespace RynthCore.Plugin.Shared; - -/// Constants of the "RynthILT.Hub" interface. -public static class RynthIltHub -{ - /// The providing plugin's display name. - public const string PluginName = "RynthILT"; - - /// Tab flag: the Mini Remote shows this tab now (an ILT world, or forced, and the tab is usable). - public const uint TabShown = 1; - /// Tab flag: the server reports the tab's feature on (Character is always available). - public const uint TabAvailable = 2; - - // Sections RynthAi draws through RenderSection (each draws nothing off ILT). - /// Remote tab, Bank section: the ILT bank balances. - public const string SectionRemoteBank = "remote-bank"; - /// Remote tab, Guardian line: the Temple guardian's last answer. - public const string SectionRemoteGuardian = "remote-guardian"; - /// Quests tab: the "Quest bonus (/qb)" list. - public const string SectionQuestBonus = "quests-qb"; - /// Pets tab: the /pets and /shinies logs. - public const string SectionPetLogs = "pets-logs"; - /// - /// Pets tab, Breeding sub-tab: the pet breeding tracker, the sub-tab's whole body (RynthILT 0.3.1+; - /// older copies draw nothing). Since 2026-10-20 RynthAi shows it because GetSubTabs(TabParentPets) - /// lists it (RynthILT: an ILT world unless FeaturePetBreeding is off); older RynthAi decided itself. - /// - public const string SectionPetBreeding = "pets-breeding"; - /// - /// Pets tab, under the roster: the ACECustom pet charms (Summon Essence Refill and its "summon from - /// empty" opt-in, Universal Summoning Mastery, the casting supplies warning). RynthILT 2026-10-20+; - /// it was RynthAi's. Draws its own leading separator; nothing off ILT. - /// - public const string SectionPetCharms = "pets-charms"; - /// Pets tab, under the charms: ACECustom siphon-lens auto-capture (switch, lens, status). As SectionPetCharms. - public const string SectionPetCapture = "pets-capture"; - - /// GetSubTabs parent: RynthAi's Pets tab (its first sub-tab, the roster, is RynthAi's own). - public const string TabParentPets = "pets"; - - /// - /// GetSetting / SetSetting key: the Vaulted Dungeons keeper's master switch (0 off, 1 on; RynthILT's - /// per-character setting since 2026-10-20, RynthAi's profile's before). RynthAi mirrors it into the - /// engine's Settings > Navigation row; -1 (no row) off ILT. - /// - public const string SettingVaultedDungeons = "vaulted-dungeons"; - /// Mini Remote menu, under Infinite Leaftide: why no ILT feature is on, the Force-ILT override, Refresh. - public const string SectionIltStatus = "ilt-status"; - /// Mini Remote menu without RynthCore's server list: RynthILT's own Infinite Leaftide items. - public const string SectionServerMenu = "server-menu"; - /// - /// Remote tab, Stats section, under RynthAi's per-hour lines: the server's own session rates (RynthILT: - /// Enlightened Coins and pyreals per hour). RynthILT 2026-10-20+; RynthAi drew them from GetRates before. - /// - public const string SectionRemoteStats = "remote-stats"; - /// - /// The Remote tab's Options popup, under RynthAi's own section switches: the server's Remote sections' - /// switches (RynthILT: Bank, Guardian answer; saved by RynthILT, which then draws or skips SectionRemoteBank / - /// SectionRemoteGuardian). RynthILT 2026-10-20+; they were RynthAi's huds.json flags. - /// - public const string SectionRemoteOptions = "remote-options"; - - /// GetText id: the tail RynthAi adds to its one-line session report ("" or ", Coins 1.2k/h, Pyr 4.5m/h"). - public const string TextSessionReport = "session-report"; - /// GetText id: the RynthCore server id this plugin's tabs and menu entries belong to ("ilt"). - public const string TextServerId = "server-id"; - - /// Feature keys RynthAi reads (GetFeature). - public const string FeatureQuests = "quests"; - public const string FeaturePetRefill = "pet_refill"; - public const string FeatureUniversalMastery = "universal_mastery"; - /// ACECustom siphon lenses (monster capture into a pet essence). - public const string FeatureMonsterCapture = "monster_capture"; - public const string FeatureRequireComps = "require_spell_comps"; - /// Pet breeding (the Pets tab's Breeding sub-tab is hidden while the server reports it off). - public const string FeaturePetBreeding = "pet_breeding"; -} - -/// One ILT tab as GetTabs hands it out. Blittable. -[StructLayout(LayoutKind.Sequential)] -public unsafe struct IltTabV1 -{ - /// The tab id (UTF-8, NUL-terminated): saved as the Mini Remote's tab, "/ra hub open <id>". - public fixed byte Id[24]; - /// The tab bar label (UTF-8, NUL-terminated). - public fixed byte Label[32]; - /// The size of the tab body (the child it draws in). - public float Width; - public float Height; - /// RynthIltHub.Tab* bits. - public uint Flags; -} - -[StructLayout(LayoutKind.Sequential)] -public unsafe struct RynthIltHubApiV1 -{ - public const string InterfaceName = "RynthILT.Hub"; - public const uint InterfaceVersion = 1; - - /// - /// The same table under a server-neutral name (2026-10-20): RynthAi asks the engine's active server's - /// owner plugin for it first, so any server plugin can offer the Mini Remote tabs, sections and verbs - /// in this layout. RynthILT serves both names. - /// - public const string NeutralInterfaceName = "RynthServer.Hub"; - - /// - /// The table's size up to and including Command, as every RynthILT since the interface's first - /// release fills it. Readers check StructSize against this (not sizeof, which grows as functions - /// are appended) and check for the appended functions with . - /// - public static uint BaseStructSize => (uint)(2 * sizeof(uint) + 9 * sizeof(nint)); - - /// Whether a table RynthILT built is big enough to hold the function at . - public static bool Has(RynthIltHubApiV1* t, int offset) => t != null && t->StructSize >= (uint)(offset + sizeof(nint)); - - /// Byte offset of the n-th function appended after the base table (0 = AllowSummonOnEmpty). - private static int Appended(int n) => (int)BaseStructSize + n * sizeof(nint); - - /// Offset of (for ). - public static int AllowSummonOnEmptyOffset => Appended(0); - /// Offset of . - public static int GetSubTabsOffset => Appended(1); - /// Offset of . - public static int GetSettingOffset => Appended(2); - /// Offset of . - public static int SetSettingOffset => Appended(3); - /// Offset of . - public static int GetTextOffset => Appended(4); - - public uint Version; // InterfaceVersion of the table RynthILT filled; 0 once it has shut down - public uint StructSize; // sizeof(RynthIltHubApiV1) as RynthILT built it - - /// IsIltWorld(): 1 when this world is Infinite Leaftide / ACECustom (or forced). Any thread. - public delegate* unmanaged[Cdecl] IsIltWorld; - - /// GetFeature(key): the server's bit for a feature, -1 unknown, 0 off, 1 on (-1 off ILT). Any thread. - public delegate* unmanaged[Cdecl] GetFeature; - - /// GetRates(coinsPerHour, pyrealsPerHour): ILT session rates; 0 (nothing written) off ILT. Any thread. - public delegate* unmanaged[Cdecl] GetRates; - - /// GetForceIlt(): this character's "Treat this world as ILT" override (1 on). Any thread. - public delegate* unmanaged[Cdecl] GetForceIlt; - - /// SetForceIlt(on): sets that override. Any thread (applied and saved on RynthILT's next tick). - public delegate* unmanaged[Cdecl] SetForceIlt; - - /// - /// GetTabs(tabs, capacity): every ILT tab in tab-bar order with its flags. Writes up to - /// capacity, returns how many there are (tabs null: just the count). Render thread. - /// - public delegate* unmanaged[Cdecl] GetTabs; - - /// RenderTab(id): draws that tab's body into the current (child) window; 1 = drawn. Render thread. - public delegate* unmanaged[Cdecl] RenderTab; - - /// RenderSection(id): draws a RynthIltHub.Section* into the current window; 1 = drawn. Render thread. - public delegate* unmanaged[Cdecl] RenderSection; - - /// - /// Command(text): one of the ILT "/ra" verbs, as typed after "/ra" ("hub bank", "hub attr run", - /// "guardian handin", "bounty show", "rates reset"). RynthILT answers in chat itself. - /// 1 = handled, 0 = not an ILT verb. Pump thread. - /// - public delegate* unmanaged[Cdecl] Command; - - // ── Appended 2026-10-20 (check with Has before calling) ───────────────── - - /// - /// AllowSummonOnEmpty(): 1 when a pet may be summoned from an EMPTY essence because the server - /// refills it (ACECustom's Summon Essence Refill charm is on, the player opted in, and the server - /// confirmed the feature). RynthAi's PetManager hook asks this; 0 off ILT and whenever unsure (an - /// unknown state never spends pyreals). Cached by RynthILT's tick. Any thread. - /// - public delegate* unmanaged[Cdecl] AllowSummonOnEmpty; - - /// - /// GetSubTabs(parent, tabs, capacity): the sub-tabs RynthILT adds to one of RynthAi's tabs - /// (parent RynthIltHub.TabParentPets: the Pets tab's Breeding). Each tab's Id is a section id - /// drawn with RenderSection; Width / Height are 0 (the parent's size). Writes up to capacity, - /// returns how many (tabs null: the count); 0 off ILT or for an unknown parent. Render thread. - /// - public delegate* unmanaged[Cdecl] GetSubTabs; - - /// - /// GetSetting(key): one of the server plugin's settings that another plugin shows (RynthIltHub.Setting*; - /// RynthAi mirrors them into the engine's Settings window). The value, or -1 when the plugin has no - /// such setting to offer now (unknown key, before login, off ILT). Any thread. - /// - public delegate* unmanaged[Cdecl] GetSetting; - - /// SetSetting(key, value): changes that setting (saved by RynthILT); 1 = taken, 0 = not ours / not now. Any thread. - public delegate* unmanaged[Cdecl] SetSetting; - - /// - /// GetText(id, buffer, capacity): a short text RynthAi shows (RynthIltHub.Text*), UTF-8, truncated to - /// capacity. Returns its length; 0 for nothing (unknown id, off ILT). Any thread. - /// - public delegate* unmanaged[Cdecl] GetText; -} diff --git a/Plugins/Shared/RynthIltServerApi.cs b/Plugins/Shared/RynthIltServerApi.cs deleted file mode 100644 index a485b5e..0000000 --- a/Plugins/Shared/RynthIltServerApi.cs +++ /dev/null @@ -1,74 +0,0 @@ -// ============================================================================ -// RynthSuite - Plugins/Shared/RynthIltServerApi.cs -// The "RynthILT.Server" interface: what RynthILT knows about the Infinite Leaftide -// server, for any plugin that wants it without drawing RynthILT's UI (RynthOracle's -// Fellowship tab, for one). One call hands out a JSON snapshot: whether this is an -// ILT world, every Leaftide feature RynthILT supports with the server's state for it, -// and the server's fellowship rules. -// Separate from "RynthILT.Hub" (RynthIltHubApi.cs) so that interface, which RynthAi asks -// for at an exact version, never has to change for this. -// Compiled into RynthILT and its readers (linked source), so the layout can't drift. -// -// Rules (as the other shared interfaces): -// - Append-only: new functions go at the end, and Version goes up. -// - Strings are UTF-8, NUL-terminated. The JSON itself is plain ASCII. -// - Every function returns safely (no exception crosses the boundary). -// - The table is allocated once per loaded copy of RynthILT and never freed; shutdown -// sets Version to 0, and a reader re-queries (host GetPluginInterface) when it sees that. -// -// GetProfileJson payload (every field may be missing on an older RynthILT; read leniently): -// { -// "ilt": true, // ILT world (its world list, or the character's override) -// "world": "InfiniteLeaftide", // the world name the server announced ("" before login) -// "forced": false, // "Treat this world as ILT" is on -// "source": "probe", // where the feature bits came from ("ilt-features", "probe", "") -// "checked": "2026-10-13T21:25:37Z", // last server-options check (UTC), "" = never -// "features": [ { "key": "bank", "label": "Banking", "group": "Character", -// "state": 1, "where": "Mini Remote > Banking tab" }, ... ], -// // state: 1 on, 0 off, -1 not known yet -// "fellowship": { "maxMembers": 29, "zoneShare": 1, "blackjack": 0, "luminanceShare": 1 }, -// "questBonus": { "disabled": false, "generation": 2, "count": 41, "status": "12 completed, 3 incomplete", -// "completed": [ "flag", ... ], "incomplete": [ "flag", ... ] } -// // the /qb list; ILT worlds only (generation 0 = not loaded yet) -// } -// ============================================================================ - -using System.Runtime.InteropServices; - -namespace RynthCore.Plugin.Shared; - -/// Constants of the "RynthILT.Server" interface. -public static class RynthIltServer -{ - /// The providing plugin's display name. - public const string PluginName = "RynthILT"; - - /// Feature state in the profile JSON: the server reports it on. - public const int StateOn = 1; - /// Feature state: the server reports it off. - public const int StateOff = 0; - /// Feature state: not known yet (not checked, not an ILT world, or no RynthILT). - public const int StateUnknown = -1; - - /// A retail fellowship's member limit (what a reader assumes without RynthILT). - public const int RetailFellowshipMax = 9; -} - -[StructLayout(LayoutKind.Sequential)] -public unsafe struct RynthIltServerApiV1 -{ - public const string InterfaceName = "RynthILT.Server"; - public const uint InterfaceVersion = 1; - - public uint Version; // InterfaceVersion of the table RynthILT filled; 0 once it has shut down - public uint StructSize; // sizeof(RynthIltServerApiV1) as RynthILT built it - - /// - /// GetProfileJson(buffer, capacity): writes the profile JSON (UTF-8, NUL-terminated) into - /// buffer when it fits, and returns its length in bytes without the NUL. A return value of - /// capacity or more means nothing was written: call again with a bigger buffer. 0 = nothing - /// to report (RynthILT shutting down). Any thread (it hands out a snapshot RynthILT's pump - /// rebuilds about once a second). - /// - public delegate* unmanaged[Cdecl] GetProfileJson; -} diff --git a/Plugins/Shared/RynthServerHubApi.cs b/Plugins/Shared/RynthServerHubApi.cs new file mode 100644 index 0000000..a5314ef --- /dev/null +++ b/Plugins/Shared/RynthServerHubApi.cs @@ -0,0 +1,212 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/RynthServerHubApi.cs +// The "RynthServer.Hub" interface: a server plugin's part of RynthAi's Mini +// Remote. The Mini Remote stays RynthAi's (its window, tab bar, Remote, Pets and +// Crafting tabs) and knows no server's content: the active server's plugin +// supplies its tabs and the Pets tab's sub-tabs, its sections drawn inside +// RynthAi's surfaces (Remote, Pets, Options, menu), its feature bits, texts and +// mirrored settings, its "/ra" verbs and the pet summon-from-empty gate. +// +// RynthAi asks the plugin that owns RynthCore's active server (plugin API v86, +// GetServerStateJson "activePlugin") for this interface, else the owners of the +// other servers RynthCore lists (a server plugin may follow its own world check). +// A server plugin answers it with the table below; RynthILT also serves the same +// table under its own older name (RynthIltHubApi.cs). +// +// The ids and the layout are the wire format: they kept their values and order +// when the interface was split out of RynthIltHubApi.cs (2026-10-21), so every +// copy of RynthILT since its first release still fits. +// Compiled into RynthAi and the server plugins that serve it (linked source), so +// the layout can't drift. +// +// Rules (as the RynthAi.* interfaces, Shared/RynthAiScriptApi.cs): +// - Append-only: new functions go at the end, and Version goes up. +// - Strings are UTF-8, NUL-terminated. +// - Threads: each function says where it may be called. The render-thread ones +// draw into the caller's current ImGui window and context (the engine's cimgui, +// shared by both plugins). +// - Every function returns safely (no exception crosses the boundary), and returns +// 0 / "unknown" once the serving plugin has shut down. +// - The table is allocated once per loaded copy of the serving plugin and never +// freed: its functions stay callable from the render thread while plugins shut +// down (a plugin DLL is never unloaded, see the engine's +// PluginManager.PluginsUnloaded). Shutdown sets Version to 0; a caller +// re-queries (host GetPluginInterface) when it sees that, after a plugin +// reload, or every few seconds. +// ============================================================================ + +using System.Runtime.InteropServices; + +namespace RynthCore.Plugin.Shared; + +/// Constants of the "RynthServer.Hub" interface (section, tab, text, feature and setting ids). +public static class RynthServerHub +{ + /// Tab flag: the Mini Remote shows this tab now (the plugin's server, or forced, and the tab is usable). + public const uint TabShown = 1; + /// Tab flag: the server reports the tab's feature on. + public const uint TabAvailable = 2; + + // Sections RynthAi draws through RenderSection, each in one of its own surfaces. A plugin draws + // nothing (returns 0) for a section it doesn't have, or off its server. + /// Remote tab, above the rebuff line: the server's bank balances. + public const string SectionRemoteBank = "remote-bank"; + /// Remote tab, under the translate line: a line of the server's own (e.g. a quest NPC's last answer). + public const string SectionRemoteGuardian = "remote-guardian"; + /// Remote tab, Stats section, under RynthAi's per-hour lines: the server's own session rates. + public const string SectionRemoteStats = "remote-stats"; + /// + /// The Remote tab's Options popup, under RynthAi's own section switches: the switches of the server's + /// Remote sections (saved by the plugin, which then draws or skips SectionRemoteBank / SectionRemoteGuardian). + /// + public const string SectionRemoteOptions = "remote-options"; + /// Pets tab, under the roster: the server's pet extras (charms, refills). Draws its own leading separator. + public const string SectionPetCharms = "pets-charms"; + /// Pets tab, under SectionPetCharms: the server's monster capture (as SectionPetCharms). + public const string SectionPetCapture = "pets-capture"; + /// Pets tab, last: the server's pet logs. + public const string SectionPetLogs = "pets-logs"; + /// + /// Mini Remote menu, under the plugin's server (TextServerId) in RynthCore's server list: the plugin's + /// status (why no feature is on, its override, Refresh). The id keeps its first owner's name. + /// + public const string SectionServerStatus = "ilt-status"; + /// Mini Remote menu without RynthCore's server list (an older RynthCore): the plugin's own menu items. + public const string SectionServerMenu = "server-menu"; + + /// GetSubTabs parent: RynthAi's Pets tab (its first sub-tab, the roster, is RynthAi's own). + public const string TabParentPets = "pets"; + + /// GetText id: the tail RynthAi adds to its one-line session report ("" or ", Coins 1.2k/h, Pyr 4.5m/h"). + public const string TextSessionReport = "session-report"; + /// GetText id: the RynthCore server id this plugin's tabs and menu entries belong to. + public const string TextServerId = "server-id"; + + /// Feature key RynthAi reads (GetFeature): the server's /myquests (0 = off: no login refresh). + public const string FeatureQuests = "quests"; + + /// + /// GetSetting / SetSetting key: the server plugin's Vaulted Dungeons switch (0 off, 1 on), which RynthAi + /// mirrors into the engine's Settings > Navigation row; -1 (no row) when the plugin doesn't offer it. + /// + public const string SettingVaultedDungeons = "vaulted-dungeons"; +} + +/// One tab as GetTabs / GetSubTabs hand it out. Blittable. +[StructLayout(LayoutKind.Sequential)] +public unsafe struct ServerHubTabV1 +{ + /// The tab id (UTF-8, NUL-terminated): saved as the Mini Remote's tab, "/ra hub open <id>". + public fixed byte Id[24]; + /// The tab bar label (UTF-8, NUL-terminated). + public fixed byte Label[32]; + /// The size of the tab body (the child it draws in). + public float Width; + public float Height; + /// RynthServerHub.Tab* bits. + public uint Flags; +} + +[StructLayout(LayoutKind.Sequential)] +public unsafe struct RynthServerHubApiV1 +{ + public const string InterfaceName = "RynthServer.Hub"; + public const uint InterfaceVersion = 1; + + /// + /// The table's size up to and including Command, as the interface's first release filled it. + /// Readers check StructSize against this (not sizeof, which grows as functions are appended) and + /// check for the appended functions with . + /// + public static uint BaseStructSize => (uint)(2 * sizeof(uint) + 9 * sizeof(nint)); + + /// Whether a table is big enough to hold the function at . + public static bool Has(RynthServerHubApiV1* t, int offset) => t != null && t->StructSize >= (uint)(offset + sizeof(nint)); + + /// Byte offset of the n-th function appended after the base table (0 = AllowSummonOnEmpty). + private static int Appended(int n) => (int)BaseStructSize + n * sizeof(nint); + + /// Offset of (for ). + public static int AllowSummonOnEmptyOffset => Appended(0); + /// Offset of . + public static int GetSubTabsOffset => Appended(1); + /// Offset of . + public static int GetSettingOffset => Appended(2); + /// Offset of . + public static int SetSettingOffset => Appended(3); + /// Offset of . + public static int GetTextOffset => Appended(4); + + public uint Version; // InterfaceVersion of the table the plugin filled; 0 once it has shut down + public uint StructSize; // sizeof(RynthServerHubApiV1) as the plugin built it + + /// IsServerWorld(): 1 when this world is the plugin's server (or forced there). Any thread. + public delegate* unmanaged[Cdecl] IsServerWorld; + + /// GetFeature(key): the server's bit for a feature, -1 unknown, 0 off, 1 on (-1 off its server). Any thread. + public delegate* unmanaged[Cdecl] GetFeature; + + /// + /// GetRates(first, second): two session rates of the server's (per hour); 0 (nothing written) off its + /// server. Any thread. RynthAi no longer reads it (SectionRemoteStats draws them); kept for the layout. + /// + public delegate* unmanaged[Cdecl] GetRates; + + /// GetForceServer(): this character's "treat this world as the plugin's server" override (1 on). Any thread. + public delegate* unmanaged[Cdecl] GetForceServer; + + /// SetForceServer(on): sets that override. Any thread (applied and saved on the plugin's next tick). + public delegate* unmanaged[Cdecl] SetForceServer; + + /// + /// GetTabs(tabs, capacity): every tab of the plugin's, in tab-bar order with its flags. Writes up to + /// capacity, returns how many there are (tabs null: just the count). Render thread. + /// + public delegate* unmanaged[Cdecl] GetTabs; + + /// RenderTab(id): draws that tab's body into the current (child) window; 1 = drawn. Render thread. + public delegate* unmanaged[Cdecl] RenderTab; + + /// RenderSection(id): draws a RynthServerHub.Section* (or a sub-tab's id) into the current window; 1 = drawn. Render thread. + public delegate* unmanaged[Cdecl] RenderSection; + + /// + /// Command(text): one of the plugin's "/ra" verbs, as typed after "/ra" ("hub bank", "rates reset"). + /// The plugin answers in chat itself. 1 = handled, 0 = not one of its verbs. Pump thread. + /// + public delegate* unmanaged[Cdecl] Command; + + // ── Appended 2026-10-20 (check with Has before calling) ───────────────── + + /// + /// AllowSummonOnEmpty(): 1 when a pet may be summoned from an EMPTY essence because the server + /// refills it (the player opted in and the server confirmed the feature). RynthAi's PetManager + /// hook asks this; 0 off the plugin's server and whenever unsure (an unknown state never spends + /// pyreals). Any thread. + /// + public delegate* unmanaged[Cdecl] AllowSummonOnEmpty; + + /// + /// GetSubTabs(parent, tabs, capacity): the sub-tabs the plugin adds to one of RynthAi's tabs (parent + /// RynthServerHub.TabParentPets). Each tab's Id is a section id drawn with RenderSection; Width / + /// Height are 0 (the parent's size). Writes up to capacity, returns how many (tabs null: the count); + /// 0 off its server or for an unknown parent. Render thread. + /// + public delegate* unmanaged[Cdecl] GetSubTabs; + + /// + /// GetSetting(key): one of the plugin's settings that another plugin shows (RynthServerHub.Setting*; + /// RynthAi mirrors them into the engine's Settings window). The value, or -1 when the plugin has no + /// such setting to offer now (unknown key, before login, off its server). Any thread. + /// + public delegate* unmanaged[Cdecl] GetSetting; + + /// SetSetting(key, value): changes that setting (saved by the plugin); 1 = taken, 0 = not ours / not now. Any thread. + public delegate* unmanaged[Cdecl] SetSetting; + + /// + /// GetText(id, buffer, capacity): a short text RynthAi shows (RynthServerHub.Text*), UTF-8, truncated to + /// capacity. Returns its length; 0 for nothing (unknown id, off its server). Any thread. + /// + public delegate* unmanaged[Cdecl] GetText; +} diff --git a/Plugins/Shared/RynthServerProfileApi.cs b/Plugins/Shared/RynthServerProfileApi.cs index 51cfe46..88f7911 100644 --- a/Plugins/Shared/RynthServerProfileApi.cs +++ b/Plugins/Shared/RynthServerProfileApi.cs @@ -42,8 +42,13 @@ // } ], // "discord": "", "website": "", "wiki": "", "source": "", // "values": { // live numbers for this character on this server ({} when none; -// "voidDotDurationScale": 1.35 // ServerProfileView.Value reads one): RynthConquest's Void DoT -// } // duration rule, which RynthOracle's Void timers apply +// // ServerProfileView.Value reads one; RynthServerProfile.Value*): +// "voidDotDurationScale": 1.35, // RynthConquest's Void DoT duration rule, which RynthOracle's +// // Void timers apply; +// "difficultyTier": 3, // the difficulty tier where the player stands (0 = the unscaled +// // world; absent = the server has no tiers, or hasn't said yet), +// "difficultyHealthPercent": 5 // and the monster health one tier adds, in percent of tier 0's +// } // (RynthAelrynth; RynthAi keeps learned HP and kills per tier) // } // ============================================================================ @@ -62,6 +67,22 @@ public static class RynthServerProfile public const string BottingAllowed = "allowed"; public const string BottingRestricted = "restricted"; public const string BottingForbidden = "forbidden"; + + // "values" keys with a meaning across RynthSuite (a server plugin publishes them with + // ServerPackPlugin.SetProfileValue; a reader takes them from the active server's owner). + + /// + /// The difficulty tier where the player stands: the same monsters (same wcids) at a scaled + /// strength, 0 = the unscaled world. Absent: the server has no tiers (or hasn't sent one yet), + /// and readers behave as at tier 0. Whole numbers. + /// + public const string ValueDifficultyTier = "difficultyTier"; + + /// + /// The monster health one difficulty tier adds, in percent of the tier-0 value (5 = +5% a tier, + /// so tier 3 is 1.15 times tier 0's). Absent with a tier: 0 (health doesn't scale). + /// + public const string ValueDifficultyHealthPercent = "difficultyHealthPercent"; } [StructLayout(LayoutKind.Sequential)] diff --git a/Plugins/Shared/RynthServerQuestPackApi.cs b/Plugins/Shared/RynthServerQuestPackApi.cs new file mode 100644 index 0000000..146148c --- /dev/null +++ b/Plugins/Shared/RynthServerQuestPackApi.cs @@ -0,0 +1,76 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/RynthServerQuestPackApi.cs +// The "RynthServer.QuestPack" interface: a server plugin's own quest list (its +// quests, timers and the retail quests it can't show), for a quest reader such +// as RynthOracle, which merges it into its retail list without knowing the +// server. Added 2026-10-21, when the server packs left RynthOracle for their +// server plugins (Plugins/Shared/ServerPack: Resources\quests..csv). +// RynthCore says which server is active and which plugin owns it (plugin API +// v86, GetServerStateJson: "active", "activePlugin"); the reader asks only that +// plugin for this interface (host GetPluginInterface), so a pack shows only +// while its server is the active one. No interface = no pack (retail quests). +// Compiled into the server plugins and their readers (linked source), so the +// layout can't drift. +// +// Rules (as the other shared interfaces): +// - Append-only: new functions go at the end, and Version goes up. +// - Strings are UTF-8, NUL-terminated. The info JSON is plain ASCII. +// - Every function returns safely (no exception crosses the boundary). +// - The table is allocated once per loaded copy of the plugin and never freed; +// shutdown sets Version to 0, and a reader re-queries when it sees that. +// +// GetPackInfoJson payload (schema 1; read leniently, fields may be added): +// { +// "schema": 1, +// "server": "conquest", // the server's RynthCore id (the reader's override file: quests..csv) +// "tag": "Conquest", // what quest lists call the server: the master list's Server column, +// // and the label a reader shows ("546 Conquest quests") +// "plugin": "RynthConquest", "version": "0.2.0", +// "rows": 546, // data rows in the CSV +// "bytes": 48939, // the CSV's length in UTF-8 bytes (GetPackCsv's answer) +// "revision": 1 // goes up when the plugin's pack changes (read the CSV again) +// } +// +// GetPackCsv payload: the pack as CSV text (UTF-8), the columns of RynthOracle's +// quest list: QuestFlag, Server, Quest, Url, Info, Hint, Repeatable, plus the +// optional MinDelta (seconds), MaxSolves, Source ("set by ...") and NotOnServer +// (TRUE: the retail quest's flag can't be read on this server; hide it there). +// ============================================================================ + +using System.Runtime.InteropServices; + +namespace RynthCore.Plugin.Shared; + +/// Constants of the "RynthServer.QuestPack" interface. +public static class RynthServerQuestPack +{ + /// The info JSON's schema. + public const int Schema = 1; + + /// The longest pack a reader takes (bytes); a bigger one is refused, not cut. + public const int MaxCsvBytes = 8 * 1024 * 1024; +} + +[StructLayout(LayoutKind.Sequential)] +public unsafe struct RynthServerQuestPackApiV1 +{ + public const string InterfaceName = "RynthServer.QuestPack"; + public const uint InterfaceVersion = 1; + + public uint Version; // InterfaceVersion of the table the plugin filled; 0 once it has shut down + public uint StructSize; // sizeof(RynthServerQuestPackApiV1) as the plugin built it + + /// + /// GetPackInfoJson(buffer, capacity): writes the info JSON (UTF-8, NUL-terminated) into buffer + /// when it fits, and returns its length in bytes without the NUL. A return value of capacity or + /// more means nothing was written: call again with a bigger buffer. 0 = no pack (or shutting + /// down). Any thread. + /// + public delegate* unmanaged[Cdecl] GetPackInfoJson; + + /// + /// GetPackCsv(buffer, capacity): the pack CSV, with GetPackInfoJson's buffer rules (the info's + /// "bytes" says how big a buffer it needs). 0 = no pack. Any thread. + /// + public delegate* unmanaged[Cdecl] GetPackCsv; +} diff --git a/Plugins/Shared/RynthUi/RynthIcons.cs b/Plugins/Shared/RynthUi/RynthIcons.cs new file mode 100644 index 0000000..89447b2 --- /dev/null +++ b/Plugins/Shared/RynthUi/RynthIcons.cs @@ -0,0 +1,131 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/RynthUi/RynthIcons.cs (GENERATED: do not edit) +// The Phosphor icons (MIT) baked into the engine's font atlas, by Phosphor's +// names: put one in a label or a button. Written by Tools/gen-rynthui-icons.py +// from RynthCore's ImGui/PhosphorIcons.cs (its Baked list); an icon that isn't +// baked would draw as nothing, so it isn't here. Tools/RynthUi.Tests checks +// this file against the engine's. +// ============================================================================ + +namespace RynthCore.Plugin.Shared.RynthUi; + +internal static class RynthIcons +{ + public const string AppWindow = "\uE5DA"; + public const string ArrowCircleUp = "\uE030"; + public const string ArrowCounterClockwise = "\uE038"; + public const string ArrowDown = "\uE03E"; + public const string ArrowFatDown = "\uE518"; + public const string ArrowFatLinesDown = "\uE524"; + public const string ArrowLeft = "\uE058"; + public const string ArrowRight = "\uE06C"; + public const string ArrowSquareIn = "\uE5DC"; + public const string ArrowSquareOut = "\uE5DE"; + public const string ArrowUp = "\uE08E"; + public const string ArrowsClockwise = "\uE094"; + public const string ArrowsInLineVertical = "\uE532"; + public const string ArrowsOutLineVertical = "\uE536"; + public const string Backpack = "\uE922"; + public const string Bag = "\uE0B0"; + public const string Barbell = "\uE0B6"; + public const string BatteryCharging = "\uE0BA"; + public const string Binoculars = "\uEA64"; + public const string Brain = "\uE74E"; + public const string CaretDown = "\uE136"; + public const string CaretLeft = "\uE138"; + public const string CaretRight = "\uE13A"; + public const string CaretUp = "\uE13C"; + public const string CastleTurret = "\uE9D0"; + public const string ChartBar = "\uE150"; + public const string ChartLineUp = "\uE156"; + public const string ChatCircleText = "\uE16E"; + public const string Check = "\uE182"; + public const string CheckSquare = "\uE186"; + public const string ClipboardText = "\uE198"; + public const string ClockCounterClockwise = "\uE1A0"; + public const string Code = "\uE1BC"; + public const string Coins = "\uE78E"; + public const string Compass = "\uE1C8"; + public const string Copy = "\uE1CA"; + public const string Crosshair = "\uE1D6"; + public const string Crown = "\uE614"; + public const string DotsSixVertical = "\uEAE2"; + public const string DotsThree = "\uE1FE"; + public const string Drop = "\uE210"; + public const string Eraser = "\uE21E"; + public const string Eye = "\uE220"; + public const string FileCode = "\uE914"; + public const string FilePlus = "\uE236"; + public const string Files = "\uE710"; + public const string Fire = "\uE242"; + public const string Flask = "\uE79E"; + public const string FloppyDisk = "\uE248"; + public const string Footprints = "\uEA88"; + public const string Funnel = "\uE266"; + public const string Gear = "\uE270"; + public const string Gift = "\uE276"; + public const string GlobeHemisphereWest = "\uE28C"; + public const string GraduationCap = "\uE62C"; + public const string Hammer = "\uE80E"; + public const string Heart = "\uE2A8"; + public const string HeartBreak = "\uEBE8"; + public const string Heartbeat = "\uE2AC"; + public const string Hourglass = "\uE2B2"; + public const string HourglassMedium = "\uE2B8"; + public const string Info = "\uE2CE"; + public const string Keyboard = "\uE2D8"; + public const string Knife = "\uE636"; + public const string Leaf = "\uE2DA"; + public const string Lightning = "\uE2DE"; + public const string ListChecks = "\uEADC"; + public const string Lock = "\uE2FA"; + public const string LockOpen = "\uE306"; + public const string MagicWand = "\uE6B6"; + public const string MagnifyingGlass = "\uE30C"; + public const string MapPin = "\uE316"; + public const string MapPinPlus = "\uE314"; + public const string MapTrifold = "\uE31A"; + public const string Minus = "\uE32A"; + public const string Monitor = "\uE32E"; + public const string NavigationArrow = "\uEADE"; + public const string Package = "\uE390"; + public const string Path = "\uE39C"; + public const string PencilSimple = "\uE3B4"; + public const string Play = "\uE3D0"; + public const string Plus = "\uE3D4"; + public const string PushPin = "\uE3E2"; + public const string Resize = "\uED6E"; + public const string Robot = "\uE762"; + public const string Ruler = "\uE6B8"; + public const string Scales = "\uE750"; + public const string Scissors = "\uEAE0"; + public const string Shield = "\uE40A"; + public const string ShieldSlash = "\uE410"; + public const string ShieldWarning = "\uE412"; + public const string Skull = "\uE916"; + public const string SlidersHorizontal = "\uE434"; + public const string SneakerMove = "\uED60"; + public const string Snowflake = "\uE5AA"; + public const string SortAscending = "\uE444"; + public const string SortDescending = "\uE446"; + public const string Sparkle = "\uE6A2"; + public const string Spiral = "\uE9FA"; + public const string Square = "\uE45E"; + public const string SquaresFour = "\uE464"; + public const string Star = "\uE46A"; + public const string Stop = "\uE46C"; + public const string Storefront = "\uE470"; + public const string Sun = "\uE472"; + public const string Sword = "\uE5BA"; + public const string Target = "\uE47C"; + public const string TerminalWindow = "\uEAE8"; + public const string TextAa = "\uE6EE"; + public const string Trash = "\uE4A6"; + public const string TreasureChest = "\uEDE2"; + public const string TrendDown = "\uE4AC"; + public const string User = "\uE4C2"; + public const string UsersThree = "\uE68E"; + public const string Warning = "\uE4E0"; + public const string Wrench = "\uE5D4"; + public const string X = "\uE4F6"; +} diff --git a/Plugins/Shared/RynthUi/RynthUi.cs b/Plugins/Shared/RynthUi/RynthUi.cs new file mode 100644 index 0000000..96fdce4 --- /dev/null +++ b/Plugins/Shared/RynthUi/RynthUi.cs @@ -0,0 +1,226 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/RynthUi/RynthUi.cs +// The engine's look for a plugin's own windows (RynthCore docs/PLUGIN_WINDOWS.md): +// the player's colour theme and the engine's fonts (plugin API v89, with the +// default theme's colours and ImGui's current font on older engines), and the +// widgets the engine's own faces are made of (FaceKit's flat buttons, icon +// buttons, labels, badges, vital bars), so a plugin's screens look like the +// rest of RynthCore. Icons: RynthIcons (the ones baked into the atlas). +// +// Call RynthUi.Init(Host) once in the plugin's Initialize. Everything else is +// for drawing: AC's render thread, inside RynthPluginRenderEmbed. Colours are +// ImGui's packed ABGR, read each frame (a theme change shows at once). Text +// that isn't a literal goes through SafeImGui. Compiled into each plugin that +// draws (linked source, like SafeImGui.cs and ImGuiNativeBinding.cs). +// ============================================================================ + +using System; +using System.Numerics; +using ImGuiNET; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.Shared.RynthUi; + +internal static unsafe class RynthUi +{ + private static RynthCoreHost? _host; + + /// The plugin's host, once (Initialize). + public static void Init(RynthCoreHost host) => _host = host; + + /// True when the engine hands out its theme and fonts (plugin API v89+). + public static bool Themed => _host?.HasUiTheme == true; + + // ── Colours ────────────────────────────────────────────────────────── + + /// A theme colour (ABGR): the player's, or RynthCore's default theme on an older engine. + public static uint Color(RynthUiColor token) + { + uint fallback = Fallback(token); + return _host is RynthCoreHost h ? h.GetUiColor(token, fallback) : fallback; + } + + public static uint Text => Color(RynthUiColor.Text); + public static uint Mute => Color(RynthUiColor.TextMuted); + /// The accent (teal by default): titles, the current item. + public static uint Accent => Color(RynthUiColor.Accent); + /// The highlight (amber by default): what to notice. + public static uint Highlight => Color(RynthUiColor.Highlight); + public static uint ButtonFill => Color(RynthUiColor.Button); + public static uint Border => Color(RynthUiColor.Border); + public static uint Field => Color(RynthUiColor.Field); + public static uint Selected => Color(RynthUiColor.Selected); + public static uint RowAlt => Color(RynthUiColor.RowAlt); + /// A face's background (an edge-to-edge window paints it itself). + public static uint Background => Color(RynthUiColor.Background); + public static uint AccentFill => Color(RynthUiColor.AccentFill); + public static uint Green => Color(RynthUiColor.Green); + public static uint Red => Color(RynthUiColor.Red); + + /// ARGB (as the colour pickers write it) to ImGui's ABGR. + public static uint Argb(uint argb) => (argb & 0xFF00FF00) | ((argb & 0xFF) << 16) | ((argb >> 16) & 0xFF); + + public static Vector4 Vec(uint abgr) => ImGui.ColorConvertU32ToFloat4(abgr); + + public static uint Lighten(uint abgr) => Scale(abgr, 1.25f, 12); + public static uint Darken(uint abgr) => Scale(abgr, 0.8f, 0); + /// Half as opaque (a disabled control's text). + public static uint Faded(uint abgr) => (abgr & 0x00FFFFFF) | ((abgr >> 25) << 24); + public static uint WithAlpha(uint abgr, uint alpha) => (abgr & 0x00FFFFFF) | (alpha << 24); + + private static uint Scale(uint abgr, float k, int add) + { + uint a = abgr & 0xFF000000; + uint r = (uint)Math.Min(255, (int)((abgr & 0xFF) * k) + add); + uint g = (uint)Math.Min(255, (int)(((abgr >> 8) & 0xFF) * k) + add); + uint b = (uint)Math.Min(255, (int)(((abgr >> 16) & 0xFF) * k) + add); + return a | (b << 16) | (g << 8) | r; + } + + /// RynthCore's default theme (ThemePalette.Default), for engines before v89. + internal static uint Fallback(RynthUiColor token) => Argb(token switch + { + RynthUiColor.Text => 0xFFF2F7FC, + RynthUiColor.TextMuted => 0xFFC8D6E4, + RynthUiColor.Accent => 0xFF26D9E6, + RynthUiColor.Highlight => 0xFFE8B333, + RynthUiColor.Button => 0xFF16283A, + RynthUiColor.Border => 0xFF34587A, + RynthUiColor.Field => 0xFF141F29, + RynthUiColor.Selected => 0xFF1A2E42, + RynthUiColor.RowAlt => 0xFF101822, + RynthUiColor.Background => 0xFF0A0F14, + RynthUiColor.PanelGlass => 0xF212121C, + RynthUiColor.AccentFill => 0xFF264C59, + RynthUiColor.BoxBg => 0xFF0A121A, + RynthUiColor.FrameBg => 0xFF1A2230, + RynthUiColor.FrameHover => 0xFF2A3850, + RynthUiColor.FrameActive => 0xFF34466A, + RynthUiColor.Green => 0xFF33CC66, + RynthUiColor.Red => 0xFFE05A5A, + RynthUiColor.TitleBar => 0xFF1A1A28, + RynthUiColor.WindowBorder => 0xFF008080, + _ => 0xFFFFFFFF, + }); + + // ── Fonts ──────────────────────────────────────────────────────────── + + /// The engine's font at the panel's text size, or ImGui's current font on an older engine. + public static ImFontPtr Font(RynthUiFont font) + { + IntPtr p = _host?.GetUiFont(font) ?? IntPtr.Zero; + return p != IntPtr.Zero ? new ImFontPtr((ImFont*)p) : ImGui.GetFont(); + } + + /// Pushes until the scope is disposed: using (RynthUi.PushFont(RynthUiFont.UiBold11)) { ... }. + public static FontScope PushFont(RynthUiFont font) + { + ImGui.PushFont(Font(font)); + return new FontScope(); + } + + public readonly struct FontScope : IDisposable + { + public void Dispose() => ImGui.PopFont(); + } + + // ── Widgets (FaceKit's, the engine's faces) ────────────────────────── + + /// Coloured text at the cursor. + public static void Label(string text, uint color) + { + ImGui.PushStyleColor(ImGuiCol.Text, color); + ImGui.TextUnformatted(text); + ImGui.PopStyleColor(); + } + + /// A flat bordered button at (screen pixels); true when clicked. + public static bool Button(string id, string label, Vector2 pos, Vector2 size, uint fg, uint bg, + bool enabled = true, bool leftAlign = false, uint border = 0) + { + bool clicked = ButtonFrame(id, pos, size, bg, enabled, border); + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + Vector2 ts = ImGui.CalcTextSize(label); + float tx = leftAlign ? pos.X + 6 : pos.X + (size.X - ts.X) * 0.5f; + dl.PushClipRect(pos, pos + size, true); + dl.AddText(new Vector2(tx, pos.Y + (size.Y - ts.Y) * 0.5f), enabled ? fg : Faded(fg), label); + dl.PopClipRect(); + return clicked; + } + + /// The button's look with an icon (RynthIcons) centred: Ui14 for 20+ px buttons, Ui11 smaller. + public static bool IconButton(string id, string icon, Vector2 pos, Vector2 size, uint fg, uint bg, + bool enabled = true, uint border = 0, RynthUiFont font = RynthUiFont.Ui14) + { + bool clicked = ButtonFrame(id, pos, size, bg, enabled, border); + DrawCentered(ImGui.GetWindowDrawList(), Font(font), icon, pos, size, enabled ? fg : Faded(fg)); + return clicked; + } + + /// Width a button needs for in the current font. + public static float ButtonWidth(string label) => ImGui.CalcTextSize(label).X + 16; + + private static bool ButtonFrame(string id, Vector2 pos, Vector2 size, uint bg, bool enabled, uint border) + { + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + ImGui.SetCursorScreenPos(pos); + bool clicked = ImGui.InvisibleButton(id, size) && enabled; + bool hot = enabled && ImGui.IsItemHovered(); + uint fill = enabled && ImGui.IsItemActive() ? Darken(bg) : hot ? Lighten(bg) : bg; + dl.AddRectFilled(pos, pos + size, fill, 3); + dl.AddRect(pos, pos + size, border != 0 ? border : Border, 3); + return clicked; + } + + /// A small rounded count ("12", "99+") at , tall. + public static float Badge(ImDrawListPtr dl, Vector2 p, float h, string text, uint fill, uint fg) + { + ImFontPtr f = Font(RynthUiFont.Ui9); + float tw = f.CalcTextSizeA(f.FontSize, float.MaxValue, 0, text).X; + float w = tw + 8; + dl.AddRectFilled(p, p + new Vector2(w, h), fill, h * 0.5f); + dl.AddText(f, f.FontSize, p + new Vector2(4, (h - f.FontSize) * 0.5f), fg, text); + return w; + } + + /// + /// A vital bar: (0-1) of filled, with + /// ("300/400") centred in Ui9 when there is room. + /// + public static void VitalBar(ImDrawListPtr dl, Vector2 p, Vector2 size, float fraction, uint fill, uint bg, string? text = null) + { + fraction = float.IsFinite(fraction) ? Math.Clamp(fraction, 0f, 1f) : 0f; + dl.AddRectFilled(p, p + size, bg, 2); + if (fraction > 0) dl.AddRectFilled(p, p + new Vector2(size.X * fraction, size.Y), fill, 2); + if (string.IsNullOrEmpty(text)) return; + ImFontPtr f = Font(RynthUiFont.Ui9); + Vector2 ts = f.CalcTextSizeA(f.FontSize, float.MaxValue, 0, text); + if (ts.X + 4 > size.X || f.FontSize > size.Y + 2) return; + dl.AddText(f, f.FontSize, p + (size - ts) * 0.5f, Text, text); + } + + /// + /// An icon (one glyph) centred in the box at , by the glyph's own bounds + /// (the engine's PhosphorIcons.DrawCentered), at the font's size. + /// + public static void DrawCentered(ImDrawListPtr dl, ImFontPtr font, string glyph, Vector2 min, Vector2 size, uint color) + { + if (string.IsNullOrEmpty(glyph)) return; + float px = font.FontSize; + if (px <= 0) return; + Vector2 centre; + // ImFontGlyph (1.91): a 4-byte bitfield, AdvanceX, then X0 Y0 X1 Y1 (read by offset). + byte* g = font.NativePtr == null ? null : (byte*)ImGuiNative.ImFont_FindGlyphNoFallback(font.NativePtr, glyph[0]); + if (g != null && glyph.Length == 1) + { + float* box = (float*)(g + 8); + centre = new Vector2((box[0] + box[2]) * 0.5f, (box[1] + box[3]) * 0.5f); + } + else + { + centre = font.CalcTextSizeA(px, float.MaxValue, 0f, glyph) * 0.5f; + } + Vector2 at = min + size * 0.5f - centre; + dl.AddText(font, px, new Vector2(MathF.Round(at.X), MathF.Round(at.Y)), color, glyph); + } +} diff --git a/Plugins/Shared/ServerPack/ServerChatRequest.cs b/Plugins/Shared/ServerPack/ServerChatRequest.cs deleted file mode 100644 index 4bd477e..0000000 --- a/Plugins/Shared/ServerPack/ServerChatRequest.cs +++ /dev/null @@ -1,23 +0,0 @@ -// ServerChatRequest.cs - "the server plugin just sent this command": a short time window in which the -// command's reply counts as the plugin's own, so the server's code (ServerPackPlugin.ServerChatText) -// can hide replies to its own requests and still show the same command typed by hand. A time window, -// as RynthOracle has always done it (ported from Oracle of Dereth by Advis Eveldan, MIT): these replies -// carry nothing tying them to the request. Each reply line extends it, so a long reply stays ours to its end. -// Pure: RynthServerPack.Tests covers it. -namespace RynthCore.Plugin.ServerPack; - -internal sealed class ServerChatRequest -{ - public const long WindowMs = 5000; - private long _untilMs; - - public void Sent(long nowMs) => _untilMs = nowMs + WindowMs; - public void Clear() => _untilMs = 0; - public bool Awaiting(long nowMs) => nowMs < _untilMs; - - /// A reply line arrived: keep the window open a little longer. - public void Extend(long nowMs) - { - if (Awaiting(nowMs)) _untilMs = nowMs + 2000 > _untilMs ? nowMs + 2000 : _untilMs; - } -} diff --git a/Plugins/Shared/ServerPack/ServerPackExports.cs b/Plugins/Shared/ServerPack/ServerPackExports.cs deleted file mode 100644 index 4b98af7..0000000 --- a/Plugins/Shared/ServerPack/ServerPackExports.cs +++ /dev/null @@ -1,158 +0,0 @@ -// ServerPackExports.cs - The native exports every server plugin has (compiled into each one). -// UnmanagedCallersOnly entry points can't live in a generic or shared assembly, so each server -// plugin compiles this file itself, around its own ServerPackPlugin. -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Threading; -using RynthCore.PluginCore; -using RynthCore.PluginSdk; - -namespace RynthCore.Plugin.ServerPack; - -public static unsafe class ServerPackExports -{ - private static readonly RynthPluginRuntime Runtime = new(); - - /// The live plugin (null before init and after shutdown). - internal static ServerPackPlugin? Plugin => Runtime.Plugin; - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })] - private static int Init(RynthCoreApiNative* api) => Runtime.Init(api); - - /// - /// Plugin API v68 plugin-to-plugin interfaces: "RynthServer.Profile" v1 (ServerPackInterface), - /// the server's settings for any plugin RynthCore's GetServerStateJson points at this one. - /// - [UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })] - private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version) - { - try - { - string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? ""; - return ServerPackInterface.Query(iface, version); - } - catch - { - return IntPtr.Zero; // an exception crossing UnmanagedCallersOnly would fail-fast the client - } - } - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void Shutdown() - { - try { ServerPackInterface.Release(); } catch { } - Runtime.Shutdown(); - IntPtr old = Interlocked.Exchange(ref _sectionsPtr, IntPtr.Zero); - if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old); - _sectionsJson = null; - } - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetName() => ServerPackPlugin.NamePointer; - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetVersion() => ServerPackPlugin.VersionPointer; - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void Tick() => Runtime.OnTick(); - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void OnLoginComplete() => Runtime.OnLoginComplete(); - - [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void OnLogout() => Runtime.OnLogout(); - - // "/rserver ..." commands. - [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag); - - // Incoming chat, for the server's own code (ServerPackPlugin.ServerChatText). Pump thread. - [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag); - - /// The standalone server card ("/rserver"). Render thread. - [UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void Render() - { - try { Runtime.OnRender(); } - catch { /* an exception crossing UnmanagedCallersOnly would fail-fast the client */ } - } - - /// - /// The engine's plugin-command broker: "servermenu" from RynthCore (2026.10.5.48+). The ANSI - /// strings are copied before returning (the caller frees them); the payload is only parsed, so - /// any thread is fine. - /// - [UnmanagedCallersOnly(EntryPoint = "RynthPluginApplyRemoteCommand", CallConvs = new[] { typeof(CallConvCdecl) })] - public static void ApplyRemoteCommand(IntPtr actionAnsi, IntPtr valueAnsi) - { - try - { - string action = actionAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(actionAnsi) ?? string.Empty) : string.Empty; - if (action.Length == 0 || action.Length > 32) return; - string value = valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty; - Runtime.Plugin?.ApplyRemoteCommand(action, value); - } - catch { /* never let a managed exception cross the native boundary */ } - } - - /// - /// RynthCore's Mini Remote sections: "section:server-<id>" (":popout" added in a popped-out - /// window) draws the server card into the engine's current window, "section:server-<id>.<page>" - /// one of the server's own pages (ServerPackPages). 1 = drawn, 0 = not ready or not ours. - /// - [UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })] - public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight) - { - try - { - if (surface == null) return 0; - string name = Marshal.PtrToStringUTF8((IntPtr)surface) ?? string.Empty; - if (name.EndsWith(":popout", StringComparison.Ordinal)) name = name[..^":popout".Length]; - var plugin = Runtime.Plugin; - if (plugin == null) return 0; - float wantH; - if (name.Equals(ServerPackPlugin.SettingsSurface, StringComparison.Ordinal)) - { - if (!plugin.RenderEmbeddedCard(out wantH)) return 0; - } - else - { - string? page = ServerPackPages.PageIdOf(name, RynthPluginInfo.ServerId); - if (page == null || !plugin.RenderEmbeddedPage(page, out wantH)) return 0; - } - if (wantWidth != null) *wantWidth = width; - if (wantHeight != null) *wantHeight = wantH; - return 1; - } - catch - { - return 0; // an exception crossing UnmanagedCallersOnly would fail-fast the client - } - } - - private static IntPtr _sectionsPtr = IntPtr.Zero; - private static string? _sectionsJson; - - /// - /// RynthCore 2026.10.5.46+: the server and the card's Mini Remote spot (UTF-8 JSON, schema 1). - /// Null before login. An unchanged manifest keeps the same buffer. - /// - [UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSectionsJson", CallConvs = new[] { typeof(CallConvCdecl) })] - public static IntPtr GetSectionsJson() - { - try - { - string? json = Runtime.Plugin?.BuildSectionsJson(); - if (json == null) return IntPtr.Zero; - if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr; - _sectionsJson = json; - IntPtr newPtr = Marshal.StringToCoTaskMemUTF8(json); - IntPtr oldPtr = Interlocked.Exchange(ref _sectionsPtr, newPtr); - if (oldPtr != IntPtr.Zero) Marshal.FreeCoTaskMem(oldPtr); - return newPtr; - } - catch { return IntPtr.Zero; } - } -} diff --git a/Plugins/Shared/ServerPack/ServerPackInfo.cs b/Plugins/Shared/ServerPack/ServerPackInfo.cs deleted file mode 100644 index b7a6d8f..0000000 --- a/Plugins/Shared/ServerPack/ServerPackInfo.cs +++ /dev/null @@ -1,110 +0,0 @@ -// ServerPackInfo.cs - What a server plugin knows about its game server (shared by every server plugin). -// -// Identity (id, name, hosts, world names) comes from the plugin's csproj through RynthPluginInfo, the -// same values the engine reads from the embedded manifest, so detection has one source. The rest is -// what is publicly known about the server (ServerData.cs in each project): connection, rule set, -// summary, links, account limits and the botting policy. Unknown stays empty; nothing is guessed. -// Pure: RynthServerPack.Tests compiles it. -using System; - -namespace RynthCore.Plugin.ServerPack; - -/// What the server's rules say about bots (RynthAi automation). -internal enum BottingPolicy -{ - /// Not published here: check the server's own rules. - Unknown, - Allowed, - /// Allowed with limits (attended only, a client cap, ...): see . - Restricted, - /// The server forbids bots. - Forbidden, -} - -/// A chat command the server adds, and what it does. -internal sealed record ServerCommand(string Command, string What); - -/// -/// A salvage the server's own recipes apply (beyond retail tinkering), shown on the Mini Remote's -/// Crafting tab under "Server tinkering". -/// -/// The Crafting tab: "armor", "melee", "missile", "caster", "jewelry", "items" or "trinkets". -/// The bag's MaterialType (131), e.g. 64 = Steel. -/// What it does, one short line. -/// "tink" (repeatable), "imbue" (one per item) or "once" (one application). -/// Counts toward the item's 10 tinks. -/// The bag's name must contain this (bags that share a material id); "" = any. -/// An int property of the item that reads 2 once this salvage is on it (0 = none). -/// The bag must first be prepared on the chosen tier's Ammunition (its name then carries the tier). -/// Apply order on the tab (lower first); 0 = by kind (imbues, then tinks, then one-application rows). -/// Applied last, and only once the item's tink slots are full. -/// Rows with the same group share one cap per item (); "" = none. -/// The group's combined cap per item (with ). -internal sealed record ServerSalvage(string Bench, int Material, string Effect, string Kind = "tink", - bool UsesTinkSlot = true, string NameMatch = "", int AppliedInt = 0, - bool Prepared = false, int Order = 0, bool AfterCap = false, - string StackGroup = "", int StackCap = 0); - -internal sealed class ServerPackInfo -{ - public ServerPackInfo(string id, string name, string[] hosts, string[] worldNames) - { - Id = (id ?? string.Empty).Trim().ToLowerInvariant(); - Name = string.IsNullOrWhiteSpace(name) ? Id : name.Trim(); - Hosts = hosts ?? Array.Empty(); - WorldNames = worldNames ?? Array.Empty(); - } - - /// The engine's id for the server ("coldeve"); a built-in one ("ilt", "aelrynth") keeps the engine's own detection. - public string Id { get; } - public string Name { get; } - /// Connect hosts (the first is the one players are given). - public string[] Hosts { get; } - /// World names the server announces at login. - public string[] WorldNames { get; } - - public int Port { get; init; } = 9000; - /// "ACE" or "GDLE" (the launcher's emulator setting). - public string Emulator { get; init; } = "ACE"; - /// "PvE" or "PvP". - public string Ruleset { get; init; } = "PvE"; - /// "Stable", "Development", ... as the server list says. - public string Status { get; init; } = string.Empty; - /// The server's own one-paragraph description. - public string Summary { get; init; } = string.Empty; - /// Notable rules and features, one line each. - public string[] Facts { get; init; } = Array.Empty(); - /// Chat commands the server adds (only ones known to exist). - public ServerCommand[] Commands { get; init; } = Array.Empty(); - /// The server's own tinkering salvage (only recipes known to exist); empty = none defined. - public ServerSalvage[] Salvage { get; init; } = Array.Empty(); - /// - /// Jewelry that is a trinket on this server (the Crafting tab's Trinkets bench, not Jewelry): name - /// words, case-insensitive, and words that rule a name out again ("top" but not "topaz"). Empty: - /// the server has no trinkets (retail: every jewelry piece is Jewelry). - /// - public string[] TrinketNames { get; init; } = Array.Empty(); - public string[] TrinketExcept { get; init; } = Array.Empty(); - /// "3 accounts", "3 active characters", ...; empty when not published. - public string AccountLimit { get; init; } = string.Empty; - public BottingPolicy Botting { get; init; } = BottingPolicy.Unknown; - /// The rule in the server's words, when there is one. - public string BottingNote { get; init; } = string.Empty; - public string Discord { get; init; } = string.Empty; - public string Website { get; init; } = string.Empty; - public string Wiki { get; init; } = string.Empty; - /// Where the facts come from, and when they were checked. - public string Source { get; init; } = string.Empty; - - /// "play.coldeve.ac:9000" (the first host), or "" with none. - public string Address => Hosts.Length == 0 ? string.Empty : Hosts[0] + ":" + Port; - - /// The botting line for the card. - public string BottingText => Botting switch - { - BottingPolicy.Allowed => "Allowed" + (BottingNote.Length > 0 ? " - " + BottingNote : string.Empty), - BottingPolicy.Restricted => "Restricted" + (BottingNote.Length > 0 ? " - " + BottingNote : string.Empty), - BottingPolicy.Forbidden => "Forbidden" + (BottingNote.Length > 0 ? " - " + BottingNote : string.Empty), - _ => "Not published here - check the server's rules" + (Discord.Length > 0 ? " (Discord)" : string.Empty), - }; -} diff --git a/Plugins/Shared/ServerPack/ServerPackInterface.cs b/Plugins/Shared/ServerPack/ServerPackInterface.cs deleted file mode 100644 index 1d84a47..0000000 --- a/Plugins/Shared/ServerPack/ServerPackInterface.cs +++ /dev/null @@ -1,91 +0,0 @@ -// ServerPackInterface.cs - A server plugin's side of "RynthServer.Profile" -// (Plugins/Shared/RynthServerProfileApi.cs): the server's settings as JSON (ServerPackProfile) for -// other plugins, answered through RynthPluginQueryInterface (ServerPackExports). -// -// The table is allocated once per loaded copy of the plugin and never freed (a plugin DLL is never -// unloaded); after Release() it reports Version 0 and GetProfileJson answers 0. Before the plugin is -// up, or between characters, the profile still describes the server (active false, no world). -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; -using System.Threading; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.ServerPack; - -internal static unsafe class ServerPackInterface -{ - private static RynthServerProfileApiV1* _table; - private static volatile bool _released; - - /// The last JSON handed out, and what it was built for (rebuilt only when that changes). - private sealed record Snapshot(bool Active, string World, int ValuesRevision, string Json); - private static Snapshot? _last; - - /// The table for (, ), or 0 when it isn't ours. - public static IntPtr Query(string iface, uint version) - { - if (iface != RynthServerProfileApiV1.InterfaceName || version < 1 || version > RynthServerProfileApiV1.InterfaceVersion || _released) - return IntPtr.Zero; - if (_table == null) - { - var t = (RynthServerProfileApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerProfileApiV1)); - t->StructSize = (uint)sizeof(RynthServerProfileApiV1); - t->GetProfileJson = &GetProfileJson; - t->Version = RynthServerProfileApiV1.InterfaceVersion; - _table = t; - } - return (IntPtr)_table; - } - - /// Plugin shutdown: readers see Version 0 and re-query; GetProfileJson answers 0. - public static void Release() - { - _released = true; - if (_table != null) _table->Version = 0; - } - - /// The JSON to hand out now. Any thread: the plugin's state is read through volatile fields. - internal static string CurrentJson(ServerPackPlugin? plugin) - { - ServerPackInfo info = plugin?.Info ?? ServerPackPlugin.StaticInfo; - bool active = plugin?.Active ?? false; - string world = plugin?.World ?? string.Empty; - int valuesRevision = plugin?.ProfileValues.Revision ?? -1; - Snapshot? last = Volatile.Read(ref _last); - if (last != null && last.Active == active && last.World == world && last.ValuesRevision == valuesRevision) return last.Json; - KeyValuePair[] values = plugin != null - ? plugin.ProfileValues.Snapshot(out valuesRevision) - : Array.Empty>(); - string json = ServerPackProfile.BuildJson(info, RynthPluginInfo.Name, RynthPluginInfo.Version, active, world, values); - Volatile.Write(ref _last, new Snapshot(active, world, valuesRevision, json)); - return json; - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GetProfileJson(byte* buffer, int capacity) - { - try - { - if (_released) return 0; - return Write(CurrentJson(ServerPackExports.Plugin), buffer, capacity); - } - catch { return 0; } - } - - /// - /// Copies as NUL-terminated UTF-8 into the caller's buffer when it fits, - /// and returns its byte length either way (length >= capacity: too small, nothing written). - /// - internal static int Write(string json, byte* buffer, int capacity) - { - int length = Encoding.UTF8.GetByteCount(json); - if (buffer == null || capacity <= length) return length; - fixed (char* src = json) - Encoding.UTF8.GetBytes(src, json.Length, buffer, capacity); - buffer[length] = 0; - return length; - } -} diff --git a/Plugins/Shared/ServerPack/ServerPackModel.cs b/Plugins/Shared/ServerPack/ServerPackModel.cs deleted file mode 100644 index b38ad05..0000000 --- a/Plugins/Shared/ServerPack/ServerPackModel.cs +++ /dev/null @@ -1,242 +0,0 @@ -// ServerPackModel.cs - A server plugin's view of "is this my server", and what it tells RynthCore. -// -// RynthCore owns the verdict. Each server plugin declares its server in its Mini Remote sections -// manifest (RynthPluginGetSectionsJson, "servers"), so RynthCore detects it (connect host, then the -// announced world name), applies this character's Auto / On / Off override, and pushes the result -// to the plugin as "servermenu" (RynthCore UI/ServerMenus.cs): -// V id name active 0/1 force auto|on|off detected 0/1 reason -// Other line kinds are RynthAi's menus and are skipped. Until a push arrives (an engine older than -// 2026.10.5.48), the plugin falls back to matching the world name itself. -// -// Pushes arrive on whichever thread sent them; each is parsed into one immutable view and published -// with a single reference write, so the render thread always reads a whole one. -// Pure (no host calls): RynthServerPack.Tests covers it. -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; - -namespace RynthCore.Plugin.ServerPack; - -/// RynthCore's verdict for this plugin's server. -internal sealed record ServerVerdictView(string Name, bool Active, string Force, bool Detected, string Reason); - -internal sealed class ServerPackModel -{ - /// Payloads longer than this are not ours (a push is a few hundred bytes). - public const int MaxPayload = 64 * 1024; - - private readonly ServerPackInfo _info; - private ServerVerdictView? _engine; - private long _engineAtMs; - - public ServerPackModel(ServerPackInfo info) => _info = info; - - public ServerPackInfo Info => _info; - - /// The last RynthCore verdict for this server (null until a push lists it). Any thread. - public ServerVerdictView? Engine => Volatile.Read(ref _engine); - - /// When the last push arrived (Environment.TickCount64), 0 for never. - public long EngineAtMs => Interlocked.Read(ref _engineAtMs); - - /// A RynthCore "servermenu" push. Any thread. False when it was not usable. - public bool ApplyEngine(string? payload, long nowMs) - { - ServerVerdictView? view = ParseEngine(payload, _info.Id, out bool listed); - if (!listed) return false; - Volatile.Write(ref _engine, view); - Interlocked.Exchange(ref _engineAtMs, nowMs); - return true; - } - - /// Logout: the next character's verdict comes fresh. - public void Clear() - { - Volatile.Write(ref _engine, null); - Interlocked.Exchange(ref _engineAtMs, 0); - } - - /// - /// True when this plugin should act: RynthCore's verdict when it sent one, else the world - /// name () against the plugin's own list. - /// - public bool IsActive(string? world) - { - ServerVerdictView? v = Engine; - return v != null ? v.Active : WorldMatches(world, _info.WorldNames); - } - - /// - /// The verdict for in a "servermenu" payload. - /// is false when the payload has no server lines at all (not a push); the view is null when it has - /// some but not this server (RynthCore hasn't read this plugin's manifest yet). - /// - public static ServerVerdictView? ParseEngine(string? payload, string serverId, out bool listed) - { - listed = false; - if (string.IsNullOrEmpty(payload) || payload.Length > MaxPayload || string.IsNullOrEmpty(serverId)) return null; - ServerVerdictView? view = null; - foreach (string raw in payload.Split('\n')) - { - string[] f = raw.TrimEnd('\r').Split('\t'); - if (f[0] != "V" || f.Length < 6) continue; - listed = true; - if (!f[1].Equals(serverId, StringComparison.OrdinalIgnoreCase)) continue; - view = new ServerVerdictView(f[2], f[3] == "1", NormalizeForce(f[4]), f[5] == "1", f.Length >= 7 ? f[6] : string.Empty); - } - return view; - } - - /// "auto", "on" or "off" (anything else reads as auto). - public static string NormalizeForce(string? text) - { - string t = (text ?? string.Empty).Trim().ToLowerInvariant(); - return t is "on" or "off" ? t : "auto"; - } - - /// "/rc server {id} {mode}" for auto / on / off; "" for anything else. - public static string ForceCommand(string serverId, string mode) - { - string m = (mode ?? string.Empty).Trim().ToLowerInvariant(); - if (m is not ("auto" or "on" or "off") || !IsSafeId(serverId)) return string.Empty; - return "/rc server " + serverId + " " + m; - } - - /// True for an id RynthCore accepts in a command: 1-32 of a-z, 0-9 and '-'. - public static bool IsSafeId(string? id) - { - if (string.IsNullOrEmpty(id) || id.Length > 32) return false; - foreach (char c in id) - if (!(c is >= 'a' and <= 'z' || c is >= '0' and <= '9' || c == '-')) return false; - return true; - } - - /// Case-insensitive world-name match, '*' standing for any text (RynthCore's rules). - public static bool WorldMatches(string? world, string[] patterns) - { - if (string.IsNullOrWhiteSpace(world)) return false; - string w = world.Trim(); - foreach (string p in patterns) - if (!string.IsNullOrWhiteSpace(p) && Glob(w, p.Trim())) return true; - return false; - } - - private static bool Glob(string text, string pattern) - { - if (!pattern.Contains('*')) return text.Equals(pattern, StringComparison.OrdinalIgnoreCase); - string[] parts = pattern.Split('*'); - int pos = 0; - for (int i = 0; i < parts.Length; i++) - { - string part = parts[i]; - if (part.Length == 0) continue; - if (i == 0) - { - if (!text.StartsWith(part, StringComparison.OrdinalIgnoreCase)) return false; - pos = part.Length; - continue; - } - if (i == parts.Length - 1) - return text.Length - pos >= part.Length && text.EndsWith(part, StringComparison.OrdinalIgnoreCase); - int at = text.IndexOf(part, pos, StringComparison.OrdinalIgnoreCase); - if (at < 0) return false; - pos = at + part.Length; - } - return true; - } - - // ── RynthPluginGetSectionsJson ──────────────────────────────────────── - - /// The Mini Remote surface of the server card. - public static string SurfaceFor(string serverId) => "section:server-" + serverId; - - /// - /// The Mini Remote section the server cards share: right after Session Stats (core order 0) and - /// before Map (100). Every server plugin declares it the same way; the first declaration wins. - /// - public const string SectionId = "server"; - public const string SectionLabel = "Server"; - public const int SectionOrder = 50; - - /// - /// The plugin's sections manifest (schema 1): its server, for RynthCore to detect, and the server - /// card in the shared "Server" section, shown only while that server is active (detected or - /// forced in RynthCore Options > Diagnostics). The card left the Char section on 2026-10-13: that - /// section is Session Stats now, session stats only. - /// (ServerPackPages, already validated) are the server's own views: - /// primary views of the same section, so each gets a sub-tab there, also only on that server. - /// - public static string BuildSectionsJson(ServerPackInfo info, string pluginName, IReadOnlyList? pages = null) - { - var sb = new StringBuilder(512); - sb.Append("{\"version\":1,\"servers\":[{\"id\":").Append(Q(info.Id)).Append(",\"name\":").Append(Q(info.Name)); - sb.Append(",\"worldNames\":["); - AppendList(sb, info.WorldNames); - sb.Append("],\"hosts\":["); - AppendList(sb, info.Hosts); - sb.Append("]}],\"sections\":[{\"id\":").Append(Q(SectionId)).Append(",\"label\":").Append(Q(SectionLabel)); - sb.Append(",\"order\":").Append(SectionOrder).Append("}],\"contributions\":[{\"section\":").Append(Q(SectionId)); - sb.Append(",\"server\":").Append(Q(info.Id)); - sb.Append(",\"label\":").Append(Q(info.Name + " server (" + pluginName + ")")); - sb.Append(",\"surface\":").Append(Q(SurfaceFor(info.Id))); - sb.Append(",\"primary\":false,\"height\":320,\"enabled\":true,\"tooltip\":"); - sb.Append(Q("What is known about " + info.Name + ": rules, account limits, botting policy, links and setup (" - + pluginName + "; also /rserver).")); - sb.Append(",\"order\":130}"); - if (pages != null) - { - for (int i = 0; i < pages.Count; i++) - { - ServerPage p = pages[i]; - sb.Append(",{\"section\":").Append(Q(SectionId)); - sb.Append(",\"server\":").Append(Q(info.Id)); - sb.Append(",\"label\":").Append(Q(p.Label)); - sb.Append(",\"surface\":").Append(Q(ServerPackPages.SurfaceFor(info.Id, p.Id))); - sb.Append(",\"primary\":true,\"width\":").Append(ServerPackPages.Width).Append(",\"height\":").Append(ServerPackPages.Height); - sb.Append(",\"enabled\":true,\"tooltip\":").Append(Q(p.Tooltip.Length > 0 ? p.Tooltip : p.Label + " (" + pluginName + ")")); - sb.Append(",\"order\":").Append(100 + i).Append('}'); - } - } - sb.Append("]}"); - return sb.ToString(); - } - - private static void AppendList(StringBuilder sb, string[] values) - { - for (int i = 0; i < values.Length; i++) sb.Append(i == 0 ? "" : ",").Append(Q(values[i])); - } - - /// A JSON string literal. - public static string Q(string? s) - { - var sb = new StringBuilder((s?.Length ?? 0) + 2).Append('"'); - foreach (char c in s ?? string.Empty) - { - switch (c) - { - case '"': sb.Append("\\\""); break; - case '\\': sb.Append("\\\\"); break; - case '\n': sb.Append("\\n"); break; - case '\r': sb.Append("\\r"); break; - case '\t': sb.Append("\\t"); break; - default: - if (c < 0x20) sb.Append("\\u").Append(((int)c).ToString("x4")); - else sb.Append(c); - break; - } - } - return sb.Append('"').ToString(); - } - - // ── The launcher side ───────────────────────────────────────────────── - - /// How to set up an account for this server in the RynthCore launcher. - public static string[] LauncherSteps(ServerPackInfo info) => new[] - { - "1. Launcher > Servers > Add: pick \"" + info.Name + "\" under Known server. It fills in " - + (info.Address.Length > 0 ? info.Address : "the host and port") + " (" + info.Emulator + ").", - "2. Launcher > Accounts > Add: choose that server, then the account and character.", - "3. Launch: RynthCore loads this plugin only for clients connecting to " + info.Name + ".", - }; -} diff --git a/Plugins/Shared/ServerPack/ServerPackPages.cs b/Plugins/Shared/ServerPack/ServerPackPages.cs deleted file mode 100644 index a45f327..0000000 --- a/Plugins/Shared/ServerPack/ServerPackPages.cs +++ /dev/null @@ -1,86 +0,0 @@ -// ServerPackPages.cs - Pages a server plugin adds beside its server card (RynthConquest's Conquest and -// Leaderboards pages, RynthAelrynth's Leaderboards, ...). -// -// A server's own features need somewhere to show. The ServerPackPlugin.ServerPages hook lists them -// once, at construction; the shared code then -// * declares each one in the sections manifest as a primary view of the shared "Server" section, -// shown only while this plugin's server is active (contribution "server": ), so RynthCore's -// Mini Remote gives it a sub-tab next to the server card; -// * draws it through RynthPluginRenderEmbed under the surface "section:server-." -// (":popout" added in a popped-out window), into the engine's current window and context; -// * shows the same pages as tabs of the standalone "/rserver" window, after the card. -// Draw runs on the render thread: a page reads its state under its own lock and queues anything it -// sends for the plugin tick (ServerPackPlugin.RunOnTick). -// Pure (no ImGui, no host calls): RynthServerPack.Tests covers it. -using System; -using System.Collections.Generic; - -namespace RynthCore.Plugin.ServerPack; - -/// -/// One page a server plugin adds. is 1-16 of a-z, 0-9 and '-' (part of the -/// surface name); draws the body into the current ImGui window (render thread). -/// -internal sealed record ServerPage(string Id, string Label, string Tooltip, Action Draw); - -internal static class ServerPackPages -{ - /// At most this many pages per plugin (the Mini Remote shows them as one row of tabs). - public const int MaxPages = 6; - /// The longest page id (keeps "section:server-<32-char id>.<page>" under the engine's 64). - public const int MaxIdLength = 16; - /// The engine caps contribution labels at 48 characters. - public const int MaxLabelLength = 48; - /// Page views open at this size in the Mini Remote (it fits the window to the view). - public const int Width = 540, Height = 520; - - /// True for a page id: 1-16 of a-z, 0-9 and '-'. - public static bool IsValidId(string? id) - { - if (string.IsNullOrEmpty(id) || id.Length > MaxIdLength) return false; - foreach (char c in id) - if (!(c is >= 'a' and <= 'z' || c is >= '0' and <= '9' || c == '-')) return false; - return true; - } - - /// "section:server-conquest.bank": the page's surface. - public static string SurfaceFor(string serverId, string pageId) => ServerPackModel.SurfaceFor(serverId) + "." + pageId; - - /// - /// The page id a surface names for this server ("section:server-conquest.bank" -> "bank"), or - /// null for the card, another server's surface or anything else. ":popout" is ignored. - /// - public static string? PageIdOf(string? surface, string serverId) - { - if (string.IsNullOrEmpty(surface)) return null; - string name = surface.EndsWith(":popout", StringComparison.Ordinal) ? surface[..^":popout".Length] : surface; - string prefix = ServerPackModel.SurfaceFor(serverId) + "."; - if (!name.StartsWith(prefix, StringComparison.Ordinal)) return null; - string id = name[prefix.Length..]; - return IsValidId(id) ? id : null; - } - - /// - /// The pages kept from what a plugin listed: valid, unique ids, a label, at most - /// ; each one dropped is reported to . - /// - public static List Validate(IEnumerable? pages, Action? log = null) - { - var kept = new List(); - if (pages == null) return kept; - foreach (ServerPage p in pages) - { - if (p == null) continue; - string why = !IsValidId(p.Id) ? "its id isn't 1-16 of a-z, 0-9 and '-'" - : string.IsNullOrWhiteSpace(p.Label) ? "it has no label" - : p.Draw == null ? "it has nothing to draw" - : kept.Exists(k => k.Id == p.Id) ? "another page has its id" - : kept.Count >= MaxPages ? $"a plugin has at most {MaxPages} pages" - : string.Empty; - if (why.Length > 0) { log?.Invoke($"Page '{p.Id}' left out: {why}."); continue; } - string label = p.Label.Trim(); - kept.Add(p with { Label = label.Length <= MaxLabelLength ? label : label[..MaxLabelLength], Tooltip = p.Tooltip ?? string.Empty }); - } - return kept; - } -} diff --git a/Plugins/Shared/ServerPack/ServerPackPlugin.cs b/Plugins/Shared/ServerPack/ServerPackPlugin.cs deleted file mode 100644 index 754ded7..0000000 --- a/Plugins/Shared/ServerPack/ServerPackPlugin.cs +++ /dev/null @@ -1,397 +0,0 @@ -// ServerPackPlugin.cs - The shared body of every server plugin (RynthColdeve, RynthAelrynth, ...), -// built like RynthILT: one plugin per game server, so each one ships and updates on its own. -// -// What it does for its server: -// * declares the server to RynthCore (RynthPluginGetSectionsJson "servers": its hosts and world -// names), so RynthCore detects it and puts this plugin's views in the right Mini Remote spots -// (contributions with "server": show only while that server is active); -// * shows the server card (ServerPackUi): RynthCore's verdict, this character's override, what is -// known about the server, and how to set an account up for it in the launcher; -// * stays quiet anywhere else. RynthCore usually doesn't even load it there: the embedded manifest -// names the server's hosts, and the engine loads only the plugin for the host the client -// connects to (PluginManifestGate.SelectServerPlugins). -// -// Server-specific features: add files to the server's project implementing the partial hooks below -// (ServerLoginComplete, ServerTick, ServerChatCommand, ...). Unimplemented hooks compile away. -// -// What the shared code gives a server's own features (added 2026-10-20, when RynthOracle's and -// RynthInventory's Conquest and Aelrynth features moved into RynthConquest and RynthAelrynth, so a -// shared plugin carries nothing for one server): -// ServerPages(list) pages of its own (ServerPackPages.cs): sub-tabs of the Mini Remote's -// Server section, only while its server is active, and tabs of the -// /rserver window. Draw runs on the render thread. -// ServerChatText(...) every incoming chat line (pump thread), to read the server's replies -// and hide the ones answering the plugin's own requests (eat). -// ServerChatBar(text) every line sent through the chat bar (AC's thread: note it only), -// to tell the player's typed command from the plugin's own. -// Settings the plugin's own settings file (ServerPackSettings.cs), loaded before -// ServerInitialize; MigrateOnce imports a setting from its old home. -// SetProfileValue(key, n) a live number in its "RynthServer.Profile" ("values"), for other -// plugins that apply a server rule without knowing the server. -// ServerCommandVerbs(list) its own "/rserver " words, handled in ServerChatCommand. -// RunOnTick(action) work for the next tick (a page's button, on the render thread). -// Send(command) a chat command as if typed (pump thread, logged in only); -// LogTagged(text) the engine log, "[RynthConquest] ..."; ChatLine(text) the chat window. -// The tick, chat and command hooks only run while a character is logged in; each -// should check Active itself, since the plugin can be loaded for a world that isn't its server. -// -// Threads: OnTick, login/logout, chat lines and the engine's export calls run on the plugin pump. -// OnChatBarEnter runs on AC's main thread, so it only queues. The card and the pages draw on the -// render thread (OnRender, RynthPluginRenderEmbed) and queue their commands for the tick. -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using ImGuiNET; -using RynthCore.PluginCore; - -namespace RynthCore.Plugin.ServerPack; - -public sealed partial class ServerPackPlugin : RynthPluginBase -{ - internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi(RynthPluginInfo.Name); - internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi( - RynthPluginInfo.Version.Length > 0 ? RynthPluginInfo.Version : "0.1.0"); - - /// The chat command every server plugin answers ("/rserver [show|hide|toggle|info]"). - internal const string ChatCommand = "/rserver"; - - /// The card's surface in RynthCore's Mini Remote sections ("section:server-coldeve"). - internal static readonly string SettingsSurface = ServerPackModel.SurfaceFor(RynthPluginInfo.ServerId); - - private readonly ServerPackModel _model; - private readonly ServerPackUi _ui; - private readonly string _sectionsJson; - // The server's own pages (ServerPages), validated; what was left out is logged at Initialize. - private readonly List _pages; - private readonly List _pageNotes = new(); - private readonly ServerPackSettings _settings = new(ServerPackSettings.DefaultPath(RynthPluginInfo.Name)); - private readonly ServerProfileValues _profileValues = new(); - // RynthCore commands from the card (render thread), run on the next tick. - private readonly ConcurrentQueue _engineCommands = new(); - // "/rserver ..." lines from OnChatBarEnter, run on the next tick. - private readonly ConcurrentQueue _commands = new(); - // The server code's work for the tick (RunOnTick: its pages' buttons). - private readonly ConcurrentQueue _tickActions = new(); - // The server's own "/rserver" verbs (ServerCommandVerbs). - private readonly HashSet _serverVerbs = new(StringComparer.OrdinalIgnoreCase); - private volatile bool _loginComplete; - private volatile string? _world; - private bool _wasActive; - - public ServerPackPlugin() - { - ServerPackInfo info = ServerData.Create(); - _model = new ServerPackModel(info); - var pages = new List(); - ServerPages(pages); - _pages = ServerPackPages.Validate(pages, _pageNotes.Add); - var verbs = new List(); - ServerCommandVerbs(verbs); - foreach (string v in verbs) if (!string.IsNullOrWhiteSpace(v)) _serverVerbs.Add(v.Trim()); - _ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world, _pages); - _sectionsJson = ServerPackModel.BuildSectionsJson(info, RynthPluginInfo.Name, _pages); - } - - internal ServerPackInfo Info => _model.Info; - - private static ServerPackInfo? _staticInfo; - - /// The server's facts before the plugin object exists ("RynthServer.Profile" asked early). - internal static ServerPackInfo StaticInfo => _staticInfo ??= ServerData.Create(); - - /// RynthCore (or the world name) says this is the plugin's server now. - internal bool Active => _loginComplete && _model.IsActive(_world); - - /// The world name the client reports ("" before login). Any thread. - internal string World => _world ?? string.Empty; - - // ── Hooks for a server's own features (implement in the server's project) ── - - partial void ServerInitialize(); - partial void ServerLoginComplete(); - partial void ServerLogout(); - partial void ServerShutdown(); - /// Every plugin tick while logged in; = this is the plugin's server. - partial void ServerTick(bool active); - /// "/rserver <verb> ..." verbs the shared code doesn't know; set handled to stop the help text. - partial void ServerChatCommand(string[] parts, ref bool handled); - /// - /// The server's own "/rserver" verbs (lower case), so "/rserver vault" reaches ServerChatCommand - /// instead of being read as another server's id. Called once, from the constructor. - /// - partial void ServerCommandVerbs(List verbs); - /// Extra lines for "/rserver info". - partial void ServerInfoLines(Action line); - /// The server's own pages (ServerPackPages.cs). Called once, from the constructor (no Host yet). - partial void ServerPages(List pages); - /// - /// An incoming chat line (pump thread, logged in only): set to keep it out of - /// the chat window (it comes in true when an earlier plugin already ate it). - /// - partial void ServerChatText(string text, int chatType, ref bool eat); - /// - /// A line sent through the chat bar, typed or another plugin's command (trimmed), before - /// "/rserver" is looked at. AC's main thread: only note it (interlocked state or a queue). - /// - partial void ServerChatBar(string text); - - // ── What the server's own code uses ────────────────────────────────── - - /// The plugin's settings file (loaded before ServerInitialize). Pump thread. - internal ServerPackSettings Settings => _settings; - - /// The live numbers of the profile ("values"). Any thread. - internal ServerProfileValues ProfileValues => _profileValues; - - /// The pages this plugin draws. - internal IReadOnlyList Pages => _pages; - - /// Publishes a live number in the "RynthServer.Profile" JSON ("values"). Any thread. - internal void SetProfileValue(string key, double value) => _profileValues.Set(key, value); - - /// Runs on the next tick while logged in (dropped at logout). Any thread. - internal void RunOnTick(Action action) - { - if (action != null) _tickActions.Enqueue(action); - } - - /// Sends a chat command as if typed; false when nothing went out. Pump thread. - internal bool Send(string command) - => _loginComplete && !string.IsNullOrWhiteSpace(command) && Host.HasInvokeChatParser && Host.InvokeChatParser(command); - - /// The plugin's log, tagged with its name. - internal void LogTagged(string message) => Host.Log($"[{RynthPluginInfo.Name}] {message}"); - - public override int Initialize() - { - Host.Log($"[{RynthPluginInfo.Name}] Plugin initialized for {Info.Name} ({Info.Id})."); - // The server card draws through the engine's cimgui (and so in its current context, a popped-out - // Mini Remote's included), never a second copy of ImGui (ImGuiNativeBinding.cs). Found and fixed - // by SilentKelpie (rynth PR #12); re-implemented here. - RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log($"[{RynthPluginInfo.Name}] {msg}")); - foreach (string note in _pageNotes) LogTagged(note); - _settings.Load(); - if (_settings.LastError.Length > 0) LogTagged($"Settings ({_settings.FilePath}) not read: {_settings.LastError}; using defaults."); - ServerInitialize(); - return 0; - } - - // Also called on a freshly (re)loaded plugin while already in game. - public override void OnLoginComplete() - { - _loginComplete = true; - _wasActive = false; - RefreshWorld(); - ServerLoginComplete(); - } - - public override void OnLogout() - { - _loginComplete = false; - _world = null; - while (_commands.TryDequeue(out _)) { } - while (_engineCommands.TryDequeue(out _)) { } - while (_tickActions.TryDequeue(out _)) { } - _model.Clear(); - _profileValues.Clear(); - ServerLogout(); - } - - public override void Shutdown() => ServerShutdown(); - - public override void OnTick() - { - if (!_loginComplete) return; - if (_world == null) RefreshWorld(); - while (_commands.TryDequeue(out string[]? parts)) RunCommand(parts); - while (_engineCommands.TryDequeue(out string? command)) - { - if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command)) - ChatLine($"[{RynthPluginInfo.Name}] RynthCore didn't take: " + command); - } - while (_tickActions.TryDequeue(out Action? action)) - { - try { action(); } - catch (Exception ex) { LogTagged($"A queued action failed: {ex.GetType().Name}: {ex.Message}"); } - } - - bool active = Active; - if (active && !_wasActive && Info.Botting == BottingPolicy.Forbidden) - ChatLine($"[{RynthPluginInfo.Name}] {Info.Name} forbids bots: don't run RynthAi's combat, navigation or looting here."); - _wasActive = active; - ServerTick(active); - } - - /// The world name the client reports (the server's own once logged in). - private void RefreshWorld() - { - if (Host.HasGetWorldName && Host.TryGetWorldName(out string w) && !string.IsNullOrWhiteSpace(w)) - _world = w.Trim(); - } - - // ── RynthCore's verdict ────────────────────────────────────────────── - - /// RynthPluginApplyRemoteCommand: "servermenu" from RynthCore. Any thread: parsed and published only. - internal void ApplyRemoteCommand(string action, string value) - { - if (action.Equals("servermenu", StringComparison.OrdinalIgnoreCase)) - _model.ApplyEngine(value, Environment.TickCount64); - } - - /// - /// RynthPluginGetSectionsJson: the server and the card's Mini Remote spot. Always declared - /// (the manifest is static): the engine only collects it once in game, and keeping it across - /// logout and character switches stops the server dropping out of Options > Diagnostics. - /// - internal string? BuildSectionsJson() => _sectionsJson; - - // ── Drawing ────────────────────────────────────────────────────────── - - /// The standalone card window. Render thread. - public override void OnRender() - { - if (!_loginComplete || !_ui.WindowOpen || Host.ImGuiContext == IntPtr.Zero) return; - IntPtr previous = ImGui.GetCurrentContext(); - ImGui.SetCurrentContext(Host.ImGuiContext); - try { _ui.RenderWindow(); } - catch (Exception ex) { Host.Log($"[{RynthPluginInfo.Name}] Server window failed: {ex.Message}"); _ui.WindowOpen = false; } - finally { ImGui.SetCurrentContext(previous); } - } - - /// - /// RynthPluginRenderEmbed "section:server-<id>": the card in RynthCore's Mini Remote, drawn - /// into the engine's current window and context (popped-out windows have their own). - /// is the height it used. False until login. Render thread. - /// - internal bool RenderEmbeddedCard(out float wantHeight) => RenderEmbedded(_ui.RenderBody, "Server card", out wantHeight); - - /// - /// RynthPluginRenderEmbed "section:server-<id>.<page>": one of the server's pages - /// (ServerPages) in RynthCore's Mini Remote. False for a page this plugin doesn't have, or before login. - /// - internal bool RenderEmbeddedPage(string pageId, out float wantHeight) - { - wantHeight = 0; - ServerPage? page = _pages.Find(p => p.Id == pageId); - return page != null && RenderEmbedded(page.Draw, "Page " + page.Label, out wantHeight); - } - - private bool RenderEmbedded(Action draw, string what, out float wantHeight) - { - wantHeight = 0; - if (!_loginComplete) return false; - IntPtr previous = ImGui.GetCurrentContext(); - IntPtr context = previous != IntPtr.Zero ? previous : Host.ImGuiContext; - if (context == IntPtr.Zero) return false; - ImGui.SetCurrentContext(context); - try - { - float startY = ImGui.GetCursorPosY(); - draw(); - wantHeight = MathF.Max(40f, ImGui.GetCursorPosY() - startY + 4f); - return true; - } - catch (Exception ex) - { - Host.Log($"[{RynthPluginInfo.Name}] {what} failed: {ex.Message}"); - return false; - } - finally { ImGui.SetCurrentContext(previous); } - } - - // ── Chat ───────────────────────────────────────────────────────────── - - /// Incoming chat (pump thread): the server's own code reads it (ServerChatText). - public override void OnChatWindowText(string? text, int chatType, ref int eat) - { - if (!_loginComplete || string.IsNullOrEmpty(text)) return; - bool eaten = eat != 0; - ServerChatText(text, chatType, ref eaten); - if (eaten) eat = 1; - } - - // ── Commands ───────────────────────────────────────────────────────── - - public override void OnChatBarEnter(string? text, ref int eat) - { - if (!_loginComplete || string.IsNullOrEmpty(text)) return; - string trimmed = text.Trim(); - ServerChatBar(trimmed); - if (!trimmed.Equals(ChatCommand, StringComparison.OrdinalIgnoreCase) - && !trimmed.StartsWith(ChatCommand + " ", StringComparison.OrdinalIgnoreCase)) - return; - string[] parts = trimmed.Split(' ', StringSplitOptions.RemoveEmptyEntries); - // "/rserver ...": only that server's plugin answers (several load when the host is unknown). - if (parts.Length >= 2 && ServerPackModel.IsSafeId(parts[1].ToLowerInvariant()) && !IsVerb(parts[1])) - { - if (!parts[1].Equals(Info.Id, StringComparison.OrdinalIgnoreCase)) return; - parts = Shift(parts); - } - eat = 1; - _commands.Enqueue(parts); - } - - private bool IsVerb(string word) => - word.ToLowerInvariant() is "show" or "hide" or "toggle" or "info" or "help" or "on" or "off" or "auto" - || _serverVerbs.Contains(word); - - /// Drops the server id: "/rserver coldeve info" -> "/rserver info". - private static string[] Shift(string[] parts) - { - var rest = new string[parts.Length - 1]; - rest[0] = parts[0]; - Array.Copy(parts, 2, rest, 1, parts.Length - 2); - return rest; - } - - private void RunCommand(string[] parts) - { - string verb = parts.Length >= 2 ? parts[1].ToLowerInvariant() : "toggle"; - switch (verb) - { - case "show": - _ui.WindowOpen = true; - return; - case "hide": - _ui.WindowOpen = false; - return; - case "toggle": - _ui.WindowOpen = !_ui.WindowOpen; - return; - case "auto": - case "on": - case "off": - _engineCommands.Enqueue(ServerPackModel.ForceCommand(Info.Id, verb)); - return; - case "info": - PrintInfo(); - return; - } - - bool handled = false; - ServerChatCommand(parts, ref handled); - if (handled) return; - ChatLine($"[{RynthPluginInfo.Name}] {ChatCommand} [show|hide|toggle] - the {Info.Name} server card (also in the Mini Remote's Char section)."); - ChatLine($"[{RynthPluginInfo.Name}] {ChatCommand} info - what is known about {Info.Name}; {ChatCommand} auto|on|off - this character's override."); - } - - private void PrintInfo() - { - string tag = $"[{RynthPluginInfo.Name}] "; - ServerVerdictView? v = _model.Engine; - string verdict = v != null - ? (v.Active ? "on for this world" : "not this world") + (v.Reason.Length > 0 ? " (" + v.Reason + ")" : "") - : (_model.IsActive(_world) ? "this world, by its name" : "not this world, by its name") + " (no RynthCore verdict yet)"; - ChatLine(tag + Info.Name + ": " + verdict); - if (Info.Address.Length > 0) ChatLine(tag + "Address " + Info.Address + " (" + Info.Emulator + ", " + Info.Ruleset + ")"); - if (Info.AccountLimit.Length > 0) ChatLine(tag + "Account limit: " + Info.AccountLimit); - ChatLine(tag + "Botting: " + Info.BottingText); - ServerInfoLines(line => ChatLine(tag + line)); - } - - internal void ChatLine(string text) - { - if (Host.HasWriteToChat) Host.WriteToChat(text, 1); - } -} diff --git a/Plugins/Shared/ServerPack/ServerPackProfile.cs b/Plugins/Shared/ServerPack/ServerPackProfile.cs deleted file mode 100644 index 700c431..0000000 --- a/Plugins/Shared/ServerPack/ServerPackProfile.cs +++ /dev/null @@ -1,252 +0,0 @@ -// ServerPackProfile.cs - A server plugin's settings as JSON, for other plugins ("RynthServer.Profile", -// Plugins/Shared/RynthServerProfileApi.cs, served by ServerPackExports' RynthPluginQueryInterface). -// -// RynthCore's GetServerStateJson (plugin API v86) names the active server and the plugin that owns -// it; a reader (RynthOracle, RynthAi's "/ra server", ...) asks that plugin for this profile to get -// the server's rules without knowing the server: connection, rule set, botting policy, account -// limits, commands, tinkering salvage and links. Everything ServerPackInfo holds, nothing guessed. -// -// The JSON is plain ASCII (anything else is \u-escaped), so a reader can show it in the AC client. -// Pure (no host calls): RynthServerPack.Tests covers it. -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text; - -namespace RynthCore.Plugin.ServerPack; - -/// -/// Live numbers a server plugin publishes in its profile ("values"), for other plugins that apply a -/// server rule without knowing the server: e.g. RynthConquest's "voidDotDurationScale" (how much -/// longer this character's Void damage-over-time lasts there), which RynthOracle's Void timers use. -/// Set from the server's own code (ServerPackPlugin.SetProfileValue), read by the profile interface -/// on any thread; goes up on every change, so the JSON is rebuilt only then. -/// -internal sealed class ServerProfileValues -{ - private readonly object _gate = new(); - private readonly List> _values = new(); - private volatile int _revision; - - /// Goes up whenever a value changes. - public int Revision => _revision; - - /// 1-48 of letters, digits, '.', '_' and '-'. - public static bool IsValidKey(string? key) - { - if (string.IsNullOrEmpty(key) || key.Length > 48) return false; - foreach (char c in key) - if (!(char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or '-')) return false; - return true; - } - - /// Sets (or adds) a value; false for a bad key or a number that isn't finite. Any thread. - public bool Set(string key, double value) - { - if (!IsValidKey(key) || !double.IsFinite(value)) return false; - lock (_gate) - { - int i = _values.FindIndex(v => v.Key == key); - if (i >= 0) - { - if (_values[i].Value.Equals(value)) return true; - _values[i] = new KeyValuePair(key, value); - } - else _values.Add(new KeyValuePair(key, value)); - _revision++; - } - return true; - } - - /// Drops one value (true when it was there). Any thread. - public bool Remove(string key) - { - lock (_gate) - { - int i = _values.FindIndex(v => v.Key == key); - if (i < 0) return false; - _values.RemoveAt(i); - _revision++; - return true; - } - } - - /// Drops every value (logout: the next character publishes its own). Any thread. - public void Clear() - { - lock (_gate) - { - if (_values.Count == 0) return; - _values.Clear(); - _revision++; - } - } - - /// A copy of the values and the revision it belongs to. Any thread. - public KeyValuePair[] Snapshot(out int revision) - { - lock (_gate) - { - revision = _revision; - return _values.ToArray(); - } - } -} - -internal static class ServerPackProfile -{ - /// The profile JSON's schema (RynthServerProfile.Schema). - public const int Schema = 1; - - /// The "botting" value for a policy. - public static string BottingName(BottingPolicy policy) => policy switch - { - BottingPolicy.Allowed => "allowed", - BottingPolicy.Restricted => "restricted", - BottingPolicy.Forbidden => "forbidden", - _ => "unknown", - }; - - /// - /// The profile for : is this plugin's verdict - /// (RynthCore's when it pushed one), the world name the client reports, - /// the live numbers the server's own code published (ServerProfileValues). - /// - public static string BuildJson(ServerPackInfo info, string pluginName, string pluginVersion, bool active, string? world, - IReadOnlyList>? values = null) - { - var sb = new StringBuilder(1024); - sb.Append("{\"schema\":").Append(Schema); - Field(sb, "id", info.Id); - Field(sb, "name", info.Name); - Field(sb, "plugin", pluginName); - Field(sb, "version", pluginVersion); - sb.Append(",\"active\":").Append(active ? "true" : "false"); - Field(sb, "world", world ?? string.Empty); - List(sb, "hosts", info.Hosts); - List(sb, "worldNames", info.WorldNames); - sb.Append(",\"port\":").Append(info.Port); - Field(sb, "emulator", info.Emulator); - Field(sb, "ruleset", info.Ruleset); - Field(sb, "status", info.Status); - Field(sb, "botting", BottingName(info.Botting)); - Field(sb, "bottingNote", info.BottingNote); - Field(sb, "accountLimit", info.AccountLimit); - Field(sb, "summary", info.Summary); - List(sb, "facts", info.Facts); - sb.Append(",\"commands\":["); - for (int i = 0; i < info.Commands.Length; i++) - { - if (i > 0) sb.Append(','); - sb.Append("{\"command\":"); - Str(sb, info.Commands[i].Command); - sb.Append(",\"what\":"); - Str(sb, info.Commands[i].What); - sb.Append('}'); - } - sb.Append(']'); - // Added within schema 1: readers that don't know "salvage" skip it. The optional row fields - // (applied, prepared, order, afterCap, stackGroup + stackCap) are written only when set. - sb.Append(",\"salvage\":["); - for (int i = 0; i < info.Salvage.Length; i++) - { - ServerSalvage s = info.Salvage[i]; - if (i > 0) sb.Append(','); - sb.Append("{\"bench\":"); - Str(sb, s.Bench); - sb.Append(",\"material\":").Append(s.Material); - sb.Append(",\"kind\":"); - Str(sb, s.Kind); - sb.Append(",\"effect\":"); - Str(sb, s.Effect); - sb.Append(",\"slot\":").Append(s.UsesTinkSlot ? "true" : "false"); - sb.Append(",\"nameMatch\":"); - Str(sb, s.NameMatch); - if (s.AppliedInt != 0) sb.Append(",\"applied\":").Append(s.AppliedInt); - if (s.Prepared) sb.Append(",\"prepared\":true"); - if (s.Order != 0) sb.Append(",\"order\":").Append(s.Order); - if (s.AfterCap) sb.Append(",\"afterCap\":true"); - if (!string.IsNullOrEmpty(s.StackGroup)) - { - sb.Append(",\"stackGroup\":"); - Str(sb, s.StackGroup); - sb.Append(",\"stackCap\":").Append(s.StackCap); - } - sb.Append('}'); - } - sb.Append(']'); - // Added within schema 1 (2026-10-20), only when the server has trinkets. - if (info.TrinketNames.Length > 0) - { - sb.Append(",\"trinkets\":{"); - sb.Append("\"names\":["); - for (int i = 0; i < info.TrinketNames.Length; i++) { if (i > 0) sb.Append(','); Str(sb, info.TrinketNames[i]); } - sb.Append("],\"except\":["); - for (int i = 0; i < info.TrinketExcept.Length; i++) { if (i > 0) sb.Append(','); Str(sb, info.TrinketExcept[i]); } - sb.Append("]}"); - } - Field(sb, "discord", info.Discord); - Field(sb, "website", info.Website); - Field(sb, "wiki", info.Wiki); - Field(sb, "source", info.Source); - // Added within schema 1: live numbers for this character on this server ({} when none). - sb.Append(",\"values\":{"); - if (values != null) - { - bool first = true; - foreach (KeyValuePair v in values) - { - if (!ServerProfileValues.IsValidKey(v.Key) || !double.IsFinite(v.Value)) continue; - if (!first) sb.Append(','); - first = false; - Str(sb, v.Key); - sb.Append(':').Append(v.Value.ToString("R", CultureInfo.InvariantCulture)); - } - } - sb.Append('}'); - sb.Append('}'); - return sb.ToString(); - } - - private static void Field(StringBuilder sb, string name, string? value) - { - sb.Append(",\"").Append(name).Append("\":"); - Str(sb, value); - } - - private static void List(StringBuilder sb, string name, string[]? values) - { - sb.Append(",\"").Append(name).Append("\":["); - if (values != null) - { - for (int i = 0; i < values.Length; i++) - { - if (i > 0) sb.Append(','); - Str(sb, values[i]); - } - } - sb.Append(']'); - } - - /// A JSON string literal in plain ASCII (control and non-ASCII characters \u-escaped). - private static void Str(StringBuilder sb, string? s) - { - sb.Append('"'); - foreach (char c in s ?? string.Empty) - { - switch (c) - { - case '"': sb.Append("\\\""); break; - case '\\': sb.Append("\\\\"); break; - case '\n': sb.Append("\\n"); break; - case '\r': sb.Append("\\r"); break; - case '\t': sb.Append("\\t"); break; - default: - if (c < 0x20 || c > 0x7e) sb.Append("\\u").Append(((int)c).ToString("x4")); - else sb.Append(c); - break; - } - } - sb.Append('"'); - } -} diff --git a/Plugins/Shared/ServerPack/ServerPackRefresh.cs b/Plugins/Shared/ServerPack/ServerPackRefresh.cs deleted file mode 100644 index 3887d72..0000000 --- a/Plugins/Shared/ServerPack/ServerPackRefresh.cs +++ /dev/null @@ -1,88 +0,0 @@ -// ServerPackRefresh.cs - The Refresh button a server page starts with, and the status line beside it -// (as RynthOracle's pages have it): the page's own command is asked for again, refused for a few -// seconds after it went out (so the button can't spam the server), and the line waits for the reply -// ("Waiting...", then "Updated hh:mm:ss", or "No reply yet" after a while). -// Render thread: Draw runs inside the page's own lock; the page's refresh callback only decides and -// queues what to send (ServerPackPlugin.RunOnTick). -using System; -using System.Collections.Generic; -using System.Numerics; -using ImGuiNET; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.ServerPack; - -/// What a Refresh did, and (when it asked the server) how to tell the reply has landed. -internal sealed record ServerRefreshResult(string What, Func? Done = null); - -internal sealed class ServerRefreshRow -{ - public const long CooldownMs = 3000; - public const long ReplyWaitMs = 15_000; - public const string TooSoon = "That was just asked for; wait a few seconds before asking again."; - - private static readonly Vector4 Yellow = new(0.95f, 0.85f, 0.35f, 1f); - private static readonly Vector4 Red = new(0.95f, 0.45f, 0.40f, 1f); - - private readonly Dictionary _sent = new(); - private string _scope = string.Empty, _what = string.Empty; - private Func? _done; - private bool _doneSeen; - private long _atMs; - private DateTime _atLocal, _doneLocal; - - /// The same request (by ) twice within is refused. - public bool CoolingDown(string key, long nowMs) - { - if (_sent.TryGetValue(key, out long t) && nowMs - t < CooldownMs) return true; - _sent[key] = nowMs; - return false; - } - - /// Forgets the status line and the cooldowns (logout). - public void Reset() - { - _sent.Clear(); - _scope = _what = string.Empty; - _done = null; - } - - /// - /// The row: Refresh (tooltip ) and, for the page that last refreshed - /// (), what happened. - /// - public void Draw(string scope, string help, Func refresh) - { - long now = Environment.TickCount64; - if (ImGui.SmallButton("Refresh##refresh_" + scope)) - { - ServerRefreshResult r; - try { r = refresh(); } - catch (Exception ex) { r = new ServerRefreshResult("Couldn't refresh: " + ex.Message); } - _scope = scope; - _what = r.What; - _done = r.Done; - _doneSeen = false; - _atMs = now; - _atLocal = DateTime.Now; - } - if (help.Length > 0 && ImGui.IsItemHovered()) SafeImGui.SetTooltip(help); - if (_scope != scope || _what.Length == 0) return; - - ImGui.SameLine(); - if (_done != null && !_doneSeen && _done()) - { - _doneSeen = true; - _doneLocal = DateTime.Now; - } - if (_done != null && !_doneSeen) - { - if (now - _atMs > ReplyWaitMs) SafeImGui.TextColored(Red, "No reply yet. Press Refresh to ask again."); - else SafeImGui.TextColored(Yellow, _what + " Waiting for the reply..."); - } - else if (_done != null) - SafeImGui.TextDisabled($"Updated {_doneLocal:HH:mm:ss}. {_what}"); - else - SafeImGui.TextDisabled($"Refreshed {_atLocal:HH:mm:ss}. {_what}"); - } -} diff --git a/Plugins/Shared/ServerPack/ServerPackSettings.cs b/Plugins/Shared/ServerPack/ServerPackSettings.cs deleted file mode 100644 index 0b9b1ac..0000000 --- a/Plugins/Shared/ServerPack/ServerPackSettings.cs +++ /dev/null @@ -1,158 +0,0 @@ -// ServerPackSettings.cs - A server plugin's own settings file, %APPDATA%\RynthCore\.json -// (rynthconquest.json, ...), for the server's features (ServerPackPlugin.Settings). -// -// Flat named values (true/false, text), written by hand and read with JsonDocument: plugin types -// never go through System.Text.Json's serializer, which roots them across hot reloads. Values the -// plugin doesn't ask for are kept as they were written, so an older or newer copy of the plugin -// never drops another's. MigrateOnce imports settings that used to live elsewhere (another -// plugin's file) exactly once, and remembers that it did. -// Pure (file I/O only): RynthServerPack.Tests covers it. Pump thread only. -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Text.Json; - -namespace RynthCore.Plugin.ServerPack; - -internal sealed class ServerPackSettings -{ - // name -> the value's JSON text, in file order. - private readonly List> _values = new(); - - public ServerPackSettings(string path) => FilePath = path; - - /// %APPDATA%\RynthCore\<plugin name, lower case>.json. - public static string DefaultPath(string pluginName) => Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", pluginName.ToLowerInvariant() + ".json"); - - public string FilePath { get; } - - /// Why the last Load or Save failed ("" when it didn't). - public string LastError { get; private set; } = string.Empty; - - /// Reads the file; a missing or broken one means defaults (the next save rewrites it). - public void Load() - { - _values.Clear(); - LastError = string.Empty; - try - { - if (!File.Exists(FilePath)) return; - using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(FilePath)); - if (doc.RootElement.ValueKind != JsonValueKind.Object) { LastError = "not a JSON object"; return; } - foreach (JsonProperty p in doc.RootElement.EnumerateObject()) - Put(p.Name, p.Value.GetRawText()); - } - catch (Exception ex) - { - _values.Clear(); - LastError = ex.Message; - } - } - - /// Writes the file (through a temporary file, so a crash never leaves half of one). False on failure. - public bool Save() - { - try - { - var sb = new StringBuilder("{\n"); - for (int i = 0; i < _values.Count; i++) - { - sb.Append(" ").Append(Quote(_values[i].Key)).Append(": ").Append(_values[i].Value); - sb.Append(i + 1 < _values.Count ? ",\n" : "\n"); - } - sb.Append("}\n"); - Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!); - string tmp = FilePath + ".tmp"; - File.WriteAllText(tmp, sb.ToString()); - File.Move(tmp, FilePath, overwrite: true); - LastError = string.Empty; - return true; - } - catch (Exception ex) - { - LastError = ex.Message; - return false; - } - } - - public bool Has(string name) => Find(name) >= 0; - - public bool GetBool(string name, bool fallback) - { - int i = Find(name); - return i < 0 ? fallback : _values[i].Value switch { "true" => true, "false" => false, _ => fallback }; - } - - /// Sets a value; true when it changed (the caller saves). - public bool SetBool(string name, bool value) => Put(name, value ? "true" : "false"); - - public string GetString(string name, string fallback) - { - int i = Find(name); - if (i < 0) return fallback; - try - { - using JsonDocument doc = JsonDocument.Parse(_values[i].Value); - return doc.RootElement.ValueKind == JsonValueKind.String ? doc.RootElement.GetString() ?? fallback : fallback; - } - catch (JsonException) { return fallback; } - } - - public bool SetString(string name, string value) => Put(name, Quote(value ?? string.Empty)); - - /// - /// Runs once per settings file: unless is - /// already set, it runs, the marker is set and the file saved. True when it ran now. - /// - public bool MigrateOnce(string marker, Action migrate) - { - if (GetBool(marker, false)) return false; - migrate(this); - SetBool(marker, true); - Save(); - return true; - } - - /// - /// A true/false value from another JSON settings file (an old home of a moved setting), or null - /// when the file, the value or its type isn't there. Never throws. - /// - public static bool? ReadBoolFrom(string path, string name) - { - try - { - if (!File.Exists(path)) return null; - using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path)); - if (doc.RootElement.ValueKind != JsonValueKind.Object || !doc.RootElement.TryGetProperty(name, out JsonElement v)) return null; - return v.ValueKind switch { JsonValueKind.True => true, JsonValueKind.False => false, _ => null }; - } - catch - { - return null; - } - } - - private int Find(string name) - { - for (int i = 0; i < _values.Count; i++) - if (string.Equals(_values[i].Key, name, StringComparison.Ordinal)) return i; - return -1; - } - - private bool Put(string name, string json) - { - int i = Find(name); - if (i >= 0) - { - if (_values[i].Value == json) return false; - _values[i] = new KeyValuePair(name, json); - return true; - } - _values.Add(new KeyValuePair(name, json)); - return true; - } - - private static string Quote(string s) => "\"" + JsonEncodedText.Encode(s).ToString() + "\""; -} diff --git a/Plugins/Shared/ServerPack/ServerPackUi.cs b/Plugins/Shared/ServerPack/ServerPackUi.cs deleted file mode 100644 index 7db36ba..0000000 --- a/Plugins/Shared/ServerPack/ServerPackUi.cs +++ /dev/null @@ -1,240 +0,0 @@ -// ServerPackUi.cs - A server plugin's "server card". -// -// Drawn in two places: RynthCore's Mini Remote, the shared "Server" section, this server's area -// (the surface "section:server-" through RynthPluginRenderEmbed), and its own window ("/rserver"). -// Shows RynthCore's verdict and this character's Auto / On / Off override (read only: it is set in -// RynthCore Options > Diagnostics, 2026-10-13), what is known about the server (address, rule set, -// account limit, botting policy, its features), the commands it adds, its links, and how to set an -// account up for it in the launcher. Render thread only. -using System; -using System.Collections.Generic; -using System.Numerics; -using ImGuiNET; -using RynthCore.Plugin.Shared; - -namespace RynthCore.Plugin.ServerPack; - -internal sealed class ServerPackUi -{ - private static readonly Vector4 Teal = new(0.30f, 0.85f, 0.80f, 1f); - private static readonly Vector4 Mute = new(0.60f, 0.62f, 0.66f, 1f); - private static readonly Vector4 Warn = new(0.95f, 0.55f, 0.45f, 1f); - private static readonly Vector4 Good = new(0.55f, 0.85f, 0.45f, 1f); - - private readonly ServerPackModel _model; - private readonly string _pluginLabel; - private readonly Func _world; - private readonly string _windowTitle; - private readonly IReadOnlyList _pages; - private string _status = string.Empty; - - /// The standalone window is open ("/rserver"). - public bool WindowOpen; - - /// "RynthColdeve 0.1.0", for the title and the card. - /// The world name the client reports now (null when unknown). - /// The server's own pages: tabs of the window after the card. - public ServerPackUi(ServerPackModel model, string pluginLabel, Func world, IReadOnlyList? pages = null) - { - _model = model; - _pluginLabel = pluginLabel; - _world = world; - _pages = pages ?? Array.Empty(); - _windowTitle = model.Info.Name + " server (" + pluginLabel + ")##server_" + model.Info.Id; - } - - /// The standalone window, while open: the card, and the server's pages as tabs when it has some. - public void RenderWindow() - { - if (!WindowOpen) return; - ImGui.SetNextWindowSize(new Vector2(_pages.Count > 0 ? 560 : 460, 520), ImGuiCond.FirstUseEver); - bool open = WindowOpen; - if (ImGui.Begin(_windowTitle, ref open)) - { - if (_pages.Count == 0) RenderBody(); - else if (ImGui.BeginTabBar("##server_tabs_" + _model.Info.Id)) - { - if (ImGui.BeginTabItem("Server##card")) - { - RenderBody(); - ImGui.EndTabItem(); - } - foreach (ServerPage page in _pages) - { - if (!ImGui.BeginTabItem(page.Label + "##page_" + page.Id)) continue; - if (ImGui.BeginChild("##page_body_" + page.Id)) page.Draw(); - ImGui.EndChild(); - ImGui.EndTabItem(); - } - ImGui.EndTabBar(); - } - } - ImGui.End(); - WindowOpen = open; - } - - /// The card's content, into the current window. - public void RenderBody() - { - ServerPackInfo info = _model.Info; - RenderVerdict(info); - ImGui.Separator(); - RenderFacts(info); - if (info.Commands.Length > 0) - { - ImGui.Separator(); - RenderCommands(info); - } - ImGui.Separator(); - RenderLinks(info); - ImGui.Separator(); - RenderSetup(info); - if (info.Source.Length > 0) - { - ImGui.Spacing(); - SafeImGui.TextDisabled("Server data: " + info.Source); - } - if (_status.Length > 0) - { - ImGui.Separator(); - SafeImGui.TextWrapped(_status); - } - } - - private void RenderVerdict(ServerPackInfo info) - { - ServerVerdictView? v = _model.Engine; - if (v == null) - { - bool byName = _model.IsActive(_world()); - SafeImGui.TextColored(byName ? Teal : Mute, byName - ? info.Name + ": this world (by its name)" - : info.Name + ": not this world (by its name)"); - ImGui.PushStyleColor(ImGuiCol.Text, Mute); - ImGui.TextWrapped("Waiting for RynthCore's verdict and the override (RynthCore 2026.10.5.48 or later sends them)."); - ImGui.PopStyleColor(); - return; - } - - SafeImGui.TextColored(v.Active ? Teal : Mute, v.Active ? info.Name + ": on for this world" : info.Name + ": not this world"); - if (v.Reason.Length > 0) - { - ImGui.PushStyleColor(ImGuiCol.Text, Mute); - SafeImGui.TextWrapped(v.Reason); - ImGui.PopStyleColor(); - } - // Read only: a server is forced in one place, RynthCore Options > Diagnostics (2026-10-13). - SafeImGui.TextDisabled("This character: " + ForceText(ServerPackModel.NormalizeForce(v.Force)) - + " (change it in RynthCore Options > Diagnostics)"); - if (ImGui.IsItemHovered()) - SafeImGui.SetTooltip("RynthCore's server selection (Options > Diagnostics) forces a server for this character,\n" - + "or /rc server " + info.Id + " auto|on|off in chat."); - } - - /// The override as words: Auto (detected), On (forced on) or Off (forced off). - private static string ForceText(string force) => force switch - { - "on" => "forced on", - "off" => "forced off", - _ => "auto (detected)", - }; - - private static void RenderFacts(ServerPackInfo info) - { - if (ImGui.BeginTable("##facts_" + info.Id, 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp)) - { - ImGui.TableSetupColumn("Item", ImGuiTableColumnFlags.WidthFixed, 110); - ImGui.TableSetupColumn("Value"); - Row("Address", info.Address.Length > 0 ? info.Address : "(not published)"); - Row("Emulator", info.Emulator); - Row("Rule set", info.Ruleset); - if (info.Status.Length > 0) Row("Status", info.Status); - Row("Account limit", info.AccountLimit.Length > 0 ? info.AccountLimit : "(not published)"); - ImGui.TableNextRow(); - ImGui.TableNextColumn(); - ImGui.TextUnformatted("Botting"); - ImGui.TableNextColumn(); - Vector4 color = info.Botting switch - { - BottingPolicy.Forbidden => Warn, - BottingPolicy.Restricted => Warn, - BottingPolicy.Allowed => Good, - _ => Mute, - }; - ImGui.PushStyleColor(ImGuiCol.Text, color); - SafeImGui.TextWrapped(info.BottingText); - ImGui.PopStyleColor(); - ImGui.EndTable(); - } - - if (info.Botting == BottingPolicy.Forbidden) - SafeImGui.TextColored(Warn, "This server forbids bots: don't run RynthAi's combat, navigation or looting here."); - - if (info.Summary.Length > 0) - { - ImGui.Spacing(); - SafeImGui.TextWrapped(info.Summary); - } - foreach (string fact in info.Facts) - SafeImGui.BulletText(fact); - } - - private static void Row(string label, string value) - { - ImGui.TableNextRow(); - ImGui.TableNextColumn(); - SafeImGui.Text(label); - ImGui.TableNextColumn(); - SafeImGui.TextWrapped(value); - } - - private void RenderCommands(ServerPackInfo info) - { - ImGui.TextUnformatted("Server commands"); - for (int i = 0; i < info.Commands.Length; i++) - { - ServerCommand c = info.Commands[i]; - ImGui.PushID(i); - if (ImGui.SmallButton("Copy")) Copy(c.Command); - ImGui.PopID(); - ImGui.SameLine(); - SafeImGui.Text(c.Command); - ImGui.SameLine(); - SafeImGui.TextDisabled("- " + c.What); - } - } - - private void RenderLinks(ServerPackInfo info) - { - ImGui.TextUnformatted("Links"); - bool any = false; - any |= Link("Discord", info.Discord); - any |= Link("Website", info.Website); - any |= Link("Wiki", info.Wiki); - if (!any) ImGui.TextDisabled("(none published)"); - } - - private bool Link(string label, string url) - { - if (url.Length == 0) return false; - ImGui.PushID(label); - if (ImGui.SmallButton("Copy")) Copy(url); - ImGui.PopID(); - ImGui.SameLine(); - SafeImGui.Text(label + ": " + url); - return true; - } - - private static void RenderSetup(ServerPackInfo info) - { - ImGui.TextUnformatted("Account setup (RynthCore launcher)"); - foreach (string step in ServerPackModel.LauncherSteps(info)) - SafeImGui.TextWrapped(step); - } - - private void Copy(string text) - { - ImGui.SetClipboardText(text); - _status = "Copied: " + text; - } -} diff --git a/Plugins/Shared/ServerPack/ServerPlugin.props b/Plugins/Shared/ServerPack/ServerPlugin.props deleted file mode 100644 index 0a65166..0000000 --- a/Plugins/Shared/ServerPack/ServerPlugin.props +++ /dev/null @@ -1,80 +0,0 @@ - - - - net10.0-windows - x86 - win-x86 - Library - true - enable - true - Shared - true - Size - false - RynthCore.Plugin.ServerPack - x86 - - 66 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Plugins/Shared/ServerQuestPackClient.cs b/Plugins/Shared/ServerQuestPackClient.cs new file mode 100644 index 0000000..178b9a5 --- /dev/null +++ b/Plugins/Shared/ServerQuestPackClient.cs @@ -0,0 +1,201 @@ +// ============================================================================ +// RynthSuite - Plugins/Shared/ServerQuestPackClient.cs +// A quest reader's side of "RynthServer.QuestPack" (RynthServerQuestPackApi.cs): +// the active server's own quest list, from the plugin RynthCore names as its +// owner (GetServerStateJson "activePlugin", ServerStateClient.cs). The reader +// never names a server: whatever pack the active server's plugin offers is +// the pack, and a plugin that offers none (or an engine older than v86, with +// no server list) means retail quests only. +// +// The info JSON is polled (every 2 s, cheap); the CSV is read only when the +// owner, its table or the info changes. Revision goes up when the pack does. +// Needs, linked into the reader: RynthServerQuestPackApi.cs, EngineServerState.cs. +// Pump thread only. +// ============================================================================ + +using System; +using System.Text; +using System.Text.Json; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.Shared; + +/// A server plugin's quest pack as a reader took it. +/// The plugin that offered it. +/// The server's RynthCore id (the reader's override file name). +/// What quest lists call the server (the master list's Server column; the label shown). +/// Data rows, as the plugin counted them. +/// The plugin's pack revision. +/// The pack itself. +internal sealed record ServerQuestPack(string Plugin, string ServerId, string Tag, int Rows, int Revision, string Csv); + +/// The "RynthServer.QuestPack" info JSON, read leniently. +internal sealed record ServerQuestPackInfo(string ServerId, string Tag, string Plugin, int Rows, int Bytes, int Revision) +{ + /// The info, or null for junk, another schema, or a pack without a size. + public static ServerQuestPackInfo? Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return null; + try + { + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement r = doc.RootElement; + if (r.ValueKind != JsonValueKind.Object) return null; + if (!r.TryGetProperty("schema", out JsonElement s) || s.ValueKind != JsonValueKind.Number || s.GetInt32() != RynthServerQuestPack.Schema) return null; + int bytes = Int(r, "bytes"); + if (bytes <= 0) return null; + return new ServerQuestPackInfo(Str(r, "server"), Str(r, "tag"), Str(r, "plugin"), Int(r, "rows"), bytes, Int(r, "revision")); + } + catch (JsonException) + { + return null; + } + } + + private static string Str(JsonElement r, string name) => + r.TryGetProperty(name, out JsonElement e) && e.ValueKind == JsonValueKind.String ? (e.GetString() ?? string.Empty).Trim() : string.Empty; + + private static int Int(JsonElement r, string name) => + r.TryGetProperty(name, out JsonElement e) && e.ValueKind == JsonValueKind.Number && e.TryGetInt32(out int v) ? v : 0; +} + +internal sealed unsafe class ServerQuestPackClient +{ + private const long PollMs = 2000; + private const long RequeryMs = 10_000; + private const int MaxInfoBytes = 64 * 1024; + + private string _owner = string.Empty; + private uint* _tableVersion; + private delegate* unmanaged[Cdecl] _getInfo; + private delegate* unmanaged[Cdecl] _getCsv; + private long _nextPollAt, _nextQueryAt; + private string _infoJson = string.Empty; + + /// The pack the owner offers now; null when it offers none (or there is no owner). + public ServerQuestPack? Pack { get; private set; } + + /// Goes up whenever changes. + public int Revision { get; private set; } + + /// The plugin last asked ("" = none). + public string Owner => _owner; + + /// + /// The pack to merge: the one only while its plugin owns the active server + /// in (RynthCore's server list), else none. Pure: the readers' tests use it. + /// + public static ServerQuestPack? ForActive(EngineServerState? state, ServerQuestPack? offered) => + offered != null && state is { HasActive: true } && state.ActivePlugin.Length > 0 + && state.ActivePlugin.Equals(offered.Plugin, StringComparison.OrdinalIgnoreCase) + ? offered + : null; + + /// The plugin to ask: the owner of the active server, "" with none (or no server list). + public static string OwnerOf(EngineServerState? state) => state is { HasActive: true } ? state.ActivePlugin : string.Empty; + + /// Logout: forget everything; the next poll reads fresh. + public void Clear() + { + DropTable(); + _owner = string.Empty; + _nextPollAt = _nextQueryAt = 0; + SetPack(null); + } + + /// Polls 's pack when due; polls now. Pump thread. + public void Poll(RynthCoreHost host, string? owner, long now, bool force = false) + { + if (!force && now < _nextPollAt) return; + _nextPollAt = now + PollMs; + owner = (owner ?? string.Empty).Trim(); + if (!owner.Equals(_owner, StringComparison.OrdinalIgnoreCase)) + { + DropTable(); + _owner = owner; + _nextQueryAt = 0; + SetPack(null); + } + if (owner.Length == 0) return; + if (_tableVersion != null && *_tableVersion == 0) + { + // The plugin shut down (a reload): ask the new copy. + DropTable(); + _nextQueryAt = 0; + } + if (_getInfo == null) + { + if (force) _nextQueryAt = 0; + if (now < _nextQueryAt || !host.HasGetPluginInterface) return; + _nextQueryAt = now + RequeryMs; + if (!Query(host, owner)) + { + SetPack(null); // this server's plugin offers no pack + return; + } + } + + string info = Read(_getInfo, 1024, MaxInfoBytes); + if (info == _infoJson && (Pack != null || info.Length == 0)) return; + _infoJson = info; + ServerQuestPackInfo? parsed = ServerQuestPackInfo.Parse(info); + if (parsed == null || parsed.Bytes > RynthServerQuestPack.MaxCsvBytes) + { + SetPack(null); + return; + } + string csv = Read(_getCsv, parsed.Bytes + 1, RynthServerQuestPack.MaxCsvBytes + 1); + if (csv.Length == 0) + { + _infoJson = string.Empty; // try again on the next poll + SetPack(null); + return; + } + SetPack(new ServerQuestPack(owner, parsed.ServerId, parsed.Tag, parsed.Rows, parsed.Revision, csv)); + } + + private bool Query(RynthCoreHost host, string owner) + { + var p = (RynthServerQuestPackApiV1*)host.GetPluginInterface(owner, RynthServerQuestPackApiV1.InterfaceName, RynthServerQuestPackApiV1.InterfaceVersion); + if (p == null || p->Version < 1 || p->StructSize < (uint)sizeof(RynthServerQuestPackApiV1) || p->GetPackInfoJson == null || p->GetPackCsv == null) + return false; + _tableVersion = &p->Version; + _getInfo = p->GetPackInfoJson; + _getCsv = p->GetPackCsv; + return true; + } + + /// Copies a string out, growing the buffer once when the plugin says it didn't fit ("" = none). + private static string Read(delegate* unmanaged[Cdecl] fn, int first, int max) + { + if (fn == null) return string.Empty; + var buffer = new byte[Math.Max(16, Math.Min(first, max))]; + for (int attempt = 0; attempt < 2; attempt++) + { + int len; + fixed (byte* b = buffer) len = fn(b, buffer.Length); + if (len <= 0) return string.Empty; + if (len < buffer.Length) return Encoding.UTF8.GetString(buffer, 0, len); + if (len + 1 > max) return string.Empty; + buffer = new byte[len + 1]; + } + return string.Empty; + } + + private void SetPack(ServerQuestPack? pack) + { + if (pack == null && Pack == null) return; + if (pack != null && Pack != null && pack.Plugin == Pack.Plugin && pack.Revision == Pack.Revision && pack.Csv == Pack.Csv) return; + Pack = pack; + if (pack == null) _infoJson = string.Empty; + Revision++; + } + + private void DropTable() + { + _tableVersion = null; + _getInfo = null; + _getCsv = null; + _infoJson = string.Empty; + } +} diff --git a/RynthSuite.slnx b/RynthSuite.slnx index 5ba75bb..401b2a4 100644 --- a/RynthSuite.slnx +++ b/RynthSuite.slnx @@ -13,6 +13,8 @@ + + diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index cea74b8..b7fa338 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -77,6 +77,9 @@ internal static unsafe class FakeHost public static (uint Hp, uint Stam, uint Mana) BaseVitals; public static string WorldName = ""; public static string AccountName = ""; + /// A test's extra engine calls (e.g. FakeServerState), set into the table last by Create; Reset clears it. + public delegate void ApiHook(ref RynthCoreApiNative api); + public static ApiHook? ConfigureApi; /// The player's facing, 0 = north, clockwise (read back through the pose quaternion). public static double HeadingDeg; public static readonly Dictionary Wcids = new(); @@ -321,6 +324,7 @@ internal static unsafe class FakeHost ObjectPropertiesCalls = false; PropertyRecord = null; PropertyQueries.Clear(); ObjectStates.Clear(); OnUseObject = null; OnUseObjectOn = null; TargetVitals.Clear(); LiveObjectsCalls = false; + ConfigureApi = null; } /// @@ -516,6 +520,7 @@ internal static unsafe class FakeHost api.Version = Math.Max(api.Version, 84u); api.GetObjectPropertiesFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetObjectProperties; } + ConfigureApi?.Invoke(ref api); LastApi = api; if (EquippedCalls) api.Version = Math.Max(api.Version, 87u); // v87 GetWieldedItems return new RynthCoreHost(api); diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeServerHub.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeServerHub.cs index 766661b..d328d7b 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeServerHub.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeServerHub.cs @@ -8,7 +8,7 @@ using RynthCore.Plugin.Shared; namespace RynthCore.RynthAiHostTests.Fakes; /// -/// A stand-in for a server plugin's "RynthILT.Hub" table (Plugins/Shared/RynthIltHubApi.cs), so the +/// A stand-in for a server plugin's "RynthServer.Hub" table (Plugins/Shared/RynthServerHubApi.cs), so the /// tests can check what RynthAi does WITH a server plugin (RynthILT) as well as without one. Its /// functions answer from the static state below; RynthAi's ServerHubClient takes the table through /// UseTableForTests. The render functions draw nothing (no ImGui frame in the tests): they only @@ -35,7 +35,7 @@ internal static unsafe class FakeServerHub /// GetText: id -> text (missing = ""). public static readonly Dictionary Texts = new(StringComparer.OrdinalIgnoreCase); - private static RynthIltHubApiV1* _table; + private static RynthServerHubApiV1* _table; public static void Reset() { @@ -58,9 +58,9 @@ internal static unsafe class FakeServerHub { if (_table == null) { - var t = (RynthIltHubApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthIltHubApiV1)); - t->StructSize = (uint)sizeof(RynthIltHubApiV1); - t->IsIltWorld = &IsIltWorld; + var t = (RynthServerHubApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerHubApiV1)); + t->StructSize = (uint)sizeof(RynthServerHubApiV1); + t->IsServerWorld = &IsIltWorld; t->GetFeature = &GetFeature; t->GetTabs = &GetTabs; t->RenderTab = &RenderTab; @@ -71,7 +71,7 @@ internal static unsafe class FakeServerHub t->GetSetting = &GetSetting; t->SetSetting = &SetSetting; t->GetText = &GetText; - t->Version = RynthIltHubApiV1.InterfaceVersion; + t->Version = RynthServerHubApiV1.InterfaceVersion; _table = t; } return (IntPtr)_table; @@ -99,7 +99,7 @@ internal static unsafe class FakeServerHub } [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GetTabs(IltTabV1* tabs, int capacity) => 0; + private static int GetTabs(ServerHubTabV1* tabs, int capacity) => 0; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int RenderTab(byte* id) => 0; @@ -150,7 +150,7 @@ internal static unsafe class FakeServerHub private static int AllowSummonOnEmpty() => AllowEmpty ? 1 : 0; [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int GetSubTabs(byte* parent, IltTabV1* tabs, int capacity) + private static int GetSubTabs(byte* parent, ServerHubTabV1* tabs, int capacity) { string p = Utf8(parent) ?? string.Empty; if (!SubTabs.TryGetValue(p, out var list)) return 0; @@ -161,7 +161,7 @@ internal static unsafe class FakeServerHub Write(list[i].Label, tabs[i].Label, 32); tabs[i].Width = 0; tabs[i].Height = 0; - tabs[i].Flags = RynthIltHub.TabShown | RynthIltHub.TabAvailable; + tabs[i].Flags = RynthServerHub.TabShown | RynthServerHub.TabAvailable; } return list.Count; } diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeServerState.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeServerState.cs new file mode 100644 index 0000000..f4eb227 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeServerState.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.RynthAiHostTests.Fakes; + +/// +/// RynthCore's server list (plugin API v86 GetServerStateJson) and the active server owner's +/// "RynthServer.Profile" table (GetPluginInterface), for tests of what RynthAi does with a server +/// plugin's profile values. after FakeHost.Reset and before FakeHost.Create; +/// the JSON can change between calls (the next poll reads it). Other interfaces answer nothing. +/// +internal static unsafe class FakeServerState +{ + /// GetServerStateJson's answer ("" = none, the call fails). + public static string StateJson = string.Empty; + /// The profile JSON the owner plugin serves ("" = it serves no profile). + public static string ProfileJson = string.Empty; + /// The plugin that serves it ("" = any plugin asked). + public static string ProfilePlugin = string.Empty; + /// Every (plugin, interface) asked for. + public static readonly List<(string Plugin, string Iface)> Queries = new(); + + private static RynthServerProfileApiV1* _profile; + + public static void Reset() + { + StateJson = ProfileJson = ProfilePlugin = string.Empty; + Queries.Clear(); + } + + /// Puts the two engine calls into the next FakeHost.Create. + public static void Install() => FakeHost.ConfigureApi = Configure; + + private static void Configure(ref RynthCoreApiNative api) + { + api.Version = Math.Max(api.Version, 86u); + api.GetServerStateJsonFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetServerStateJson; + api.GetPluginInterfaceFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetPluginInterface; + } + + /// A GetServerStateJson answer (schema 1) with one active server (or none: ""). + public static string State(string activeId, string activeName, string activePlugin, string world, params (string Id, string Name, bool Detected, string Plugin)[] others) + { + var sb = new StringBuilder(); + sb.Append("{\"schema\":1,\"revision\":1,\"host\":\"\",\"world\":\"").Append(world).Append("\",\"pick\":\"auto\",") + .Append("\"active\":\"").Append(activeId).Append("\",\"activeName\":\"").Append(activeName) + .Append("\",\"activePlugin\":\"").Append(activePlugin).Append("\",\"servers\":["); + bool first = true; + void Row(string id, string name, bool active, bool detected, string plugin) + { + if (!first) sb.Append(','); + first = false; + sb.Append("{\"id\":\"").Append(id).Append("\",\"name\":\"").Append(name).Append("\",\"active\":").Append(active ? "true" : "false") + .Append(",\"detected\":").Append(detected ? "true" : "false").Append(",\"force\":\"auto\",\"builtIn\":false,\"plugin\":\"") + .Append(plugin).Append("\",\"reason\":\"\"}"); + } + if (activeId.Length > 0) Row(activeId, activeName, true, true, activePlugin); + foreach (var o in others) Row(o.Id, o.Name, false, o.Detected, o.Plugin); + sb.Append("]}"); + return sb.ToString(); + } + + /// A minimal profile JSON with these "values". + public static string Profile(string id, params (string Key, double Value)[] values) + { + var sb = new StringBuilder("{\"schema\":1,\"id\":\"").Append(id).Append("\",\"values\":{"); + for (int i = 0; i < values.Length; i++) + { + if (i > 0) sb.Append(','); + sb.Append('"').Append(values[i].Key).Append("\":").Append(values[i].Value.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + } + return sb.Append("}}").ToString(); + } + + private static int Write(string s, byte* buffer, int capacity) + { + byte[] b = Encoding.UTF8.GetBytes(s); + if (b.Length >= capacity || buffer == null) return b.Length; + for (int i = 0; i < b.Length; i++) buffer[i] = b[i]; + buffer[b.Length] = 0; + return b.Length; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetServerStateJson(byte* buffer, int capacity) => StateJson.Length == 0 ? -1 : Write(StateJson, buffer, capacity); + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static IntPtr GetPluginInterface(IntPtr plugin, IntPtr iface, uint version) + { + string p = Marshal.PtrToStringAnsi(plugin) ?? string.Empty; + string i = Marshal.PtrToStringAnsi(iface) ?? string.Empty; + Queries.Add((p, i)); + if (i != RynthServerProfileApiV1.InterfaceName || version != RynthServerProfileApiV1.InterfaceVersion || ProfileJson.Length == 0 + || (ProfilePlugin.Length > 0 && !p.Equals(ProfilePlugin, StringComparison.OrdinalIgnoreCase))) + return IntPtr.Zero; + if (_profile == null) + { + var t = (RynthServerProfileApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerProfileApiV1)); + t->StructSize = (uint)sizeof(RynthServerProfileApiV1); + t->GetProfileJson = &GetProfileJson; + t->Version = RynthServerProfileApiV1.InterfaceVersion; + _profile = t; + } + return (IntPtr)_profile; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int GetProfileJson(byte* buffer, int capacity) => ProfileJson.Length == 0 ? 0 : Write(ProfileJson, buffer, capacity); +} diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 3327fe6..4b16357 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -148,6 +148,7 @@ internal static class Program SelfRatingsTests.Register(runner); ServerHubClientLookupTests.Register(runner); UbMtSafetyTests.Register(runner); + DifficultyTierTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/DamageRowsTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/DamageRowsTests.cs index c5e6ddc..2a73465 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/DamageRowsTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/DamageRowsTests.cs @@ -253,7 +253,7 @@ internal static class DamageRowsTests var host = FakeHost.Create(Player); var bot = new Bot(host, "one-wcid"); - // The same Rampager from every source: learned at real Dereth and at an Aelrynth + // The same Rampager from every source: learned at real Dereth and at a server's // difficulty tier (kept per (wcid, tier)), appraised this session, standing nearby, // and in creatures.json under a differently cased name. bot.Store.RecordKill(Wand, RampagerA, "Rampager", "Fire", 7, 3, 435); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/DifficultyTierTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/DifficultyTierTests.cs new file mode 100644 index 0000000..f2cdff1 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/DifficultyTierTests.cs @@ -0,0 +1,237 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text.Json; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.CreatureData; +using RynthCore.Plugin.Shared; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The difficulty tier (2026-10-21; RynthAi's AwakenedTier read one server's tier itself before): +// RynthAi takes the tier where the player stands and the health percent a tier from the active +// server plugin's "RynthServer.Profile" values ("difficultyTier", "difficultyHealthPercent"; +// RynthAelrynth publishes Aelrynth's) and names no server. Without them everything is tier 0, as on +// every server before; with them HP is scaled and learned numbers are kept per tier. The creature +// data folder a server already has (by RynthCore's server id, its name or the world name; the old +// "Aelrynth" folder included) is read where it is. +internal static class DifficultyTierTests +{ + private const uint Player = 0x50000D01; + private const uint Drudge = 7; + private const uint Appraised = 0x7A11; // a wcid no other test's creature data holds + private const uint Wand = 0x80000401; + private static readonly BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("difficulty tier: without a server plugin's values it is tier 0, nothing is scaled, the panel shows no picker", NoValues); + r.Add("difficulty tier: a server plugin's tier and percent scale HP and keep learned numbers per tier", WithValues); + r.Add("difficulty tier: the creature data folder a server already has is kept (the old 'Aelrynth' one included)", CreatureFolder); + } + + // ── Fixture ────────────────────────────────────────────────────────────── + + private sealed class Bot + { + public readonly RynthAiPlugin P = new(); + public readonly MonsterDamageStore Store = new(); + public readonly CreatureProfileStore Creatures = new(); + private readonly RynthCoreHost _host; + + public Bot(RynthCoreHost host, string name) + { + _host = host; + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var cache = new WorldObjectCache(host); + cache.SetPlayerId(Player); + Set("_objectCache", cache); + Set("_playerId", Player); + string folder = Path.Combine(Program.TempRoot, "difficulty-tier", name); + if (Directory.Exists(folder)) Directory.Delete(folder, true); + Directory.CreateDirectory(folder); + Store.SetCharacter(folder); + Set("_damageStore", Store); + Set("_creatureStore", Creatures); + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + + /// A fresh read of the server's values (the once-a-second refresh, now), then RynthAi's tick of it. + public void Tick() + { + P.DifficultyTier.Refresh(_host, force: true); + typeof(RynthAiPlugin).GetMethod("TickDifficultyTier", Any)!.Invoke(P, null); + } + + public string TierJson() => P.BuildDifficultyTierJson(); + + public (int Hp, string Source) Detail(uint wcid) + { + using var doc = JsonDocument.Parse(P.BuildMonsterDetailJson(wcid)); + return (doc.RootElement.GetProperty("hp").GetInt32(), doc.RootElement.GetProperty("hpSrc").GetString() ?? ""); + } + } + + private static Bot NewBot(string name, string world, bool serverState) + { + FakeHost.Reset(); + FakeServerState.Reset(); + FakeHost.WorldName = world; + if (serverState) FakeServerState.Install(); + return new Bot(FakeHost.Create(Player), name); + } + + // ── Tests ──────────────────────────────────────────────────────────────── + + private static void NoValues() + { + // No server list at all (an engine without GetServerStateJson): the world name keys the data. + var bot = NewBot("none", "Some World", serverState: false); + bot.Store.RecordKill(Wand, Drudge, "Drudge Skulker", "Fire", 7, 2, 900); + bot.Tick(); + Check.False(bot.P.DifficultyTier.Active, "no server plugin reports a tier"); + Check.Eq((bot.P.DifficultyTier.Current, bot.P.DifficultyTier.HealthPercentPerTier), (0, 0.0), "tier 0, no percent"); + Check.Eq(bot.Store.Difficulty, 0, "the damage store records at tier 0"); + Check.Eq(bot.TierJson(), "{\"show\":false}", "the Damage panel shows no tier picker"); + Check.Eq(bot.Creatures.ServerKey, "Some_World", "creature data under the world name, as before"); + bot.P.SetMonsterHp(Drudge, 1000); + Check.Eq(bot.Store.GetManualHp(Drudge), 1000.0, "a typed HP is kept as typed"); + Check.Eq(bot.Detail(Drudge), (1000, "set by you"), "and shown as typed"); + bot.P.SetDamageViewTier(5); + Check.Eq(bot.P.DamageViewDifficulty, 0, "a picked tier means nothing without tiers"); + Check.Eq(bot.Detail(Drudge).Hp, 1000, "the HP stays tier 0's"); + Check.Near(bot.Store.GetLearnedHp(Drudge), 900, 0.01, "the learned HP is tier 0's"); + + // A server plugin that is active but publishes no tier (any other server): the same. + var other = NewBot("other", "Other World", serverState: true); + FakeServerState.StateJson = FakeServerState.State("other", "Other", "RynthOther", "Other World"); + FakeServerState.ProfileJson = FakeServerState.Profile("other", ("voidDotDurationScale", 1.35)); + other.Tick(); + Check.False(other.P.DifficultyTier.Active, "another value isn't a tier"); + Check.Eq(other.TierJson(), "{\"show\":false}", "no picker"); + Check.Eq(other.Store.Difficulty, 0, "tier 0"); + Check.True(FakeServerState.Queries.Any(q => q.Plugin == "RynthOther" && q.Iface == RynthServerProfileApiV1.InterfaceName), + "the values come from the active server's owner plugin"); + + // Pure checks of the scale and the reading. + Check.Eq(DifficultyTier.HealthScale(3, 5), 1.15, "tier 3 at 5% a tier: x1.15"); + Check.Eq((DifficultyTier.HealthScale(0, 5), DifficultyTier.HealthScale(3, 0), DifficultyTier.HealthScale(-1, 5)), (1.0, 1.0, 1.0), + "tier 0, no percent, or a negative tier: x1"); + Check.False(DifficultyTier.Read("", "x").Active || DifficultyTier.Read("{broken", "x").Active + || DifficultyTier.Read("{\"values\":{\"difficultyTier\":\"3\"}}", "x").Active, "no profile, broken JSON, text: no tier"); + var odd = DifficultyTier.Read("{\"values\":{\"difficultyTier\":-4,\"difficultyHealthPercent\":5000}}", "x"); + Check.True(odd.Active && odd.Tier == 0 && odd.HealthPercent == 0, "a negative tier reads 0, an absurd percent 0"); + var round = DifficultyTier.Read("{\"values\":{\"difficultyTier\":2.6,\"difficultyHealthPercent\":2.5}}", "x"); + Check.True(round.Tier == 3 && round.HealthPercent == 2.5, "a tier is a whole number; the percent may not be"); + } + + private static void WithValues() + { + var bot = NewBot("values", "Test World", serverState: true); + FakeServerState.StateJson = FakeServerState.State("testsrv", "Test Server", "RynthTestSrv", "Test World"); + FakeServerState.ProfileJson = FakeServerState.Profile("testsrv", ("difficultyTier", 3), ("difficultyHealthPercent", 5)); + bot.Store.RecordKill(Wand, Drudge, "Drudge Skulker", "Fire", 7, 2, 900); // tier 0, before the tier is known + bot.Tick(); + DifficultyTier t = bot.P.DifficultyTier; + Check.True(t.Active, "the server plugin reports a tier"); + Check.Eq((t.Current, t.HealthPercentPerTier, t.Source), (3, 5.0, "RynthTestSrv"), "tier 3, +5% a tier, from its plugin"); + Check.Eq(bot.Store.Difficulty, 3, "the damage store records under tier 3"); + Check.Eq(bot.TierJson(), "{\"show\":true,\"current\":3,\"view\":3,\"following\":true,\"percent\":5,\"tiers\":[0,3]}", + "the Damage panel's picker (the export's JSON shape)"); + Check.Eq(bot.Creatures.ServerKey, "testsrv", "a new server's creature data goes under its RynthCore id"); + + // HP: typed at the shown tier, kept as tier 0's, shown scaled. + bot.P.SetMonsterHp(Drudge, 1150); + Check.Near(bot.Store.GetManualHp(Drudge), 1000, 1e-9, "1150 typed at tier 3 is kept as tier 0's 1000"); + var (hp3, src3) = bot.Detail(Drudge); + Check.True(hp3 == 1150 && src3.Contains("+15%"), $"shown at tier 3 as 1150, +15% ({src3})"); + bot.P.SetDamageViewTier(0); + Check.Eq(bot.TierJson(), "{\"show\":true,\"current\":3,\"view\":0,\"following\":false,\"percent\":5,\"tiers\":[0,3]}", "tier 0 picked"); + Check.Eq(bot.Detail(Drudge), (1000, "set by you"), "tier 0 shows the value itself"); + bot.P.SetDamageViewTier(-1); + + // Learned numbers per tier. + bot.Store.RecordKill(Wand, Drudge, "Drudge Skulker", "Fire", 7, 3, 1350); + Check.Near(bot.Store.GetLearnedHp(Drudge, 3), 1350, 0.01, "tier 3 learned its own HP"); + Check.Near(bot.Store.GetLearnedHp(Drudge, 0), 900, 0.01, "tier 0's is untouched"); + Check.Eq(string.Join(",", bot.Store.KnownDifficulties()), "3", "tier 3 is known"); + bot.Creatures.Upsert(new CreatureProfile { Name = "Scaled Golem", Wcid = Appraised, MaxHealth = 1380 }, t.Current); + Check.True(bot.Creatures.TryGetByWcid(Appraised, out var prof) && prof!.MaxHealth == 0 && bot.Creatures.MaxHealthAt(prof, 3) == 1380, + "an appraisal at tier 3 is filed under tier 3, not as tier 0's health"); + + // The server moves the player to tier 0, then a percent-less tier, then publishes none. + FakeServerState.ProfileJson = FakeServerState.Profile("testsrv", ("difficultyTier", 0), ("difficultyHealthPercent", 5)); + bot.Tick(); + Check.True(t.Active && t.Current == 0 && bot.Store.Difficulty == 0, "tier 0: still a server with tiers, records at tier 0"); + Check.Eq(bot.TierJson(), "{\"show\":true,\"current\":0,\"view\":0,\"following\":true,\"percent\":5,\"tiers\":[0,3]}", "the picker stays"); + FakeServerState.ProfileJson = FakeServerState.Profile("testsrv", ("difficultyTier", 2)); + bot.Tick(); + Check.True(t.Current == 2 && t.HealthPercentPerTier == 0 && t.HealthScale(2) == 1.0, "a tier without a percent: per-tier data, no scaling"); + FakeServerState.ProfileJson = FakeServerState.Profile("testsrv"); + bot.Tick(); + Check.False(t.Active, "no values: no tier"); + Check.Eq((bot.Store.Difficulty, bot.TierJson()), (0, "{\"show\":false}"), "back to tier 0 and no picker"); + + // Logout forgets it; the next login reads fresh. + t.Reset(); + Check.True(!t.Active && t.ServerKey.Length == 0, "logout: nothing carries over"); + } + + private static void CreatureFolder() + { + string saved = CreatureProfileStore.Folder; + string root = Path.Combine(Program.TempRoot, "difficulty-tier-folders"); + if (Directory.Exists(root)) Directory.Delete(root, true); + try + { + CreatureProfileStore.Folder = root; + void Seed(string folder, uint wcid, uint hp) + { + var s = new CreatureProfileStore(); + s.SetServer(folder); + s.Upsert(new CreatureProfile { Name = "Drudge Skulker", Wcid = wcid, MaxHealth = hp }); + s.SaveIfDirty(); + } + Seed("Aelrynth", Drudge, 280); // RynthAi before 2026-10-21: every Aelrynth world name + Seed("InfiniteLeaftide", Drudge, 300); // and every other server: the world name + Check.Eq(CreatureProfileStore.ExistingServerFolder("aelrynth"), "Aelrynth", "found in any case, named as on disk"); + Check.Null(CreatureProfileStore.ExistingServerFolder("coldeve"), "no folder"); + + string? Exists(string k) => CreatureProfileStore.ExistingServerFolder(k); + EngineServerState? S(string json) => EngineServerState.Parse(json); + Check.Eq(DifficultyTier.ResolveServerKey(S(FakeServerState.State("aelrynth", "Aelrynth", "RynthAelrynth", "Aeshnidae")), "Aeshnidae", Exists), + "Aelrynth", "the old Aelrynth folder is kept (found by the server's name; not 'Aeshnidae', not a new 'aelrynth')"); + Check.Eq(DifficultyTier.ResolveServerKey(S(FakeServerState.State("ilt", "Infinite Leaftide", "RynthILT", "InfiniteLeaftide")), "InfiniteLeaftide", Exists), + "InfiniteLeaftide", "a world-named folder is kept"); + Check.Eq(DifficultyTier.ResolveServerKey(S(FakeServerState.State("coldeve", "Coldeve", "RynthColdeve", "Coldeve Two")), "Coldeve Two", Exists), + "coldeve", "a server without a folder yet: its RynthCore id"); + Check.Eq(DifficultyTier.ResolveServerKey(S(FakeServerState.State("", "", "", "Aeshnidae", ("aelrynth", "Aelrynth", true, "RynthAelrynth"))), "Aeshnidae", Exists), + "Aelrynth", "a server detected but turned off for this character keeps its folder"); + Check.Eq(DifficultyTier.ResolveServerKey(S(FakeServerState.State("", "", "", "Some World")), "Some World", Exists), + "Some_World", "no server: the world name, as before"); + Check.Eq(DifficultyTier.ResolveServerKey(null, "Some World", Exists), "Some_World", "no server list: the world name, as before"); + Check.Eq(DifficultyTier.ResolveServerKey(null, "", Exists), "", "nothing known yet: no key"); + + // Through the plugin: RynthAelrynth's server, the old folder read in place. + var bot = NewBot("aelrynth-folder", "Aeshnidae", serverState: true); + FakeServerState.StateJson = FakeServerState.State("aelrynth", "Aelrynth", "RynthAelrynth", "Aeshnidae"); + FakeServerState.ProfileJson = FakeServerState.Profile("aelrynth", ("difficultyTier", 2), ("difficultyHealthPercent", 5)); + bot.Tick(); + Check.Eq(bot.Creatures.ServerKey, "Aelrynth", "the creature store reads the Aelrynth folder"); + Check.True(bot.Creatures.TryGetByWcid(Drudge, out var p) && p!.MaxHealth == 280, "with what was learned there"); + Check.Eq(string.Join(",", Directory.GetDirectories(root).Select(Path.GetFileName).OrderBy(n => n)), "Aelrynth,InfiniteLeaftide", + "no new folder was made, nothing moved"); + Check.Eq(bot.P.DifficultyTier.Current, 2, "and the tier is the server plugin's"); + } + finally + { + CreatureProfileStore.Folder = saved; + } + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MiniRemoteMoveTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MiniRemoteMoveTests.cs index a6e842a..b2939ba 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/MiniRemoteMoveTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MiniRemoteMoveTests.cs @@ -20,6 +20,8 @@ namespace RynthCore.RynthAiHostTests.Tests; internal static class MiniRemoteMoveTests { private const uint Player = 0x50000E01; + /// A server plugin's Pets sub-tab id (RynthILT's Breeding; RynthAi itself never names it). + private const string BreedingSection = "pets-breeding"; private const string LegacyHubJson = """ { @@ -42,6 +44,24 @@ internal static class MiniRemoteMoveTests r.Add("vaulted dungeons: the master switch is RynthILT's; RynthAi mirrors it for the engine row (none without RynthILT)", VaultedMasterSwitch); r.Add("profile: the old Server Features fields still round-trip (RynthILT migrates them)", LegacyProfileFields); r.Add("RynthAi.Hub: table, spell names, nothing before login", HubTable); + r.Add("mini remote: the server hub is asked of the active server's owner, then of each listed owner once", HubOwnerOrder); + } + + /// + /// Whom ServerHubClient asks for "RynthServer.Hub" (2026-10-21: it names no plugin itself, RynthILT + /// included): RynthCore's active server's owner first, then every other server's owner it lists. + /// + private static void HubOwnerOrder() + { + Check.Eq(ServerHubClient.OwnerOrder(null).Count, 0, "no server list (an engine before v86): nobody is asked"); + var st = EngineServerState.Parse("{\"schema\":1,\"active\":\"b\",\"activeName\":\"B\",\"activePlugin\":\"PluginB\",\"servers\":[" + + "{\"id\":\"a\",\"plugin\":\"PluginA\"},{\"id\":\"b\",\"active\":true,\"plugin\":\"PluginB\"}," + + "{\"id\":\"c\",\"plugin\":\"\"},{\"id\":\"d\",\"plugin\":\"plugina\"}]}"); + Check.Eq(string.Join(",", ServerHubClient.OwnerOrder(st)), "PluginB,PluginA", + "the active server's owner first, then the others once each (none for a server without one)"); + var none = EngineServerState.Parse("{\"schema\":1,\"active\":\"\",\"servers\":[{\"id\":\"a\",\"plugin\":\"PluginA\"}]}"); + Check.Eq(string.Join(",", ServerHubClient.OwnerOrder(none)), "PluginA", + "no active server: the listed owners (a plugin following its own world check or override)"); } private static string Folder(string name) @@ -107,14 +127,14 @@ internal static class MiniRemoteMoveTests ilt.Tick(); Check.False(ilt.Loaded, "no RynthILT (no plugin interfaces on this host)"); Check.False(ilt.ServerActive, "so never an ILT world"); - Check.Eq(ilt.Feature(RynthIltHub.FeaturePetRefill), -1, "feature bits unknown"); - Check.False(ilt.IsOff(RynthIltHub.FeatureQuests), "unknown is not off (/myquests still refreshes)"); + Check.Eq(ilt.Feature("pet_refill"), -1, "feature bits unknown"); + Check.False(ilt.IsOff(RynthServerHub.FeatureQuests), "unknown is not off (/myquests still refreshes)"); Check.Eq(ilt.Tabs().Count, 0, "no ILT tabs"); - Check.False(ilt.RenderSection(RynthIltHub.SectionQuestBonus), "no ILT sections"); + Check.False(ilt.RenderSection(RynthServerHub.SectionRemoteBank), "no ILT sections"); Check.False(ilt.Command("hub bank"), "no ILT verbs taken"); - Check.Eq(ilt.Text(RynthIltHub.TextSessionReport), string.Empty, "no server rates in the session report"); - Check.Eq(ilt.Text(RynthIltHub.TextServerId), string.Empty, "no server of a plugin's in the menu"); - Check.Eq(ilt.Setting(RynthIltHub.SettingVaultedDungeons), -1, "no server setting offered"); + Check.Eq(ilt.Text(RynthServerHub.TextSessionReport), string.Empty, "no server rates in the session report"); + Check.Eq(ilt.Text(RynthServerHub.TextServerId), string.Empty, "no server of a plugin's in the menu"); + Check.Eq(ilt.Setting(RynthServerHub.SettingVaultedDungeons), -1, "no server setting offered"); Check.False(c.SkipLoginQuestRefresh, "the login /myquests refresh isn't skipped"); } @@ -184,11 +204,11 @@ internal static class MiniRemoteMoveTests private static void RemoteTextsFromServerPlugin() { var c = NewController("texts", out _, out _, serverPlugin: true); - Check.Eq(c.ServerHub.Text(RynthIltHub.TextSessionReport), string.Empty, "nothing until the plugin says something"); - FakeServerHub.Texts[RynthIltHub.TextSessionReport] = ", Coins 12/h, Pyr 3.4m/h"; - FakeServerHub.Texts[RynthIltHub.TextServerId] = "ilt"; - Check.Eq(c.ServerHub.Text(RynthIltHub.TextSessionReport), ", Coins 12/h, Pyr 3.4m/h", "the report's tail is the plugin's"); - Check.Eq(c.ServerHub.Text(RynthIltHub.TextServerId), "ilt", "and the server its menu entries belong to"); + Check.Eq(c.ServerHub.Text(RynthServerHub.TextSessionReport), string.Empty, "nothing until the plugin says something"); + FakeServerHub.Texts[RynthServerHub.TextSessionReport] = ", Coins 12/h, Pyr 3.4m/h"; + FakeServerHub.Texts[RynthServerHub.TextServerId] = "ilt"; + Check.Eq(c.ServerHub.Text(RynthServerHub.TextSessionReport), ", Coins 12/h, Pyr 3.4m/h", "the report's tail is the plugin's"); + Check.Eq(c.ServerHub.Text(RynthServerHub.TextServerId), "ilt", "and the server its menu entries belong to"); } /// @@ -210,15 +230,15 @@ internal static class MiniRemoteMoveTests FakeServerHub.AllowEmpty = true; Check.True(c.Pets.AllowSummonOnEmpty(), "RynthILT says yes (charm on, opted in, confirmed): summon from empty"); Check.Eq(c.Pets.SubTabs().Count, 0, "no sub-tabs until RynthILT offers one"); - FakeServerHub.SubTabs[RynthIltHub.TabParentPets] = new() { (RynthIltHub.SectionPetBreeding, "Breeding") }; + FakeServerHub.SubTabs[RynthServerHub.TabParentPets] = new() { (BreedingSection, "Breeding") }; Check.Eq(c.Pets.SubTabs().Count, 1, "RynthILT's Breeding sub-tab"); - Check.Eq(c.Pets.FindSubTab("breeding"), RynthIltHub.SectionPetBreeding, "found by its short id"); - Check.Eq(c.Pets.FindSubTab("Breed"), RynthIltHub.SectionPetBreeding, "and the 'breed' alias"); + Check.Eq(c.Pets.FindSubTab("breeding"), BreedingSection, "found by its short id"); + Check.Eq(c.Pets.FindSubTab("Breed"), BreedingSection, "and the 'breed' alias"); Check.Eq(c.Pets.FindSubTab("roster"), null, "the roster isn't a server sub-tab"); FakeHost.Chat.Clear(); Check.True(c.HandleCommand("hub", new[] { "open", "breeding" }), "hub open breeding"); Check.True(FakeHost.Chat.Any(x => x.Contains("tab pets:show")), "shows the Pets tab"); - Check.Eq(c.Pets.PendingSubTab, RynthIltHub.SectionPetBreeding, "on the Breeding sub-tab"); + Check.Eq(c.Pets.PendingSubTab, BreedingSection, "on the Breeding sub-tab"); Check.Eq(FakeServerHub.Commands.Count, 0, "RynthAi handled it itself (nothing forwarded)"); } @@ -266,13 +286,13 @@ internal static class MiniRemoteMoveTests dash.ServerSettingSet = (key, value) => client.SetSetting(key, value); sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload)!; Check.True(sent.EnableVaultedDungeons == null, "RynthILT not offering it (off ILT): still hidden"); - FakeServerHub.Settings[RynthIltHub.SettingVaultedDungeons] = 0; + FakeServerHub.Settings[RynthServerHub.SettingVaultedDungeons] = 0; sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload)!; Check.True(sent.EnableVaultedDungeons == false, "offered: the row shows RynthILT's value (off)"); dash.ApplySettingsJson("{\"EnableVaultedDungeons\":true}"); - Check.Eq(FakeServerHub.Settings[RynthIltHub.SettingVaultedDungeons], 1, "the checkbox turns RynthILT's switch on"); + Check.Eq(FakeServerHub.Settings[RynthServerHub.SettingVaultedDungeons], 1, "the checkbox turns RynthILT's switch on"); dash.ApplySettingsJson("{\"NavRingThickness\":6}"); - Check.Eq(FakeServerHub.Settings[RynthIltHub.SettingVaultedDungeons], 1, "an older engine's save (no such field) leaves it alone"); + Check.Eq(FakeServerHub.Settings[RynthServerHub.SettingVaultedDungeons], 1, "an older engine's save (no such field) leaves it alone"); Check.False(s.EnableVaultedDungeons, "RynthAi's old field is never written"); } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs index 9523798..dae5d3a 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs @@ -114,6 +114,22 @@ internal static class OffhandTests Check.Eq(OffhandPlanner.Choose(OffhandMode.Weapon, MainHandKind.OneHandedMelee, 30, all, true, true, false).Id, 10, "no slot-wield call on the engine: no dual wield, the shield"); Check.Eq(P(OffhandMode.Auto, MainHandKind.OneHandedMelee, l: new[] { main }).Id, 0, "the main weapon is never its own off hand"); + + // Drakkon, 2026-10-21: Frost and Acid Hand Wraps, the off-hand pick Frost. Against a monster + // weak to frost, Frost is the main weapon; the off hand gets Acid, not nothing (Auto with no + // shield listed used to leave it empty). + var frost = new OffhandCandidate(30, "Frost Hand Wraps", false, false); + var acid = new OffhandCandidate(40, "Acid Hand Wraps", false, false); + var wraps = new[] { frost, acid }; + OffhandPlan swapped = OffhandPlanner.Choose(OffhandMode.Auto, MainHandKind.OneHandedMelee, 30, wraps, true, false, true, 30, "Default offhand"); + Check.Eq(swapped.Id, 40, "the off-hand pick is in the main hand: the other weapon goes in the off hand"); + Check.True(swapped.Source.Contains("main hand"), "and the log says why: " + swapped.Source); + Check.Eq(OffhandPlanner.Choose(OffhandMode.Auto, MainHandKind.OneHandedMelee, 40, wraps, true, false, true, 30, "Default offhand").Id, 30, + "Acid in the main hand: the pick, Frost, as before"); + Check.Eq(OffhandPlanner.Choose(OffhandMode.Auto, MainHandKind.OneHandedMelee, 30, wraps, false, false, true, 30, "Default offhand").Id, 0, + "without Dual Wield: still nothing (no shield listed)"); + Check.Eq(OffhandPlanner.Choose(OffhandMode.Auto, MainHandKind.OneHandedMelee, 30, new[] { frost, shield }, true, false, true, 30, "Default offhand").Id, 10, + "no other weapon listed: the mode (here the shield)"); } // ── The rig ─────────────────────────────────────────────────────────────── diff --git a/Tools/RynthCore.RynthAiTests/Tests/MonsterDamageTierTests.cs b/Tools/RynthCore.RynthAiTests/Tests/MonsterDamageTierTests.cs index e9533b1..043a881 100644 --- a/Tools/RynthCore.RynthAiTests/Tests/MonsterDamageTierTests.cs +++ b/Tools/RynthCore.RynthAiTests/Tests/MonsterDamageTierTests.cs @@ -6,8 +6,8 @@ using RynthCore.RynthAiTests.Harness; namespace RynthCore.RynthAiTests.Tests; -// MonsterDamageStore and Aelrynth's difficulty tiers (2026-10-03). Awakened worlds and scaled -// copies hold the same monsters (same wcids) with +5% health, skills and damage a tier, so the +// MonsterDamageStore and difficulty tiers (2026-10-03; a server plugin reports them, DifficultyTier). +// Scaled worlds and copies hold the same monsters (same wcids) with more health, skills and damage a tier, so the // store keeps the HP pool, casts-to-kill, accuracy, fight times and damage taken per (wcid, // tier). Tier 0 must stay today's data in today's rows: on every other server the tier is // always 0, and a file written there must be what the old code wrote. @@ -54,7 +54,7 @@ internal static class MonsterDamageTierTests var (_, dir, file) = Seeded("roundtrip"); string before = File.ReadAllText(file); Check.False(before.Contains("\nA"), "no tier rows in a tier-0-only file"); - Check.False(before.Contains("Aelrynth difficulty"), "no tier header in a tier-0-only file"); + Check.False(before.Contains("difficulty tiers"), "no tier header in a tier-0-only file"); var again = new MonsterDamageStore(); again.SetCharacter(dir); @@ -121,6 +121,7 @@ internal static class MonsterDamageTierTests string[] all = File.ReadAllLines(file); bool IsTierLine(string l) => l.StartsWith("A") || l.StartsWith("# A"); Check.Eq(string.Join("\n", all.Where(l => !IsTierLine(l))), string.Join("\n", tier0), "tier-0 lines identical"); + Check.True(all.Any(l => l.StartsWith("# Above tier 0: the server's difficulty tiers")), "the tier rows' header"); Check.True(all.Any(l => l.StartsWith("AH|10|7|Drudge Skulker|1350|1")), "AH row written"); Check.True(all.Any(l => l.StartsWith("AD|10|7|Drudge Skulker|" + Wand + "|Fire|7|3|1")), "AD row written"); Check.True(all.Any(l => l.StartsWith("AU|10|7|")), "AU row written"); diff --git a/Tools/RynthILT.Tests/AetheriaChunkTests.cs b/Tools/RynthILT.Tests/AetheriaChunkTests.cs deleted file mode 100644 index bd0ab06..0000000 --- a/Tools/RynthILT.Tests/AetheriaChunkTests.cs +++ /dev/null @@ -1,277 +0,0 @@ -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// The Lugian-hammer aetheria rules (Hub/IltChunkClap.cs): Infinite Leaftide aetheria goes up to -// level 10, and aetheria carrying a C, CD or CDR rating is kept unless its keep switch is off. -// The cap covers levelled Coalesced Aetheria; an unlevelled one chunks, as in ub-IT. Corrupted -// weapons follow ub-IT's hard rules and its optional keep rules, and /clap needs a colour with its -// own trinket. -internal static class AetheriaChunkTests -{ - public static void Register(Runner r) - { - r.Add("aetheria: the chunk cap runs to one past ILT's level 10", Cap); - r.Add("aetheria: C / CD / CDR ratings are kept by default, each with its own switch", Ratings); - r.Add("aetheria: rating level - at or above keeps, below chunks (Coalesced too)", RatingLevel); - r.Add("aetheria: the level cap applies to levelled Coalesced Aetheria; unlevelled Coalesced chunks (ub-IT)", CoalescedCap); - r.Add("aetheria: a failed read is not 'unlevelled': unreadable pieces are kept, levelled Coalesced keeps its cap", UnreadableAetheria); - r.Add("aetheria: never-chunk, tinker / imbue, item XP, ratings and the cap each keep a piece", AetheriaRules); - r.Add("chunk: kind by class and name; chunks and powder are clap material", Kinds); - r.Add("corrupted: ub-IT hard rules (workmanship, cleave 1, or 2 on two-handed non-thrust)", CorruptedHardRules); - r.Add("corrupted: ub-IT keep rules, all off by default", CorruptedKeepRules); - r.Add("corrupted: a failed read is kept; two-handed cleave 2 chunks and other cleave 2 does not", UnreadableCorrupted); - r.Add("chunk: busy blocks peace mode, not combat with chunk-in-combat on (ub-IT v2.0.1059)", BusyGate); - r.Add("chunk: a target that leaves the pack counts as chunked; still carried after 10 s times out", WaitOutcome); - r.Add("clap: the server's WCIDs, each colour paired with its trinket, Coalesced only unrevealed level 1-3", ClapPairs); - } - - /// - /// Coalesced Aetheria has its level from loot (ACECustom 1-10, ratings at 6+); it used to skip - /// the cap, so a cap of 9 still chunked a level 10 Coalesced piece. - /// - private static void CoalescedCap() - { - Check.True(IltChunkClap.UnderChunkCap(8, 9), "level 8 under a cap of 9"); - Check.False(IltChunkClap.UnderChunkCap(9, 9), "level 9 is not below 9"); - Check.False(IltChunkClap.UnderChunkCap(10, 9), "a level 10 Coalesced piece is kept"); - Check.True(IltChunkClap.UnderChunkCap(10, 11), "11 chunks every level"); - Check.False(IltChunkClap.UnderChunkCap(0, 11), "revealed aetheria with no level read: never chunked"); - Check.False(IltChunkClap.UnderChunkCap(9, 9, coalesced: true), "a levelled Coalesced piece keeps the cap"); - Check.True(IltChunkClap.UnderChunkCap(0, 4, coalesced: true), "an unlevelled Coalesced piece chunks (it used to be kept forever)"); - Check.True(IltChunkClap.UnderChunkCap(0, 1, coalesced: true), "even with the lowest cap"); - } - - private static readonly IltChunkClap.AetheriaFacts PlainCoalesced = new( - Coalesced: true, MaxLevel: 0, NeverChunk: false, ItemXp: 0, Tinkers: 0, Imbue: 0, Crit: 0, CritDamage: 0, CritDamageResist: 0); - - private static void AetheriaRules() - { - var g = new IltGearState(); - Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced), null, "a plain unlevelled Coalesced piece chunks"); - Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { MaxLevel = 3 }), null, "level 3 under the default cap of 4"); - Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { MaxLevel = 4 }), "level at or above the cap", "level 4 at the default cap"); - Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { NeverChunk = true }), "never-chunk flag", "bool 9030"); - Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Tinkers = 1 }), "tinkered or imbued", "tinkered"); - Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Imbue = 4 }), "tinkered or imbued", "imbued"); - Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { ItemXp = 100 }), "has item XP", "levelled by use"); - Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Crit = 2 }), "kept for its C / CD / CDR rating", "a C 2 piece is kept by default"); - g.KeepAetheriaWithCrit = false; - Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Crit = 2 }), null, "C switch off: a C 2 piece chunks"); - Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Coalesced = false }), "no level read", "revealed aetheria needs a level"); - } - - /// - /// The rules read 0 for "the item has none" and for "the host could not read it". An unlevelled - /// Coalesced piece is chunked (ub-IT), but only when its level was truly read as none; a piece whose - /// properties could not be read is kept, whatever the numbers say. - /// - private static void UnreadableAetheria() - { - var g = new IltGearState(); - Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced), null, "read as unlevelled: chunks"); - Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Unreadable = "no appraisal" }), - "item data unreadable (no appraisal)", "the same piece with failed reads: kept"); - Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { MaxLevel = 2, Unreadable = "no item XP" }), - "item data unreadable (no item XP)", "a levelled piece with failed reads: kept"); - Check.Eq(IltChunkClap.AetheriaSkip(new IltGearState { ChunkAetheriaUnderLevel = 1 }, PlainCoalesced), null, "unlevelled chunks at the lowest cap too"); - - // Levelled Coalesced pieces keep the cap. - var cap9 = new IltGearState { ChunkAetheriaUnderLevel = 9 }; - Check.Eq(IltChunkClap.AetheriaSkip(cap9, PlainCoalesced with { MaxLevel = 8 }), null, "levelled 8 under a cap of 9"); - Check.Eq(IltChunkClap.AetheriaSkip(cap9, PlainCoalesced with { MaxLevel = 9 }), "level at or above the cap", "levelled 9 at a cap of 9"); - Check.Eq(IltChunkClap.AetheriaSkip(cap9, PlainCoalesced with { MaxLevel = 10 }), "level at or above the cap", "levelled 10 over a cap of 9"); - Check.Eq(IltChunkClap.AetheriaSkip(new IltGearState { ChunkAetheriaUnderLevel = 11 }, PlainCoalesced with { MaxLevel = 10 }), null, "cap 11 chunks every level"); - } - - private static void UnreadableCorrupted() - { - var g = new IltGearState(); - Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Unreadable = "no appraisal" }), - "item data unreadable (no appraisal)", "failed reads: kept (they would read as a plain weapon)"); - var keepCb = new IltGearState { KeepCorruptedCrushingBlow = true }; - Check.Eq(IltChunkClap.CorruptedSkip(keepCb, PlainSword with { Unreadable = "float properties" }), - "item data unreadable (float properties)", "a keep rule whose float cannot be read keeps the weapon"); - var twoHanded = PlainSword with { WieldSkill = 41, Cleaving = 2 }; - Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded), null, "two-handed cleave 2 chunks"); - Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Cleaving = 2 }), "cleave over the limit", "other cleave 2 is kept"); - Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { WieldSkill = 0, WeaponType = 11 }), null, "WeaponType two-handed counts"); - Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { AttackType = 2 }), "cleave over the limit", "two-handed thrust keeps the 1 limit"); - } - - private static void Kinds() - { - var gem = RynthCore.Loot.AcObjectClass.Gem; - Check.Eq(IltChunkClap.KindOf(gem, "Coalesced Aetheria"), IltChunkClap.ChunkKind.Aetheria, "Coalesced"); - Check.Eq(IltChunkClap.KindOf(gem, "Blue Aetheria"), IltChunkClap.ChunkKind.Aetheria, "revealed sigil"); - Check.Eq(IltChunkClap.KindOf(gem, "Red Aetheria Chunk"), IltChunkClap.ChunkKind.None, "chunk"); - Check.Eq(IltChunkClap.KindOf(gem, "Aetheria Powder"), IltChunkClap.ChunkKind.None, "powder"); - Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.MeleeWeapon, "Corrupted Greatsword"), IltChunkClap.ChunkKind.Corrupted, "melee"); - Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.MissileWeapon, "Corrupted Bow"), IltChunkClap.ChunkKind.Corrupted, "missile"); - Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.WandStaffOrb, "Corrupted Orb"), IltChunkClap.ChunkKind.None, "casters are not chunked (ub-IT)"); - Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.MeleeWeapon, "Greatsword"), IltChunkClap.ChunkKind.None, "not corrupted"); - } - - private static readonly IltChunkClap.CorruptedFacts PlainSword = new() { Workmanship = 6, AttackType = 4, WieldSkill = 45 }; - - private static void CorruptedHardRules() - { - var g = new IltGearState(); - Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword), null, "a plain corrupted sword chunks"); - Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Workmanship = 0 }), "no workmanship", "workmanship 0"); - Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Tinkers = 1 }), "tinkered or imbued", "tinkered"); - Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Imbue = 1 }), "tinkered or imbued", "imbued"); - Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { NeverChunk = true }), "never-chunk flag", "bool 9030"); - Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Cleaving = 1 }), null, "one-handed cleave 1"); - Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Cleaving = 2 }), "cleave over the limit", "one-handed cleave 2"); - - var twoHanded = PlainSword with { WieldSkill = 41, Cleaving = 2 }; - Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded), null, "two-handed cleave 2 chunks (it never did before)"); - Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { Cleaving = 3 }), "cleave over the limit", "two-handed cleave 3"); - Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { AttackType = 2 }), "cleave over the limit", "a two-handed thrust weapon keeps the 1 limit"); - Check.Eq(IltChunkClap.MaxChunkCleave(0, 11, 4), 2, "WeaponType TwoHanded counts too"); - Check.Eq(IltChunkClap.MaxChunkCleave(45, 0, 4), 1, "one-handed"); - } - - private static void CorruptedKeepRules() - { - var g = new IltGearState(); - var loaded = PlainSword with - { - CritFrequency = 0.1, CritMultiplier = 1.5, IgnoreArmor = 0.2, Slayer = 5, AttackType = 160, - ElementalBonus = 10, MaxDamage = 400, Spells = new[] { 2072 }, - }; - Check.Eq(IltChunkClap.CorruptedSkip(g, loaded), null, "every keep rule is off by default"); - - Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedCrushingBlow = true }, loaded), "kept: Crushing Blow", "Crushing Blow"); - Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedBitingStrike = true }, loaded), "kept: Biting Strike", "Biting Strike"); - Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedArmorCleaving = true }, loaded), "kept: Armor Cleaving", "Armor Cleaving"); - Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedAnySlayer = true }, loaded), "kept: slayer", "slayer"); - Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMultiStrike = true }, loaded), "kept: multi-strike", "multi-strike 160"); - Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMultiStrike = true }, PlainSword), null, "a single slash is not multi-strike"); - Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedElementalBonus = true }, loaded), "kept: elemental bonus", "elemental"); - Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMaxDamageAtLeast = 400 }, loaded), "kept: max damage", "max damage at the limit"); - Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMaxDamageAtLeast = 401 }, loaded), null, "max damage under the limit"); - Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedAnySpell = true }, loaded), "kept: has a spell", "any spell"); - Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedSpellIds = "100, 2072" }, loaded), "kept: listed spell", "listed spell id"); - Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedSpellIds = "100 200" }, loaded), null, "other spell ids"); - - Check.Eq(IltChunkClap.ParseSpellIds("1, 2;3 x -4 0").Count, 3, "positive ids only, any separator"); - Check.Eq(IltChunkClap.ParseSpellIds(null).Count, 0, "no list"); - } - - /// - /// Silentkelpie 2026-10-18: a Coalesced piece was chunked (Red Aetheria Chunk arrived) with no - /// result line, and it was filed as skipped after 10 s instead of counted. - /// - private static void WaitOutcome() - { - Check.Eq(IltChunkClap.WaitOutcome(500, targetStillCarried: true), IltChunkClap.ChunkWait.Waiting, "still carried, within the wait"); - Check.Eq(IltChunkClap.WaitOutcome(1_100, targetStillCarried: false), IltChunkClap.ChunkWait.Gone, "gone from the pack: chunked"); - Check.Eq(IltChunkClap.WaitOutcome(12_000, targetStillCarried: false), IltChunkClap.ChunkWait.Gone, "gone beats the timeout"); - Check.Eq(IltChunkClap.WaitOutcome(10_000, targetStillCarried: true), IltChunkClap.ChunkWait.TimedOut, "still carried at 10 s: timed out"); - } - - private static void BusyGate() - { - Check.True(IltChunkClap.AllowsChunkWhileBusy(isBusy: false, isPeace: true, chunkInCombat: false), "idle in peace"); - Check.False(IltChunkClap.AllowsChunkWhileBusy(isBusy: true, isPeace: true, chunkInCombat: true), "busy in peace waits"); - Check.True(IltChunkClap.AllowsChunkWhileBusy(isBusy: true, isPeace: false, chunkInCombat: true), "busy swinging with chunk-in-combat"); - Check.False(IltChunkClap.AllowsChunkWhileBusy(isBusy: true, isPeace: false, chunkInCombat: false), "busy in combat without it"); - } - - /// - /// ACECustom /clap: red (Coalesced 42636 at 1-3, chunk 310147, powder 42644) with Empyrean - /// Trinkets (34276); blue (42635, 310149, 300019) with Falatacot (34277). 42635/42636 were taken - /// for chunks, and one side alone counted, so auto-clap sent /clap with nothing to pair. - /// - private static void ClapPairs() - { - const string Co = "Coalesced Aetheria"; - Check.Eq(IltChunkClap.ClapPartOf(42636, Co, 2), IltChunkClap.ClapPart.Red, "red Coalesced level 2"); - Check.Eq(IltChunkClap.ClapPartOf(42635, Co, 3), IltChunkClap.ClapPart.Blue, "blue Coalesced level 3"); - Check.Eq(IltChunkClap.ClapPartOf(42636, Co, 0), IltChunkClap.ClapPart.Red, "level not read yet: the server decides"); - Check.Eq(IltChunkClap.ClapPartOf(42636, Co, 4), IltChunkClap.ClapPart.None, "level 4 Coalesced is not clapped"); - Check.Eq(IltChunkClap.ClapPartOf(42636, "Aetheria", 1), IltChunkClap.ClapPart.None, "revealed aetheria is not clapped"); - Check.Eq(IltChunkClap.ClapPartOf(42637, Co, 1), IltChunkClap.ClapPart.None, "yellow has no clap use"); - Check.Eq(IltChunkClap.ClapPartOf(310147, "Red Aetheria Chunk", 0), IltChunkClap.ClapPart.Red, "red chunk"); - Check.Eq(IltChunkClap.ClapPartOf(310149, "Blue Aetheria Chunk", 0), IltChunkClap.ClapPart.Blue, "blue chunk"); - Check.Eq(IltChunkClap.ClapPartOf(310150, "Yellow Aetheria Chunk", 0), IltChunkClap.ClapPart.None, "yellow chunk"); - Check.Eq(IltChunkClap.ClapPartOf(42644, "Aetheria Powder", 0), IltChunkClap.ClapPart.Red, "red powder"); - Check.Eq(IltChunkClap.ClapPartOf(300019, "Aetheria Powder", 0), IltChunkClap.ClapPart.Blue, "blue powder"); - Check.Eq(IltChunkClap.ClapPartOf(34276, "Ancient Empyrean Trinket", 0), IltChunkClap.ClapPart.Empyrean, "Empyrean trinket"); - Check.Eq(IltChunkClap.ClapPartOf(34277, "Ancient Falatacot Trinket", 0), IltChunkClap.ClapPart.Falatacot, "Falatacot trinket"); - Check.Eq(IltChunkClap.ClapPartOf(0, "Red Aetheria Chunk", 0), IltChunkClap.ClapPart.Red, "no WCID yet: the chunk name"); - Check.Eq(IltChunkClap.ClapPartOf(0, Co, 1), IltChunkClap.ClapPart.None, "no WCID yet: a Coalesced piece's colour is unknown"); - Check.Eq(IltChunkClap.ClapPartOf(273, "Pyreal", 0), IltChunkClap.ClapPart.None, "anything else"); - - var R = IltChunkClap.ClapPart.Red; var B = IltChunkClap.ClapPart.Blue; - var E = IltChunkClap.ClapPart.Empyrean; var F = IltChunkClap.ClapPart.Falatacot; - Check.True(IltChunkClap.CanClap(new[] { R, E }), "red + Empyrean"); - Check.True(IltChunkClap.CanClap(new[] { B, F }), "blue + Falatacot"); - Check.False(IltChunkClap.CanClap(new[] { R, F }), "red needs Empyrean, not Falatacot"); - Check.False(IltChunkClap.CanClap(new[] { B, E }), "blue needs Falatacot, not Empyrean"); - Check.False(IltChunkClap.CanClap(new[] { E, F }), "trinkets alone"); - Check.False(IltChunkClap.CanClap(new[] { R, B }), "aetheria alone"); - Check.False(IltChunkClap.CanClap(System.Array.Empty()), "nothing carried"); - } - - private static void Cap() - { - Check.Eq(IltInventory.AetheriaMaxLevel, 10, "ILT max aetheria level"); - Check.Eq(IltChunkClap.ClampUnderLevel(0), 1, "below 1 clamps to 1"); - Check.Eq(IltChunkClap.ClampUnderLevel(7), 7, "7 (retail clamp was 6) is allowed"); - Check.Eq(IltChunkClap.ClampUnderLevel(11), 11, "11 chunks every level"); - Check.Eq(IltChunkClap.ClampUnderLevel(50), 11, "above 11 clamps to 11"); - Check.Eq(new IltGearState().ChunkAetheriaUnderLevel, 4, "the default cap is unchanged"); - } - - private static void Ratings() - { - var g = new IltGearState(); - Check.True(g.KeepAetheriaWithCrit && g.KeepAetheriaWithCritDamage && g.KeepAetheriaWithCritDamageResist, "all keep switches on by default"); - Check.False(IltChunkClap.KeptForRatings(g, 0, 0, 0), "no rating: chunkable"); - Check.True(IltChunkClap.KeptForRatings(g, 2, 0, 0), "C kept"); - Check.True(IltChunkClap.KeptForRatings(g, 0, 1, 0), "CD kept"); - Check.True(IltChunkClap.KeptForRatings(g, 0, 0, 3), "CDR kept"); - - g.KeepAetheriaWithCrit = false; - Check.False(IltChunkClap.KeptForRatings(g, 2, 0, 0), "C chunkable with its switch off"); - Check.True(IltChunkClap.KeptForRatings(g, 2, 0, 3), "CDR still keeps a C+CDR sigil"); - g.KeepAetheriaWithCritDamage = false; - g.KeepAetheriaWithCritDamageResist = false; - Check.False(IltChunkClap.KeptForRatings(g, 3, 3, 3), "every switch off: ratings don't protect"); - } - - /// - /// The rating level: a C / CD / CDR rating at or above it keeps the piece, a lower one chunks - /// (if the level cap allows). The default of 1 keeps any rating, as before. - /// - private static void RatingLevel() - { - var g = new IltGearState(); - Check.Eq(g.KeepAetheriaRatingAtLeast, 1, "default: any rating keeps"); - Check.True(IltChunkClap.KeptForRatings(g, 1, 0, 0), "C 1 kept at the default"); - - g.KeepAetheriaRatingAtLeast = 2; - Check.False(IltChunkClap.KeptForRatings(g, 1, 0, 0), "C 1 below level 2: chunks"); - Check.True(IltChunkClap.KeptForRatings(g, 2, 0, 0), "C 2 at level 2: kept"); - Check.True(IltChunkClap.KeptForRatings(g, 3, 0, 0), "C 3 above level 2: kept"); - Check.True(IltChunkClap.KeptForRatings(g, 1, 0, 2), "CDR 2 keeps a C 1 + CDR 2 piece"); - Check.False(IltChunkClap.KeptForRatings(g, 1, 1, 1), "every rating below the level: chunks"); - - g.KeepAetheriaWithCrit = false; - Check.False(IltChunkClap.KeptForRatings(g, 5, 0, 0), "a switch that is off ignores the level"); - - Check.Eq(IltChunkClap.ClampRatingLevel(0), 1, "below 1 clamps to 1"); - Check.Eq(IltChunkClap.ClampRatingLevel(99), IltChunkClap.MaxRatingLevel, "clamped to the maximum"); - - var coalescedC1 = PlainCoalesced with { Crit = 1 }; - var level2 = new IltGearState { KeepAetheriaRatingAtLeast = 2 }; - Check.Eq(IltChunkClap.AetheriaSkip(level2, coalescedC1), null, "an unlevelled C 1 Coalesced piece chunks at rating level 2"); - Check.Eq(IltChunkClap.AetheriaSkip(level2, PlainCoalesced with { Crit = 2 }), "kept for its C / CD / CDR rating", "a C 2 one is kept"); - Check.Eq(IltChunkClap.AetheriaSkip(level2, coalescedC1 with { MaxLevel = 6 }), "level at or above the cap", - "a low rating does not override the level cap"); - } -} diff --git a/Tools/RynthILT.Tests/AttributeRaiserTests.cs b/Tools/RynthILT.Tests/AttributeRaiserTests.cs deleted file mode 100644 index 01765da..0000000 --- a/Tools/RynthILT.Tests/AttributeRaiserTests.cs +++ /dev/null @@ -1,543 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.PluginSdk; -using RynthCore.RynthAiHostTests.Fakes; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// Server Features gate + the infinite-attribute raiser (2026-10-06; RynthAi's ILT Hub, in RynthILT -// since 2026-10-13). The gate decides from RynthILT's server list (world-name patterns) and the -// character's "Treat this world as ILT" whether the ILT features ask the server at all; the raiser reads "/xp all" costs and spends unassigned XP with "/attr 1" -// on the ticked stats, in the chosen order, never below the reserve. -internal static class AttributeRaiserTests -{ - private const uint Player = 0x50000C01; - - public static void Register(Runner r) - { - r.Add("server features: name patterns (exact, wildcards, case)", Patterns); - r.Add("server features: list parsing and the override", ListAndOverride); - r.Add("attr raiser: pick by mode (priority, round robin, cheapest)", PickModes); - r.Add("attr raiser: pick respects ticks, reserve and unknown costs", PickLimits); - r.Add("attr raiser: order repair and stat names from server lines", OrderAndNames); - r.Add("attr raiser: a run reads costs, raises in order, stops when nothing is affordable", FullRun); - r.Add("attr raiser: off when the world is not in the Server Features list", GatedOff); - r.Add("attr raiser: safety (stale costs, another stat's reply, gate off mid-run, held off)", Safety); - r.Add("attr raiser: by-hand +1 / +10 priced like UB, refused when unaffordable, costs read on tab open", ByHandPriced); - r.Add("aug planner: /aug pulled on tab open, totals, reset targets, copy texts", AugPlanner); - r.Add("aug refresh: banner alone does not end /aug; Current updates from level lines", AugRefreshWaitsForLevelLines); - r.Add("aug refresh: a probe that left Current empty retries /aug once; a click during the probe runs after it", AugProbeRetry); - r.Add("aug lines: separators in the level (4,300 / 4.300 / 4 300 / 4'300) and trailing notes read", AugLineValues); - r.Add("aug costs: UB's ILT model (tier starts at its S level) in closed form", AugCostModel); - r.Add("aug costs: per-server multipliers and rules, saved and reset", AugCostSettings); - } - - /// UB Augs.cs GetCumulativeCost difference, level by level (the reference the closed form must match). - private static decimal UbLoop(IltAugCostRow r, double[] m, int cur, int tgt) - { - decimal step = r.Base * (decimal)r.LinearPercent / 100m, total = 0; - for (int i = cur + 1; i <= tgt; i++) - { - decimal b = r.Base + (i - 1) * step; - double mult = i < r.S1 ? m[0] : i < r.S2 ? m[1] : i < r.S3 ? m[2] : i < r.S4 ? m[3] : m[4]; - total += b * (decimal)mult; - } - return total; - } - - private static void AugCostModel() - { - var rows = IltAugCosts.DefaultRows().ToDictionary(x => x.Key); - var m = IltAugCosts.DefaultMultipliers; - var creature = rows["creature"]; - Check.Eq(IltAugCosts.LumCost(creature, m, 2748, 2749), 750_000m + 2748 * 975_000m, "level 2749 (S1 - 1) is the last x1 level"); - Check.Eq(IltAugCosts.LumCost(creature, m, 2749, 2750), (750_000m + 2749 * 975_000m) * 4, "level 2750 (S1) is the first x4 level"); - Check.Eq(rows["specialization"].S2, 2500, "Specialization uses UB's 1750/2500/3000/3750"); - Check.Eq(rows["summon"].S1, 1750, "Summon uses UB's 1750/2500/3000/3750"); - Check.Eq(creature.Cap, 0, "no target cap by default (UB has none)"); - - foreach (var (key, cur, tgt) in new[] { ("creature", 0, 6000), ("item", 1200, 3600), ("specialization", 1700, 3800), - ("duration", 999, 1001), ("summon", 3749, 3751), ("life", 10, 10) }) - Check.Eq(IltAugCosts.LumCost(rows[key], m, cur, tgt), UbLoop(rows[key], m, cur, tgt), $"{key} {cur}->{tgt} matches UB's loop"); - var odd = new double[] { 1.5, 2, 3.25, 10, 0 }; - Check.Eq(IltAugCosts.LumCost(rows["war"], odd, 1500, 4000), UbLoop(rows["war"], odd, 1500, 4000), "custom multipliers match the loop"); - Check.Eq(IltAugCosts.LumCost(creature, m, 50, 40), 0m, "a target below current costs nothing"); - Check.True(IltAugCosts.LumCost(creature, m, 0, IltAugCosts.NoCapLimit) > 0, "the largest uncapped target is priced without overflow"); - } - - private static void AugCostSettings() - { - string file = IltAugCosts.FilePath; - if (File.Exists(file)) File.Delete(file); - var settings = new IltSettings(); - var hub = NewHub("InfiniteLeaftide", settings, "aug-costs", out _); - var prog = hub.Progression; - prog.ApplyAugLines(new List { "War: 1700" }); - hub.State.Character.AugTargets["war"] = 1800; - - string Snapshot() - { - var sb = new System.Text.StringBuilder(); - prog.AppendSnapshotJson(sb); - return "{" + sb + "}"; - } - System.Text.Json.JsonElement Aug(string json) => System.Text.Json.JsonDocument.Parse(json).RootElement.GetProperty("aug"); - - var before = Aug(Snapshot()); - Check.False(before.GetProperty("cfg").GetProperty("custom").GetBoolean(), "a world starts on the defaults"); - Check.Eq(before.GetProperty("cfg").GetProperty("mults").GetArrayLength(), 5, "five tier multipliers in the snapshot"); - string lumBefore = before.GetProperty("totLum").GetString() ?? ""; - - prog.HandleRemote(new[] { "augmult", "1", "2" }); - var after = Aug(Snapshot()); - Check.True(after.GetProperty("cfg").GetProperty("custom").GetBoolean(), "an edit gives the world its own rules"); - Check.Eq(after.GetProperty("cfg").GetProperty("mults")[1].GetDouble(), 2.0, "multiplier saved"); - Check.True((after.GetProperty("totLum").GetString() ?? "") != lumBefore, "the plan re-prices with the new multiplier"); - - prog.HandleRemote(new[] { "augcfg", "war", "s1", "1800" }); - prog.HandleRemote(new[] { "augcfg", "war", "base", "1m" }); - prog.HandleRemote(new[] { "augcfg", "war", "s2", "100" }); - var war = prog.AugCosts.For("InfiniteLeaftide").Augs.First(x => x.Key == "war"); - Check.Eq(war.S1, 1800, "S1 edited"); - Check.Eq(war.Base, 1_000_000L, "base accepts k/m/b suffixes"); - Check.Eq(war.S2, 1800, "S2 can't go below S1"); - Check.Eq(prog.AugCosts.For("Aelrynth").Multipliers[1], 4.0, "another world keeps the defaults"); - - var reloaded = new IltAugCosts(); - Check.Eq(reloaded.For("infiniteleaftide").Multipliers[1], 2.0, "rules are saved per world (name ignores case)"); - - prog.HandleRemote(new[] { "augcfgreset" }); - Check.False(prog.AugCosts.IsCustom("InfiniteLeaftide"), "reset drops the world's rules"); - Check.Eq(new IltAugCosts().For("InfiniteLeaftide").Multipliers[1], 4.0, "and the reset is saved"); - } - - private static void ByHandPriced() - { - Check.Eq(IltAttributeRaiser.ProjectCost(1_000, 1), 1_000L, "one level costs the reported cost"); - // 1000 * (1.077^10 - 1) / 0.077 = 14,281.7 (UB's EstimateMultiLevelCost). - Check.Eq(IltAttributeRaiser.ProjectCost(1_000, 10), 14_281L, "ten levels grow 7.7% each"); - Check.Eq(IltAttributeRaiser.ProjectCost(0, 10), 0L, "unknown cost projects nothing"); - Check.Eq(IltAttributeRaiser.ProjectCost(long.MaxValue / 2, 10), long.MaxValue, "saturates instead of overflowing"); - - var settings = new IltSettings(); - var hub = NewHub("InfiniteLeaftide", settings, "attr-byhand", out _); - var raiser = hub.Progression.Attributes; - FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 5_000; - // Levels already known (as after the login probe), so the tab doesn't queue /aug ahead of /xp all. - hub.Progression.ApplyAugLines(new List { "Creature: 1" }); - - // Opening the tab (a snapshot poll) reads the costs once per login. - var sb = new System.Text.StringBuilder(); - hub.Progression.AppendSnapshotJson(sb); - Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "the first snapshot reads the costs"); - Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 1,000", - "[XP] Your XP cost for next 1 Strength level is: 4,000"); - TickUntil(hub, () => false, 400); - int reads = FakeHost.ChatCommands.Count(x => x == "/xp all"); - hub.Progression.AppendSnapshotJson(new System.Text.StringBuilder()); - TickUntil(hub, () => false, 400); - Check.Eq(FakeHost.ChatCommands.Count(x => x == "/xp all"), reads, "later snapshots don't read again"); - - sb.Clear(); - raiser.AppendJson(sb); - string json = sb.ToString(); - System.Text.Json.JsonDocument.Parse("{" + json + "}").Dispose(); - Check.True(json.Contains("\"key\":\"coo\"") && json.Contains("\"afford1\":true") && json.Contains("\"cost10\":\"~14.3K\""), - $"Coordination: +1 affordable, +10 projected (got {json})"); - Check.True(json.Contains("\"updated\":\"") && !json.Contains("\"updated\":\"-\""), "the last-updated time is set"); - - // +10 Coordination (~14.3K of 5K) is refused; +1 Strength (4K of 5K) goes out. - raiser.RaiseManual("coo", 10); - var status = new System.Text.StringBuilder(); - raiser.AppendJson(status); - Check.True(status.ToString().Contains("Not enough unassigned XP"), "an unaffordable +10 is refused with the reason"); - raiser.RaiseManual("str", 1); - Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr str 1")), "an affordable +1 is sent"); - Check.False(FakeHost.ChatCommands.Contains("/attr coo 10"), "the refused +10 was never sent"); - } - - private static void AugPlanner() - { - var settings = new IltSettings(); - var hub = NewHub("InfiniteLeaftide", settings, "aug-planner", out _); - var prog = hub.Progression; - - prog.AppendSnapshotJson(new System.Text.StringBuilder()); - Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/aug")), "opening the tab pulls /aug once"); - prog.ApplyAugLines(new List { "Creature: 100", "Specialize: 2", "Summon: 0" }); - - prog.HandleRemote(new[] { "augtarget", "creature", "110" }); - var sb = new System.Text.StringBuilder(); - prog.AppendSnapshotJson(sb); - string json = sb.ToString(); - using (var doc = System.Text.Json.JsonDocument.Parse("{" + json + "}")) - { - var aug = doc.RootElement.GetProperty("aug"); - Check.Eq(aug.GetProperty("totCur").GetInt64(), 102L, "totals: current"); - Check.Eq(aug.GetProperty("totTgt").GetInt64(), 112L, "totals: target"); - Check.Eq(aug.GetProperty("totInc").GetInt64(), 10L, "totals: increase"); - Check.Eq(aug.GetProperty("totCoins").GetInt64(), 30L, "Creature costs 3 coins a level"); - var creature = aug.GetProperty("rows").EnumerateArray().First(x => x.GetProperty("key").GetString() == "creature"); - Check.Eq(creature.GetProperty("inc").GetInt32(), 10, "row: increase"); - string discord = aug.GetProperty("copyDiscord").GetString() ?? ""; - Check.True(discord.StartsWith("```", StringComparison.Ordinal) && discord.Contains("TOTALS:") && discord.Contains("Creature"), - "Discord copy is a code-block table with totals"); - Check.True(discord.All(ch => ch < 128), "copy text is ASCII (the engine reads the snapshot as ANSI)"); - string ingame = aug.GetProperty("copyIngame").GetString() ?? ""; - Check.True(ingame.Contains("Crit: 100") && ingame.Contains("Spec: 2") && !ingame.Contains("Sum:"), - $"in-game copy lists current levels with short names (got '{ingame}')"); - } - - prog.HandleRemote(new[] { "augreset" }); - Check.Eq(hub.State.Character.AugTargets["creature"], 100, "reset targets: back to current"); - Check.Eq(hub.State.Character.AugTargets["summon"], 0, "reset targets: unloaded augs go to 0"); - Check.Eq(FakeHost.ChatCommands.Count(x => x == "/aug"), 1, "levels loaded: no second automatic /aug"); - } - - /// - /// Refresh current must not finish on the /aug banner alone (chat-hold lag used to leave Current at 0). - /// - private static void AugRefreshWaitsForLevelLines() - { - var settings = new IltSettings(); - var hub = NewHub("InfiniteLeaftide", settings, "aug-refresh-idle", out _); - var prog = hub.Progression; - // Seed so EnsureAugs does not queue its own /aug ahead of our Refresh. - prog.ApplyAugLines(new List { "Creature: 1" }); - - prog.HandleRemote(new[] { "augload" }); - Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/aug")), "Refresh current sends /aug"); - Reply(hub, "---------------------------", "Advanced Augmentation Levels:"); - // Longer than IdleEndMs (2s): without ArmsIdle this used to ApplyAugLines([]) and clear the status. - var until = DateTime.UtcNow.AddMilliseconds(2500); - while (DateTime.UtcNow < until) { hub.Tick(); Thread.Sleep(25); } - Check.True(FakeHost.ChatCommands.Count(x => x == "/aug") == 1, "still waiting on the same /aug (banner did not end it)"); - - Reply(hub, "Creature:4,300", "Item:100", "Specialize: 2"); - Check.True(TickUntil(hub, () => - { - var sb = new System.Text.StringBuilder(); - prog.AppendSnapshotJson(sb); - return sb.ToString().Contains("\"cur\":4300", StringComparison.Ordinal); - }), "Current updates once Creature:/Item: lines arrive"); - } - - // Silentkelpie (PR #12): the login probe could end on the banner alone (chat-hold backlog) and leave - // Current empty with nothing to retry it; a Refresh current click during the probe was dropped. - private static void AugProbeRetry() - { - var hub = NewHub("InfiniteLeaftide", new IltSettings(), "aug-probe-retry", out _); - var prog = hub.Progression; - - // Probe reply: the banner and no level lines. The tap runs ApplyAugLines then AfterExternalAugCapture. - prog.ApplyAugLines(new List { "---------------------------", "Advanced Augmentation Levels:" }); - prog.AfterExternalAugCapture(); - Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/aug")), "Current still empty: /aug is sent again"); - prog.AfterExternalAugCapture(); // the retry is in flight, and was the one retry - prog.ApplyAugLines(new List { "Advanced Augmentation Levels:" }); - prog.AfterExternalAugCapture(); - for (int i = 0; i < 20; i++) { hub.Tick(); Thread.Sleep(25); } - Check.Eq(FakeHost.ChatCommands.Count(x => x == "/aug"), 1, "only one retry"); - - Reply(hub, "Creature:4,300", "Item:100"); - Check.True(TickUntil(hub, () => - { - var sb = new System.Text.StringBuilder(); - prog.AppendSnapshotJson(sb); - return sb.ToString().Contains("\"cur\":4300", StringComparison.Ordinal); - }), "the retry's level lines fill Current"); - - // A probe with levels needs no retry. - var hub2 = NewHub("InfiniteLeaftide", new IltSettings(), "aug-probe-ok", out _); - hub2.Progression.ApplyAugLines(new List { "Creature: 12" }); - hub2.Progression.AfterExternalAugCapture(); - for (int i = 0; i < 20; i++) { hub2.Tick(); Thread.Sleep(25); } - Check.Eq(FakeHost.ChatCommands.Count(x => x == "/aug"), 0, "levels present: no retry"); - } - - private static void AugLineValues() - { - Check.True(IltParse.AugLine.IsMatch("Creature:4,300") && IltParse.AugLine.IsMatch("Creature: 4.300") - && IltParse.AugLine.IsMatch("Creature: 4 300") && IltParse.AugLine.IsMatch("Creature: 4'300"), "the regex matches each grouping"); - Check.False(IltParse.AugLine.IsMatch("Creature: none") || IltParse.AugLine.IsMatch("Advanced Augmentation Levels:"), "and not a line with no number"); - Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature:4,300").Groups[2].Value), 4300L, "comma"); - Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 4.300").Groups[2].Value), 4300L, "period"); - Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 4 300").Groups[2].Value), 4300L, "space"); - Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 4'300").Groups[2].Value), 4300L, "apostrophe"); - Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 1,234,567").Groups[2].Value), 1234567L, "two groups"); - Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Duration: 5 (adds 3)").Groups[2].Value), 5L, "a trailing note"); - Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Specialize: 2").Groups[2].Value), 2L, "plain"); - Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Item: 2750").Groups[2].Value), 2750L, "no separator"); - Check.Eq(IltParse.ParseAugValue(""), 0L, "empty"); - - var hub = NewHub("InfiniteLeaftide", new IltSettings(), "aug-values", out _); - hub.Progression.ApplyAugLines(new List { "Creature: 2 750", "Item: 1.200", "Life: 300" }); - var sb = new System.Text.StringBuilder(); - hub.Progression.AppendSnapshotJson(sb); - string snap = sb.ToString(); - Check.True(snap.Contains("\"cur\":2750", StringComparison.Ordinal) && snap.Contains("\"cur\":1200", StringComparison.Ordinal) - && snap.Contains("\"cur\":300", StringComparison.Ordinal), "the planner takes the grouped levels whole"); - } - - private static void Patterns() - { - Check.True(ServerFeatureGate.Matches("InfiniteLeaftide", "InfiniteLeaftide"), "exact"); - Check.True(ServerFeatureGate.Matches("infiniteleaftide", "InfiniteLeaftide"), "exact ignores case"); - Check.False(ServerFeatureGate.Matches("InfiniteLeaftide2", "InfiniteLeaftide"), "exact means the whole name"); - Check.True(ServerFeatureGate.Matches("Leaftide Test", "*Leaftide*"), "contains"); - Check.True(ServerFeatureGate.Matches("MyLeaftide", "*tide"), "ends with"); - Check.True(ServerFeatureGate.Matches("Leaftide-PTR", "Leaf*"), "starts with"); - Check.True(ServerFeatureGate.Matches("Aelrynth Infinite", "Ael*Inf*"), "two wildcards"); - Check.False(ServerFeatureGate.Matches("Aelrynth", "*Leaftide*"), "no match"); - Check.False(ServerFeatureGate.Matches("ab", "a*bb"), "the end part must fit after the start"); - Check.True(ServerFeatureGate.NameMatches("Aelrynth", new[] { "", "InfiniteLeaftide", "aelrynth" }, out string m) && m == "aelrynth", - "NameMatches reports the pattern that matched"); - Check.False(ServerFeatureGate.NameMatches("", ServerFeatureGate.DefaultServerNames, out _), "an unknown world never matches"); - } - - private static void ListAndOverride() - { - var list = ServerFeatureGate.ParseList(" InfiniteLeaftide , *Leaftide*;Aelrynth,,aelrynth "); - Check.Eq(string.Join("|", list), "InfiniteLeaftide|*Leaftide*|Aelrynth", "trimmed, split on , and ;, de-duplicated ignoring case"); - Check.Eq(ServerFeatureGate.FormatList(list), "InfiniteLeaftide, *Leaftide*, Aelrynth", "formatted back for the text box"); - - var s = new IltSettings(); - Check.True(s.ServerNames.Contains("InfiniteLeaftide"), "fresh settings start with the defaults"); - Check.True(ServerFeatureGate.IsEnabled("InfiniteLeaftide", s, forceOn: false), "the default list covers InfiniteLeaftide"); - Check.False(ServerFeatureGate.IsEnabled("Aelrynth", s, forceOn: false), "another world is off by default"); - Check.True(ServerFeatureGate.IsEnabled("Aelrynth", s, forceOn: true), "the character's override turns it on anywhere"); - s.ServerNames = new List { "Aelrynth" }; - Check.True(ServerFeatureGate.IsEnabled("aelrynth", s, forceOn: false), "a world added to the list is on"); - Check.False(ServerFeatureGate.IsEnabled("InfiniteLeaftide", s, forceOn: false), "a world removed from the list is off"); - Check.True(ServerFeatureGate.IsEnabled("InfiniteLeaftide", null, forceOn: false), "no settings yet: the defaults apply"); - s.ServerNames = new List(); - Check.True(ServerFeatureGate.IsEnabled("InfiniteLeaftide", s, forceOn: false), "an emptied list falls back to the defaults"); - } - - private static readonly string[] Order = { "coo", "qui", "str", "end", "foc", "sel", "hea", "sta", "man" }; - - private static void PickModes() - { - var cost = new Dictionary { ["coo"] = 500, ["qui"] = 300, ["str"] = 100 }; - var ticked = new HashSet { "coo", "qui", "str" }; - int rr = 0; - Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, ticked, cost, 1000, ref rr), "coo", - "priority: the first affordable stat in the order"); - Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, ticked, cost, 400, ref rr), "qui", - "priority: skips a stat it can't afford"); - Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, ticked, cost, 1000, ref rr), "str", - "cheapest: the lowest next-level cost"); - var tie = new Dictionary { ["coo"] = 100, ["str"] = 100 }; - Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, ticked, tie, 1000, ref rr), "coo", - "cheapest: a tie goes to the higher-priority stat"); - - rr = 0; - var picks = new List(); - for (int i = 0; i < 4; i++) picks.Add(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 1000, ref rr)); - Check.Eq(string.Join(",", picks), "coo,qui,str,coo", "round robin: one each in order, then around again"); - rr = 0; - Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 400, ref rr), "qui", - "round robin: an unaffordable stat is passed over"); - Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 400, ref rr), "str", - "round robin: carries on from the last pick"); - } - - private static void PickLimits() - { - var cost = new Dictionary { ["coo"] = 500, ["qui"] = 300 }; - int rr = 0; - Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet(), cost, 10_000, ref rr), - "nothing ticked: nothing raised"); - Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet { "qui" }, cost, 10_000, ref rr), "qui", - "an unticked stat is never spent on, even at the top of the order"); - Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet { "coo", "qui" }, cost, 0, ref rr), - "no budget (XP at or below the reserve): nothing raised"); - Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet { "str" }, cost, 10_000, ref rr), - "a stat whose cost wasn't read is not raised blind"); - var zero = new Dictionary { ["coo"] = 0 }; - Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, new HashSet { "coo" }, zero, 10_000, ref rr), - "a zero cost (unparsed) is not raised"); - } - - private static void OrderAndNames() - { - var repaired = IltAttributeRaiser.RepairOrder(new List { "sel", "bogus", "Self", "Strength", "hea" }); - Check.Eq(string.Join(",", repaired), "sel,str,hea,coo,qui,end,foc,sta,man", - "saved order kept, duplicates/junk dropped, missing stats appended in the default order"); - Check.Eq(IltAttributeRaiser.RepairOrder(null).Count, 9, "a missing order becomes the default"); - Check.Eq(string.Join(",", IltAttributeRaiser.RepairSelection(new List { "Coordination", "coo", "x" })), "coo", - "selection: names map to abbreviations, duplicates and junk dropped"); - - Check.Eq(IltAttributeRaiser.Find("MaxHealth")?.Abbr, "hea", "cost line 'MaxHealth'"); - Check.Eq(IltAttributeRaiser.Find("Maximum Stamina")?.Abbr, "sta", "'Maximum Stamina'"); - Check.Eq(IltAttributeRaiser.Find("Self")?.Abbr, "sel", "Self"); - Check.Eq(IltAttributeRaiser.Find("qui")?.Abbr, "qui", "abbreviation"); - Check.Null(IltAttributeRaiser.Find("Luck"), "unknown names are rejected"); - - var cost = IltParse.XpCost.Match("[XP] Your XP cost for next 1 Coordination level is: 12,345,678"); - Check.True(cost.Success && cost.Groups[1].Value == "Coordination" && IltParse.ParseLeadingLong(cost.Groups[2].Value) == 12_345_678, - "the /xp all cost line parses"); - var raised = IltParse.AttrRaised.Match("[ATTR] Quickness attribute raised by 1, costing 9,876!"); - Check.True(raised.Success && raised.Groups[1].Value == "Quickness" && raised.Groups[2].Value == "1" - && IltParse.ParseLeadingLong(raised.Groups[3].Value) == 9876, "the /attr success line parses"); - } - - // ── The loop on the fake host ───────────────────────────────────────────── - - private static IltHubController NewHub(string world, IltSettings settings, string folder, out RynthCoreHost host) - { - FakeHost.Reset(); - FakeHost.WorldName = world; - host = FakeHost.Create(Player); - string dir = Path.Combine(Program.TempRoot, folder); - Directory.CreateDirectory(dir); - // No RynthAi here (the fake host has no GetPluginInterface): RynthILT runs on its own. - return new IltHubController(host, dir, settings, new RynthAiClient(host)); - } - - /// Ticks the hub until or the timeout (the chat queue spaces sends by real time). - private static bool TickUntil(IltHubController hub, Func done, int timeoutMs = 6000) - { - var until = DateTime.UtcNow.AddMilliseconds(timeoutMs); - while (DateTime.UtcNow < until) - { - hub.Tick(); - if (done()) return true; - Thread.Sleep(25); - } - return false; - } - - private static void Reply(IltHubController hub, params string[] lines) - { - foreach (string l in lines) hub.OnChat(l); - } - - private static void FullRun() - { - var settings = new IltSettings(); - var hub = NewHub("InfiniteLeaftide", settings, "attr-run", out _); - var c = hub.State.Character; - c.AttrRaiseStats = new List { "coo", "qui" }; - c.AttrRaiseMode = (int)IltAttributeRaiser.Mode.Priority; - c.AttrKeepXp = 200; - FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 2_500; - var raiser = hub.Progression.Attributes; - - Check.Null(raiser.Blocker(), "an ILT world with /xp not reported off: the raiser can run"); - raiser.Start(auto: false); - Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "a run starts by reading the costs"); - Reply(hub, "[XP] Your XP cost for next 1 Strength level is: 50", - "[XP] Your XP cost for next 1 Coordination level is: 1,000", - "[XP] Your XP cost for next 1 Quickness level is: 1,200"); - Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr coo 1")), - "priority: Coordination first (Strength is cheaper but not ticked)"); - - FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 1_500; - Reply(hub, "[ATTR] Coordination attribute raised by 1, costing 1,000!"); - Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Count(x => x == "/xp all") >= 2), "costs are read again after each raise"); - Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 2,000", - "[XP] Your XP cost for next 1 Quickness level is: 1,200"); - Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr qui 1")), - "Coordination now costs more than the spendable 1,300: Quickness next"); - - FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 300; - Reply(hub, "[ATTR] Quickness attribute raised by 1, costing 1,200!"); - Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Count(x => x == "/xp all") >= 3), "third cost read"); - Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 2,000", - "[XP] Your XP cost for next 1 Quickness level is: 1,500"); - Check.True(TickUntil(hub, () => !raiser.Running), "nothing affordable above the reserve: the run ends"); - Check.Eq(FakeHost.ChatCommands.Count(x => x.StartsWith("/attr", StringComparison.Ordinal)), 2, "exactly two raises sent"); - string summary = FakeHost.Chat.LastOrDefault(x => x.Contains("Attribute raise")) ?? ""; - Check.True(summary.Contains("Coordination +1") && summary.Contains("Quickness +1") && summary.Contains("2.2K"), - $"the run reports what it raised and spent (got '{summary}')"); - - var sb = new System.Text.StringBuilder(); - raiser.AppendJson(sb); - string json = sb.ToString(); - Check.True(json.StartsWith("\"attr\":{\"off\":false", StringComparison.Ordinal), "the Progression snapshot carries the raiser"); - Check.True(json.Contains("\"key\":\"coo\"") && json.Contains("\"cost\":\"2.0K\""), "rows carry the last read costs"); - System.Text.Json.JsonDocument.Parse("{" + json + "}").Dispose(); // throws if the JSON is malformed - - // Panel commands: order, ticks, mode, reserve, a manual +10. - raiser.HandleRemote("attrmove", new[] { "attrmove", "qui", "up" }); - Check.Eq(c.AttrOrder[0], "qui", "attrmove up"); - raiser.HandleRemote("attron", new[] { "attron", "str", "on" }); - Check.True(c.AttrRaiseStats.Contains("str"), "attron"); - raiser.HandleRemote("attrmode", new[] { "attrmode", "2" }); - Check.Eq(c.AttrRaiseMode, 2, "attrmode"); - raiser.HandleRemote("attrkeep", new[] { "attrkeep", "1.5b" }); - Check.Eq(c.AttrKeepXp, 1_500_000_000L, "attrkeep takes k/m/b suffixes"); - raiser.HandleRemote("attrraise", new[] { "attrraise", "foc", "10" }); - Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr foc 10")), "a manual +10 sends /attr foc 10"); - } - - private static void Safety() - { - var settings = new IltSettings(); - var hub = NewHub("InfiniteLeaftide", settings, "attr-safety", out _); - var c = hub.State.Character; - var raiser = hub.Progression.Attributes; - c.AttrRaiseStats = new List { "coo", "qui" }; - FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 10_000; - - // A cost seen earlier (passively, here by a hand-typed /xp all) is not trusted by a run: - // only the costs in the run's own read count. - Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 100"); - raiser.Start(auto: false); - Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "run reads costs"); - Reply(hub, "[XP] Your XP cost for next 1 Quickness level is: 500"); // Coordination missing this time - Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Any(x => x.StartsWith("/attr", StringComparison.Ordinal))), "a raise is sent"); - Check.Eq(FakeHost.ChatCommands.First(x => x.StartsWith("/attr", StringComparison.Ordinal)), "/attr qui 1", - "Coordination's older cost is not used when this read left it out"); - - // A reply about another stat (some other /attr sender) is not taken as our success. - Reply(hub, "[ATTR] Strength attribute raised by 1, costing 50!"); - Check.True(TickUntil(hub, () => !raiser.Running), "a reply about another stat ends the run"); - Check.Eq(FakeHost.ChatCommands.Count(x => x.StartsWith("/attr", StringComparison.Ordinal)), 1, "and nothing more is raised"); - Check.False(FakeHost.Chat.Any(x => x.Contains("Attribute raise")), "and no raise is reported"); - - // The world leaves Server Features mid-run: the next step stops. - FakeHost.ChatCommands.Clear(); - raiser.Start(auto: false); - Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "second run reads costs"); - settings.ServerNames = new List { "SomewhereElse" }; - Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 100"); - Check.True(TickUntil(hub, () => !raiser.Running), "the run stops once the world is off"); - Check.False(FakeHost.ChatCommands.Any(x => x.StartsWith("/attr", StringComparison.Ordinal)), "no raise after the gate closed"); - settings.ServerNames = new List(ServerFeatureGate.DefaultServerNames); - - // Another XP spender running: neither Raise now nor +N starts. - bool spending = true; - raiser.HoldOff = () => spending; - FakeHost.ChatCommands.Clear(); - raiser.Start(auto: false); - raiser.RaiseManual("coo", 1); - TickUntil(hub, () => false, 600); - Check.False(raiser.Running, "held off: Raise now doesn't start"); - Check.False(FakeHost.ChatCommands.Any(), "held off: nothing is sent"); - } - - private static void GatedOff() - { - var settings = new IltSettings(); - var hub = NewHub("Aelrynth", settings, "attr-gated", out _); - var raiser = hub.Progression.Attributes; - hub.State.Character.AttrRaiseStats = new List { "coo" }; - Check.NotNull(raiser.Blocker(), "a world not in the list: blocked"); - raiser.Start(auto: false); - TickUntil(hub, () => false, 600); - Check.False(FakeHost.ChatCommands.Any(), "nothing is sent off a feature world"); - - settings.ServerNames.Add("Aelrynth"); - Check.Null(raiser.Blocker(), "adding the world to the server list unblocks it"); - settings.ServerNames.Remove("Aelrynth"); - hub.State.ForceLeaftideFeatures = true; - Check.Null(raiser.Blocker(), "so does the character's override"); - } -} diff --git a/Tools/RynthILT.Tests/BankCommandTests.cs b/Tools/RynthILT.Tests/BankCommandTests.cs deleted file mode 100644 index 0ff8a0f..0000000 --- a/Tools/RynthILT.Tests/BankCommandTests.cs +++ /dev/null @@ -1,146 +0,0 @@ -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// Banking tab (IltBankCommands): the deposit / withdraw commands match ACECustom's /bank handler -// (upstream 2026-10-11), and only the bank's own reply lines count as a deposit / withdraw result. -internal static class BankCommandTests -{ - public static void Register(Runner r) - { - r.Add("bank: deposit commands (everything, one kind, luminance tokens)", Deposits); - r.Add("bank: withdraw commands, trade notes by denomination and count", Withdrawals); - r.Add("bank: withdraw input is checked before anything is sent", WithdrawRefusals); - r.Add("bank: reply lines are recognised, balance and chat lines are not", Replies); - r.Add("bank: one item table matches ACECustom's handler (deposit / withdraw / transfer)", ItemTable); - r.Add("bank: transfer commands, trade notes by denomination, quoted names", Transfers); - r.Add("bank: transfer replies (notes' equivalent, bound prestige coins) are recognised", TransferReplies); - r.Add("bank: only the balance dump is backstop-eaten, and only just after a quiet refresh", LeakedDump); - } - - private static int TransferIndex(string code) => - System.Array.FindIndex(IltBankCommands.Transfers, t => t.Code == code); - - private static void ItemTable() - { - string Codes(System.Collections.Generic.IEnumerable codes) => string.Join(",", codes); - // ACECustom HandleBank (upstream 976606695): deposit everything; withdraw all but peas and - // luminance tokens; transfer all but those and the bound prestige coins. - Check.Eq(Codes(System.Linq.Enumerable.Select(IltBankCommands.Deposits, d => d.Args)), ",p,ps,l,lum,k,mk,e,we,pc,n", "deposits"); - Check.Eq(Codes(System.Linq.Enumerable.Select(IltBankCommands.Withdrawals, w => w.Code)), "p,l,k,mk,e,we,pc,n", "withdrawals"); - Check.Eq(Codes(System.Linq.Enumerable.Select(IltBankCommands.Transfers, t => t.Code)), "p,l,k,mk,e,we,n", "transfers"); - Check.Eq(TransferIndex("pc"), -1, "prestige coins are bound: never offered for transfer"); - Check.Eq(TransferIndex("ps"), -1, "pyreal peas: deposit only"); - Check.Eq(IltBanking.Currencies.Length, IltBankCommands.Transfers.Length, "the transfer form uses the table"); - Check.Eq(IltBanking.Currencies[0].Code, "p", "saved transfer index 0 is still pyreals"); - Check.Eq(IltBanking.Currencies[5].Code, "we", "saved transfer indexes 0-5 keep their currency"); - } - - private static void Transfers() - { - int mmd = System.Array.FindIndex(IltBankCommands.NoteDenominations, n => n.Code == "mmd"); - Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 250_000, -1, "Bob", out _), "/bank t p 250000 Bob", "pyreals"); - Check.Eq(IltBankCommands.Transfer(TransferIndex("mk"), 3, -1, " Bob ", out _), "/bank t mk 3 Bob", "name trimmed"); - Check.Eq(IltBankCommands.Transfer(TransferIndex("l"), 10, -1, "Some Name", out _), "/bank t l 10 \"Some Name\"", - "a name with a space is quoted (the server reads one argument)"); - Check.Eq(IltBankCommands.Transfer(TransferIndex("n"), 4, mmd, "Bob", out _), "/bank t n mmd 4 Bob", "four 250K notes"); - Check.True(IltBankCommands.IsNoteTransfer(TransferIndex("n")), "notes transfer by denomination"); - Check.False(IltBankCommands.IsNoteTransfer(TransferIndex("p")), "pyreals don't"); - Check.Eq(IltBankCommands.NoteValue(mmd, 4), 1_000_000L, "4 x 250K"); - - Check.Eq(IltBankCommands.Transfer(-1, 10, -1, "Bob", out string e1), "", "no currency refused"); - Check.Eq(e1, "Pick a currency.", "why"); - Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 0, -1, "Bob", out _), "", "zero refused"); - Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 10, -1, " ", out string e2), "", "no recipient refused"); - Check.Eq(e2, "Enter a recipient.", "why"); - Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 10, -1, "Bob\" x", out _), "", "a quote can't break out of the name"); - Check.Eq(IltBankCommands.Transfer(TransferIndex("n"), 4, 99, "Bob", out _), "", "bad denomination refused"); - Check.Eq(IltBankCommands.Transfer(TransferIndex("n"), IltBankCommands.MaxNoteCount + 1, mmd, "Bob", out _), "", "too many notes refused"); - } - - private static void TransferReplies() - { - Check.True(IltBankCommands.IsTransferReply("Transferred 1,000,000 Pyreals to Bob"), "result"); - Check.True(IltBankCommands.IsTransferReply("(Equivalent to 4x MMD notes)"), "trade-note equivalent"); - Check.True(IltBankCommands.IsTransferReply("[BANK] Prestige Coins are bound to you and cannot be transferred."), "bound coins"); - Check.True(IltBankCommands.IsTransferReply("[Transfer] This command may only be run once every 5 seconds."), "throttled"); - Check.True(IltBankCommands.IsTransferReply("Invalid denomination. Use: i(100), v(500)"), "bad denomination"); - Check.False(IltBankCommands.IsTransferReply("[BANK] Pyreals: 1,000"), "a balance line is not"); - Check.False(IltBankCommands.IsTransferReply("Bob tells you, \"Transferred 5\""), "a tell is not"); - } - - private static int DepositIndex(string args) => - System.Array.FindIndex(IltBankCommands.Deposits, d => d.Args == args); - - private static int WithdrawIndex(string code) => - System.Array.FindIndex(IltBankCommands.Withdrawals, w => w.Code == code); - - private static void Deposits() - { - Check.Eq(IltBankCommands.Deposit(0), "/b d", "Everything is a plain deposit"); - Check.Eq(IltBankCommands.Deposit(DepositIndex("p")), "/b d p", "pyreals"); - Check.Eq(IltBankCommands.Deposit(DepositIndex("pc")), "/b d pc", "prestige coins"); - Check.Eq(IltBankCommands.Deposit(DepositIndex("lum")), "/b lum", "luminance tokens use /b lum"); - Check.Eq(IltBankCommands.Deposit(-1), "", "unknown index sends nothing"); - Check.Eq(IltBankCommands.Deposit(IltBankCommands.Deposits.Length), "", "past the end sends nothing"); - } - - private static void Withdrawals() - { - Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("p"), 1_500_000, 0, out _), "/b w p 1500000", "pyreals"); - Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("pc"), 3, 0, out _), "/b w pc 3", "prestige coins"); - int mmd = System.Array.FindIndex(IltBankCommands.NoteDenominations, n => n.Code == "mmd"); - Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("n"), 5, mmd, out _), "/b w n mmd 5", "five 250K notes"); - } - - private static void WithdrawRefusals() - { - Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("p"), 0, 0, out string e1), "", "zero refused"); - Check.True(e1.Length > 0, "zero says why"); - Check.Eq(IltBankCommands.Withdraw(-1, 10, 0, out _), "", "no currency refused"); - Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("n"), 10, 99, out _), "", "bad denomination refused"); - Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("n"), IltBankCommands.MaxNoteCount + 1, 0, out string e2), "", - "more notes than the server allows refused"); - Check.True(e2.Contains("50,000"), "says the limit"); - } - - private static void Replies() - { - Check.True(IltBankCommands.IsActionReply("Deposited 12,345 pyreals"), "deposit"); - Check.True(IltBankCommands.IsActionReply("No pyreal peas found to deposit"), "nothing to deposit"); - Check.True(IltBankCommands.IsActionReply("Withdrew 2 prestige coins"), "withdraw"); - Check.True(IltBankCommands.IsActionReply("Starting Banked Lum: 5B (5,000,000,000)"), "token deposit start"); - Check.True(IltBankCommands.IsActionReply("[Withdraw] This command may only be run once every 5 seconds."), "throttled"); - Check.True(IltBankCommands.IsActionReply("You don't have enough luminance banked. Need 10 but only have 5."), "short"); - Check.False(IltBankCommands.IsActionReply("[BANK] Pyreals: 1,000"), "a balance line is not an action reply"); - Check.False(IltBankCommands.IsActionReply("No one is near."), "other 'No ...' lines are not"); - Check.False(IltBankCommands.IsActionReply("Bob tells you, \"Deposited 5 pyreals\""), "a tell is not"); - Check.False(IltBankCommands.IsActionReply(""), "empty"); - } - - /// - /// SilentKelpie's backstop for a quiet refresh whose reply leaked into chat, narrowed: the dump's - /// header and "Label: N" lines only, never errors, bound-coin notes or Transferred / Received lines, - /// and never a balance read outside the window after a quiet refresh (a macro's or plugin's /bank). - /// - private static void LeakedDump() - { - Check.True(IltBanking.IsBalanceDumpLine("[BANK] Your balances are:"), "header"); - Check.True(IltBanking.IsBalanceDumpLine("[BANK] Pyreals: 1,000"), "pyreals"); - Check.True(IltBanking.IsBalanceDumpLine("[BANK] Luminance: 2,500,000"), "luminance"); - Check.True(IltBanking.IsBalanceDumpLine("[BANK] Weakly Enlightened Coins: 3"), "weakly enlightened coins"); - Check.True(IltBanking.IsBalanceDumpLine("[BANK] Prestige Coins: 2 (bound to you and cannot be traded)"), "prestige coins"); - Check.False(IltBanking.IsBalanceDumpLine("[BANK] Too many parameters"), "an error"); - Check.False(IltBanking.IsBalanceDumpLine("[BANK] Prestige Coins are bound to you and cannot be transferred."), "the bound-coin note"); - Check.False(IltBanking.IsBalanceDumpLine("Transferred 1,000,000 Pyreals to Bob"), "a transfer reply"); - Check.False(IltBanking.IsBalanceDumpLine("Received 5 Pyreals from Bob"), "a received line"); - Check.False(IltBanking.IsBalanceDumpLine("Bob tells you, \"[BANK] Pyreals: 5\""), "a tell quoting a dump"); - - const long Win = IltBanking.QuietBalanceWindowMs; - Check.True(IltBanking.EatLeakedDump(true, 1_000, 1_000 + Win), "a dump line inside the window is eaten"); - Check.False(IltBanking.EatLeakedDump(true, 1_000 + Win + 1, 1_000 + Win), "after the window it shows (a macro's /bank)"); - Check.False(IltBanking.EatLeakedDump(true, 1_000, 0), "no quiet refresh out: it shows (typed /bank, loud refresh, other plugins)"); - Check.False(IltBanking.EatLeakedDump(false, 1_000, 1_000 + Win), "a non-dump [BANK] line inside the window still shows"); - } -} diff --git a/Tools/RynthILT.Tests/BountyReviewTests.cs b/Tools/RynthILT.Tests/BountyReviewTests.cs deleted file mode 100644 index 2b434c8..0000000 --- a/Tools/RynthILT.Tests/BountyReviewTests.cs +++ /dev/null @@ -1,252 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using RynthCore.Plugin.RynthILT.Bounty; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// The RynthILT review of SilentKelpie's tracker (2026-10-09). Two promises, checked here on a -// fake clock: -// * rate: at most one "/bounty list" per MinRefreshSeconds (5 s floor, whatever asks: kills, -// award lines every kill, Refresh spam, opening and closing the window), and none while the -// window is closed; -// * hidden chat: only the reply to the tracker's own read is eaten. A /bounty the player types -// is shown, also when it overlaps a read of ours, and our own command coming back through the -// engine's chat bar dispatcher is not mistaken for the player's. -internal static class BountyReviewTests -{ - public static void Register(Runner r) - { - r.Add("review: awards on every kill never read more than once per MinRefreshSeconds", AwardsEveryKill); - r.Add("review: Refresh spam and window open/close keep the 5 s floor", RefreshSpamAndToggling); - r.Add("review: a long mixed session: every read 5 s apart and only while the window is open", MixedSession); - r.Add("review: a /bounty list the player types is shown and stands in for the next read", TypedListShown); - r.Add("review: a /bounty the player types during our read: the rest of that read is shown", TypedDuringCapture); - r.Add("review: our own /bounty list coming back through the chat bar is not the player's", OwnEcho); - r.Add("review: command matching and long lines", Matching); - } - - private const string Header = "Bounties:"; - private const string Line = " Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills."; - private const string Footer = "Bounty: type /bounty to see the bounties where you stand."; - - private sealed class Rig - { - public long Ms = 1_000_000; - public readonly List SentAt = new(); - public readonly List SentWhileOpen = new(); - public BountyTracker T = null!; - public bool Open; - private long _lastPollMs; - - public void Step(long ms) - { - for (long e = 0; e < ms; e += 250) - { - Ms += 250; - if (Open && Ms - _lastPollMs >= 1000) { T.BuildJson(); _lastPollMs = Ms; } - T.Tick(); - } - } - - /// The server answers our read at once (header, a line, footer). - public void Reply() - { - T.OnChat(Header); - T.OnChat(Line); - T.OnChat(Footer); - } - } - - private static Rig New(int minRefreshSeconds = 5) - { - var rig = new Rig(); - rig.T = new BountyTracker(cmd => - { - if (cmd != BountyTracker.ListCommand) return; - rig.SentAt.Add(rig.Ms); - rig.SentWhileOpen.Add(rig.T.WindowOpen); - }, _ => { }, _ => { }, string.Empty, () => rig.Ms); - rig.T.Command($"set minrefreshseconds {minRefreshSeconds}"); - return rig; - } - - private static long MinGap(List at) - { - long min = long.MaxValue; - for (int i = 1; i < at.Count; i++) min = Math.Min(min, at[i] - at[i - 1]); - return min; - } - - private static void AwardsEveryKill() - { - var rig = New(minRefreshSeconds: 10); - rig.Open = true; - // A 1-kill bounty with no cooldown: every kill prints an award, for two minutes. - for (int s = 0; s < 120; s++) - { - rig.T.OnKill(); - rig.T.OnChat("Bounty complete! +1 Ascension Coin gained."); - rig.T.OnChat("Next bounty requires 1 kill."); - rig.Step(1000); - if (rig.T.Reading) rig.Reply(); - } - Check.True(rig.SentAt.Count >= 2, $"it still reads ({rig.SentAt.Count} reads)"); - Check.True(rig.SentAt.Count <= 13, $"at most one read per 10 s over 120 s ({rig.SentAt.Count} reads)"); - Check.True(MinGap(rig.SentAt) >= 10_000, $"reads at least MinRefreshSeconds apart (min gap {MinGap(rig.SentAt)} ms)"); - } - - private static void RefreshSpamAndToggling() - { - var rig = New(minRefreshSeconds: 30); - rig.Open = true; - rig.Step(500); - rig.Reply(); - Check.Eq(rig.SentAt.Count, 1, "opening reads once"); - - // Refresh clicked every half second for 20 s: manual reads keep the 5 s floor. - for (int i = 0; i < 40; i++) - { - rig.T.Command("refresh"); - rig.Step(500); - if (rig.T.Reading) rig.Reply(); - } - Check.True(rig.SentAt.Count <= 5, $"20 s of Refresh spam: at most 4 more reads ({rig.SentAt.Count} in all)"); - Check.True(MinGap(rig.SentAt) >= 5_000, $"manual reads at least 5 s apart (min gap {MinGap(rig.SentAt)} ms)"); - - // Kills while closed, then the window toggled open and shut every 4 s for a minute. - int before = rig.SentAt.Count; - for (int i = 0; i < 15; i++) - { - rig.Open = false; - rig.T.OnKill(); - rig.Step(4000); - rig.Open = true; - rig.Step(1000); - if (rig.T.Reading) rig.Reply(); - } - Check.True(rig.SentAt.Count - before <= 3, $"open/close every 5 s for 75 s with MinRefreshSeconds 30: at most 3 reads ({rig.SentAt.Count - before})"); - Check.True(MinGap(rig.SentAt) >= 5_000, "and never two within 5 s"); - Check.True(rig.SentWhileOpen.All(o => o), "every read went out with the window open"); - } - - private static void MixedSession() - { - var rig = New(minRefreshSeconds: 5); - var rnd = new Random(20261009); - for (int s = 0; s < 1800; s++) // 30 minutes - { - if (s % 120 == 0) rig.Open = !rig.Open; - int roll = rnd.Next(100); - if (roll < 30) rig.T.OnKill(); - else if (roll < 35) rig.T.OnChat("Bounty complete! +1 Ascension Coin gained."); - else if (roll < 37) rig.T.Command("refresh"); - else if (roll < 38) rig.T.OnChat("Bounty unlocked: Ascension Coin - 1 kill required."); - rig.Step(1000); - if (rig.T.Reading && rnd.Next(4) != 0) rig.Reply(); // now and then the server says nothing - } - Check.True(rig.SentAt.Count > 10, $"reads happened ({rig.SentAt.Count})"); - Check.True(MinGap(rig.SentAt) >= 5_000, $"every read at least 5 s after the last (min gap {MinGap(rig.SentAt)} ms)"); - Check.True(rig.SentWhileOpen.All(o => o), "every read went out with the window open"); - } - - private static void TypedListShown() - { - var rig = New(minRefreshSeconds: 5); - rig.Open = true; - rig.Step(500); - rig.Reply(); - Check.Eq(rig.SentAt.Count, 1, "first read"); - rig.Step(10_000); - - // The player types /bounty list: the reply is shown (nothing eaten) and still applied. - rig.T.NoteTypedCommand("/bounty list"); - Check.True(rig.T.Reading, "the typed list is captured (shown)"); - Check.False(rig.T.OnChat(Header), "typed reply: the header stays in chat"); - Check.False(rig.T.OnChat(" Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills."), "typed reply: the lines stay in chat"); - Check.False(rig.T.OnChat(Footer), "typed reply: the footer stays in chat"); - Check.False(rig.T.Reading, "and the footer ends it"); - Check.Eq(rig.T.State.Entries.Count, 1, "the typed reply fills the list"); - - // It counts as the latest read: a kill right after waits the full interval. - rig.T.OnKill(); - rig.Step(4000); - Check.Eq(rig.SentAt.Count, 1, "no read of ours on top of the player's"); - rig.Step(2000); - Check.Eq(rig.SentAt.Count, 2, "the kill's read comes MinRefreshSeconds after the typed one"); - Check.True(rig.T.OnChat(Header) && rig.T.OnChat(Line) && rig.T.OnChat(Footer), "our own read is eaten again"); - - // "/bounty" (where you stand) output is never eaten. - rig.T.NoteTypedCommand("/bounty"); - Check.False(rig.T.OnChat("Bounty: 1 Ascension Coin - 0 of 1 kills."), "a /bounty line stays in chat"); - Check.False(rig.T.OnChat("Bounty: there is no bounty here."), "'no bounty here' stays in chat"); - } - - private static void TypedDuringCapture() - { - var rig = New(minRefreshSeconds: 5); - rig.Open = true; - rig.Step(500); - Check.Eq(rig.SentAt.Count, 1, "our read went out"); - rig.T.NoteTypedCommand(BountyTracker.ListCommand); // our own echo first (consumed) - Check.True(rig.T.OnChat(Header), "our reply's header is eaten"); - - // The player types /bounty list while our reply is still coming in. - rig.Step(250); - rig.T.NoteTypedCommand("/bounty list"); - Check.False(rig.T.OnChat(Line), "after the player asked, reward lines are shown"); - Check.False(rig.T.OnChat(Footer), "and so is the footer"); - Check.False(rig.T.OnChat(Header), "the player's own reply: header shown"); - Check.False(rig.T.OnChat(Line), "the player's own reply: line shown"); - Check.False(rig.T.OnChat(Footer), "the player's own reply: footer shown"); - Check.False(rig.T.OnChat("Bounty complete! +1 Ascension Coin gained."), "award lines are never eaten"); - - // On a server without /bounty, the player's typed /bounty during our read: the refusal shows. - var rig2 = New(); - rig2.Open = true; - rig2.Step(500); - rig2.T.NoteTypedCommand("/bounty"); - Check.False(rig2.T.OnChat("Unknown command: bounty"), "the refusal of the player's own /bounty stays in chat"); - } - - private static void OwnEcho() - { - var rig = New(minRefreshSeconds: 5); - rig.Open = true; - rig.Step(500); - Check.Eq(rig.SentAt.Count, 1, "our read went out"); - rig.Step(250); - rig.T.NoteTypedCommand("/bounty list"); // the engine's dispatcher passing our own line back - Check.True(rig.T.OnChat(Header), "our echo is recognised: the reply is still eaten"); - Check.True(rig.T.OnChat(Line), "reward lines eaten"); - Check.True(rig.T.OnChat(Footer), "footer eaten"); - - // An echo that comes too late is taken for the player's: that read is shown, never eaten wrongly. - rig.Step(10_000); - Check.Eq(rig.SentAt.Count, 1, "no new read yet (nothing asked)"); - rig.T.Command("refresh"); - rig.Step(500); - Check.Eq(rig.SentAt.Count, 2, "refresh reads"); - rig.Step(3000); - rig.T.NoteTypedCommand("/bounty list"); - Check.False(rig.T.OnChat(Header), "a late echo errs on the shown side"); - } - - private static void Matching() - { - Check.True(BountyTracker.IsBountyCommand("/bounty"), "/bounty"); - Check.True(BountyTracker.IsBountyCommand("/bounty list"), "/bounty list"); - Check.True(BountyTracker.IsBountyCommand("@Bounty all"), "@bounty all"); - Check.False(BountyTracker.IsBountyCommand("/bountyhunter"), "a longer command is not /bounty"); - Check.False(BountyTracker.IsBountyCommand("/b hello"), "chat"); - Check.True(BountyTracker.IsListCommand("/bounty list") && BountyTracker.IsListCommand("/BOUNTY ALL"), "list commands"); - Check.False(BountyTracker.IsListCommand("/bounty") || BountyTracker.IsListCommand("/bounty list now"), "not list commands"); - - var rig = New(); - rig.Open = true; - rig.Step(500); - string longLine = " Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills." + new string(' ', 600) + "x"; - Check.False(rig.T.OnChat(longLine), "a line over 512 characters is never eaten or parsed"); - } -} diff --git a/Tools/RynthILT.Tests/BountyTests.cs b/Tools/RynthILT.Tests/BountyTests.cs deleted file mode 100644 index 1c00dc9..0000000 --- a/Tools/RynthILT.Tests/BountyTests.cs +++ /dev/null @@ -1,388 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text.Json; -using RynthCore.Plugin.RynthILT.Bounty; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// ACECustom bounty tracker (2026-10-09). The server keeps the kill counts (BountyProgress is a -// server-only property), so the engine's Bounties window has RynthILT read "/bounty list" quietly -// and parse it. The line formats below are copied from ACECustom BountyManager (ShowAllBounties / -// ShowBounty / Award / NextBountyLine). The tracker runs on a fake clock; the engine's 1 s poll -// of RynthPluginGetBountiesJson is simulated by calling BuildJson. -internal static class BountyTests -{ - public static void Register(Runner r) - { - r.Add("bounty: /bounty list lines (counting, cooldown, QB, layers, commas)", ListLines); - r.Add("bounty: /bounty lines, waits and chat events", HereLinesAndEvents); - r.Add("bounty: a full read replaces the list, a partial one updates it", ApplyListRules); - r.Add("bounty: kills and awards stamp the row; an ended cooldown shows 0 kills; state survives a relog", ChangesAndCooldown); - r.Add("bounty: /bounty updates only the one reward it can mean", HereMatching); - r.Add("bounty: an open window reads the list quietly, kills and awards re-read it", WindowReadsAndKills); - r.Add("bounty: closed window sends nothing; unknown command stops reads; no reply times out", ClosedAndUnsupported); - r.Add("bounty: the window's JSON (options, QB filter, closest first) parses in the engine", BridgeJson); - } - - // ── Parsing ──────────────────────────────────────────────────────────────── - - private static void ListLines() - { - Check.True(BountyParse.TryParseListLine(" Lugian Mines: 1 Ascension Coin every 100 kills (at most every 5 min) - you: 34 of 100 kills.", out var a), - "counting line parses (leading indentation)"); - Check.Eq(a.Where, "Lugian Mines", "area"); - Check.Eq(a.Amount, 1L, "amount"); - Check.Eq(a.Item, "Ascension Coin", "item"); - Check.Eq(a.KillsRequired, 100, "kills per award"); - Check.Eq(a.CooldownSeconds, 300, "cooldown"); - Check.Eq(a.Status.Status, BountyStatus.Counting, "status"); - Check.Eq(a.Status.Kills, 34, "kills so far"); - - Check.True(BountyParse.TryParseListLine("All zones: 3 Pyreal Nugget every 1,000 kills (at most every 2 min 30 sec) - you: unlocks in 1 hr 15 sec, then 1,000 kills required.", out var b), - "cooldown line parses"); - Check.Eq(b.Where, "All zones", "all-zones area"); - Check.Eq(b.KillsRequired, 1000, "N0 kills"); - Check.Eq(b.CooldownSeconds, 150, "2 min 30 sec"); - Check.Eq(b.Status.Status, BountyStatus.Cooldown, "cooldown status"); - Check.Eq(b.Status.WaitSeconds, 3615, "1 hr 15 sec"); - Check.Eq(b.Status.KillsRequired, 1000, "kills after the cooldown"); - - Check.True(BountyParse.TryParseListLine("Valley of Death: 1,500 Trade Note - Large every 1 kill - you: needs 5,000 QB (you have 3,210).", out var c), - "QB line with no cooldown and a hyphenated item parses"); - Check.Eq(c.Amount, 1500L, "N0 amount"); - Check.Eq(c.Item, "Trade Note - Large", "item keeps its own ' - '"); - Check.Eq(c.KillsRequired, 1, "one kill"); - Check.Eq(c.CooldownSeconds, 0, "no cooldown"); - Check.Eq(c.Status.Status, BountyStatus.NeedsQb, "QB status"); - Check.Eq(c.Status.QbRequired, 5000L, "QB needed"); - Check.Eq(c.Status.QbHave, 3210L, "QB had"); - - Check.True(BountyParse.TryParseListLine("Halls of Metos: Lower (layer 2): 2 Ascension Coin every 50 kills - you: 0 of 50 kills.", out var d), - "an area with ': ' and a layer parses"); - Check.Eq(d.Where, "Halls of Metos: Lower (layer 2)", "area keeps its colon and layer"); - - Check.False(BountyParse.TryParseListLine("Bounties:", out _), "the header is not a reward"); - Check.False(BountyParse.TryParseListLine("Bounty: type /bounty to see the bounties where you stand.", out _), "the footer is not a reward"); - Check.False(BountyParse.TryParseListLine("Bob says, \"Lugian Mines: 1 coin every 100 kills\"", out _), "chat talk is not a reward"); - Check.True(BountyParse.IsListTerminator("Bounty: type /bounty to see the bounties where you stand."), "footer ends the reply"); - Check.True(BountyParse.IsListTerminator("Bounty: there are no bounties anywhere right now."), "'none anywhere' ends the reply"); - Check.True(BountyParse.IsNoBountiesAnywhere("Bounty: there are no bounties anywhere right now."), "'none anywhere' is recognised"); - Check.False(BountyParse.IsListTerminator("Bounty: there is no bounty here."), "/bounty's 'none here' is not the list's end"); - Check.True(BountyParse.IsUnknownCommand("Unknown command: bounty"), "ACE's unknown-command reply is recognised"); - Check.False(BountyParse.IsUnknownCommand("Unknown command: bank"), "another command's reply is not ours"); - } - - private static void HereLinesAndEvents() - { - Check.True(BountyParse.TryParseHereLine("Bounty: 1 Ascension Coin - 12 of 100 kills.", out var h1), "plain /bounty line"); - Check.Eq(h1.Scope, "", "no scope"); - Check.Eq(h1.Status.Kills, 12, "kills"); - Check.True(BountyParse.TryParseHereLine("Bounty (all zones): 3 Pyreal Nugget - unlocks in 45 sec, then 1 kill required.", out var h2), "all-zones /bounty line"); - Check.Eq(h2.Scope, "all zones", "all-zones scope"); - Check.Eq(h2.Status.WaitSeconds, 45, "45 sec"); - Check.True(BountyParse.TryParseHereLine("Bounty (Thaelaryn Island): 1 Ascension Coin - needs 500 QB (you have 20).", out var h3), "region /bounty line"); - Check.Eq(h3.Scope, "Thaelaryn Island", "region scope"); - Check.False(BountyParse.TryParseHereLine("Bounty: there is no bounty here.", out _), "'none here' is not a reward"); - Check.False(BountyParse.TryParseHereLine("Bounty: +1 Ascension Coin will follow in a moment.", out _), "held notice is not a reward"); - - Check.Eq(BountyParse.ParseWaitSeconds("5 min"), 300, "5 min"); - Check.Eq(BountyParse.ParseWaitSeconds("2 hr 3 min 4 sec"), 7384, "hr min sec"); - Check.Eq(BountyParse.ParseWaitSeconds("soon"), 0, "unparseable wait"); - - Check.True(BountyParse.TryParseEvent("Bounty unlocked: Ascension Coin - 100 kills required.", out var k1, out string item1, out int n1, out _) - && k1 == BountyEventKind.Unlocked && item1 == "Ascension Coin" && n1 == 100, "unlock event"); - Check.True(BountyParse.TryParseEvent("Bounty complete! +3 Pyreal Nuggets gained.", out var k2, out string item2, out _, out _) - && k2 == BountyEventKind.Complete && item2 == "Pyreal Nuggets", "award event"); - Check.True(BountyParse.TryParseEvent("Next bounty unlocks in 2 min 30 sec - 1 kill required.", out var k3, out _, out int n3, out int w3) - && k3 == BountyEventKind.NextCooldown && n3 == 1 && w3 == 150, "next-cooldown event"); - Check.True(BountyParse.TryParseEvent("Next bounty requires 1,000 kills.", out var k4, out _, out int n4, out _) - && k4 == BountyEventKind.NextReady && n4 == 1000, "next-ready event"); - Check.True(BountyParse.TryParseEvent("Bounty: Your inventory is full. +1 Ascension Coin gained (3 total). They're safe until you make room.", out var k5, out _, out _, out _) - && k5 == BountyEventKind.Held, "held event"); - Check.False(BountyParse.TryParseEvent("Bounty: there is no bounty here.", out _, out _, out _, out _), "'none here' is not an event"); - Check.False(BountyParse.TryParseEvent("Bounty: 1 Ascension Coin - 12 of 100 kills.", out _, out _, out _, out _), "a status line is not an event"); - Check.False(BountyParse.TryParseEvent("Bounty: type /bounty to see the bounties where you stand.", out _, out _, out _, out _), "the footer is not an event"); - } - - // ── Applying reads ───────────────────────────────────────────────────────── - - private static BountyListLine L(string line) - { - Check.True(BountyParse.TryParseListLine(line, out var l), "fixture parses: " + line); - return l; - } - - private static void ApplyListRules() - { - var t = New(out _, out _, out _); - var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc); - t.ApplyList(new[] - { - L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."), - L("All zones: 3 Pyreal Nugget every 50 kills - you: 0 of 50 kills."), - }, complete: true, noneAnywhere: false, t0); - Check.Eq(t.State.Entries.Count, 2, "full read: two rewards"); - Check.Eq(t.State.ListedUtc, t0, "read time stamped"); - - // A partial reply (no footer) only updates what it names; the other rows stay. - t.ApplyList(new[] { L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 11 of 100 kills.") }, - complete: false, noneAnywhere: false, t0.AddSeconds(5)); - Check.Eq(t.State.Entries.Count, 2, "partial read keeps the other row"); - Check.Eq(t.State.Entries[0].Kills, 11, "partial read updates the named row in place"); - - // A full read drops areas that are gone and keeps the server's order. - t.ApplyList(new[] - { - L("Thaelaryn Island: 1 Ascension Coin every 20 kills - you: 4 of 20 kills."), - L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 12 of 100 kills."), - }, complete: true, noneAnywhere: false, t0.AddSeconds(10)); - Check.Eq(string.Join(",", t.State.Entries.Select(e => e.Where)), "Thaelaryn Island,Lugian Mines", "server order, removed area gone"); - - t.ApplyList(Array.Empty(), complete: true, noneAnywhere: true, t0.AddSeconds(20)); - Check.Eq(t.State.Entries.Count, 0, "'none anywhere' empties the list"); - Check.True(t.State.NoneAnywhere, "and says so"); - } - - private static void ChangesAndCooldown() - { - string file = Path.Combine(Program.TempRoot, "bounty-changes", BountyTracker.FileName); - var t = New(out _, out _, out _, file); - var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc); - const string Head = "Lugian Mines: 1 Ascension Coin every 3 kills (at most every 5 min) - you: "; - t.ApplyList(new[] { L(Head + "1 of 3 kills.") }, true, false, t0); - Check.Eq(t.State.Entries[0].ChangedUtc, default(DateTime), "first sighting is not a change"); - - t.ApplyList(new[] { L(Head + "2 of 3 kills.") }, true, false, t0.AddSeconds(10)); - Check.Eq(t.State.Entries[0].ChangedUtc, t0.AddSeconds(10), "a new kill stamps the row"); - - t.ApplyList(new[] { L(Head + "unlocks in 5 min, then 3 kills required.") }, true, false, t0.AddSeconds(20)); - var e = t.State.Entries[0]; - Check.Eq(e.ChangedUtc, t0.AddSeconds(20), "the award stamps the row"); - Check.Eq(e.UnlockAtUtc, t0.AddSeconds(320), "unlock time = read time + wait"); - Check.Eq(BountyTracker.Effective(e, t0.AddSeconds(100)).Status, BountyStatus.Cooldown, "still cooling down"); - var after = BountyTracker.Effective(e, t0.AddSeconds(321)); - Check.True(after.Status == BountyStatus.Counting && after.Kills == 0, "after the cooldown: 0 of N kills"); - Check.True(BountyTracker.Describe(e, t0.AddSeconds(100)).Contains("unlocks in 3 min 40 sec"), "chat text counts the cooldown down"); - - // The state survives a relog (the window fills right after login). - t.Command("set hideqblocked 1"); - t.Save(); - var loaded = New(out _, out _, out _, file); - Check.Eq(loaded.State.Entries.Count, 1, "entries saved per character"); - Check.Eq(loaded.State.Entries[0].UnlockAtUtc, t0.AddSeconds(320), "unlock time saved"); - Check.True(loaded.State.HideQbLocked, "options saved"); - } - - private static void HereMatching() - { - var t = New(out _, out _, out _); - var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc); - t.ApplyList(new[] - { - L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."), - L("Halls of Metos: 1 Ascension Coin every 100 kills - you: 50 of 100 kills."), - L("Thaelaryn Island: 2 Ascension Coin every 20 kills - you: 4 of 20 kills."), - L("All zones: 1 Ascension Coin every 100 kills - you: 0 of 100 kills."), - }, true, false, t0); - - Check.True(BountyParse.TryParseHereLine("Bounty (Thaelaryn Island): 2 Ascension Coin - 5 of 20 kills.", out var region), "fixture"); - Check.True(t.ApplyHere(region, t0.AddSeconds(5)), "a region line names its area"); - Check.Eq(t.State.Entries[2].Kills, 5, "region row updated"); - - Check.True(BountyParse.TryParseHereLine("Bounty (all zones): 1 Ascension Coin - 1 of 100 kills.", out var zones), "fixture"); - Check.True(t.ApplyHere(zones, t0.AddSeconds(6)), "an all-zones line names its area"); - Check.Eq(t.State.Entries[3].Kills, 1, "all-zones row updated"); - - Check.True(BountyParse.TryParseHereLine("Bounty: 1 Ascension Coin - 11 of 100 kills.", out var plain), "fixture"); - Check.False(t.ApplyHere(plain, t0.AddSeconds(7)), "two dungeons pay the same reward: left alone"); - Check.Eq(t.State.Entries[0].Kills, 10, "first dungeon untouched"); - Check.Eq(t.State.Entries[1].Kills, 50, "second dungeon untouched"); - } - - // ── The read loop ────────────────────────────────────────────────────────── - - private const string ListReplyCounting = " Lugian Mines: 1 Ascension Coin every 100 kills - you: 34 of 100 kills."; - private const string Footer = "Bounty: type /bounty to see the bounties where you stand."; - - private static void WindowReadsAndKills() - { - var t = New(out var clock, out var sent, out _); - t.Command("set minrefreshseconds 5"); - Run(t, clock, 500, windowOpen: true); - Check.Eq(Reads(sent), 1, "opening the window reads /bounty list"); - Check.True(t.Reading, "a read is in progress"); - - Check.True(t.OnChat("Bounties:"), "the header is hidden from chat"); - Check.True(t.OnChat(ListReplyCounting), "reward lines are hidden from chat"); - Check.True(t.OnChat(Footer), "the footer is hidden and ends the read"); - Check.False(t.Reading, "the read is over"); - Check.Eq(t.State.Entries.Count, 1, "the read fills the list"); - Check.Eq(t.State.Entries[0].Kills, 34, "with the player's kills"); - - // A kill re-reads after the debounce, but not sooner than MinRefreshSeconds after the last read. - t.OnKill(); - Run(t, clock, 3000, windowOpen: true); - Check.Eq(Reads(sent), 1, "no re-read inside MinRefreshSeconds"); - Run(t, clock, 3000, windowOpen: true); - Check.Eq(Reads(sent), 2, "a kill re-reads the list"); - t.OnChat("Bounties:"); - t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills - you: 35 of 100 kills."); - t.OnChat(Footer); - Check.Eq(t.State.Entries[0].Kills, 35, "the kill shows up"); - Check.True(t.State.Entries[0].ChangedUtc != default, "and the row is highlighted"); - - // Award lines are shown to the player and also trigger a read, once MinRefreshSeconds - // have passed since the last one (review 2026-10-09: awards used to skip the interval). - Check.False(t.OnChat("Bounty complete! +1 Ascension Coin gained."), "award lines stay in chat"); - Check.Eq(t.State.LastEvent, "Bounty complete! +1 Ascension Coin gained.", "the window shows the last event"); - Run(t, clock, 2000, windowOpen: true); - Check.Eq(Reads(sent), 2, "the award's re-read waits for MinRefreshSeconds"); - Run(t, clock, 3000, windowOpen: true); - Check.Eq(Reads(sent), 3, "an award re-reads the list"); - - // A reply whose footer never comes ends after a quiet moment, as a partial update. - t.OnChat("Bounties:"); - t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills (at most every 5 min) - you: unlocks in 5 min, then 100 kills required."); - Run(t, clock, 2000, windowOpen: true); - Check.False(t.Reading, "a reply without its footer still ends"); - Check.Eq(t.State.Entries[0].Status, (int)BountyStatus.Cooldown, "and is applied"); - - // Lines the player asks for themselves are not hidden but still update the list. - Check.False(t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills - you: 0 of 100 kills."), "a typed /bounty list line stays in chat"); - Check.Eq(t.State.Entries[0].Status, (int)BountyStatus.Counting, "and updates the row"); - - // Closing the window (the engine stops polling; 3 s grace) stops the reads. - Run(t, clock, 5000, windowOpen: false); - int before = Reads(sent); - t.OnKill(); - Run(t, clock, 20000, windowOpen: false); - Check.Eq(Reads(sent), before, "no reads once the window is closed"); - } - - private static void ClosedAndUnsupported() - { - var t = New(out var clock, out var sent, out var chat); - t.Command("set minrefreshseconds 5"); - t.OnKill(); - Run(t, clock, 10000, windowOpen: false); - Check.Eq(Reads(sent), 0, "closed window: kills send nothing"); - - Run(t, clock, 500, windowOpen: true); - Check.Eq(Reads(sent), 1, "opening the window reads the list"); - Check.True(t.OnChat("Unknown command: bounty"), "the unknown-command reply to our read is hidden"); - Check.True(t.Unsupported, "'Unknown command: bounty' marks the server unsupported"); - - t.OnKill(); - Run(t, clock, 10 * 60_000, windowOpen: true); - Check.Eq(Reads(sent), 1, "no automatic reads on an unsupported server, periodic included"); - - t.HandleChatCommand(new[] { "/ilt", "bountys", "refresh" }); - Check.False(t.Unsupported, "a manual refresh tries again"); - Run(t, clock, 500, windowOpen: true); - Check.Eq(Reads(sent), 2, "and reads the list"); - Check.True(chat.Any(c => c.Contains("Reading /bounty list")), "the command answers in chat"); - - Run(t, clock, 11000, windowOpen: true); - Check.False(t.Reading, "no reply: the read is abandoned"); - Check.True(t.BuildJson().Contains("no reply to /bounty list"), "and the window says so"); - - // With the window closed a manual refresh sends nothing (review 2026-10-09: reads only - // while the window is open); the next open reads. - Run(t, clock, 5000, windowOpen: false); - Check.True(t.Command("refresh").Contains("window is open"), "a closed-window refresh says why it waits"); - Check.Eq(Reads(sent), 2, "a closed-window refresh sends nothing"); - Run(t, clock, 500, windowOpen: true); - Check.Eq(Reads(sent), 3, "the next open reads"); - - chat.Clear(); - t.HandleChatCommand(new[] { "/ilt", "bounty" }); - Check.True(chat.Any(c => c.Contains("/rc bounties")), "'/ilt bounty' points at the window"); - } - - private static void BridgeJson() - { - var t = New(out _, out _, out _); - var now = DateTime.UtcNow; - t.ApplyList(new[] - { - L("Valley of Death: 1,500 Trade Note - Large every 1 kill - you: needs 5,000 QB (you have 3,210)."), - L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."), - L("Thaelaryn Island: 2 Ascension Coin every 20 kills (at most every 5 min) - you: unlocks in 2 min, then 20 kills required."), - L("Halls of Metos: 1 Ascension Coin every 10 kills - you: 9 of 10 kills."), - }, true, false, now); - - Check.Eq(t.Command("set minrefreshseconds 1"), "", "option accepted"); - Check.Eq(t.State.MinRefreshSeconds, BountyTracker.MinRefreshFloorSeconds, "MinRefreshSeconds is clamped to the floor"); - t.Command("set periodicminutes 999"); - Check.Eq(t.State.PeriodicRefreshMinutes, BountyTracker.PeriodicCeilingMinutes, "PeriodicRefreshMinutes is clamped"); - Check.True(t.Command("set nonsense 1").Contains("unknown"), "unknown option is reported"); - - using (var doc = JsonDocument.Parse(t.BuildJson())) - { - var root = doc.RootElement; - Check.Eq(root.GetProperty("rows").GetArrayLength(), 4, "all rows by default"); - Check.Eq(root.GetProperty("rows")[0].GetProperty("where").GetString(), "Valley of Death", "server order by default"); - Check.Eq(root.GetProperty("minRefreshSeconds").GetInt32(), 5, "camelCase option names"); - } - - t.Command("set hideqblocked 1"); - t.Command("set sortbyprogress on"); - string json = t.BuildJson(); - using (var doc = JsonDocument.Parse(json)) - { - var rows = doc.RootElement.GetProperty("rows"); - Check.Eq(rows.GetArrayLength(), 3, "QB-locked row hidden"); - Check.Eq(doc.RootElement.GetProperty("hiddenCount").GetInt32(), 1, "and counted"); - Check.Eq(rows[0].GetProperty("where").GetString(), "Halls of Metos", "closest first: 9 of 10"); - Check.Eq(rows[2].GetProperty("where").GetString(), "Thaelaryn Island", "cooldowns after counting rows"); - } - -#if ENGINE_BOUNTIES - var snap = RynthCore.Engine.UI.Data.BountiesSnapshot.Parse(json); - Check.NotNull(snap, "the engine parses the plugin's JSON"); - Check.True(snap!.HideQbLocked && snap.SortByProgress, "engine sees the options"); - Check.Eq(snap.MinRefreshSeconds, 5, "engine sees MinRefreshSeconds"); - Check.Eq(snap.HiddenCount, 1, "engine sees the hidden count"); - Check.Eq(snap.Rows.Count, 3, "engine sees the rows"); - var cd = snap.Rows.Single(r => r.Where == "Thaelaryn Island"); - Check.Eq(cd.Status, (int)RynthCore.Engine.UI.Data.BountyRowStatus.Cooldown, "engine status enum matches the plugin's"); - Check.True(cd.UnlockInSec > 100 && cd.UnlockInSec <= 120, $"cooldown seconds left ({cd.UnlockInSec})"); - Check.Eq(cd.CooldownSeconds, 300, "cooldown length"); - var halls = snap.Rows[0]; - Check.True(halls.Kills == 9 && halls.KillsRequired == 10 && halls.Amount == 1 && halls.Item == "Ascension Coin", "row fields"); -#endif - } - - // ── Helpers ──────────────────────────────────────────────────────────────── - - private sealed class Clock { public long Ms = 1_000_000; } - - private static BountyTracker New(out Clock clock, out List sent, out List chat, string file = "") - { - var c = new Clock(); - var s = new List(); - var ch = new List(); - if (file.Length > 0) Directory.CreateDirectory(Path.GetDirectoryName(file)!); - var t = new BountyTracker(s.Add, ch.Add, _ => { }, file, () => c.Ms); - clock = c; - sent = s; - chat = ch; - return t; - } - - private static int Reads(List sent) => sent.Count(x => x == BountyTracker.ListCommand); - - /// Advances the clock in 250 ms steps, ticking; with the window open the engine polls every second. - private static void Run(BountyTracker t, Clock clock, long ms, bool windowOpen) - { - for (long elapsed = 0; elapsed < ms; elapsed += 250) - { - clock.Ms += 250; - if (windowOpen && elapsed % 1000 == 0) t.BuildJson(); - t.Tick(); - } - } -} diff --git a/Tools/RynthILT.Tests/BreedingTests.cs b/Tools/RynthILT.Tests/BreedingTests.cs deleted file mode 100644 index 5501050..0000000 --- a/Tools/RynthILT.Tests/BreedingTests.cs +++ /dev/null @@ -1,379 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.Json; -using RynthCore.Plugin.RynthILT; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.Plugin.Shared; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// The pet breeding tracker (IltBreedingRules / IltBreedingEssence / IltBreedingSupplies / IltPetBreeding): -// the server's rules and where each value came from, the parsers for ACECustom's appraisal block, -// chat and "@breed-debug" (formats copied from PetDevice_Breeding.cs / PetDevice_Maturity.cs), each -// breeding gate, the pair planner's odds, the supply refusals, and the JSON RynthOracle reads. -internal static class BreedingTests -{ - public static void Register(Runner r) - { - r.Add("breeding: tier table has one WCID per tier in every family, no repeats", TierTable); - r.Add("breeding: rules come from the server, else the ILT profile, else ACE", RuleSources); - r.Add("breeding: stat mutation odds follow ACE's decay, floor and incense cap", MutationOdds); - r.Add("breeding: appraisal text gives the stud's charges, refill window and growth", AppraisalParse); - r.Add("breeding: chat lines give charges, the guardian, growth stages and events", ChatParse); - r.Add("breeding: @breed-debug reply is captured whole or line by line and parsed", DebugParse); - r.Add("breeding: each gate (charges, rest, growth, neutered, shiny, bond, tier, ID)", Gates); - r.Add("breeding: pair planner blocks wrong sexes and ranges the inherited mutations", Planner); - r.Add("breeding: supplies are refused where the server would refuse them", Supplies); - r.Add("breeding: reader JSON round-trips through RynthOracle's view", ReaderJson); - r.Add("breeding: saved state survives the hub.json source-generated serializer", StateJson); - r.Add("breeding: RynthILT.Data v2 keeps v1 readers working", DataApiVersion); - } - - private static IltBreedingRules Rules() => new(new IltBreedingState()); - - /// A healthy adult essence's facts (tier 150, bond 120, appraised). - private static BreedEssenceFacts Facts(int id, bool male, uint wcid = 48946) => new() - { - Id = id, - Name = (male ? "Stud " : "Dam ") + id, - Wcid = wcid, - HasId = true, - Bond = 120, - MaleOverride = male, - }; - - private static void TierTable() - { - var seen = new HashSet(); - foreach (uint[] row in IltBreedingEssence.Families) - { - Check.Eq(row.Length, IltBreedingEssence.Tiers.Length, "row " + row[0]); - foreach (uint w in row) Check.True(seen.Add(w), "WCID " + w + " appears once"); - } - Check.Eq(IltBreedingEssence.Families.Length, 36, "36 combat pet families"); - Check.Eq(IltBreedingEssence.TierOf(48942), 50, "first fire skeleton is tier 50"); - Check.Eq(IltBreedingEssence.TierOf(49212), 200, "an out-of-run WCID keeps its slot (tier 200)"); - Check.Eq(IltBreedingEssence.TierOf(787801072), 300, "the last tier-300 essence"); - Check.Eq(IltBreedingEssence.TierOf(12345, 125), 125, "unknown WCID: a tier-valued level requirement"); - Check.Eq(IltBreedingEssence.TierOf(12345, 126), 0, "unknown WCID, odd level: unknown tier"); - Check.True(IltBreedingEssence.IsCombatEssence(49551), "range end is included"); - } - - private static void RuleSources() - { - IltBreedingRules r = Rules(); - Check.Eq(r.Value(IltBreedingRules.MinTier).Source, BreedRuleSource.AceDefault, "min tier: ACE default"); - Check.Eq(r.GetInt(IltBreedingRules.MinTier), 100, "min tier 100"); - Check.Eq(r.Value(IltBreedingRules.MutationDecay).Source, BreedRuleSource.IltProfile, "decay: ILT profile"); - Check.Near(r.Get(IltBreedingRules.MutationDecay), 0.1, 1e-9, "ILT decay 0.1"); - Check.Near(r.Get(IltBreedingRules.GuardianEnabled), 1, 1e-9, "ILT runs the mating guardian"); - - DateTime t = new(2026, 10, 15, 12, 0, 0, DateTimeKind.Utc); - Check.True(r.Learn(IltBreedingRules.MaleCharges, 12, t), "a new value is a change"); - Check.False(r.Learn(IltBreedingRules.MaleCharges, 12, t), "the same value again isn't"); - Check.Eq(r.Value(IltBreedingRules.MaleCharges).Source, BreedRuleSource.Server, "learned: seen on server"); - Check.Eq(r.GetInt(IltBreedingRules.MaleCharges), 12, "learned value wins"); - Check.False(r.Learn("not_a_rule", 1, t), "unknown keys are ignored"); - Check.Eq(r.RoomText(), "landblock 0x0106 variant 2", "Seedy Motel room"); - - IltBreedingRules frozen = r.Frozen(); - r.Learn(IltBreedingRules.MaleCharges, 8, t); - Check.Eq(frozen.GetInt(IltBreedingRules.MaleCharges), 12, "a frozen copy doesn't follow later learning"); - - Check.Eq(r.StageName(2), "Whelp", "default stage names"); - Check.True(r.LearnStageName(2, "Pup"), "a server's own stage name"); - Check.Eq(r.StageName(2), "Pup", "seen name wins"); - for (int i = 0; i < IltBreedingRules.MaxEvents + 5; i++) r.AddEvent("x", "e" + i, t); - Check.Eq(r.State.Log.Count, IltBreedingRules.MaxEvents, "event log is capped"); - Check.Eq(r.State.Log[^1].Text, "e" + (IltBreedingRules.MaxEvents + 4), "newest kept last"); - } - - private static void MutationOdds() - { - IltBreedingRules r = Rules(); - Check.Near(r.StatMutationChance(0, 0), 0.05, 1e-9, "base 5%"); - Check.Near(r.StatMutationChance(4, 0), 0.05 / 1.4, 1e-9, "decay 0.1 x 4 mutations"); - Check.Near(r.StatMutationChance(0, 0.10), 0.15, 1e-9, "exquisite incense adds 10%"); - Check.Near(r.CombinedIncense(0.4, 0.3), 0.5, 1e-9, "both parents' incense capped at 50%"); - r.Learn(IltBreedingRules.MutationDecay, 10, DateTime.UtcNow); - Check.Near(r.StatMutationChance(4, 0), 0.02, 1e-9, "never below the 2% floor"); - } - - private static void AppraisalParse() - { - double now = 1_800_000_000; - double lastRefill = now - (20 * 3600 + 50 * 60); - string desc = "A fire skeleton essence.\nSex: Male (9/12 breeding charges today) - refills in 3h 10m\nBond: Unbound (imprints on first summon)"; - var seen = IltBreedingRules.FromAppraisal(desc, lastRefill, now); - Check.True(seen.Contains((IltBreedingRules.MaleCharges, 12)), "max charges from the stud line"); - Check.True(seen.Contains((IltBreedingRules.MaleRefillHours, 24)), "refill window from the countdown"); - - string growth = "Sex: Female (ready to breed)\nGrowth: Whelp 2/5 - 75 kills to Juvenile, 195 to Adult"; - Check.True(IltBreedingRules.FromAppraisal(growth, 0, now).Contains((IltBreedingRules.MaturityStages, 5)), "stage count"); - Check.True(IltBreedingRules.TryParseGrowth(growth, out string name, out int stage, out int stages, out int toNext, out string next, out int toAdult), "growth line"); - Check.Eq(name, "Whelp", "stage name"); - Check.Eq(stage, 2, "stage"); - Check.Eq(stages, 5, "stages"); - Check.Eq(toNext, 75, "to next"); - Check.Eq(next, "Juvenile", "next stage"); - Check.Eq(toAdult, 195, "to adult"); - - Check.True(IltBreedingRules.TryParseGrowth("Growth: Young Adult 5/5 - 60 kills to Adult", out name, out stage, out _, out toNext, out next, out toAdult), "last stage"); - Check.Eq(name, "Young Adult", "two-word stage name"); - Check.Eq(next, "Adult", "last stage leads to Adult"); - Check.Eq(toAdult, 60, "last stage: to adult = to next"); - Check.False(IltBreedingRules.TryParseGrowth("Growth: Adult", out _, out _, out _, out _, out _, out _), "an adult has no countdown"); - } - - private static void ChatParse() - { - var a = IltBreedingRules.FromChat("[Breeding] Fire Skeleton Essence spent a breeding charge: 7/12 left today."); - Check.True(a.Contains((IltBreedingRules.MaleCharges, 12)), "charge line gives the max"); - var g = IltBreedingRules.FromChat("The union stirs something... Mating Spirit rises before A and B! Only the two parents can harm it. They have 120s to bring it down together."); - Check.True(g.Contains((IltBreedingRules.GuardianEnabled, 1)), "guardian on"); - Check.True(g.Contains((IltBreedingRules.GuardianSeconds, 120)), "guardian timer"); - var d = IltBreedingRules.FromChat("[Breeding] Your pet performs the courtship dance, waiting for a partner... (Your partner must have their pet summoned in the same room and *dance* within 5 seconds)."); - Check.True(d.Contains((IltBreedingRules.DanceWindow, 5)), "dance window"); - Check.Eq(IltBreedingRules.FromChat("You say, \"hello\"").Count, 0, "ordinary chat says nothing"); - - Check.True(IltBreedingRules.TryParseGrownInto("Pup has grown into a Whelp! Its body swells with new strength. (2/5)", out int stage, out string name), "growth line"); - Check.Eq(stage, 2, "stage number"); - Check.Eq(name, "Whelp", "stage name"); - - Check.Eq(IltPetBreeding.EventKind("The mating ritual has begun between A and B..."), "ritual", "ritual"); - Check.Eq(IltPetBreeding.EventKind("Congratulations! A baby pet has been born: Pup! Placed in Bob's inventory."), "birth", "birth"); - Check.Eq(IltPetBreeding.EventKind("A baby pet has been born: Pup! Bob's packs are full, so the baby has been tucked away"), "birth", "deferred birth"); - Check.Eq(IltPetBreeding.EventKind("Pup has reached adulthood! It stands at its full size"), "adult", "adulthood"); - Check.Eq(IltPetBreeding.EventKind("Pup has imprinted on you. It is now bound to this character"), "imprint", "imprint"); - Check.Eq(IltPetBreeding.EventKind("[Breeding] The spectral guardian dissolves back into the ether..."), "guardian", "guardian lost"); - Check.Eq(IltPetBreeding.EventKind("Bob tells you, \"breed?\""), null, "not a breeding line"); - } - - private const string DebugReply = - "=== PET BREEDING DIAGNOSTICS ===\n" + - "Breeding System Enabled: True\n" + - "Your Location: Landblock=0x0106, Cell=0x01060186, Variant=2\n" + - "Allowed Target: whole landblock 0x106, Variant=2 => Location Match: VALID (Room OK)\n" + - "Your Active Pet: Fire Skeleton (WCID 48900) | Device: Fire Skeleton Essence\n" + - " Sex: Male (9/10 charges)\n" + - "Eligible breeding partners nearby: 1\n" + - "================================\n"; - - private static void DebugParse() - { - Check.True(IltBreedingRules.IsDebugLine(DebugReply.TrimEnd('\n')), "whole message is a reply line"); - Check.True(IltBreedingRules.IsDebugEnd(DebugReply.TrimEnd('\n')), "whole message ends the reply"); - Check.True(IltBreedingRules.IsDebugEnd("================================"), "rule line alone ends it"); - Check.False(IltBreedingRules.IsDebugEnd("=== PET BREEDING DIAGNOSTICS ==="), "the header doesn't"); - Check.False(IltBreedingRules.IsDebugLine("Bob says, \"hi\""), "chat isn't"); - - BreedDebugInfo whole = IltBreedingRules.ParseDebug(new[] { DebugReply }); - BreedDebugInfo split = IltBreedingRules.ParseDebug(DebugReply.Split('\n')); - foreach (BreedDebugInfo d in new[] { whole, split }) - { - Check.Eq(d.Enabled, (bool?)true, "enabled"); - Check.Eq(d.AllowedLandblock, 0x106u, "landblock"); - Check.Eq(d.AllowedVariant, 2, "variant"); - Check.Eq(d.AllowedKind, "whole landblock", "kind"); - Check.Eq(d.LocationOk, (bool?)true, "in the room"); - Check.Eq(d.Partners, 1, "partners"); - Check.Eq(d.PetSex, "Male (9/10 charges)", "pet sex line"); - } - var rules = IltBreedingRules.FromChat(DebugReply); - Check.True(rules.Contains((IltBreedingRules.Landblock, 0x106)), "room landblock learned"); - Check.True(rules.Contains((IltBreedingRules.Variant, 2)), "room variant learned"); - } - - private static void Gates() - { - IltBreedingRules r = Rules(); - double now = 1_800_000_000; - - BreedEssence full = IltBreedingEssence.Evaluate(Facts(1, true), r, now); - Check.True(full.Ready, "a stud that never bred is full"); - Check.Eq(full.Charges, 10, "10 charges"); - Check.Eq(full.Tier, 125, "48946 is tier 125"); - - var spent = Facts(2, true); - spent.MaleCharges = 0; - spent.MaleRefreshUnix = now - 2 * 3600; - BreedEssence noCharge = IltBreedingEssence.Evaluate(spent, r, now); - Check.Eq(noCharge.Gate, BreedGate.NoCharges, "no charges"); - Check.Near(noCharge.ReadyAtUnix, now + 22 * 3600, 1, "refills 24h after the last refill"); - - spent.MaleRefreshUnix = now - 25 * 3600; - Check.True(IltBreedingEssence.Evaluate(spent, r, now).Ready, "refilled once the window passed (the server refills on read)"); - - var dam = Facts(3, false); - dam.NextBreedUnix = now + 3600 + 300; - BreedEssence resting = IltBreedingEssence.Evaluate(dam, r, now); - Check.Eq(resting.Gate, BreedGate.Resting, "resting dam"); - Check.Eq(resting.Status, "Rest 1h 05m", "rest countdown"); - - var neut = Facts(4, false); - neut.Neutered = true; - Check.Eq(IltBreedingEssence.Evaluate(neut, r, now).Gate, BreedGate.Neutered, "neutered"); - - var shiny = Facts(5, true); - shiny.LongDesc = "Sex: Male (shiny - cannot breed)"; - Check.Eq(IltBreedingEssence.Evaluate(shiny, r, now).Gate, BreedGate.Shiny, "shiny"); - - var baby = Facts(6, false); - baby.JuvenileFlag = true; - baby.MaturityKills = 130; - BreedEssence growing = IltBreedingEssence.Evaluate(baby, r, now); - Check.Eq(growing.Gate, BreedGate.Growing, "juvenile"); - Check.Eq(growing.Stage, 3, "130 kills of 300 over 5 stages: stage 3"); - Check.Eq(growing.StageName, "Juvenile", "stage 3 name"); - Check.Eq(growing.KillsToNext, 50, "50 kills to stage 4"); - - var weak = Facts(7, true); - weak.Bond = 40; - Check.Eq(IltBreedingEssence.Evaluate(weak, r, now).Gate, BreedGate.LowBond, "bond under 100"); - - BreedEssence low = IltBreedingEssence.Evaluate(Facts(8, true, 48944), r, now); - Check.Eq(low.Gate, BreedGate.LowTier, "tier 80 is under the minimum"); - - var unread = Facts(9, true); - unread.HasId = false; - Check.Eq(IltBreedingEssence.Evaluate(unread, r, now).Gate, BreedGate.NeedsId, "not appraised yet"); - - var boosted = Facts(10, false); - boosted.Incense = 0.05; - boosted.Catalyst = true; - BreedEssence b = IltBreedingEssence.Evaluate(boosted, r, now); - Check.Eq(string.Join("|", b.Boosters), "Refined incense +5%|Chromatic Catalyst", "boosters listed"); - } - - private static void Planner() - { - IltBreedingRules r = Rules(); - double now = 1_800_000_000; - var sf = Facts(1, true); - sf.MutDamage = 2; - sf.MutCrit = 1; - sf.Incense = 0.10; - var df = Facts(2, false); - df.MutDamage = 0; - df.MutCrit = 3; - BreedEssence stud = IltBreedingEssence.Evaluate(sf, r, now), dam = IltBreedingEssence.Evaluate(df, r, now); - - BreedPairPlan p = IltBreedingPlanner.Plan(stud, dam, r); - Check.True(p.CanBreed, "both ready"); - Check.Eq(p.InheritMin, 1, "lower lines: damage 0 + crit 1"); - Check.Eq(p.InheritMax, 5, "higher lines: damage 2 + crit 3"); - Check.Near(p.ChanceBest, 0.15 / 1.1, 1e-9, "best: 1 mutation, incense 10%"); - Check.Near(p.ChanceWorst, 0.15 / 1.5, 1e-9, "worst: 5 mutations"); - Check.Near(p.PotencyChance, 0.03, 1e-9, "potency 3%"); - - BreedPairPlan wrong = IltBreedingPlanner.Plan(dam, stud, r); - Check.False(wrong.CanBreed, "swapped sexes"); - Check.True(wrong.Blockers.Any(b => b.Contains("must be male")), "says the stud must be male"); - } - - private static void Supplies() - { - IltBreedingRules r = Rules(); - double now = 1_800_000_000; - BreedSupplyDef lesser = IltBreedingSupplies.Find(IltBreedingSupplies.LesserIncense)!; - BreedSupplyDef exquisite = IltBreedingSupplies.Find(IltBreedingSupplies.ExquisiteIncense)!; - BreedSupplyDef draught = IltBreedingSupplies.Find(IltBreedingSupplies.Draught)!; - BreedSupplyDef offering = IltBreedingSupplies.Find(IltBreedingSupplies.Offering)!; - BreedSupplyDef neuter = IltBreedingSupplies.Find(IltBreedingSupplies.NeuteringKit)!; - - var f = Facts(1, false); - f.Incense = 0.05; - BreedEssence primed = IltBreedingEssence.Evaluate(f, r, now); - Check.NotNull(IltBreedingSupplies.RefuseReason(lesser, primed, r), "weaker incense refused"); - Check.Null(IltBreedingSupplies.RefuseReason(exquisite, primed, r), "stronger incense taken"); - Check.True(IltBreedingSupplies.Warning(exquisite, primed).Contains("+5%"), "and warns the +5% is lost"); - - var n = Facts(2, false); - n.Neutered = true; - Check.NotNull(IltBreedingSupplies.RefuseReason(lesser, IltBreedingEssence.Evaluate(n, r, now), r), "no incense on a neutered essence"); - - BreedEssence adult = IltBreedingEssence.Evaluate(Facts(3, true), r, now); - Check.NotNull(IltBreedingSupplies.RefuseReason(draught, adult, r), "draught: juveniles only"); - var j = Facts(4, true); - j.JuvenileFlag = true; - j.MaturityKills = 0; - Check.Null(IltBreedingSupplies.RefuseReason(draught, IltBreedingEssence.Evaluate(j, r, now), r), "draught on a juvenile"); - j.MaturityXpMult = 2.0; - Check.NotNull(IltBreedingSupplies.RefuseReason(draught, IltBreedingEssence.Evaluate(j, r, now), r), "not twice"); - - Check.Null(IltBreedingSupplies.RefuseReason(offering, adult, r), "offering with the guardian on"); - r.Learn(IltBreedingRules.GuardianEnabled, 0, DateTime.UtcNow); - Check.NotNull(IltBreedingSupplies.RefuseReason(offering, adult, r), "offering refused with the guardian off"); - Check.NotNull(IltBreedingSupplies.RefuseReason(neuter, adult, r), "the neutering kit is never used from here"); - Check.Eq(IltBreedingSupplies.PriceText(1_250_000), "1.25M", "price text"); - } - - private static void ReaderJson() - { - IltBreedingRules r = Rules(); - double now = 1_800_000_000; - var stud = IltBreedingEssence.Evaluate(Facts(11, true), r, now); - var dam = IltBreedingEssence.Evaluate(Facts(12, false), r, now); - var events = new[] { new IltBreedingEvent { Utc = new DateTime(2026, 10, 15, 20, 0, 0, DateTimeKind.Utc), Kind = "birth", Text = "A \"baby\" was born" } }; - var supplies = IltBreedingSupplies.All.Select(s => (s, s.Key == IltBreedingSupplies.RefinedIncense ? 2L : 0L)).ToList(); - var snap = new BreedingSnapshot(new[] { stud, dam }, supplies, r.All(), events, - IltBreedingRules.ParseDebug(new[] { DebugReply }), DateTime.UtcNow, IltTri.On, IltTri.On, IltTri.On, - r.RoomText(), 5, "hello", now, true, r.Frozen()); - - string json = IltPetBreeding.BuildJson(snap, r, "InfiniteLeaftide"); - using (JsonDocument.Parse(json)) { } // well-formed - IltBreedingView v = IltBreedingView.Parse(json); - Check.True(v.Loaded && v.Available, "loaded"); - Check.Eq(v.Enabled, "on", "enabled"); - Check.Eq(v.Room, "landblock 0x0106 variant 2", "room"); - Check.Eq(v.FreeSlots, 5, "free slots"); - Check.Eq(v.Essences.Count, 2, "two essences"); - Check.True(v.Essences[0].Male && v.Essences[0].Ready, "stud row"); - Check.Eq(v.Pairs.Count, 1, "one ready pairing"); - Check.Near(v.Pairs[0].ChanceBest, 0.05, 1e-6, "pair odds"); - IltBreedSupplyRow refined = v.Supplies.First(s => s.Key == IltBreedingSupplies.RefinedIncense); - Check.Eq(refined.Count, 2L, "supply count"); - Check.Eq(refined.Targets.Count, 2, "both essences can take it"); - Check.Eq(v.Supplies.First(s => s.Key == IltBreedingSupplies.LesserIncense).Targets.Count, 0, "none carried: no targets"); - Check.Eq(v.Rules.Count, IltBreedingRules.Defs.Length, "every rule"); - Check.Eq(v.Events[0].Text, "A \"baby\" was born", "quotes escaped and read back"); - Check.Eq(v.Debug?.Match, "valid", "diagnostics"); - Check.Eq(IltBreedingView.ApplyVerb(" incense2 ", 12), "apply incense2 12", "apply verb"); - } - - private static void StateJson() - { - var state = new IltHubState(); - var rules = new IltBreedingRules(state.Pet.Breeding); - rules.Learn(IltBreedingRules.MaleCharges, 12, new DateTime(2026, 10, 15, 0, 0, 0, DateTimeKind.Utc)); - rules.LearnStageName(1, "Hatchling"); - rules.AddEvent("birth", "born", DateTime.UtcNow); - string json = JsonSerializer.Serialize(state, IltHubJsonContext.Default.IltHubState); - IltHubState back = JsonSerializer.Deserialize(json, IltHubJsonContext.Default.IltHubState)!; - var again = new IltBreedingRules(back.Pet.Breeding); - Check.Eq(again.GetInt(IltBreedingRules.MaleCharges), 12, "learned rule saved"); - Check.Eq(again.StageName(1), "Hatchling", "stage name saved"); - Check.Eq(back.Pet.Breeding.Log.Count, 1, "event saved"); - - IltHubState old = JsonSerializer.Deserialize("{\"Pet\":{\"PetLog\":[\"a\"]}}", IltHubJsonContext.Default.IltHubState)!; - Check.NotNull(old.Pet.Breeding, "a hub.json from before the tracker gets an empty breeding state"); - } - - private static unsafe void DataApiVersion() - { - // Version 3 (the Temple guardians) appends after the breeding pair; a v2 reader sees the same breeding layout. - Check.Eq(RynthIltDataApiV1.InterfaceVersion, 3u, "version 3"); - Check.True(RynthIltDataApiV1.V1Size < RynthIltDataApiV1.V2Size && RynthIltDataApiV1.V2Size < (uint)sizeof(RynthIltDataApiV1), - "v2 appends to v1, v3 to v2"); - Check.Eq(RynthIltDataApiV1.V1Size, (uint)(8 + 4 * sizeof(IntPtr)), "v1 = two uints and four function pointers"); - Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1) != IntPtr.Zero, "v1 readers still get the table"); - Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 2) != IntPtr.Zero, "v2 readers too"); - Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 3) != IntPtr.Zero, "v3 readers too"); - Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 4) == IntPtr.Zero, "a future version isn't claimed"); - var t = (RynthIltDataApiV1*)DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1); - Check.True(t->GetPetBreedingJson != null && t->PetBreedingCommand != null, "breeding functions filled"); - Check.Eq(RynthIltHub.SectionPetBreeding, "pets-breeding", "section id"); - } -} diff --git a/Tools/RynthILT.Tests/ChunkTargetTests.cs b/Tools/RynthILT.Tests/ChunkTargetTests.cs deleted file mode 100644 index 857dbc6..0000000 --- a/Tools/RynthILT.Tests/ChunkTargetTests.cs +++ /dev/null @@ -1,173 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.RynthAiHostTests.Fakes; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// The chunk rules end to end: a fake inventory with the Lugian Aetheria Hammer and one candidate, -// IltChunkClap.Tick, and whether the hammer was used on the candidate. These cover what the pure -// rule tests (AetheriaChunkTests) cannot: the properties as RynthILT reads them from the host, an -// item that is not appraised, and a host that cannot tell whether an appraisal arrived. The hammer -// destroys what it is used on, so "used on it" is the thing to get right. -internal static class ChunkTargetTests -{ - private const uint Player = 0x50000F01; - private const uint Hammer = 0x5000A001; - private const uint Item = 0x5000A002; - private const uint ItemTypeGem = 0x00000800; - private const uint ItemTypeMelee = 0x00000001; - private const uint ItemTypeMisc = 0x00000080; - - public static void Register(Runner r) - { - r.Add("chunk (live path): unlevelled Coalesced chunks only when its level was truly read as none", UnlevelledVsUnreadable); - r.Add("chunk (live path): levelled Coalesced Aetheria obeys the cap; other aetheria needs a level", LevelledCap); - r.Add("chunk (live path): corrupted two-handed cleave 2 chunks, other corrupted cleave 2 does not", CorruptedCleave); - r.Add("chunk (live path): corrupted keep rules and the rating level are off by default and protect when on", KeepRulesLive); - r.Add("chunk (live path): a busy client in combat chunks with chunk-in-combat on, not off; peace waits for idle", CombatBusy); - } - - /// One chunk pass on a fake pack. Returns the targets the hammer was used on. - private static List Pass(string folder, Action settings, Action candidate, - uint itemType = ItemTypeGem, string name = "Coalesced Aetheria", bool appraised = true, - bool hostCanSayAppraised = true, bool busy = false, int combatMode = 1) - { - FakeHost.Reset(); - FakeHost.WorldName = "InfiniteLeaftide"; - FakeHost.ContentsCalls = true; - FakeHost.UseOnCalls = true; - FakeHost.WeaponCalls = hostCanSayAppraised; // installs HasAppraisalData / RequestId / combat mode - FakeHost.BusyCalls = true; - FakeHost.BusyStateValue = busy ? 1 : 0; - FakeHost.CombatModeValue = combatMode; - FakeHost.Names[Hammer] = "Lugian Aetheria Hammer"; FakeHost.ItemTypes[Hammer] = ItemTypeMisc; FakeHost.Containers[Hammer] = Player; - FakeHost.Names[Item] = name; FakeHost.ItemTypes[Item] = itemType; FakeHost.Containers[Item] = Player; - if (appraised) FakeHost.Appraised.Add(Item); - candidate(Item); - var host = FakeHost.Create(Player); - string dir = Path.Combine(Program.TempRoot, "chunk-" + folder); - Directory.CreateDirectory(dir); - var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host)); - var g = hub.State.Gear; - g.AutoChunkAetheria = true; - g.AutoChunkCorrupted = true; - settings(g); - hub.Gear.ChunkClap.Tick(10_000); - return FakeHost.UsesOn.Where(u => u.Source == Hammer).Select(u => u.Target).ToList(); - } - - private static void Ints(uint id, params (uint Key, int Value)[] values) - { - foreach (var (k, v) in values) FakeHost.Ints[(id, k)] = v; - } - - private static void UnlevelledVsUnreadable() - { - // Truly unlevelled: the appraisal arrived and the item has no level (int 319), no XP, no tinks. - Check.Eq(Pass("coal-unlevelled", _ => { }, _ => { }).Count, 1, "appraised, no level: chunked (ub-IT)"); - // Even with the cap at its lowest. - Check.Eq(Pass("coal-unlevelled-cap1", g => g.ChunkAetheriaUnderLevel = 1, _ => { }).Count, 1, "cap 1 does not stop an unlevelled one"); - // Not appraised yet: nothing is known, so it is asked for, not hammered. - var asked = Pass("coal-unappraised", _ => { }, _ => { }, appraised: false); - Check.Eq(asked.Count, 0, "not appraised: not chunked"); - Check.True(FakeHost.IdRequests.Contains(Item), "its appraisal is requested"); - // The host cannot say whether an appraisal arrived: a level of 0 might be a failed read. - Check.Eq(Pass("coal-unreadable", _ => { }, _ => { }, hostCanSayAppraised: false).Count, 0, - "host cannot confirm the appraisal: kept, not chunked"); - // The same unconfirmable host with a read level still keeps (no half-trusted piece is hammered). - Check.Eq(Pass("coal-unreadable-lvl", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 2)), hostCanSayAppraised: false).Count, 0, - "host cannot confirm the appraisal: even a read level 2 is kept"); - // A revealed (non-Coalesced) aetheria with no level is never chunked. - Check.Eq(Pass("rev-unlevelled", _ => { }, _ => { }, name: "Blue Aetheria").Count, 0, "revealed aetheria with no level: kept"); - // Item XP, tinks or the never-chunk flag keep it. - Check.Eq(Pass("coal-xp", _ => { }, id => FakeHost.Quads[(id, IltInventory.QuadItemTotalXp)] = 500).Count, 0, "has item XP: kept"); - Check.Eq(Pass("coal-tinked", _ => { }, id => Ints(id, (IltInventory.IntNumTimesTinkered, 1))).Count, 0, "tinkered: kept"); - Check.Eq(Pass("coal-never", _ => { }, id => FakeHost.Bools[(id, IltInventory.BoolNeverChunk)] = true).Count, 0, "never-chunk flag: kept"); - } - - private static void LevelledCap() - { - Check.Eq(Pass("cap-l3", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 3))).Count, 1, "level 3 under the default cap of 4"); - Check.Eq(Pass("cap-l4", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 4))).Count, 0, "level 4 at the default cap of 4: kept"); - Check.Eq(Pass("cap9-l8", g => g.ChunkAetheriaUnderLevel = 9, id => Ints(id, (IltInventory.IntItemMaxLevel, 8))).Count, 1, "level 8 under a cap of 9"); - Check.Eq(Pass("cap9-l9", g => g.ChunkAetheriaUnderLevel = 9, id => Ints(id, (IltInventory.IntItemMaxLevel, 9))).Count, 0, "level 9 at a cap of 9: kept"); - Check.Eq(Pass("cap9-l10", g => g.ChunkAetheriaUnderLevel = 9, id => Ints(id, (IltInventory.IntItemMaxLevel, 10))).Count, 0, "level 10 over a cap of 9: kept"); - Check.Eq(Pass("cap11-l10", g => g.ChunkAetheriaUnderLevel = 11, id => Ints(id, (IltInventory.IntItemMaxLevel, 10))).Count, 1, "cap 11 chunks every level"); - Check.Eq(Pass("rev-l2", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 2)), name: "Blue Aetheria").Count, 1, "a levelled revealed piece under the cap"); - } - - private static void CorruptedCleave() - { - void Weapon(uint id, int cleave, int wieldSkill = 45, int weaponType = 0, int attackType = 4) => - Ints(id, (IltInventory.IntItemWorkmanship, 6), (IltInventory.IntCleaving, cleave), (IltInventory.IntWieldSkillType, wieldSkill), - (IltInventory.IntWeaponType, weaponType), (IltInventory.IntAttackType, attackType)); - Check.Eq(Pass("cor-1h-c1", _ => { }, id => Weapon(id, 1), ItemTypeMelee, "Corrupted Sword").Count, 1, "one-handed cleave 1 chunks"); - Check.Eq(Pass("cor-1h-c2", _ => { }, id => Weapon(id, 2), ItemTypeMelee, "Corrupted Sword").Count, 0, "one-handed cleave 2 is kept"); - Check.Eq(Pass("cor-2h-c2", _ => { }, id => Weapon(id, 2, wieldSkill: 41), ItemTypeMelee, "Corrupted Greatsword").Count, 1, "two-handed cleave 2 chunks"); - Check.Eq(Pass("cor-2h-c3", _ => { }, id => Weapon(id, 3, wieldSkill: 41), ItemTypeMelee, "Corrupted Greatsword").Count, 0, "two-handed cleave 3 is kept"); - Check.Eq(Pass("cor-2h-thrust", _ => { }, id => Weapon(id, 2, wieldSkill: 41, attackType: 2), ItemTypeMelee, "Corrupted Spear").Count, 0, "two-handed thrust cleave 2 is kept"); - Check.Eq(Pass("cor-nowork", _ => { }, id => Ints(id, (IltInventory.IntCleaving, 1)), ItemTypeMelee, "Corrupted Sword").Count, 0, "no workmanship read: kept"); - Check.Eq(Pass("cor-unreadable", _ => { }, id => Weapon(id, 1), ItemTypeMelee, "Corrupted Sword", hostCanSayAppraised: false).Count, 0, - "host cannot confirm the appraisal: kept"); - Check.Eq(Pass("cor-off", g => g.AutoChunkCorrupted = false, id => Weapon(id, 1), ItemTypeMelee, "Corrupted Sword").Count, 0, "auto-chunk corrupted off: not touched"); - } - - private static void KeepRulesLive() - { - var def = new IltGearState(); - Check.True(!def.KeepCorruptedCrushingBlow && !def.KeepCorruptedBitingStrike && !def.KeepCorruptedArmorCleaving - && !def.KeepCorruptedAnySlayer && !def.KeepCorruptedMultiStrike && !def.KeepCorruptedElementalBonus - && !def.KeepCorruptedAnySpell && def.KeepCorruptedMaxDamageAtLeast == 0 && def.KeepCorruptedSpellIds == "", - "every corrupted keep rule is off by default"); - Check.Eq(def.KeepAetheriaRatingAtLeast, 1, "the rating level defaults to 1 (any rating keeps, as before)"); - - void Loaded(uint id) - { - Ints(id, (IltInventory.IntItemWorkmanship, 6), (IltInventory.IntCleaving, 1), (IltInventory.IntAttackType, 160), - (IltInventory.IntSlayerCreatureType, 5), (IltInventory.IntElementalDamageBonus, 10), (IltInventory.IntDamage, 400)); - FakeHost.Doubles[(id, IltInventory.FloatCriticalFrequency)] = 0.1; - FakeHost.Doubles[(id, IltInventory.FloatCriticalMultiplier)] = 1.5; - FakeHost.Doubles[(id, IltInventory.FloatIgnoreArmor)] = 0.2; - FakeHost.SpellIds[id] = new uint[] { 2072 }; - } - int Run(string tag, Action s) => Pass("keep-" + tag, s, Loaded, ItemTypeMelee, "Corrupted Sword").Count; - Check.Eq(Run("none", _ => { }), 1, "a loaded corrupted weapon chunks while every keep rule is off"); - Check.Eq(Run("crush", g => g.KeepCorruptedCrushingBlow = true), 0, "Crushing Blow on: kept"); - Check.Eq(Run("bite", g => g.KeepCorruptedBitingStrike = true), 0, "Biting Strike on: kept"); - Check.Eq(Run("armor", g => g.KeepCorruptedArmorCleaving = true), 0, "Armor Cleaving on: kept"); - Check.Eq(Run("slayer", g => g.KeepCorruptedAnySlayer = true), 0, "slayer on: kept"); - Check.Eq(Run("multi", g => g.KeepCorruptedMultiStrike = true), 0, "multi-strike on: kept"); - Check.Eq(Run("elem", g => g.KeepCorruptedElementalBonus = true), 0, "elemental bonus on: kept"); - Check.Eq(Run("maxdmg", g => g.KeepCorruptedMaxDamageAtLeast = 400), 0, "max damage 400 on: kept"); - Check.Eq(Run("maxdmg-hi", g => g.KeepCorruptedMaxDamageAtLeast = 401), 1, "max damage above the weapon's: chunks"); - Check.Eq(Run("spell", g => g.KeepCorruptedAnySpell = true), 0, "any spell on: kept"); - Check.Eq(Run("spellid", g => g.KeepCorruptedSpellIds = "2072"), 0, "a listed spell id: kept"); - Check.Eq(Run("spellid-other", g => g.KeepCorruptedSpellIds = "100"), 1, "another spell id: chunks"); - - // The rating level on a live Coalesced piece with a C 1 rating. - void C1(uint id) => Ints(id, (IltInventory.IntGearCrit, 1)); - Check.Eq(Pass("rate-default", _ => { }, C1).Count, 0, "C 1 is kept at the default rating level"); - Check.Eq(Pass("rate-2", g => g.KeepAetheriaRatingAtLeast = 2, C1).Count, 1, "C 1 chunks once the rating level is 2"); - Check.Eq(Pass("rate-2-c2", g => g.KeepAetheriaRatingAtLeast = 2, id => Ints(id, (IltInventory.IntGearCrit, 2))).Count, 0, "C 2 is kept at level 2"); - Check.Eq(Pass("rate-2-off", g => { g.KeepAetheriaRatingAtLeast = 2; g.KeepAetheriaWithCrit = false; }, id => Ints(id, (IltInventory.IntGearCrit, 5))).Count, 1, - "the C switch off ignores the rating level"); - } - - private static void CombatBusy() - { - Check.Eq(Pass("busy-combat-on", g => g.ChunkInCombat = true, _ => { }, busy: true, combatMode: 2).Count, 1, - "busy in combat mode with chunk-in-combat on: chunks"); - Check.Eq(Pass("busy-combat-off", g => g.ChunkInCombat = false, _ => { }, busy: true, combatMode: 2).Count, 0, - "busy in combat mode with chunk-in-combat off: waits"); - Check.Eq(Pass("idle-combat-on", g => g.ChunkInCombat = true, _ => { }, busy: false, combatMode: 2).Count, 1, - "idle in combat mode with chunk-in-combat on: chunks"); - Check.Eq(Pass("busy-peace", g => g.ChunkInCombat = true, _ => { }, busy: true, combatMode: 1).Count, 0, - "busy in peace mode waits for idle even with chunk-in-combat on"); - Check.Eq(Pass("idle-peace", g => g.ChunkInCombat = false, _ => { }, busy: false, combatMode: 1).Count, 1, - "idle in peace mode chunks"); - } -} diff --git a/Tools/RynthILT.Tests/ChunkTests.cs b/Tools/RynthILT.Tests/ChunkTests.cs deleted file mode 100644 index 0d8c931..0000000 --- a/Tools/RynthILT.Tests/ChunkTests.cs +++ /dev/null @@ -1,36 +0,0 @@ -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// Lugian-hammer chunking (Hub/IltChunkClap.cs): only the Lugian Aetheria Hammer is the tool, and -// ILT's result lines name the item and the tool. Ported from SilentKelpie's fix (2026-10-15). -internal static class ChunkTests -{ - public static void Register(Runner r) - { - r.Add("chunk: only the Lugian Aetheria Hammer is the tool, never a Lugian Hammer weapon", HammerOnly); - r.Add("chunk: ILT's result lines (item and tool named) end the wait; combat lines don't", ResultLines); - } - - /// The Flaming Lugian Hammer (a loot weapon) matched " Lugian Hammer", chunked nothing, - /// and all 9 Coalesced Aetheria timed out into the skip list. - private static void HammerOnly() - { - Check.True(IltChunkClap.IsChunkHammer("Lugian Aetheria Hammer"), "the ILT tool"); - Check.True(IltChunkClap.IsChunkHammer("lugian aetheria hammer"), "any case"); - Check.False(IltChunkClap.IsChunkHammer("Flaming Lugian Hammer"), "a loot weapon is not the tool"); - Check.False(IltChunkClap.IsChunkHammer("Lugian Hammer"), "nor the plain one"); - Check.False(IltChunkClap.IsChunkHammer("Acid Lugian Hammer"), "nor any variant"); - } - - private static void ResultLines() - { - Check.Eq(IltChunkClap.ClassifyChat("You smash the Corrupted Sword with the Lugian Aetheria Hammer."), IltChunkClap.ChunkResult.Done, "ILT corrupted line"); - Check.Eq(IltChunkClap.ClassifyChat("You smash the aetheria with the hammer."), IltChunkClap.ChunkResult.Done, "aetheria line"); - Check.Eq(IltChunkClap.ClassifyChat("The aetheria is too powerful to chunk."), IltChunkClap.ChunkResult.Refused, "refused"); - Check.Eq(IltChunkClap.ClassifyChat("You're too busy!"), IltChunkClap.ChunkResult.Busy, "busy"); - Check.Eq(IltChunkClap.ClassifyChat("You smash Corrupted Shadow for 147 points of bludgeoning damage!"), IltChunkClap.ChunkResult.None, - "a combat line naming a corrupted monster is no result"); - } -} diff --git a/Tools/RynthILT.Tests/DataApiTests.cs b/Tools/RynthILT.Tests/DataApiTests.cs deleted file mode 100644 index 3434c10..0000000 --- a/Tools/RynthILT.Tests/DataApiTests.cs +++ /dev/null @@ -1,152 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using RynthCore.Plugin.RynthILT; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.Plugin.Shared; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// "RynthILT.Data" v1 (Plugins/Shared/RynthIltDataApi.cs, DataInterface.cs): the bank JSON RynthILT -// builds (Hub/IltBankExport.cs) read back by the shared reader, the bank verb lines a reader sends -// (IltBanking.RunVerb splits them), and the table itself. The charms JSON is MoveTests' -// CharmsReaderJson. No plugin in this tree reads the interface yet. -internal static class DataApiTests -{ - public static void Register(Runner r) - { - r.Add("data: the bank JSON reads back whole: characters (current first), choices, notes, log", BankRoundTrip); - r.Add("data: the bank verb lines carry their fields in RunVerb's order", BankVerbs); - r.Add("data: bad bank JSON reads as nothing", BankBadJson); - r.Add("data: the Temple guardian JSON reads back whole (switches, answer, hand-in, rows)", GuardianRoundTrip); - // Last: Release() switches the table off for the rest of the process. - r.Add("data: the RynthILT.Data table: query, functions, release", DataTable); - } - - private static void BankRoundTrip() - { - var me = new IltBankState { Pyreals = 1_500_000, Luminance = 42, PrestigeCoins = 3, - LastUpdated = new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc).ToLocalTime() }; - var alt = new IltBankState { Pyreals = 7, LegendaryKeys = 2, LastUpdated = DateTime.Now }; - var tx = new List(); - for (int i = 0; i < IltBankExport.MaxTransactions + 5; i++) - tx.Add(new IltBankTransaction { Timestamp = new DateTime(2026, 10, 1).AddMinutes(i), Type = i % 2 == 0 ? "Sent" : "Received", - Currency = "Pyreals", Amount = i, OtherPlayer = "Bob \"the\" Builder" }); - string json = IltBankExport.Build(true, 1, "InfiniteLeaftide", "Zed", - new[] { new IltBankExport.Row("Alt", false, alt), new IltBankExport.Row("Zed", true, me) }, - "Deposited 5 Pyreals", tx); - Check.True(json.All(c => c >= 0x20 && c <= 0x7E), "plain printable ASCII"); - - IltBankView v = IltBankView.Parse(json); - Check.True(v.Loaded && v.Available, "loaded, ILT"); - Check.Eq(v.Enabled, 1, "the server has /bank"); - Check.Eq(v.World, "InfiniteLeaftide", "world"); - Check.Eq(v.Character, "Zed", "character"); - Check.Eq(v.Result, "Deposited 5 Pyreals", "last result"); - Check.Eq(v.Characters.Count, 2, "both characters"); - Check.True(v.Characters[0].Current && v.Characters[0].Name == "Zed", "the current character first"); - Check.Eq(v.Characters[0].Pyreals, 1_500_000L, "pyreals"); - Check.Eq(v.Characters[0].PrestigeCoins, 3L, "prestige coins"); - Check.Eq(v.Characters[0].UpdatedUtc, new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc), "updated, in UTC"); - Check.Eq(v.Characters[1].LegendaryKeys, 2L, "the other character's keys"); - - Check.Eq(v.Deposits.Count, IltBankCommands.Deposits.Length, "every deposit choice"); - Check.Eq(v.Withdrawals.Count, IltBankCommands.Withdrawals.Length, "every withdraw choice"); - Check.Eq(v.Transfers.Count, IltBankCommands.Transfers.Length, "every transfer choice"); - Check.True(v.Transfers.Single(t => t.Notes).Label == "Trade notes", "only trade notes count notes"); - Check.Eq(v.Notes.Count, IltBankCommands.NoteDenominations.Length, "every note denomination"); - Check.Eq(v.Notes[^1].Value, 250_000L, "MMD is 250K"); - - Check.Eq(v.Transactions.Count, IltBankExport.MaxTransactions, "the log is capped"); - Check.Eq(v.Transactions[0].Amount, (long)(IltBankExport.MaxTransactions + 4), "newest first"); - Check.Eq(v.Transactions[0].Player, "Bob \"the\" Builder", "quotes in a name survive"); - } - - private static void BankVerbs() - { - Check.Eq(IltBankView.RefreshVerb(), "refresh", "refresh"); - Check.Eq(IltBankView.DepositVerb(3), "deposit 3", "deposit"); - Check.Eq(IltBankView.WithdrawVerb(7, 4, 9), "withdraw 7 4 9", "withdraw: index, amount, note"); - Check.Eq(IltBankView.TransferVerb(6, 2, 9, " Some Name "), "transfer 6 2 9 Some Name", "transfer: the name last, trimmed"); - foreach (string verb in new[] { IltBankView.RefreshVerb(), IltBankView.DepositVerb(0), IltBankView.WithdrawVerb(0, 1, -1), - IltBankView.TransferVerb(0, 1, -1, "Bob") }) - Check.True(verb.All(c => c >= 0x20 && c <= 0x7E), "ASCII verb (DataInterface refuses anything else): " + verb); - } - - private static void BankBadJson() - { - Check.True(ReferenceEquals(IltBankView.Parse(null), IltBankView.None), "null"); - Check.True(ReferenceEquals(IltBankView.Parse("{not json"), IltBankView.None), "broken"); - Check.True(ReferenceEquals(IltBankView.Parse("[1,2]"), IltBankView.None), "not an object"); - IltBankView empty = IltBankView.Parse("{}"); - Check.True(empty.Loaded && !empty.Available && empty.Enabled == -1 && empty.Characters.Count == 0, "missing fields read as nothing known"); - } - - /// - /// Version 3: the guardian JSON RynthILT builds (IltGuardian.BuildJson) read back by the reader - /// RynthOracle's Quests tab uses, quotes and all. - /// - private static void GuardianRoundTrip() - { - var rows = new[] - { - new IltTempleAttrStatus("Strength", "Fiun \"Big\" Strongarm", 3, "Ready", "", true, true), - new IltTempleAttrStatus("Focus", "Fiun Thinker", 1, "Cooldown", "in 5h 2m", false, false), - }; - string json = IltGuardian.BuildJson("InfiniteLeaftide", chat: true, auto: false, buy: true, cooldownHours: 20, - answer: "Pyreal", npc: "Guardian of Attribute Enlightenment", answerAgeSec: 42, heard: "What is \"coin\"?", - running: true, status: "handing Pyreal to Guardian...", syncedUtc: new DateTime(2026, 10, 18, 19, 5, 0, DateTimeKind.Utc), rows); - Check.True(json.All(c => c >= 0x20 && c <= 0x7E), "plain printable ASCII"); - - IltGuardianView v = IltGuardianView.Parse(json); - Check.True(v.Loaded && v.Available && v.World == "InfiniteLeaftide", "loaded, the world"); - Check.True(v.Chat && !v.Auto && v.Buy && v.CooldownHours == 20, "the switches"); - Check.True(v.Answer == "Pyreal" && v.Npc == "Guardian of Attribute Enlightenment" && v.AnswerAgeSec == 42 && v.Heard == "What is \"coin\"?", - "the last answer"); - Check.True(v.Running && v.Status.StartsWith("handing Pyreal"), "the hand-in"); - Check.Eq(v.SyncedUtc, new DateTime(2026, 10, 18, 19, 5, 0, DateTimeKind.Utc), "the /qb read time"); - Check.Eq(v.Rows.Count, 2, "both rows"); - Check.True(v.Rows[0].Npc == "Fiun \"Big\" Strongarm" && v.Rows[0].Count == 3 && v.Rows[0].Ready && v.Rows[0].Exact, "an exact, ready row"); - Check.True(v.Rows[1].Eta == "in 5h 2m" && !v.Rows[1].Ready && !v.Rows[1].Exact, "an estimated row on cooldown"); - - IltGuardianView none = IltGuardianView.Parse(IltGuardian.BuildJson("x", false, false, false, 1, "", "", -1, "", false, "idle", - DateTime.MinValue, Array.Empty())); - Check.True(none.Answer.Length == 0 && none.AnswerAgeSec == -1 && none.SyncedUtc == DateTime.MinValue && none.Rows.Count == 0, - "no answer, no /qb read, no rows"); - } - - private static unsafe void DataTable() - { - Check.Eq(DataInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not ours"); - Check.Eq(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 4), IntPtr.Zero, "a newer version than we have: none"); - var t = (RynthIltDataApiV1*)DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1); - Check.True(t != null, "v1 is served"); - Check.Eq(t->Version, 3u, "Version 3 (v1 and v2 readers take it: it starts with their tables)"); - Check.Eq(t->StructSize, (uint)sizeof(RynthIltDataApiV1), "StructSize"); - Check.Eq(sizeof(RynthIltDataApiV1), 8 + 8 * IntPtr.Size, "header + 8 functions (v1's 4, the breeding pair, the guardian pair)"); - Check.Eq(RynthIltDataApiV1.V1Size, (uint)(8 + 4 * IntPtr.Size), "a v1 table ends before the breeding pair"); - Check.Eq(RynthIltDataApiV1.V2Size, (uint)(8 + 6 * IntPtr.Size), "a v2 table ends before the guardian pair (readers still see breeding on it)"); - Check.True(t->GetCharmsJson != null && t->GetBankJson != null && t->ToggleCharm != null && t->BankCommand != null - && t->GetPetBreedingJson != null && t->PetBreedingCommand != null - && t->GetGuardianJson != null && t->GuardianCommand != null, "every function is filled in"); - Check.Eq((IntPtr)t, DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1), "the same table each time"); - - // No plugin instance here (not logged in): nothing to report, every action refused. - byte* buf = stackalloc byte[64]; - Check.Eq(t->GetCharmsJson(buf, 64), 0, "no charms before login"); - Check.Eq(t->GetBankJson(buf, 64), 0, "no bank before login"); - Check.Eq(t->ToggleCharm(1234), 0, "no toggle before login"); - byte* verb = stackalloc byte[] { (byte)'r', (byte)'e', (byte)'f', (byte)'r', (byte)'e', (byte)'s', (byte)'h', 0 }; - Check.Eq(t->BankCommand(verb), 0, "no bank command before login"); - Check.Eq(t->GetPetBreedingJson(buf, 64), 0, "no breeding JSON before login"); - Check.Eq(t->PetBreedingCommand(verb), 0, "no breeding command before login"); - Check.Eq(t->GetGuardianJson(buf, 64), 0, "no guardian JSON before login"); - Check.Eq(t->GuardianCommand(verb), 0, "no guardian command before login"); - - DataInterface.Release(); - Check.Eq(t->Version, 0u, "Release zeroes Version (readers re-query)"); - Check.Eq(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1), IntPtr.Zero, "and nothing is served after shutdown"); - Check.Eq(t->GetBankJson(buf, 64), 0, "the old table stays callable and answers nothing"); - } -} diff --git a/Tools/RynthILT.Tests/FakeAiHub.cs b/Tools/RynthILT.Tests/FakeAiHub.cs deleted file mode 100644 index 05092c6..0000000 --- a/Tools/RynthILT.Tests/FakeAiHub.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using RynthCore.Plugin.Shared; - -namespace RynthILT.Tests; - -/// -/// A stand-in for RynthAi's "RynthAi.Hub" table (Plugins/Shared/RynthAiHubApi.cs), so the tests can -/// check what RynthILT asks of RynthAi (RynthAiClient.UseTableForTests takes it). Only the functions -/// the moved features use answer anything; the rest are absent (null), as an old RynthAi's would be. -/// Reset() before each test that uses it. -/// -internal static unsafe class FakeAiHub -{ - /// BackAwayFrom calls (object, radius, hold), and what it answers. - public static readonly List<(uint Id, float Radius, int HoldMs)> BackAways = new(); - public static int BackAwayResult = RynthAiHub.BackAwayStarted; - /// SetPlayerCounter: the last value reported per counter id. - public static readonly Dictionary Counters = new(); - /// SessionStats: the shared session's start (0 = no session: SessionStats answers 0). - public static long SessionStartTicks; - - private static RynthAiHubApiV1* _table; - - public static void Reset() - { - BackAways.Clear(); - BackAwayResult = RynthAiHub.BackAwayStarted; - Counters.Clear(); - SessionStartTicks = 0; - } - - public static IntPtr Table - { - get - { - if (_table == null) - { - var t = (RynthAiHubApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthAiHubApiV1)); - t->StructSize = (uint)sizeof(RynthAiHubApiV1); - t->BackAwayFrom = &BackAwayFrom; - t->SetPlayerCounter = &SetPlayerCounter; - t->SessionStats = &SessionStats; - t->Version = RynthAiHubApiV1.InterfaceVersion; - _table = t; - } - return (IntPtr)_table; - } - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int SessionStats(SessionStatsV1* s) - { - if (SessionStartTicks == 0 || s == null) return 0; - *s = default; - s->StartUtcTicks = SessionStartTicks; - s->SessionSeconds = 60; - return 1; - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int SetPlayerCounter(uint id, long value) - { - Counters[id] = value; - return 1; - } - - [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] - private static int BackAwayFrom(uint id, float radius, int holdMs) - { - BackAways.Add((id, radius, holdMs)); - return BackAwayResult; - } -} diff --git a/Tools/RynthILT.Tests/FeatureCatalogTests.cs b/Tools/RynthILT.Tests/FeatureCatalogTests.cs deleted file mode 100644 index 5e73202..0000000 --- a/Tools/RynthILT.Tests/FeatureCatalogTests.cs +++ /dev/null @@ -1,215 +0,0 @@ -using System; -using System.Text; -using System.Text.Json; -using RynthCore.Plugin.RynthILT; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.Plugin.Shared; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// Leaftide feature list (IltFeatureCatalog): every feature the player asked RynthILT to cover is -// listed and the states follow the server bits. Also the NUL-terminated copy RynthILT's interfaces -// ("RynthServer.Profile", "RynthILT.Data") hand their JSON out with. -internal static class FeatureCatalogTests -{ - public static void Register(Runner r) - { - r.Add("features: banking, guardian, attributes, augs, paragon x3, split arrows, T11 and fellowship are listed", Listed); - r.Add("features: state follows the server bit on ILT, built-ins are on, nothing is known off ILT", States); - r.Add("features: profile JSON is valid ASCII with features and the fellowship rules", ProfileJson); - r.Add("features: the interface copies the JSON only when it fits, NUL-terminated", InterfaceWrite); - r.Add("features: the /qb list rides the profile JSON on ILT worlds only", QuestBonusJson); - r.Add("features: the RynthILT.Server table: query, filled in, release", ServerTable); - r.Add("features: the ILT profile is on with the world; a refusal in chat turns a feature off", ProfileOnWithTheWorld); - r.Add("features: probed features read checking; options ILT runs off are off until chat shows them", ProbedAndOffInIlt); - r.Add("features: charms are on with the ILT world unless refused; rows describe themselves", Charms); - } - - /// ACECustom options Infinite Leaftide runs with off (ServerConfig defaults, PROD_DEPLOY_PLAN.md). - private static readonly string[] OffInIlt = { "pet_strain", "pet_refill", "defense_scaling" }; - - /// Features the login probe (or the /myquests tracker) answers. - private static readonly string[] Probed = - { - "bank", "attributes", "augmentations", "enlightenment", "clap", "pets", "shinies", - "fellowship_blackjack", "quests", "quest_bonus", "powerball", "blackjack", - }; - - private static void ProfileOnWithTheWorld() - { - // The features the player asked about, plus the pet switches prod runs on (bond, potency). - foreach (string key in new[] { "bank_notes", "t11", "t11_craft_gate", "split_arrows", "charms", "pet_breeding", - "pet_maturity", "pet_bond", "pet_potency", "monster_capture", "universal_mastery", - "missile_power", "t11_hit_gate", "fship" }) - { - IltFeatureInfo f = IltFeatureCatalog.Find(key)!; - Check.Eq(f.Known, IltKnown.Profile, key + " is on in the ILT profile"); - Check.Eq(IltFeatureCatalog.StateOf(f, true, _ => IltTri.Unknown), IltTri.On, key + " on with the ILT world"); - Check.Eq(IltFeatureCatalog.StateOf(f, false, _ => IltTri.On), IltTri.Unknown, key + " unknown off ILT"); - } - IltFeatureInfo mastery = IltFeatureCatalog.Find("universal_mastery")!; - Check.Eq(IltFeatureCatalog.StateOf(mastery, true, k => k == IltFeature.UniversalMastery ? IltTri.Off : IltTri.Unknown), - IltTri.Off, "a refusal in chat turns a profile feature off"); - Check.Null(IltFeatureCatalog.Find("fellowship_additive"), "upstream ACE's additive fellowship option isn't an ILT feature"); - } - - private static void ProbedAndOffInIlt() - { - foreach (string key in Probed) - { - IltFeatureInfo f = IltFeatureCatalog.Find(key)!; - Check.Eq(f.Known, IltKnown.Checked, key + " is answered by the login probe"); - Check.Eq(IltFeatureCatalog.StateText(IltFeatureCatalog.StateOf(f, true, _ => IltTri.Unknown)), "checking", key + " reads 'checking' until then"); - } - foreach (string key in OffInIlt) - { - IltFeatureInfo f = IltFeatureCatalog.Find(key)!; - Check.Eq(f.Known, IltKnown.ProfileOff, key + " is off in the ILT profile"); - Check.Eq(IltFeatureCatalog.StateOf(f, true, _ => IltTri.Unknown), IltTri.Off, key + " off with the ILT world"); - Check.Eq(IltFeatureCatalog.StateOf(f, true, _ => IltTri.On), IltTri.On, key + " on once the server shows it"); - Check.True(IltFeatureCatalog.Describe(key).Tooltip.Contains("Off in ILT"), key + "'s tooltip says it's off in ILT"); - } - - // ACECustom's three refill messages (PetDevice.TryApplyPyrealAutoRefillBeforeSummon) prove the refill is on. - Check.True(IltServerOptions.IsPyrealRefillLine("You restore one charge on your summoning essence at no cost."), "free refill"); - Check.True(IltServerOptions.IsPyrealRefillLine("You spend 1,000 pyreals to restore one charge on your summoning essence."), "paid refill"); - Check.True(IltServerOptions.IsPyrealRefillLine("You need 1,000 pyreals to auto-replenish your summoning essence. You do not have enough pyreals."), "refill too dear"); - Check.False(IltServerOptions.IsPyrealRefillLine("Your summoning essence is empty."), "an empty essence says nothing about the refill"); - } - - private static void Charms() - { - Check.Eq(IltFeatureCatalog.CharmStateOf(true, IltTri.Unknown), IltTri.On, "a charm is on with the ILT world"); - Check.Eq(IltFeatureCatalog.CharmStateOf(true, IltTri.Off), IltTri.Off, "a refused charm is off"); - Check.Eq(IltFeatureCatalog.CharmStateOf(false, IltTri.On), IltTri.Unknown, "nothing is claimed off ILT"); - - var (label, group, tooltip) = IltFeatureCatalog.Describe(IltFeature.Charm("Mana Barrier")); - Check.Eq(label, "Mana Barrier", "a charm row shows the charm's name"); - Check.Eq(group, IltFeatureCatalog.GroupCharms, "charms have their own section"); - Check.True(tooltip.Contains("Mana absorbs"), "the tooltip carries the charm's effect"); - Check.Eq(IltFeatureCatalog.Describe("something_new").Group, IltFeatureCatalog.GroupOther, "an unknown bit goes to Other"); - } - - private static readonly string[] Requested = - { - "bank", "guardian", "attributes", "augmentations", "paragon_armor", "paragon_weapons", - "paragon_jewelry", "split_arrows", "t11", "fellowship_large", "zone_share", "fellowship_blackjack", - }; - - private static void Listed() - { - foreach (string key in Requested) - Check.NotNull(IltFeatureCatalog.Find(key), "listed: " + key); - Check.Null(IltFeatureCatalog.Find("no_such_feature"), "an unknown key is not found"); - - var seen = new System.Collections.Generic.HashSet(StringComparer.OrdinalIgnoreCase); - foreach (IltFeatureInfo f in IltFeatureCatalog.All) - { - Check.True(seen.Add(f.Key), "keys are unique: " + f.Key); - Check.True(Array.IndexOf(IltFeatureCatalog.Groups, f.Group) >= 0, $"{f.Key} is in a known section ({f.Group})"); - Check.True(f.Label.Length > 0 && f.Where.Length > 0 && f.Description.Length > 0, f.Key + " has a label, a place and a description"); - } - } - - private static void States() - { - IltFeatureInfo bank = IltFeatureCatalog.Find("bank")!; - IltFeatureInfo guardian = IltFeatureCatalog.Find("guardian")!; - Check.Eq(IltFeatureCatalog.StateOf(bank, true, _ => IltTri.On), IltTri.On, "bank on when the server answers /bank"); - Check.Eq(IltFeatureCatalog.StateOf(bank, true, _ => IltTri.Off), IltTri.Off, "bank off when the server says so"); - Check.Eq(IltFeatureCatalog.StateOf(bank, true, _ => IltTri.Unknown), IltTri.Unknown, "bank unknown before the check"); - Check.Eq(IltFeatureCatalog.StateOf(guardian, true, _ => IltTri.Off), IltTri.On, "a built-in feature is on with the ILT world"); - Check.Eq(IltFeatureCatalog.StateOf(guardian, false, _ => IltTri.On), IltTri.Unknown, "nothing is claimed off ILT"); - Check.Eq(IltFeatureCatalog.StateText(IltTri.Unknown), "checking", "unknown reads 'checking'"); - Check.Eq(IltFeatureCatalog.FellowshipMax(true), 29, "ILT fellowships hold 29"); - Check.Eq(IltFeatureCatalog.FellowshipMax(false), 9, "retail fellowships hold 9"); - } - - private static void ProfileJson() - { - string json = IltFeatureCatalog.BuildProfileJson(true, "Infinite \"Leaftide\"", false, "probe", - new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc), - key => key == IltFeature.FBlackjack ? IltTri.Off : IltTri.On); - bool ascii = true; - foreach (char c in json) if (c < 0x20 || c > 0x7E) ascii = false; - Check.True(ascii, "plain printable ASCII"); - - using JsonDocument doc = JsonDocument.Parse(json); - JsonElement root = doc.RootElement; - Check.True(root.GetProperty("ilt").GetBoolean(), "ilt"); - Check.Eq(root.GetProperty("world").GetString(), "Infinite \"Leaftide\"", "quotes in the world name survive"); - Check.Eq(root.GetProperty("checked").GetString(), "2026-10-13T21:25:37Z", "checked time in UTC"); - Check.Eq(root.GetProperty("features").GetArrayLength(), IltFeatureCatalog.All.Length, "every feature in the JSON"); - JsonElement fel = root.GetProperty("fellowship"); - Check.Eq(fel.GetProperty("maxMembers").GetInt32(), 29, "fellowship size"); - Check.Eq(fel.GetProperty("zoneShare").GetInt32(), 1, "Zone Share on (built in)"); - Check.Eq(fel.GetProperty("blackjack").GetInt32(), 0, "Fellowship Blackjack off (server bit)"); - - string off = IltFeatureCatalog.BuildProfileJson(false, "", false, "", DateTime.MinValue, _ => IltTri.On); - using JsonDocument d2 = JsonDocument.Parse(off); - Check.Eq(d2.RootElement.GetProperty("fellowship").GetProperty("maxMembers").GetInt32(), 9, "off ILT: retail size"); - Check.Eq(d2.RootElement.GetProperty("checked").GetString(), "", "never checked: empty time"); - } - - private static void QuestBonusJson() - { - var qb = new IltQuestBonusInfo(false, 2, 41, "2 completed, 1 incomplete", - new[] { "flag\"one", "flagTwo" }, new[] { "flagThree" }); - string json = IltFeatureCatalog.BuildProfileJson(true, "Infinite Leaftide", false, "probe", DateTime.MinValue, _ => IltTri.On, qb); - using JsonDocument doc = JsonDocument.Parse(json); - JsonElement q = doc.RootElement.GetProperty("questBonus"); - Check.False(q.GetProperty("disabled").GetBoolean(), "enabled"); - Check.Eq(q.GetProperty("generation").GetInt32(), 2, "generation"); - Check.Eq(q.GetProperty("count").GetInt64(), 41L, "count"); - Check.Eq(q.GetProperty("status").GetString(), "2 completed, 1 incomplete", "status"); - Check.Eq(q.GetProperty("completed").GetArrayLength(), 2, "completed flags"); - Check.Eq(q.GetProperty("completed")[0].GetString(), "flag\"one", "quotes in a flag survive"); - Check.Eq(q.GetProperty("incomplete")[0].GetString(), "flagThree", "incomplete flags"); - Check.True(doc.RootElement.TryGetProperty("fellowship", out _), "the fellowship rules are still there"); - - string off = IltFeatureCatalog.BuildProfileJson(false, "", false, "", DateTime.MinValue, _ => IltTri.On, qb); - using JsonDocument d2 = JsonDocument.Parse(off); - Check.False(d2.RootElement.TryGetProperty("questBonus", out _), "off ILT: no /qb list"); - } - - private static unsafe void ServerTable() - { - Check.Eq(ServerInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not ours"); - Check.Eq(ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 2), IntPtr.Zero, "a newer version than we have: none"); - var t = (RynthIltServerApiV1*)ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 1); - Check.True(t != null && t->Version == 1 && t->StructSize == (uint)sizeof(RynthIltServerApiV1) && t->GetProfileJson != null, - "v1 is served and filled in"); - - // Before login the profile is the not-ILT default; the copy is NUL-terminated and valid JSON. - byte* buf = stackalloc byte[262144]; - int n = t->GetProfileJson(buf, 262144); - Check.True(n > 0 && n < 262144 && buf[n] == 0, "the default profile fits and is NUL-terminated"); - using JsonDocument doc = JsonDocument.Parse(Encoding.UTF8.GetString(buf, n)); - Check.False(doc.RootElement.GetProperty("ilt").GetBoolean(), "not an ILT world before login"); - Check.Eq(t->GetProfileJson(buf, 8), n, "too small: the length comes back"); - - ServerInterface.Release(); - Check.Eq(t->Version, 0u, "Release zeroes Version (readers re-query)"); - Check.Eq(t->GetProfileJson(buf, 64), 0, "answers 0 after release"); - Check.Eq(ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 1), IntPtr.Zero, "not served after release"); - } - - private static unsafe void InterfaceWrite() - { - const string json = "{\"ilt\":true}"; - byte* small = stackalloc byte[4]; - small[0] = 0x55; - Check.Eq(ProfileInterface.Write(json, small, 4), json.Length, "too small: the length is returned"); - Check.Eq(small[0], (byte)0x55, "too small: nothing written"); - - byte* exact = stackalloc byte[json.Length]; - Check.Eq(ProfileInterface.Write(json, exact, json.Length), json.Length, "no room for the NUL: too small"); - - byte* big = stackalloc byte[64]; - int n = ProfileInterface.Write(json, big, 64); - Check.Eq(n, json.Length, "fits: the length without the NUL"); - Check.Eq(big[n], (byte)0, "NUL-terminated"); - Check.Eq(Encoding.UTF8.GetString(big, n), json, "the JSON copied whole"); - } -} diff --git a/Tools/RynthILT.Tests/FellowshipCommandTests.cs b/Tools/RynthILT.Tests/FellowshipCommandTests.cs deleted file mode 100644 index fc772e9..0000000 --- a/Tools/RynthILT.Tests/FellowshipCommandTests.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Linq; -using RynthCore.Plugin.RynthILT.IltFellowship; -using RynthCore.Plugin.Shared; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// ILT's fellowship commands (IltFellowship/IltFellowshipCommands.cs, ACECustom /fship) and the -// "servercommands" format they are kept in (Plugins/Shared/ServerCommandShare.cs), checked together. -internal static class FellowshipCommandTests -{ - public static void Register(Runner r) - { - r.Add("ilt fellowship: the /fship list round-trips through the servercommands format", RoundTrip); - r.Add("ilt fellowship: chat lines quote multi-word names and need a name for create", Compose); - r.Add("ilt fellowship: bad commands and payloads are dropped", Rejects); - r.Add("ilt fellowship: RynthCore's verdict decides, else the world name", Active); - } - - private static void RoundTrip() - { - ServerCommandSet? set = ServerCommandShare.Parse(IltFellowshipCommands.Payload(active: true)); - Check.True(set != null, "parsed"); - Check.Eq(set!.Section, "fellowship", "section"); - Check.Eq(set.ServerId, "ilt", "server id"); - Check.Eq(set.ServerName, "Infinite Leaftide", "server name"); - Check.Eq(set.Commands.Count, IltFellowshipCommands.Commands.Count, "every command survives"); - for (int i = 0; i < set.Commands.Count; i++) - Check.Eq(set.Commands[i], IltFellowshipCommands.Commands[i], "command " + i); - Check.True(set.Commands.All(c => c.Command.StartsWith("/fship", StringComparison.Ordinal)), "all /fship"); - - ServerCommandSet? off = ServerCommandShare.Parse(IltFellowshipCommands.Payload(active: false)); - Check.True(off != null, "the clear parses"); - Check.Eq(off!.Commands.Count, 0, "the clear has no commands"); - } - - private static void Compose() - { - ServerCommand create = Find("Create"), invite = Find("Invite"), dismiss = Find("Dismiss"), list = Find("List nearby"); - Check.True(ServerCommandShare.Compose(create, "") == null, "create needs a name"); - Check.True(ServerCommandShare.Compose(create, " ") == null, "blank is no name"); - Check.Eq(ServerCommandShare.Compose(create, "Leaf"), "/fship create Leaf", "one word"); - Check.Eq(ServerCommandShare.Compose(create, " Leaf Hunters "), "/fship create \"Leaf Hunters\"", "quoted, spaces collapsed"); - Check.Eq(ServerCommandShare.Compose(invite, ""), "/fship add", "no name: the selected player"); - Check.Eq(ServerCommandShare.Compose(invite, "Raw Cigam"), "/fship add \"Raw Cigam\"", "multi-word player"); - Check.Eq(ServerCommandShare.Compose(dismiss, "Bo\"b\t"), "/fship remove Bob", "quotes and control characters dropped"); - Check.Eq(ServerCommandShare.Compose(list, "ignored"), "/fship list", "no argument taken"); - Check.True(dismiss.Confirm && Find("Disband").Confirm && Find("Leave").Confirm && Find("Invite landblock").Confirm, "risky ones ask"); - Check.False(invite.Confirm || list.Confirm || create.Confirm, "the rest don't"); - string longName = new string('x', 200); - Check.Eq(ServerCommandShare.CleanArgument(longName).Length, ServerCommandShare.MaxArgument, "argument capped"); - } - - private static void Rejects() - { - Check.True(ServerCommandShare.Parse(null) == null, "null"); - Check.True(ServerCommandShare.Parse("") == null, "empty"); - Check.True(ServerCommandShare.Parse("C\tX\t/fship\t\t\n") == null, "no S line"); - Check.True(ServerCommandShare.Parse("S\t\tilt\tILT\n") == null, "no section"); - - string payload = "S\tfellowship\tilt\tILT\n" + - "C\tNo slash\tfship list\t\t\n" + - "C\tSpace\t/ fship\t\t\n" + - "C\tQuote\t/fship add \"x\"\t\t\n" + - "C\t\t/fship list\t\tno label\n" + - "C\tLong\t/" + new string('a', ServerCommandShare.MaxCommand + 5) + "\t\t\n" + - "C\tShort\t/fship\t\n" + - "C\tGood\t/fship list\tzqA\ttip\n"; - ServerCommandSet? set = ServerCommandShare.Parse(payload); - Check.True(set != null, "parsed"); - Check.Eq(set!.Commands.Count, 1, "only the good command"); - Check.Eq(set.Commands[0].Flags, "A", "unknown flags dropped"); - - var many = Enumerable.Range(0, 40).Select(i => new ServerCommand("B" + i, "/fship list", "", "")); - string built = ServerCommandShare.Build(new ServerCommandSet("fellowship", "ilt", "ILT", many.ToList())); - Check.Eq(ServerCommandShare.Parse(built)!.Commands.Count, ServerCommandShare.MaxCommands, "capped"); - - string tabbed = ServerCommandShare.Build(new ServerCommandSet("fellowship", "ilt", "ILT", - new[] { new ServerCommand("A\tB", "/fship list", "", "line one\nline two") })); - ServerCommand c = ServerCommandShare.Parse(tabbed)!.Commands[0]; - Check.Eq(c.Label, "A B", "tab in a field becomes a space"); - Check.Eq(c.Tooltip, "line one line two", "newline in a field becomes a space"); - } - - private static void Active() - { - Check.True(IltFellowshipCommands.IsActive(true, "Coldeve"), "RynthCore says ILT"); - Check.False(IltFellowshipCommands.IsActive(false, "InfiniteLeaftide"), "RynthCore says not ILT"); - Check.True(IltFellowshipCommands.IsActive(null, "InfiniteLeaftide"), "no verdict yet: the world name"); - Check.False(IltFellowshipCommands.IsActive(null, "Coldeve"), "no verdict, another world"); - Check.False(IltFellowshipCommands.IsActive(null, null), "nothing known"); - } - - private static ServerCommand Find(string label) => - IltFellowshipCommands.Commands.First(c => c.Label == label); -} diff --git a/Tools/RynthILT.Tests/IltSettingsTests.cs b/Tools/RynthILT.Tests/IltSettingsTests.cs deleted file mode 100644 index 49be9d8..0000000 --- a/Tools/RynthILT.Tests/IltSettingsTests.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using RynthCore.Plugin.RynthILT.IltSettingsView; -using RynthCore.Plugin.Shared; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// RynthILT's copy of the ILT settings (IltSettingsView/IltSettingsModel.cs): RynthCore's server -// list (plugin API v86, GetServerStateJson: verdict, override, reason), the Hub's feature read, the -// engine verdict the Hub follows (IltEngineVerdict), and the RynthCore commands the view sends. -internal static class IltSettingsTests -{ - public static void Register(Runner r) - { - r.Add("ilt settings: RynthCore's server list gives the ILT verdict, override and reason", ServerList); - r.Add("ilt settings: a list without ILT, or no list at all, reads as such", NoIlt); - r.Add("ilt settings: the Hub's feature read is published whole", FeatureRead); - r.Add("ilt settings: the Hub follows RynthCore's ILT verdict once one arrives", EngineVerdict); - r.Add("ilt settings: override and world-name commands are checked before sending", Commands); - r.Add("ilt settings: logout clears the copy", ClearOnLogout); - } - - // GetServerStateJson as RynthCore writes it (UI/Sections/ServerStateJson.cs, schema 1). - private const string State = - "{\"schema\":1,\"revision\":3,\"host\":\"infiniteleaftide.online\",\"world\":\"InfiniteLeaftide\",\"pick\":\"auto\"," + - "\"active\":\"ilt\",\"activeName\":\"Infinite Leaftide\",\"activePlugin\":\"RynthILT\",\"servers\":[" + - "{\"id\":\"ilt\",\"name\":\"Infinite Leaftide\",\"active\":true,\"detected\":false,\"force\":\"on\",\"builtIn\":true," + - "\"plugin\":\"RynthILT\",\"reason\":\"forced on for this character\"}," + - "{\"id\":\"aelrynth\",\"name\":\"Aelrynth\",\"active\":false,\"detected\":false,\"force\":\"auto\",\"builtIn\":true," + - "\"plugin\":\"\",\"reason\":\"not detected\"}]}"; - - private const string NoIltState = - "{\"schema\":1,\"revision\":1,\"active\":\"\",\"servers\":[" + - "{\"id\":\"aelrynth\",\"name\":\"Aelrynth\",\"active\":true,\"detected\":true,\"force\":\"auto\"}]}"; - - private static void ServerList() - { - IltEngineView? v = IltSettingsModel.FromServerState(EngineServerState.Parse(State)); - Check.True(v?.Server != null, "the ILT server is there"); - Check.Eq(v!.Server!.Name, "Infinite Leaftide", "name"); - Check.True(v.Server.Active, "active"); - Check.False(v.Server.Detected, "not detected (forced)"); - Check.Eq(v.Server.Force, "on", "override"); - Check.Eq(v.Server.Reason, "forced on for this character", "reason"); - - IltEngineView? odd = IltSettingsModel.FromServerState(EngineServerState.Parse( - "{\"schema\":1,\"servers\":[{\"id\":\"ILT\",\"force\":\"WEIRD\"}]}")); - Check.True(odd?.Server != null, "the id ignores case"); - Check.Eq(odd!.Server!.Force, "auto", "an unknown override shows as auto"); - Check.Eq(odd.Server.Name, "Infinite Leaftide", "a missing name gets the server's"); - Check.False(odd.Server.Active, "a missing flag is off"); - } - - private static void NoIlt() - { - IltEngineView? none = IltSettingsModel.FromServerState(EngineServerState.Parse(NoIltState)); - Check.True(none != null && none.Server == null, "a list without ILT says so (not 'waiting')"); - Check.True(IltSettingsModel.FromServerState(null) == null, "no list: nothing"); - Check.True(EngineServerState.Parse("") == null && EngineServerState.Parse("{\"schema\":2}") == null, "empty or another schema: no list"); - - var model = new IltSettingsModel(); - model.ApplyServerState(EngineServerState.Parse(State)); - model.ApplyServerState(null); - Check.True(model.Engine?.Server?.Active == true, "no answer keeps the last list"); - } - - private static void FeatureRead() - { - var model = new IltSettingsModel(); - var read = new IltFeatureView("Infinite Leaftide", "probe", "12:00:00", Checking: true, IltLike: true, - new[] { new KeyValuePair("bank", 1) }); - model.PublishFeatures(read); - Check.True(ReferenceEquals(model.Features, read), "published as is"); - model.PublishFeatures(null); - Check.True(model.Features == null, "cleared while there is no Hub"); - Check.Eq(IltSettingsModel.StateText(1), "on", "1 is on"); - Check.Eq(IltSettingsModel.StateText(0), "off", "0 is off (not unknown)"); - Check.Eq(IltSettingsModel.StateText(-1), "unknown", "-1 is unknown"); - } - - private static void EngineVerdict() - { - var model = new IltSettingsModel(); - try - { - IltEngineVerdict.Attach(model); - Check.False(IltEngineVerdict.Pushed, "nothing sent yet"); - Check.True(IltEngineVerdict.Active == null, "no verdict: RynthILT's own list decides"); - model.ApplyServerState(EngineServerState.Parse(State)); - Check.True(IltEngineVerdict.Pushed, "sent"); - Check.True(IltEngineVerdict.Active == true, "RynthCore says ILT"); - model.ApplyServerState(EngineServerState.Parse(NoIltState)); - Check.True(IltEngineVerdict.Pushed && IltEngineVerdict.Active == null, "a list without ILT gives no ILT verdict"); - model.Clear(); - Check.False(IltEngineVerdict.Pushed, "logout forgets it"); - } - finally { IltEngineVerdict.Attach(null); } - Check.True(IltEngineVerdict.Active == null, "detached"); - } - - private static void Commands() - { - Check.Eq(IltSettingsModel.ForceCommand("on"), "/rc server ilt on", "on"); - Check.Eq(IltSettingsModel.ForceCommand("auto"), "/rc server ilt auto", "auto"); - Check.Eq(IltSettingsModel.ForceCommand("maybe"), "", "unknown mode sends nothing"); - Check.Eq(IltSettingsModel.NamesListCommand, "/rc server names ilt", "the names are listed by RynthCore"); - - Check.Eq(IltSettingsModel.NamesCommand(true, " *Frost* ", out _), "/rc server names ilt add *Frost*", "add, trimmed"); - Check.Eq(IltSettingsModel.NamesCommand(false, "Infinite Leaftide", out _), "/rc server names ilt remove Infinite Leaftide", "remove"); - Check.Eq(IltSettingsModel.NamesCommand(true, "", out string e1), "", "empty refused"); - Check.True(e1.Length > 0, "with a reason"); - Check.Eq(IltSettingsModel.NamesCommand(true, new string('a', IltSettingsModel.MaxPattern + 1), out _), "", "too long refused"); - Check.Eq(IltSettingsModel.NamesCommand(true, "x\n/rc reload", out _), "", "a line break can't start a second command"); - Check.Eq(IltSettingsModel.NamesCommand(true, "a/b", out _), "", "no '/'"); - } - - private static void ClearOnLogout() - { - var model = new IltSettingsModel(); - model.ApplyServerState(EngineServerState.Parse(State)); - model.PublishFeatures(new IltFeatureView("w", "", "", false, true, Array.Empty>())); - Check.True(model.Engine != null && model.Features != null, "both copies"); - model.Clear(); - Check.True(model.Engine == null && model.Features == null, "cleared"); - } -} diff --git a/Tools/RynthILT.Tests/MoveTests.cs b/Tools/RynthILT.Tests/MoveTests.cs deleted file mode 100644 index f4d6c46..0000000 --- a/Tools/RynthILT.Tests/MoveTests.cs +++ /dev/null @@ -1,599 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; -using RynthCore.Loot; -using RynthCore.Plugin.RynthILT; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.Plugin.Shared; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// The ILT Hub's move out of RynthAi into RynthILT (2026-10-13): the saved data carried over from -// RynthAi's folders (copied, never moved), the RynthILT.Hub interface table RynthAi's Mini Remote -// reads, which "/ra" verbs RynthILT takes from RynthAi, and the host-backed object view that -// replaced RynthAi's WorldObjectCache. -internal static class MoveTests -{ - public static void Register(Runner r) - { - r.Add("move: a character's RynthAi ILT Hub files are copied, the RynthAi copies left alone", MigratesCharacter); - r.Add("move: migration never overwrites RynthILT's files and runs once", MigrationIdempotent); - r.Add("move: the pre-per-server ACEmulator folder is found too", MigratesFromAceEmulatorFolder); - r.Add("move: shared Hub profiles and aug costs are copied once", MigratesShared); - r.Add("move: a migration copy that fails is reported (log + chat) and the shared ones retried", MigrationFailuresReported); - r.Add("move: a failed Hub save is reported once and retried", StoreSaveFailureReported); - r.Add("move: an unfinished copy blocks the character's Hub writes until the retry copies the original", PendingMigrationNeverShadowed); - r.Add("move: an old ilt-hub.json loads into RynthILT's state (ILT parts kept)", LegacyStateLoads); - r.Add("move: RynthAi's \"/ra\" verbs RynthILT takes (and the ones it leaves)", VerbRouting); - r.Add("move: item classes from the client's item type (the gear tools' checks)", Classification); - r.Add("move: the interface structs have the agreed layout", InterfaceLayout); - r.Add("move: server-list status lines", DescribeLines); - r.Add("move: off ILT nothing is sent, no tab or section shows; on ILT the login probe runs", DormantOffIlt); - r.Add("move: the charms JSON for RynthILT.Data readers carries the Guardian Hands", CharmsReaderJson); - r.Add("move: Character redirects to RynthOracle; Charms and Banking stay RynthILT's tabs", MovedSections); - r.Add("sections: RynthILT's manifest (rates, /fship, /qb, and the ILT tabs it shows) is valid schema-1 JSON the engine places", SectionsManifest); - // Last: Release() switches the table off for the rest of the process. - r.Add("move: the RynthILT.Hub table: query, functions, release", HubTable); - } - - private static string Root(string name) - { - string dir = Path.Combine(Program.TempRoot, "move-" + name); - if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); - Directory.CreateDirectory(dir); - IltMigration.LegacyProfilesBase = Path.Combine(dir, "RynthAi", "SettingsProfiles"); - IltMigration.LegacySharedRoot = Path.Combine(dir, "RynthAi"); - return dir; - } - - private const string LegacyHubJson = """ - { - "SchemaVersion": 1, - "ForceLeaftideFeatures": false, - "UbSidecarsImported": true, - "Bank": { "Pyreals": 1234567, "Luminance": 89, "EnlightenedCoins": 42, "AutoRefreshSeconds": 300 }, - "Pet": { "HealingEnabled": true, "HealPetName": "Healing Buddy", "PetLog": ["Fire Banshee"], "ShinyLog": [] }, - "Character": { - "QuestFilter": "temple", "QbFilter": "wait", "QuestFavorites": ["foo"], - "AttrOrder": ["qui","coo","str","end","foc","sel","hea","sta","man"], "AttrRaiseStats": ["qui"], - "AugTargets": { "war": 1800 } - }, - "Gear": { "AutoClap": true, "LastUsdPath": "C:\\vt\\x.usd", "LastEquipProfile": "Melee" }, - "Guardian": { "AutoHandIn": true, "TurnInCounts": { "Strength": 3 } } - } - """; - - private static string MakeLegacyChar(string world, string charName, bool withProfile = true) - { - string dir = Path.Combine(IltMigration.LegacyProfilesBase, IltMigration.RynthAiSafeName(world), IltMigration.RynthAiSafeName(charName)); - Directory.CreateDirectory(Path.Combine(dir, "ilt-hub-profiles")); - File.WriteAllText(Path.Combine(dir, "ilt-hub.json"), LegacyHubJson); - File.WriteAllText(Path.Combine(dir, "ilt-hub-transactions.json"), "[{\"Type\":\"Received\",\"Currency\":\"Pyreals\",\"Amount\":5}]"); - File.WriteAllText(Path.Combine(dir, "ilt-hub-profiles", "farm.json"), "{\"SchemaVersion\":1}"); - if (withProfile) - { - File.WriteAllText(Path.Combine(dir, "active_profile.txt"), "Melee"); - File.WriteAllText(Path.Combine(dir, "Melee.json"), - "{\"MetaDebug\":false,\"FeatureServerNames\":[\"InfiniteLeaftide\",\"*Leaftide*\",\"MyShard\"],\"ForceServerFeatures\":true}"); - File.WriteAllText(Path.Combine(dir, "Default.json"), "{\"FeatureServerNames\":[\"Unused\"]}"); - } - return dir; - } - - private static void MigratesCharacter() - { - string root = Root("char"); - string legacy = MakeLegacyChar("Infinite Leaftide", "Sir Tester"); - string before = File.ReadAllText(Path.Combine(legacy, "ilt-hub.json")); - var settings = new IltSettings(); - string dest = Path.Combine(root, "RynthILT", "Infinite Leaftide", "Sir Tester"); - - var done = IltMigration.MigrateCharacter(dest, "Infinite Leaftide", "Sir Tester", settings, out bool force); - Check.True(File.Exists(Path.Combine(dest, IltHubStore.StateFile)), "ilt-hub.json -> hub.json"); - Check.Eq(File.ReadAllText(Path.Combine(dest, IltHubStore.StateFile)), before, "copied byte for byte"); - Check.True(File.Exists(Path.Combine(dest, IltHubStore.TransactionsFile)), "transactions copied"); - Check.True(File.Exists(Path.Combine(dest, IltHubStore.ProfilesFolder, "farm.json")), "per-character Hub profiles copied"); - Check.True(File.Exists(Path.Combine(legacy, "ilt-hub.json")) && File.Exists(Path.Combine(legacy, "ilt-hub-transactions.json")), - "RynthAi's files are still there (copy, not move)"); - Check.True(settings.ServerNames.Contains("MyShard"), "the active profile's server names are added"); - Check.False(settings.ServerNames.Contains("Unused"), "only the ACTIVE profile is read"); - Check.Eq(settings.ServerNames.Count(n => n.Equals("InfiniteLeaftide", StringComparison.OrdinalIgnoreCase)), 1, "no duplicates"); - Check.True(force, "\"Force enable\" carries over as Treat this world as ILT"); - Check.True(done.Count >= 4, "the log line lists what was carried over: " + string.Join(", ", done)); - } - - private static void MigrationIdempotent() - { - string root = Root("idem"); - string legacy = MakeLegacyChar("InfiniteLeaftide", "Again", withProfile: false); - string dest = Path.Combine(root, "RynthILT", "InfiniteLeaftide", "Again"); - Directory.CreateDirectory(dest); - File.WriteAllText(Path.Combine(dest, IltHubStore.TransactionsFile), "[]"); // RynthILT already has one - var settings = new IltSettings(); - - IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Again", settings, out bool force); - Check.Eq(File.ReadAllText(Path.Combine(dest, IltHubStore.TransactionsFile)), "[]", "an existing RynthILT file is never overwritten"); - Check.True(File.Exists(Path.Combine(dest, IltHubStore.StateFile)), "the missing hub.json is still copied"); - Check.False(force, "no profile, no override"); - - File.WriteAllText(Path.Combine(legacy, "ilt-hub.json"), "{\"Bank\":{\"Pyreals\":1}}"); - var second = IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Again", settings, out _); - Check.Eq(second.Count, 0, "once hub.json exists the character is never migrated again"); - Check.False(File.ReadAllText(Path.Combine(dest, IltHubStore.StateFile)).Contains("\"Pyreals\":1}"), "later RynthAi edits don't overwrite RynthILT's state"); - - var none = IltMigration.MigrateCharacter(Path.Combine(root, "RynthILT", "X", "Nobody"), "X", "Nobody", settings, out _); - Check.Eq(none.Count, 0, "a character RynthAi never saw: nothing to do"); - Check.False(Directory.Exists(Path.Combine(root, "RynthILT", "X", "Nobody")), "and no folder is made for it"); - } - - private static void MigratesFromAceEmulatorFolder() - { - string root = Root("ace"); - MakeLegacyChar("ACEmulator", "Old Timer", withProfile: false); - var settings = new IltSettings(); - string dest = Path.Combine(root, "RynthILT", "InfiniteLeaftide", "Old Timer"); - Check.NotNull(IltMigration.FindLegacyCharFolder("InfiniteLeaftide", "Old Timer"), "the world folder is missing, ACEmulator\\ is used"); - IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Old Timer", settings, out _); - Check.True(File.Exists(Path.Combine(dest, IltHubStore.StateFile)), "copied from the ACEmulator folder"); - Check.Eq(IltMigration.RynthAiSafeName("Sir O'Neil-Smith"), "Sir_O'Neil-Smith", "RynthAi's folder names keep ' and - only"); - } - - private static void MigratesShared() - { - string root = Root("shared"); - Directory.CreateDirectory(Path.Combine(IltMigration.LegacySharedRoot, "IltHubProfiles")); - File.WriteAllText(Path.Combine(IltMigration.LegacySharedRoot, "IltHubProfiles", "team.json"), "{}"); - File.WriteAllText(Path.Combine(IltMigration.LegacySharedRoot, "ilt-aug-costs.json"), "{\"x\":1}"); - var settings = new IltSettings(); - string dest = Path.Combine(root, "RynthILT"); - - var done = IltMigration.MigrateShared(settings, dest); - Check.True(File.Exists(Path.Combine(dest, "Profiles", "team.json")), "shared profiles copied"); - Check.True(File.Exists(Path.Combine(dest, "ilt-aug-costs.json")), "aug costs copied"); - Check.True(settings.SharedFilesMigrated, "marked done in the settings"); - Check.Eq(done.Count, 2, "both reported"); - File.Delete(Path.Combine(dest, "ilt-aug-costs.json")); - Check.Eq(IltMigration.MigrateShared(settings, dest).Count, 0, "once only"); - Check.False(File.Exists(Path.Combine(dest, "ilt-aug-costs.json")), "a file deleted afterwards isn't brought back"); - } - - // A copy that fails (here: the RynthAi file held open by another program) is never silent: it - // is logged and queued for chat with the reason, the rest still copies, and the shared files - // aren't marked done so the next login tries again. - private static void MigrationFailuresReported() - { - string root = Root("fail"); - DataWriteGuard.Reset(); - string legacy = MakeLegacyChar("InfiniteLeaftide", "Locked Out"); - string dest = Path.Combine(root, "RynthILT", "InfiniteLeaftide", "Locked Out"); - var settings = new IltSettings(); - List done; - using (new FileStream(Path.Combine(legacy, "ilt-hub-transactions.json"), FileMode.Open, FileAccess.Read, FileShare.None)) - done = IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Locked Out", settings, out _); - Check.True(File.Exists(Path.Combine(dest, IltHubStore.StateFile)), "the other files are still copied"); - Check.False(File.Exists(Path.Combine(dest, IltHubStore.TransactionsFile)), "the held file isn't"); - Check.True(done.Any(l => l.Contains("NOT copied") && l.Contains(legacy)), "the log line says so and where the originals are: " + string.Join(", ", done)); - Check.Eq(DataWriteGuard.PendingCount, 1, "one chat line queued (shown on ILT)"); - var lines = new List(); - DataWriteGuard.DrainChat(lines.Add); - Check.True(lines.Count == 1 && lines[0].StartsWith("[RynthILT]", StringComparison.Ordinal) - && lines[0].Contains("ilt-hub-transactions.json") && lines[0].Contains("another program"), - "it names the file and the reason: " + string.Join(" | ", lines)); - - DataWriteGuard.Reset(); - Directory.CreateDirectory(Path.Combine(IltMigration.LegacySharedRoot, "IltHubProfiles")); - File.WriteAllText(Path.Combine(IltMigration.LegacySharedRoot, "IltHubProfiles", "team.json"), "{}"); - string aug = Path.Combine(IltMigration.LegacySharedRoot, "ilt-aug-costs.json"); - File.WriteAllText(aug, "{\"x\":1}"); - string sharedDest = Path.Combine(root, "RynthILT"); - using (new FileStream(aug, FileMode.Open, FileAccess.Read, FileShare.None)) - done = IltMigration.MigrateShared(settings, sharedDest); - Check.False(settings.SharedFilesMigrated, "a failed shared copy isn't marked done"); - Check.True(done.Any(l => l.Contains("NOT copied")), "and is reported: " + string.Join(", ", done)); - Check.True(DataWriteGuard.PendingCount >= 1, "in chat too"); - done = IltMigration.MigrateShared(settings, sharedDest); - Check.True(File.Exists(Path.Combine(sharedDest, "ilt-aug-costs.json")), "the next login copies it"); - Check.True(settings.SharedFilesMigrated, "then it is marked done"); - Check.Eq(done.Count, 1, "only the missing file is copied the second time: " + string.Join(", ", done)); - DataWriteGuard.Reset(); - } - - // A character whose ilt-hub.json couldn't be copied (held open by another program): the Hub - // runs from the RynthAi original read-only (or the defaults), writes no hub.json, bank log or - // per-character profile there, the pending mark survives a restart, and the next attempt copies - // the original byte for byte - never shadowed by a fresh file. - private static void PendingMigrationNeverShadowed() - { - string root = Root("pending"); - DataWriteGuard.Reset(); - string legacy = MakeLegacyChar("InfiniteLeaftide", "Held Open"); - string legacyHub = Path.Combine(legacy, "ilt-hub.json"); - string dest = Path.Combine(root, "RynthILT", "InfiniteLeaftide", "Held Open"); - string hubJson = Path.Combine(dest, IltHubStore.StateFile); - var settings = new IltSettings(); - - // Held open by another program: neither copied nor readable. - using (var held = new FileStream(legacyHub, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) - { - var done = IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Held Open", settings, out _); - Check.False(File.Exists(hubJson), "the held ilt-hub.json isn't copied"); - Check.True(IltMigration.IsPending(settings, dest), "the character is marked pending"); - Check.True(done.Any(l => l.Contains("NOT copied")), "and the log says so: " + string.Join(", ", done)); - - var store = new IltHubStore(default, dest) - { - WritesBlocked = () => IltMigration.IsPending(settings, dest), - LegacyFolder = legacy, - }; - IltHubState state = store.LoadState(); - Check.Eq(state.Bank.Pyreals, 0L, "unreadable: the Hub runs from the defaults"); - state.Bank.Pyreals = 1; - store.SaveStateIfDirty(state); - Check.False(File.Exists(hubJson), "no hub.json is written while the copy is unfinished"); - Check.False(store.SaveProfile(state, "mine", shared: false, out string why), "nor a per-character profile"); - Check.True(why.Contains("RynthAi"), "with the reason: " + why); - Check.True(store.SaveProfile(state, "team-" + Guid.NewGuid().ToString("N"), shared: true, out _), "shared profiles still save"); - - // A second login while still held: still pending, still nothing written. - IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Held Open", settings, out _); - Check.True(IltMigration.IsPending(settings, dest) && !File.Exists(hubJson), "still pending, still no hub.json"); - } - - // Readable again but not yet retried: a Hub started now reads the original, still writes nothing. - var readOnly = new IltHubStore(default, dest) - { - WritesBlocked = () => IltMigration.IsPending(settings, dest), - LegacyFolder = legacy, - }; - IltHubState fromLegacy = readOnly.LoadState(); - Check.Eq(fromLegacy.Bank.Pyreals, 1234567L, "the Hub runs from the RynthAi original, read only"); - fromLegacy.Bank.Pyreals = 2; - readOnly.SaveStateIfDirty(fromLegacy); - Check.False(File.Exists(hubJson), "and still writes no hub.json"); - - // The mark is in settings.json, so a client restart still knows the copy is unfinished. - IltSettingsStore.Save(settings); - IltSettings reloaded = IltSettingsStore.Load(); - Check.True(IltMigration.IsPending(reloaded, dest), "pending survives a restart"); - - var finished = IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Held Open", reloaded, out bool force); - Check.True(File.Exists(hubJson), "the next attempt copies it"); - Check.Eq(File.ReadAllText(hubJson), File.ReadAllText(legacyHub), "byte for byte: the original, not a fresh file"); - Check.False(IltMigration.IsPending(reloaded, dest), "no longer pending"); - Check.True(force, "the profile's Force enable still carries over on the retry"); - Check.True(finished.Any(l => l.Contains("complete")), "the log says it finished: " + string.Join(", ", finished)); - - var after = new IltHubStore(default, dest) { WritesBlocked = () => IltMigration.IsPending(reloaded, dest) }; - IltHubState loaded = after.LoadState(); - Check.Eq(loaded.Bank.Pyreals, 1234567L, "the restarted Hub loads the copied file"); - loaded.Bank.Pyreals = 7; - after.SaveStateIfDirty(loaded); - Check.True(File.ReadAllText(hubJson).Contains("\"Pyreals\": 7"), "and saves normally from then on"); - File.Delete(Path.Combine(IltSettingsStore.Folder, IltSettingsStore.FileName)); - DataWriteGuard.Reset(); - } - - // RynthILT's own saves report a failure (DataWriteGuard) and try again on the next save. - private static void StoreSaveFailureReported() - { - string root = Root("storefail"); - DataWriteGuard.Reset(); - string blocker = Path.Combine(root, "NotAFolder"); - File.WriteAllText(blocker, "a file where the character folder should be"); - var store = new IltHubStore(default, blocker); - var state = new IltHubState(); - store.SaveStateIfDirty(state); - Check.Eq(DataWriteGuard.PendingCount, 1, "the failed Hub save is queued for chat"); - store.SaveStateIfDirty(state); - Check.Eq(DataWriteGuard.PendingCount, 1, "once per folder, not every retry"); - File.Delete(blocker); - store.SaveStateIfDirty(state); - Check.True(File.Exists(Path.Combine(blocker, IltHubStore.StateFile)), "the next save retries and works"); - DataWriteGuard.Reset(); - } - - private static void LegacyStateLoads() - { - string root = Root("state"); - string dir = Path.Combine(root, "char"); - Directory.CreateDirectory(dir); - File.WriteAllText(Path.Combine(dir, IltHubStore.StateFile), LegacyHubJson); - var store = new IltHubStore(default, dir); - var s = store.LoadState(); - Check.Eq(s.Bank.Pyreals, 1234567L, "bank balances"); - Check.Eq(s.Bank.AutoRefreshSeconds, 300, "bank settings"); - Check.Eq(s.Pet.PetLog.FirstOrDefault(), "Fire Banshee", "the /pets log (an ILT part of the Pet section)"); - Check.Eq(s.Character.QbFilter, "wait", "the /qb filter"); - Check.Eq(s.Character.AttrOrder.FirstOrDefault(), "qui", "the attribute raiser's order"); - Check.Eq(s.Character.AugTargets["war"], 1800, "aug targets"); - Check.True(s.Gear.AutoClap && s.Gear.LastEquipProfile == "Melee", "gear settings"); - Check.True(s.Guardian.AutoHandIn && s.Guardian.TurnInCounts["Strength"] == 3, "guardian settings"); - Check.True(s.UbSidecarsImported, "the UB import isn't redone"); - - store.SaveStateIfDirty(s); - string saved = File.ReadAllText(Path.Combine(dir, IltHubStore.StateFile)); - Check.False(saved.Contains("HealPetName"), "the Pets tab's settings (RynthAi's now) aren't written back here"); - Check.False(saved.Contains("QuestFavorites"), "nor the Quests tab's"); - } - - private static void VerbRouting() - { - static bool Takes(string line) => RynthILTPlugin.IsIltVerb(line.Split(' ', StringSplitOptions.RemoveEmptyEntries)); - Check.True(Takes("hub bank"), "hub bank"); - Check.True(Takes("hub attr run"), "hub attr run"); - Check.True(Takes("hub refresh"), "hub refresh"); - Check.True(Takes("hub help"), "hub help (RynthILT prints the whole list)"); - Check.True(Takes("hub open banking show"), "hub open "); - Check.True(Takes("hub open guardian"), "hub open guardian (the engine panel)"); - Check.True(Takes("hub open bounties"), "hub open bounties"); - Check.False(Takes("hub open pets"), "hub open pets is RynthAi's"); - Check.False(Takes("hub open quests hide"), "hub open quests is RynthAi's"); - Check.True(Takes("hub tab gear"), "hub tab "); - Check.False(Takes("hub tab quests"), "hub tab quests is RynthAi's"); - Check.False(Takes("hub tab remote"), "the Remote tab is RynthAi's"); - Check.False(Takes("hub"), "bare /ra hub toggles RynthAi's Mini Remote"); - Check.True(Takes("guardian handin"), "guardian"); - Check.True(Takes("bounty show") && Takes("bounties") && Takes("bountys"), "bounty, bounties, bountys"); - Check.True(Takes("rates reset"), "rates reset (the Mini Remote's Reset XP)"); - Check.False(Takes("quests refresh"), "/ra quests is RynthAi's"); - Check.False(Takes("pets show"), "/ra pets is RynthAi's"); - Check.False(Takes("start"), "anything else is RynthAi's"); - // The VTank hotkey verbs (RynthAi 2026-10-13, RynthAiPlugin.VTankHotkeys.cs) stay RynthAi's. - foreach (string vt in new[] { "vtkeys", "targetlock", "recharge", "lootthis", "meleelow", "navprio", "lootprio", "navlootprio", "setmetastate Default", "testitem", "propertydump" }) - Check.False(Takes(vt), $"{vt} is RynthAi's (VTank hotkeys)"); - } - - private static void Classification() - { - Check.Eq(IltObjects.ClassifyByItemType(0x00000800), AcObjectClass.Gem, "gem (aetheria)"); - Check.Eq(IltObjects.ClassifyByItemType(0x00000001), AcObjectClass.MeleeWeapon, "melee weapon"); - Check.Eq(IltObjects.ClassifyByItemType(0x00000100), AcObjectClass.MissileWeapon, "missile weapon"); - Check.Eq(IltObjects.ClassifyByItemType(0x00008000), AcObjectClass.WandStaffOrb, "caster"); - Check.Eq(IltObjects.ClassifyByItemType(0x40000000), AcObjectClass.Salvage, "salvage (white quartz)"); - Check.Eq(IltObjects.ClassifyByItemType(0x00001000), AcObjectClass.SpellComponent, "spell component"); - Check.Eq(IltObjects.ClassifyByItemType(0x00000200), AcObjectClass.Container, "pack"); - Check.Eq(IltObjects.ClassifyByItemType(0x00000010), AcObjectClass.Monster, "creature"); - Check.Eq(IltObjects.ClassifyByItemType(0x00000002 | 0x00000004), AcObjectClass.Armor, "armor wins over clothing"); - Check.Eq(IltObjects.ClassifyByItemType(0), AcObjectClass.Unknown, "no type yet"); - } - - private static unsafe void InterfaceLayout() - { - Check.Eq(sizeof(IltTabV1), 24 + 32 + 4 + 4 + 4, "IltTabV1: id, label, width, height, flags"); - Check.Eq((int)Marshal.OffsetOf(nameof(IltTabV1.Flags)), 64, "IltTabV1.Flags offset"); - // RynthILT.Hub grew on 2026-10-20 (append-only): readers accept any table at least BaseStructSize - // long (the first release's 9 functions) and check the appended ones with Has. - Check.Eq((int)RynthIltHubApiV1.BaseStructSize, 8 + 9 * IntPtr.Size, "RynthIltHubApiV1.BaseStructSize: the first release's 9 functions"); - Check.Eq(RynthIltHubApiV1.AllowSummonOnEmptyOffset, 8 + 9 * IntPtr.Size, "AllowSummonOnEmpty right after Command"); - Check.Eq((int)Marshal.OffsetOf(nameof(RynthIltHubApiV1.AllowSummonOnEmpty)), RynthIltHubApiV1.AllowSummonOnEmptyOffset, - "AllowSummonOnEmptyOffset is where the field really is"); - Check.Eq((int)Marshal.OffsetOf(nameof(RynthIltHubApiV1.GetSubTabs)), RynthIltHubApiV1.GetSubTabsOffset, - "GetSubTabsOffset is where the field really is"); - Check.Eq((int)Marshal.OffsetOf(nameof(RynthIltHubApiV1.GetSetting)), RynthIltHubApiV1.GetSettingOffset, - "GetSettingOffset is where the field really is"); - Check.Eq((int)Marshal.OffsetOf(nameof(RynthIltHubApiV1.SetSetting)), RynthIltHubApiV1.SetSettingOffset, - "SetSettingOffset is where the field really is"); - // SessionStatsMore was appended (2026-10-13); readers accept any table at least - // BaseStructSize long, so an older RynthAi still connects. - // VaultedDungeonsEnabled was appended (2026-10-18): the Vaulted Dungeons master switch. - // BackAwayFrom was appended (2026-10-20): the generic back-away RynthILT's Handler ring evade asks for. - // SetPlayerCounter too (2026-10-20): the T11 wield counters RynthILT reads from /aug. - Check.Eq(sizeof(RynthAiHubApiV1), 8 + 14 * IntPtr.Size, "RynthAiHubApiV1: header + 14 functions"); - Check.Eq((int)Marshal.OffsetOf(nameof(RynthAiHubApiV1.SetPlayerCounter)), RynthAiHubApiV1.SetPlayerCounterOffset, - "SetPlayerCounterOffset is where the field really is"); - Check.Eq((int)Marshal.OffsetOf(nameof(RynthAiHubApiV1.BackAwayFrom)), RynthAiHubApiV1.BackAwayFromOffset, - "BackAwayFromOffset is where the field really is"); - Check.Eq((int)RynthAiHubApiV1.BaseStructSize, 8 + 10 * IntPtr.Size, "RynthAiHubApiV1.BaseStructSize: the first release's 10 functions"); - Check.Eq(RynthAiHubApiV1.SessionStatsMoreOffset, (int)RynthAiHubApiV1.BaseStructSize, "SessionStatsMore right after the base table"); - Check.Eq(RynthAiHubApiV1.VaultedDungeonsEnabledOffset, 8 + 11 * IntPtr.Size, "VaultedDungeonsEnabled right after SessionStatsMore"); - Check.Eq((int)Marshal.OffsetOf(nameof(RynthAiHubApiV1.VaultedDungeonsEnabled)), RynthAiHubApiV1.VaultedDungeonsEnabledOffset, - "VaultedDungeonsEnabledOffset is where the field really is"); - Check.Eq(sizeof(QuestFlagV1), 24, "QuestFlagV1"); - Check.Eq(sizeof(QuestStatusV1), 16, "QuestStatusV1"); - Check.Eq(RynthIltHubApiV1.InterfaceName, "RynthILT.Hub", "interface name"); - Check.Eq(RynthAiHubApiV1.InterfaceName, "RynthAi.Hub", "RynthAi's interface name"); - } - - private static void DescribeLines() - { - var s = new IltSettings(); - Check.True(ServerFeatureGate.Describe("InfiniteLeaftide", s, false).Contains("ON - matches 'InfiniteLeaftide'"), "on by name"); - Check.True(ServerFeatureGate.Describe("Aelrynth", s, true).Contains("Treat this world as ILT"), "on by the override"); - Check.True(ServerFeatureGate.Describe("Aelrynth", s, false).Contains("OFF"), "off"); - Check.True(ServerFeatureGate.Describe("", s, false).Contains("not logged in"), "before login"); - } - - private static IltHubController NewHub(string world, string folder) - { - RynthCore.RynthAiHostTests.Fakes.FakeHost.Reset(); - RynthCore.RynthAiHostTests.Fakes.FakeHost.WorldName = world; - var host = RynthCore.RynthAiHostTests.Fakes.FakeHost.Create(0x50000F01); - string dir = Path.Combine(Program.TempRoot, "move-" + folder); - Directory.CreateDirectory(dir); - return new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host)); - } - - private static void TickFor(IltHubController hub, int ms) - { - var until = DateTime.UtcNow.AddMilliseconds(ms); - while (DateTime.UtcNow < until) { hub.Tick(); System.Threading.Thread.Sleep(50); } - } - - /// - /// The charms JSON behind "RynthILT.Data" is valid JSON; on ILT it has a "hands" array (empty - /// with no hand carried) that the shared reader parses, off ILT it has none and still parses. - /// - private static void CharmsReaderJson() - { - var on = NewHub("InfiniteLeaftide", "charms-on"); - string json = on.CharmsTab.BuildReaderJson(); - using (var doc = System.Text.Json.JsonDocument.Parse(json)) - Check.True(doc.RootElement.TryGetProperty("hands", out var hands) && hands.GetArrayLength() == 0, - "on ILT: an empty hands array with no Guardian Hand carried"); - Check.True(json.All(c => c < 128), "ASCII only"); - var view = IltCharmsView.Parse(json); - Check.True(view.Loaded && view.Hands.Count == 0, "the shared reader takes it"); - - var withHands = IltCharmsView.Parse("{\"available\":true,\"charms\":[],\"hands\":[" + - "{\"id\":1234,\"name\":\"Guardian Hand\",\"active\":\"on\",\"server\":\"off\"},{\"id\":0,\"name\":\"no id\"}]}"); - Check.Eq(withHands.Hands.Count, 1, "a hand without an id is skipped (nothing to toggle)"); - Check.True(withHands.Hands[0] == new IltHandRow(1234, "Guardian Hand", "on", "off"), "id, name, active, server"); - - var off = NewHub("Aeshnidae", "charms-off"); - string offJson = off.CharmsTab.BuildReaderJson(); - using (var doc = System.Text.Json.JsonDocument.Parse(offJson)) - Check.False(doc.RootElement.TryGetProperty("hands", out _), "off ILT: no hands"); - Check.True(IltCharmsView.Parse(offJson).Hands.Count == 0, "and the reader shows none"); - } - - /// The Character tab moved out (2026-10-13); every other ILT tab is still RynthILT's. - private static void MovedSections() - { - Check.Eq(IltSections.MovedCommand(IltSection.Character), IltSections.OracleCharacterCommand, "Character -> RynthOracle Character"); - foreach (var kept in new[] { IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games }) - { - Check.True(IltSections.MovedCommand(kept) == null, $"{IltSections.Label(kept)} is still RynthILT's"); - Check.True(IltSections.IsTab(kept), $"{IltSections.Label(kept)} is a Mini Remote tab"); - } - Check.True(IltSections.MovedCommand(IltSection.VaultedDungeons) == null && IltSections.IsTab(IltSection.VaultedDungeons), - "Vaulted Dungeons is a RynthILT tab (shown only with the master switch, VaultedDungeonsTests)"); - Check.True(IltSections.Tabs.SequenceEqual(new[] { IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games, IltSection.VaultedDungeons }), - "the tab list is Banking, Gear, Charms, Games, Vaulted Dungeons"); - Check.False(IltSections.IsTab(IltSection.Character) || IltSections.IsTab(IltSection.Guardian), "Character and the Guardian aren't tabs"); - Check.True(IltSections.TryParse("char", out IltSection c) && c == IltSection.Character, "old Character names still parse (for the redirect)"); - Check.Eq(IltSections.OracleCharacterCommand, "/ro character", "Oracle command"); - } - - /// - /// RynthILT's RynthPluginGetSectionsJson: schema 1 (UI/Sections/SectionManifest.cs in RynthCore), - /// every view an ILT one, each surface one RenderEmbed answers. - /// - private static void SectionsManifest() - { - // No Hub (before the character's name is known): the always-there views only. - string bare = IltSectionsManifest.Build(IltSectionsManifest.TabsOf(null)); - using var doc = System.Text.Json.JsonDocument.Parse(bare); - var root = doc.RootElement; - Check.Eq(root.GetProperty("version").GetInt32(), 1, "schema 1"); - var sections = root.GetProperty("sections"); - Check.Eq(sections.GetArrayLength(), 2, "two sections of RynthILT's own"); - Check.Eq(sections[0].GetProperty("id").GetString(), "quests", "a Quests section (the /qb list)"); - Check.Eq(sections[1].GetProperty("id").GetString(), "games", "and Games (moved from RynthAi with the tabs)"); - var surfaces = new System.Collections.Generic.List(); - foreach (var c in root.GetProperty("contributions").EnumerateArray()) - { - Check.Eq(c.GetProperty("server").GetString(), "ilt", "an Infinite Leaftide view"); - surfaces.Add(c.GetProperty("surface").GetString() ?? ""); - } - Check.True(surfaces.SequenceEqual(new[] { RynthILTPlugin.RatesSurface, RynthILTPlugin.FellowshipSurface, RynthILTPlugin.QuestBonusSurface }), - "rates, fellowship, quest bonus: " + string.Join(",", surfaces)); - Check.True(surfaces.All(s => s.StartsWith("section:ilt-", StringComparison.Ordinal) && s.Length <= 64), "short section:ilt-* surfaces"); - Check.True(bare.All(ch => ch < 128), "ASCII only"); - - // The Mini Remote ILT tabs the Hub shows (RynthAi listed them until 2026-10-20): Gear not reported yet, - // Games hidden, Charms and Banking shown. - var tabs = new[] - { - new IltSectionsManifest.Tab("banking", 560, 520, Shown: true, Available: true), - new IltSectionsManifest.Tab("gear", 560, 520, Shown: true, Available: false), - new IltSectionsManifest.Tab("charms", 560, 520, Shown: true, Available: true), - new IltSectionsManifest.Tab("games", 520, 440, Shown: false, Available: false), - new IltSectionsManifest.Tab("character", 520, 440, Shown: true, Available: true), - }; - string json = IltSectionsManifest.Build(tabs); - var m = RynthCore.Engine.UI.Sections.SectionManifestParser.Parse("RynthILT", json, out string error); - Check.Eq(error, string.Empty, "the engine's parser takes it"); - Check.Eq(m.Contributions.Length, 6, "rates, fellowship, /qb, Banking, Gear, Charms"); - var gear = m.Contributions.Single(c => c.Surface == "section:gear"); - Check.True(gear.Section == "inventory" && !gear.Enabled && gear.Note.Length > 0, "Gear in Inventory, disabled with a note until reported"); - Check.True(m.Contributions.Any(c => c.Surface == "section:charms" && c.Enabled) && m.Contributions.Any(c => c.Surface == "section:banking" && c.Enabled), - "Charms and Banking stay RynthILT's tabs"); - Check.False(m.Contributions.Any(c => c.Surface == "section:games"), "a hidden tab isn't listed"); - Check.False(m.Contributions.Any(c => c.Surface == "section:character"), "Character moved out: never placed"); - var iltOn = new RynthCore.Engine.UI.Sections.ServerState("ilt", "Infinite Leaftide", true, true, RynthCore.Engine.UI.Sections.ServerForce.Auto, true, ""); - var on = RynthCore.Engine.UI.Sections.SectionCatalog.Build(new[] { m }, _ => false, new[] { iltOn }); - Check.True(on.Single(v => v.Id == "inventory").Panes.Any(p => p.Title == "Charms" && p.Contribution?.Plugin == "RynthILT"), - "on ILT the engine shows RynthILT's Charms in Inventory (drawn by RynthILT)"); - var off = RynthCore.Engine.UI.Sections.SectionCatalog.Build(new[] { m }, _ => false, new[] { iltOn with { Active = false } }); - Check.False(off.Single(v => v.Id == "inventory").Panes.Any(p => p.Title == "Charms"), "off ILT: none"); - Check.True(IltSectionsManifest.TryTabOf("section:banking", out IltSection bank) && bank == IltSection.Banking, "section:banking draws Banking"); - Check.False(IltSectionsManifest.TryTabOf("section:bank", out _), "only the tab's own id"); - Check.False(IltSectionsManifest.TryTabOf("section:pets", out _), "pets is RynthAi's"); - Check.False(IltSectionsManifest.TryTabOf("section:ilt-rates", out _), "not a tab"); - Check.True(RynthILTPlugin.IsParsedRemoteAction("servermenu") && RynthILTPlugin.IsParsedRemoteAction("ServerMenu") - && !RynthILTPlugin.IsParsedRemoteAction("prog"), "RynthCore's servermenu push is answered, never queued as a verb"); - } - - private static void DormantOffIlt() - { - var off = NewHub("Aeshnidae", "dormant"); - off.OnLoginComplete("Tester", forceFromMigration: false); - foreach (string line in new[] { "Your Pet Log:", "[BANK] Pyreals: 5", "Guardian of Strength tells you, \"x\"" }) off.OnChat(line); - TickFor(off, 6800); // past the 6 s login delay - Check.Eq(RynthCore.RynthAiHostTests.Fakes.FakeHost.ChatCommands.Count, 0, "off ILT: no probe, no command at all"); - Check.False(off.Options.IsIltLikeWorld, "not an ILT world"); - foreach (var s in IltSections.Tabs) Check.False(off.TabShown(s), $"no {IltSections.Label(s)} tab"); - Check.False(off.RenderSection(RynthIltHub.SectionRemoteBank) || off.RenderSection(RynthIltHub.SectionQuestBonus) - || off.RenderSection(RynthIltHub.SectionPetLogs) || off.RenderSection(RynthIltHub.SectionRemoteGuardian) - || off.RenderSection(RynthIltHub.SectionServerMenu), "no ILT section draws (checked before any ImGui call)"); - Check.True(off.BuildProgressionJson().StartsWith("{\"available\":false"), "Progression: not available"); - off.OnLogout(); - - var on = NewHub("InfiniteLeaftide", "awake"); - on.OnLoginComplete("Tester", forceFromMigration: false); - TickFor(on, 6800); - Check.True(on.Options.IsIltLikeWorld, "InfiniteLeaftide is ILT"); - Check.True(RynthCore.RynthAiHostTests.Fakes.FakeHost.ChatCommands.Count > 0, "on ILT the login probe asks the server"); - Check.False(RynthCore.RynthAiHostTests.Fakes.FakeHost.ChatCommands.Any(c => c.Contains("/ilt features", StringComparison.OrdinalIgnoreCase)), - "the server is never asked for a feature list (the ILT profile is Rynth-side)"); - // Character moved out of the Mini Remote (RynthOracle's Character tab, Session Stats); - // Charms and Banking are Infinite Leaftide's own screens and stay RynthILT's tabs. - Check.False(on.TabShown(IltSection.Character), "Character is no Mini Remote tab any more"); - Check.Eq(on.TabShown(IltSection.Gear), on.Available, "Gear shows once the server features are known"); - Check.Eq(on.TabShown(IltSection.Charms), on.Available, "Charms too"); - on.OnLogout(); - - var forced = NewHub("Aeshnidae", "forced"); - forced.OnLoginComplete("Tester", forceFromMigration: true); - Check.True(forced.Options.IsIltLikeWorld, "a migrated \"Force enable\" makes the world ILT for this character"); - forced.OnLogout(); - } - - private static unsafe void HubTable() - { - Check.Eq(HubInterface.Query("RynthAi.Hub", 1), IntPtr.Zero, "another interface's name: not ours"); - Check.Eq(HubInterface.Query(RynthIltHubApiV1.InterfaceName, 2), IntPtr.Zero, "a newer version than we have: none"); - var t = (RynthIltHubApiV1*)HubInterface.Query(RynthIltHubApiV1.InterfaceName, 1); - Check.True(t != null, "v1 is served"); - Check.Eq(t->Version, 1u, "Version 1"); - Check.Eq(t->StructSize, (uint)sizeof(RynthIltHubApiV1), "StructSize"); - Check.True(t->IsIltWorld != null && t->GetFeature != null && t->GetRates != null && t->GetForceIlt != null && t->SetForceIlt != null - && t->GetTabs != null && t->RenderTab != null && t->RenderSection != null && t->Command != null - && t->AllowSummonOnEmpty != null && t->GetSubTabs != null && t->GetSetting != null && t->SetSetting != null, - "every function is filled in"); - Check.True(RynthIltHubApiV1.Has(t, RynthIltHubApiV1.GetSubTabsOffset), "the appended functions are inside StructSize"); - Check.Eq((IntPtr)t, HubInterface.Query(RynthIltHubApiV1.InterfaceName, 1), "the same table each time"); - Check.Eq((IntPtr)t, HubInterface.Query(RynthIltHubApiV1.NeutralInterfaceName, 1), - "and under the server-neutral name RynthAi asks the active server's owner for (RynthServer.Hub)"); - - // No plugin instance here (not logged in): every function answers "nothing". - Check.Eq(t->IsIltWorld(), 0, "not ILT before login"); - byte* key = stackalloc byte[] { (byte)'b', (byte)'a', (byte)'n', (byte)'k', 0 }; - Check.Eq(t->GetFeature(key), -1, "feature unknown before login"); - Check.Eq(t->GetTabs(null, 0), 0, "no tabs before login"); - Check.Eq(t->Command(key), 0, "no command taken before login"); - Check.Eq(t->AllowSummonOnEmpty(), 0, "no summon from empty before login"); - byte* pets = stackalloc byte[] { (byte)'p', (byte)'e', (byte)'t', (byte)'s', 0 }; - Check.Eq(t->GetSubTabs(pets, null, 0), 0, "no Pets sub-tabs before login"); - Check.Eq(t->GetSetting(pets), -1, "no setting offered before login"); - Check.Eq(t->SetSetting(pets, 1), 0, "and none taken"); - - HubInterface.Release(); - Check.Eq(t->Version, 0u, "Release zeroes Version (callers re-query)"); - Check.Eq(HubInterface.Query(RynthIltHubApiV1.InterfaceName, 1), IntPtr.Zero, "and nothing is served after shutdown"); - Check.Eq(t->IsIltWorld(), 0, "the old table stays callable and answers nothing"); - } -} diff --git a/Tools/RynthILT.Tests/PetAutomationTests.cs b/Tools/RynthILT.Tests/PetAutomationTests.cs deleted file mode 100644 index 463d274..0000000 --- a/Tools/RynthILT.Tests/PetAutomationTests.cs +++ /dev/null @@ -1,189 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.Plugin.Shared; -using RynthCore.RynthAiHostTests.Fakes; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// ACECustom's parts of RynthAi's Pets tab moved to RynthILT on 2026-10-20 (Hub/IltPetAutomation.cs): -// the pet charms, the summon-from-empty refill gate RynthAi's PetManager asks through RynthILT.Hub, -// siphon-lens auto-capture and the Breeding sub-tab offer. Their settings are copied once from the -// character's RynthAi miniremote.json (IltMigration.ImportRynthAiSettings). -internal static class PetAutomationTests -{ - private const uint Player = 0x50000A01; - private const uint Lens = 0x80000A02; - private const uint Mob = 0x80000A03; - private const uint Charm = 0x80000A04; - private const uint Lb = 0xA9B40000; - - public static void Register(Runner r) - { - r.Add("pets (RynthILT): summon from empty needs the opt-in, an active refill charm and the server's word; never off ILT", RefillGate); - r.Add("pets (RynthILT): auto-capture uses the lens on a weak creature in range only, and only when switched on", Capture); - r.Add("pets (RynthILT): the Breeding sub-tab is offered on ILT unless the server reports breeding off", BreedingSubTab); - r.Add("pets (RynthILT): off ILT the Pets sections draw nothing and nothing ticks", DormantOffIlt); - r.Add("migration: the Pets tab's ACECustom options come over from RynthAi's miniremote.json once", ImportsPetSettings); - } - - private static IltHubController NewHub(string world, string folder, Action? setup = null) - { - FakeHost.Reset(); - FakeHost.WorldName = world; - FakeHost.ContentsCalls = true; - FakeHost.WeaponCalls = true; // UseObject, RequestId, appraisal state - FakeHost.LiveObjectsCalls = true; - FakeHost.Names[Player] = "Petter"; - FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f); - setup?.Invoke(); - var host = FakeHost.Create(Player); - string dir = Path.Combine(Program.TempRoot, "pets-" + folder); - if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); - Directory.CreateDirectory(dir); - var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host)); - hub.OnLoginComplete("Petter", forceFromMigration: false); - return hub; - } - - private static void Carry(uint id, string name, uint wcid) - { - FakeHost.Names[id] = name; - FakeHost.ItemTypes[id] = 0x80; // misc - FakeHost.Containers[id] = Player; - FakeHost.Wcids[id] = wcid; - } - - private static void RefillGate() - { - var hub = NewHub("InfiniteLeaftide", "refill", () => FakeHost.Bools[(Player, IltInventory.BoolPyrealRefillActive)] = true); - var pets = hub.PetAutomation; - Check.False(pets.ComputeAllowSummonOnEmpty(), "not opted in: no summon from empty"); - hub.State.Pet.RefillFromEmpty = true; - Check.True(pets.ComputeAllowSummonOnEmpty(), "opted in, and the server stamped the refill bool (active and confirmed)"); - - var charmOnly = NewHub("InfiniteLeaftide", "refill-charm", () => - { - Carry(Charm, "Summon Essence Refill Charm", IltInventory.WcidSummonRefillCharm); - FakeHost.Strings[(Charm, IltInventory.StrUse)] = "Toggles the refill. Status: ON"; - }); - charmOnly.State.Pet.RefillFromEmpty = true; - Check.True(charmOnly.PetAutomation.RefillCharmActive(), "the carried charm reads ON"); - Check.False(charmOnly.PetAutomation.ComputeAllowSummonOnEmpty(), "but the server hasn't confirmed pet_refill: never spend"); - charmOnly.Options.Set(IltFeature.PetRefill, IltTri.On); - Check.True(charmOnly.PetAutomation.ComputeAllowSummonOnEmpty(), "confirmed: summon from empty"); - charmOnly.Tick(); - Check.True(charmOnly.PetAutomation.AllowSummonOnEmpty, "the tick caches it for RynthAi (RynthILT.Hub AllowSummonOnEmpty)"); - - var off = NewHub("Aeshnidae", "refill-off", () => FakeHost.Bools[(Player, IltInventory.BoolPyrealRefillActive)] = true); - off.State.Pet.RefillFromEmpty = true; - Check.False(off.PetAutomation.ComputeAllowSummonOnEmpty(), "off ILT: never"); - off.Tick(); - Check.False(off.PetAutomation.AllowSummonOnEmpty, "and nothing cached for RynthAi"); - } - - private static void Capture() - { - var hub = NewHub("InfiniteLeaftide", "capture", () => - { - Carry(Lens, "Flawed Siphon Lens", PetCaptureRules.Lenses[0].Wcid); - FakeHost.Names[Mob] = "Drudge Skulker"; - FakeHost.ItemTypes[Mob] = 0x10; // creature - FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f); // 3 m - FakeHost.TargetVitals[Mob] = (100, 100); - }); - var pets = hub.PetAutomation; - long now = Environment.TickCount64; // the chat replies time their back-off on the real clock - pets.TickCapture(now); - Check.Eq(FakeHost.Uses.Count, 0, "switched off: no lens used"); - Check.Eq(pets.CaptureStatus, "off", "status off"); - - hub.State.Pet.AutoCapture = true; - pets.TickCapture(now); - Check.Eq(FakeHost.Uses.Count, 0, "a full-health creature: no lens"); - Check.True(pets.CaptureStatus.Contains("Drudge Skulker") && pets.CaptureStatus.Contains("need"), "it says what it waits for"); - - FakeHost.TargetVitals[Mob] = (15, 100); - pets.TickCapture(now + 1000); - Check.Eq(FakeHost.Uses.Count, 1, "15%: the lens is used"); - Check.Eq(FakeHost.Uses[0], Lens, "the chosen lens"); - pets.TickCapture(now + 1500); - Check.Eq(FakeHost.Uses.Count, 1, "the cooldown holds the next use back"); - pets.OnChat("The creature is too strong to be siphoned."); - Check.True(pets.CaptureStatus.StartsWith("refused"), "a refusal is noted"); - - FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 110f, 0f); // 14 m - pets.TickCapture(now + 60_000); - Check.Eq(FakeHost.Uses.Count, 1, "out of range: no lens"); - - hub.Options.Set(RynthIltHub.FeatureMonsterCapture, IltTri.Off); - FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f); - pets.TickCapture(now + 120_000); - Check.Eq(FakeHost.Uses.Count, 1, "the server reports monster capture off: no lens"); - Check.True(pets.CaptureStatus.Contains("disabled"), "and says so"); - } - - private static void BreedingSubTab() - { - var on = NewHub("InfiniteLeaftide", "breed-on"); - var tabs = on.SubTabs(RynthIltHub.TabParentPets); - Check.Eq(tabs.Length, 1, "one Pets sub-tab on ILT"); - Check.Eq(tabs[0].Id, RynthIltHub.SectionPetBreeding, "Breeding, drawn as the pets-breeding section"); - Check.Eq(on.SubTabs("crafting").Length, 0, "nothing for another tab"); - on.Options.Set(RynthIltHub.FeaturePetBreeding, IltTri.Off); - Check.Eq(on.SubTabs(RynthIltHub.TabParentPets).Length, 0, "the server reports breeding off: none"); - - var off = NewHub("Aeshnidae", "breed-off"); - Check.Eq(off.SubTabs(RynthIltHub.TabParentPets).Length, 0, "off ILT: none"); - } - - private static void DormantOffIlt() - { - var off = NewHub("Aeshnidae", "dormant", () => - { - Carry(Lens, "Flawed Siphon Lens", PetCaptureRules.Lenses[0].Wcid); - FakeHost.Names[Mob] = "Drudge Skulker"; - FakeHost.ItemTypes[Mob] = 0x10; - FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f); - FakeHost.TargetVitals[Mob] = (1, 100); - }); - off.State.Pet.AutoCapture = true; - for (int i = 0; i < 5; i++) { off.Tick(); System.Threading.Thread.Sleep(60); } - Check.Eq(FakeHost.Uses.Count, 0, "off ILT the capture never ticks (no lens used)"); - Check.False(off.RenderSection(RynthIltHub.SectionPetCharms) || off.RenderSection(RynthIltHub.SectionPetCapture), - "the Pets sections draw nothing (checked before any ImGui call)"); - } - - private static void ImportsPetSettings() - { - string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Petter"); - Directory.CreateDirectory(legacy); - File.WriteAllText(Path.Combine(legacy, "Default.json"), "{}"); - File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyMiniRemoteFile), - "{ \"Pet\": { \"HealingEnabled\": true, \"UsePyrealRefillPath\": true, \"AutoCaptureEnabled\": true, \"CaptureLensIndex\": 3 } }"); - var state = new IltHubState(); - Check.False(state.Pet.RefillFromEmpty || state.Pet.AutoCapture, "RynthILT's defaults: both off"); - var lines = IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Petter"); - Check.True(state.RynthAiSettingsImported, "marked done"); - Check.True(state.Pet.RefillFromEmpty, "summon from empty came over"); - Check.True(state.Pet.AutoCapture, "auto-capture came over"); - Check.Eq(state.Pet.CaptureLens, 3, "the lens came over"); - Check.True(lines.Any(l => l.Contains("auto-capture on")), "and the log line says so"); - - state.Pet.AutoCapture = false; // changed in RynthILT afterwards - Check.Eq(IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Petter").Count, 0, "the second login does nothing"); - Check.False(state.Pet.AutoCapture, "RynthILT's own change stays"); - - var fresh = new IltHubState(); - IltMigration.ImportRynthAiSettings(fresh, "InfiniteLeaftide", "Nobody"); - Check.True(fresh.RynthAiSettingsImported && !fresh.Pet.AutoCapture && !fresh.Pet.RefillFromEmpty, - "a character without RynthAi files keeps the defaults (and is marked done)"); - - File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyMiniRemoteFile), "{ broken"); - var broken = new IltHubState(); - IltMigration.ImportRynthAiSettings(broken, "InfiniteLeaftide", "Petter"); - Check.True(broken.RynthAiSettingsImported && !broken.Pet.AutoCapture, "an unreadable miniremote.json: defaults, no exception"); - } -} diff --git a/Tools/RynthILT.Tests/PetCaptureRulesTests.cs b/Tools/RynthILT.Tests/PetCaptureRulesTests.cs deleted file mode 100644 index 3e523ce..0000000 --- a/Tools/RynthILT.Tests/PetCaptureRulesTests.cs +++ /dev/null @@ -1,109 +0,0 @@ -// ACECustom MonsterCapture health / range / lens table — matches Source/ACE.Server/Entity/MonsterCapture.cs. -// Moved from RynthCore.RynthAiTests with the rules (RynthILT's IltPetCaptureRules since 2026-10-20). -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -internal static class PetCaptureRulesTests -{ - public static void Register(Runner r) - { - r.Add("pet capture: health gate matches ACECustom (≤20% or under 20 HP)", HealthGate); - r.Add("pet capture: Asheron's Lens bypasses the health gate", AsheronsBypass); - r.Add("pet capture: range is 5 m; dead creatures are never capturable", RangeAndDead); - r.Add("pet capture: lens WCIDs match PetGuideController", LensWcids); - r.Add("pet capture: a creature is left alone after 5 tries with no capture, then retried after the block", ThrottlePerTarget); - r.Add("pet capture: 15 lens uses with no capture anywhere trip the backstop; a success resets it", ThrottleBackstop); - } - - private static void HealthGate() - { - // Full health — refuse. - Check.False(PetCaptureRules.IsWeakEnough(100, 100), "100/100 too strong"); - Check.False(PetCaptureRules.IsWeakEnough(21, 100), "21% and ≥20 HP too strong"); - - // Fraction gate. - Check.True(PetCaptureRules.IsWeakEnough(20, 100), "20% exactly is allowed"); - Check.True(PetCaptureRules.IsWeakEnough(1, 100), "1% allowed"); - - // Absolute HP gate (high % but under 20 HP). - Check.True(PetCaptureRules.IsWeakEnough(15, 50), "15/50 = 30% but under 20 HP"); - Check.True(PetCaptureRules.IsWeakEnough(19, 19), "19/19 under 20 HP"); - - // Ratio-only path (no absolute HP): only the fraction half. - Check.True(PetCaptureRules.IsWeakEnoughRatio(0.20f), "ratio 0.20"); - Check.False(PetCaptureRules.IsWeakEnoughRatio(0.21f), "ratio 0.21"); - Check.False(PetCaptureRules.IsWeakEnoughRatio(0f), "ratio 0 = dead"); - Check.False(PetCaptureRules.IsWeakEnough(0, 100), "0 current = dead"); - } - - private static void AsheronsBypass() - { - var asheron = PetCaptureRules.LensAt(4); - Check.Eq(asheron.Wcid, 78780012u, "Asheron's WCID"); - Check.True(asheron.BypassesHealthGate, "bypasses health"); - Check.True(PetCaptureRules.CanAttempt(asheron, 100, 100), "full health ok for Asheron's"); - Check.False(PetCaptureRules.CanAttempt(asheron, 0, 100), "still not when dead"); - - var flawed = PetCaptureRules.LensAt(0); - Check.False(PetCaptureRules.CanAttempt(flawed, 100, 100), "Flawed refuses full health"); - Check.True(PetCaptureRules.CanAttempt(flawed, 10, 100), "Flawed at 10%"); - } - - private static void RangeAndDead() - { - Check.Eq(PetCaptureRules.CaptureRangeM, 5.0f, "5 m range"); - Check.True(PetCaptureRules.InRange(0), "at feet"); - Check.True(PetCaptureRules.InRange(5.0), "at 5 m"); - Check.False(PetCaptureRules.InRange(5.01), "past 5 m"); - Check.False(PetCaptureRules.InRange(-1), "unknown distance"); - } - - private static void LensWcids() - { - Check.Eq(PetCaptureRules.Lenses.Length, 5, "five selectable lenses"); - Check.Eq(PetCaptureRules.LensAt(0).Wcid, 78780001u, "Flawed"); - Check.Eq(PetCaptureRules.LensAt(1).Wcid, 78780002u, "Pristine"); - Check.Eq(PetCaptureRules.LensAt(2).Wcid, 78780003u, "Perfect"); - Check.Eq(PetCaptureRules.LensAt(3).Wcid, 78780010u, "Resonance"); - Check.Eq(PetCaptureRules.LensAt(4).Wcid, 78780012u, "Asheron's"); - Check.Eq(PetCaptureRules.LensNames.Length, PetCaptureRules.Lenses.Length, "combo labels match"); - } - - private static void ThrottlePerTarget() - { - var t = new PetCaptureThrottle(); - long now = 1000; - for (int i = 0; i < PetCaptureThrottle.MaxTriesPerTarget; i++) - { - Check.True(t.MayAttempt(7, now), $"try {i + 1} allowed"); - t.RecordAttempt(7, now); - now += 2500; - } - Check.False(t.MayAttempt(7, now), "5 tries used: blocked"); - Check.True(t.BlockedSecondsLeft(7, now) > 0, "block time left reported"); - Check.True(t.MayAttempt(8, now), "another creature is not blocked"); - Check.False(t.MayAttempt(7, now + PetCaptureThrottle.TargetBlockMs - 3000), "still blocked just before the block ends"); - Check.True(t.MayAttempt(7, now + PetCaptureThrottle.TargetBlockMs + 1), "block served: tries again"); - t.RecordAttempt(7, now + PetCaptureThrottle.TargetBlockMs + 1); - Check.True(t.MayAttempt(7, now + PetCaptureThrottle.TargetBlockMs + 2), "a fresh set of tries after the block"); - } - - private static void ThrottleBackstop() - { - var t = new PetCaptureThrottle(); - long now = 0; - for (int i = 0; i < PetCaptureThrottle.MaxTriesWithoutSuccess; i++) - { - Check.False(t.Exhausted, $"not exhausted before use {i + 1}"); - t.RecordAttempt(100 + i, now); // a new creature each time: per-target never trips - now += 2500; - } - Check.True(t.Exhausted, "15 uses over many creatures, no capture: exhausted"); - Check.False(t.MayAttempt(999, now), "nothing more is allowed"); - t.RecordSuccess(); - Check.False(t.Exhausted, "a capture reply resets the backstop"); - Check.True(t.MayAttempt(100, now), "and the per-target blocks"); - } -} diff --git a/Tools/RynthILT.Tests/ProfileTests.cs b/Tools/RynthILT.Tests/ProfileTests.cs deleted file mode 100644 index c6237e0..0000000 --- a/Tools/RynthILT.Tests/ProfileTests.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System; -using System.Linq; -using System.Text.Json; -using RynthCore.Plugin.RynthILT; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.Plugin.Shared; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// RynthILT's "RynthServer.Profile" (ProfileInterface.cs): the same interface and JSON the server -// plugins serve, for "ilt", carrying Infinite Leaftide's tinkering salvage (Hub/IltSalvage.cs). -// The JSON is read back with the shared reader RynthAi's Crafting tab uses (EngineServerState.cs: -// ServerSalvageView.ParseList), so the rows it plans with are the ones checked here. 2026-10-15. -internal static unsafe class ProfileTests -{ - public static void Register(Runner r) - { - r.Add("profile: RynthILT serves RynthServer.Profile for ilt", Interface); - r.Add("profile: ILT's salvage reaches the Crafting tab's reader (Leather after the cap, jewelry stack)", Salvage); - r.Add("profile: ILT's trinkets reach the Crafting tab's reader (RynthAi's TinkerCatalog rule until 2026-10-20)", Trinkets); - } - - private static void Interface() - { - Check.Eq(ProfileInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not this table"); - Check.Eq(ProfileInterface.Query(RynthServerProfileApiV1.InterfaceName, 2), IntPtr.Zero, "a newer version than we have: none"); - var t = (RynthServerProfileApiV1*)ProfileInterface.Query(RynthServerProfileApiV1.InterfaceName, 1); - Check.True(t != null, "the table"); - Check.Eq(t->Version, RynthServerProfileApiV1.InterfaceVersion, "version"); - Check.Eq(t->StructSize, (uint)sizeof(RynthServerProfileApiV1), "struct size"); - Check.True(t->GetProfileJson != null, "GetProfileJson"); - - string json = ProfileInterface.CurrentJson(true, "InfiniteLeaftide"); - using JsonDocument doc = JsonDocument.Parse(json); - JsonElement root = doc.RootElement; - Check.Eq(root.GetProperty("schema").GetInt32(), RynthServerProfile.Schema, "schema"); - Check.Eq(root.GetProperty("id").GetString(), "ilt", "the engine's ILT id"); - Check.Eq(root.GetProperty("name").GetString(), "Infinite Leaftide", "name"); - Check.Eq(root.GetProperty("plugin").GetString(), "RynthILT", "plugin"); - Check.True(root.GetProperty("active").GetBoolean(), "active"); - Check.Eq(root.GetProperty("world").GetString(), "InfiniteLeaftide", "world"); - Check.Eq(root.GetProperty("hosts")[0].GetString(), "infiniteleaftide.online", "hosts from the csproj"); - Check.Eq(ProfileInterface.CurrentJson(true, "InfiniteLeaftide"), json, "unchanged state: the same JSON"); - Check.False(JsonDocument.Parse(ProfileInterface.CurrentJson(false, null)).RootElement.GetProperty("active").GetBoolean(), - "before the Hub is up: not active"); - } - - private static void Trinkets() - { - var rule = ServerTrinketRule.Parse(ProfileInterface.CurrentJson(true, "InfiniteLeaftide")); - Check.True(rule != ServerTrinketRule.None, "the profile carries a trinket rule"); - foreach (string t in new[] { "Ornate Compass", "Tinker's Goggles", "Jade Scarab", "Pocket Watch", "Puzzle Box", "Spinning Top" }) - Check.True(rule.IsTrinket(t), t + " is a trinket"); - foreach (string j in new[] { "Yellow Topaz Ring", "Gold Necklace", "Silver Bracelet" }) - Check.False(rule.IsTrinket(j), j + " is Jewelry"); - } - - private static void Salvage() - { - var rows = ServerSalvageView.ParseList(ProfileInterface.CurrentJson(true, "InfiniteLeaftide")); - Check.Eq(rows.Count, IltSalvage.Rows.Length, "every row arrives"); - for (int i = 0; i < rows.Count; i++) - { - var a = IltSalvage.Rows[i]; - var b = rows[i]; - bool same = a.Bench == b.Bench && a.Material == b.Material && a.Kind == b.Kind && a.Effect == b.Effect - && a.UsesTinkSlot == b.UsesTinkSlot && a.NameMatch == b.NameMatch && a.AppliedInt == b.AppliedInt - && a.Prepared == b.Prepared && a.Order == b.Order && a.AfterCap == b.AfterCap - && a.StackGroup == b.StackGroup && a.StackCap == b.StackCap; - Check.True(same, $"row {i} ({a.Bench} {a.Material}) round-trips"); - } - - const int Leather = 52, Steel = 64, Serpentine = 71, Silver = 63, Diamond = 20, BlackGarnet = 15; - foreach (string bench in new[] { "melee", "missile", "caster" }) - { - var leather = rows.Single(r => r.Bench == bench && r.Material == Leather); - Check.True(leather.AfterCap, bench + " Leather: after the cap"); - Check.False(leather.UsesTinkSlot, bench + " Leather: no tink slot"); - Check.Eq(leather.Kind, "once", bench + " Leather: once"); - Check.Eq(leather.Order, 995, bench + " Leather: last"); - } - Check.Eq(rows.Count(r => r.AfterCap), 3, "only the weapon Leathers wait for the cap"); - - var stack = rows.Where(r => r.StackGroup.Length > 0).ToList(); - Check.Eq(string.Join(",", stack.Select(r => r.Bench + ":" + r.Material)), $"jewelry:{Serpentine},jewelry:{Steel}", "Serpentine + Steel stack"); - Check.True(stack.All(r => r.StackGroup == "jewelry-stack" && r.StackCap == 10 && r.Kind == "tink" && !r.UsesTinkSlot), - "one group, cap 10, repeatable, no tink slot"); - - Check.Eq(rows.Single(r => r.Bench == "jewelry" && r.Material == Silver).AppliedInt, 374, "jewelry Silver flag int"); - var diamond = rows.Single(r => r.Bench == "trinkets" && r.Material == Diamond); - Check.True(diamond.Prepared && diamond.AppliedInt == 384 && diamond.Order == 10, "trinket Diamond: prepared, flag 384, first"); - Check.Eq(rows.Count(r => r.Prepared), 4, "the four trinket tiers are prepared"); - Check.True(rows.Where(r => r.Material == BlackGarnet).All(r => r.NameMatch == "Abyssal" && r.UsesTinkSlot), - "Abyssal-Touched Gems by bag name, using a tink slot"); - Check.False(rows.Any(r => r.Bench is "armor" or "items"), "no armor or item rows"); - } -} diff --git a/Tools/RynthILT.Tests/Program.cs b/Tools/RynthILT.Tests/Program.cs deleted file mode 100644 index bc3f213..0000000 --- a/Tools/RynthILT.Tests/Program.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.IO; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// Offline tests for the RynthILT plugin: the ACECustom bounty tracker (parsing, merging, the -// quiet /bounty list read loop on a fake clock, persistence, the bridge JSON) and the ILT Hub -// (attribute raiser, aug costs, bank commands, sigil chain, and the move out of RynthAi: data -// migration, the RynthILT.Hub table, verb routing, the object view) and its RynthServer.Profile -// (ILT's tinkering salvage). Each test prints PASS / FAIL. -// -// Run: dotnet run -c Release (all tests) -// dotnet run -c Release -- window (tests whose name contains "window") -internal static class Program -{ - /// Scratch folder next to the exe for files tests write. Emptied at start. - public static string TempRoot { get; } = Path.Combine(AppContext.BaseDirectory, "scratch"); - - private static int Main(string[] args) - { - if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true); - Directory.CreateDirectory(TempRoot); - - // SAFETY: every file the ILT Hub would write under %APPDATA%\RynthCore\RynthILT or read from - // the RynthAi folder points at the scratch folder before any test runs. - RynthCore.Plugin.RynthILT.Hub.IltAugCosts.FilePath = Path.Combine(TempRoot, "ilt-aug-costs.json"); - RynthCore.Plugin.RynthILT.Hub.IltHubStore.SharedRoot = Path.Combine(TempRoot, "RynthILT"); - RynthCore.Plugin.RynthILT.Hub.IltSettingsStore.Folder = Path.Combine(TempRoot, "RynthILT"); - RynthCore.Plugin.RynthILT.Hub.IltMigration.LegacyProfilesBase = Path.Combine(TempRoot, "RynthAi", "SettingsProfiles"); - RynthCore.Plugin.RynthILT.Hub.IltMigration.LegacySharedRoot = Path.Combine(TempRoot, "RynthAi"); - RynthCore.Plugin.RynthILT.RynthLog.Init(default, Path.Combine(TempRoot, "Logs")); - RynthCore.Plugin.Shared.DataWriteGuard.PluginName = "RynthILT"; // as RynthILTPlugin.Initialize sets it - - var runner = new Runner(); - BountyTests.Register(runner); - BountyReviewTests.Register(runner); - AttributeRaiserTests.Register(runner); - SigilChainTests.Register(runner); - BankCommandTests.Register(runner); - MoveTests.Register(runner); - ChunkTests.Register(runner); - ProfileTests.Register(runner); - FeatureCatalogTests.Register(runner); - IltSettingsTests.Register(runner); - FellowshipCommandTests.Register(runner); - AetheriaChunkTests.Register(runner); - ChunkTargetTests.Register(runner); - RingChainTests.Register(runner); - VaultedDungeonsTests.Register(runner); - PetCaptureRulesTests.Register(runner); - PetAutomationTests.Register(runner); - RingEvadeTests.Register(runner); - VaultedSwitchTests.Register(runner); - T11Tests.Register(runner); - RemoteTabTests.Register(runner); - // Before DataApiTests: its last test releases the RynthILT.Data table, which the breeding version test queries. - BreedingTests.Register(runner); - DataApiTests.Register(runner); - return runner.Run("RynthILT tests", args.Length > 0 ? args[0] : null); - } -} diff --git a/Tools/RynthILT.Tests/RemoteTabTests.cs b/Tools/RynthILT.Tests/RemoteTabTests.cs deleted file mode 100644 index 10a976f..0000000 --- a/Tools/RynthILT.Tests/RemoteTabTests.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System; -using System.IO; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.Plugin.Shared; -using RynthCore.RynthAiHostTests.Fakes; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// The ILT parts of RynthAi's Remote tab moved to RynthILT on 2026-10-20: the coin / pyreal lines under -// RynthAi's Stats ("remote-stats"), the session report's tail (GetText "session-report"), the Bank and -// Guardian sections' switches (RynthILT's own now, drawn in RynthAi's Options popup, "remote-options"), -// and the coin session restarting with RynthAi's shared session instead of RynthAi sending "rates reset". -internal static class RemoteTabTests -{ - public static void Register(Runner r) - { - r.Add("remote tab (RynthILT): its texts for RynthAi (server id, the session report's coins) and none off ILT", Texts); - r.Add("remote tab (RynthILT): Bank / Guardian follow RynthILT's own switches; the stats and options draw nothing off ILT", Switches); - r.Add("remote tab (RynthILT): the coins start over when RynthAi's shared session restarts", FollowsSession); - r.Add("migration: RynthAi's huds.json Bank / Guardian switches come over once", ImportsSwitches); - } - - private static IltHubController NewHub(string world, string folder) - { - FakeHost.Reset(); - FakeAiHub.Reset(); - FakeHost.WorldName = world; - var host = FakeHost.Create(0x50000D21); - var ai = new RynthAiClient(host); - ai.UseTableForTests(FakeAiHub.Table); - string dir = Path.Combine(Program.TempRoot, "remote-" + folder); - if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); - Directory.CreateDirectory(dir); - var hub = new IltHubController(host, dir, new IltSettings(), ai); - hub.OnLoginComplete("Remoter", forceFromMigration: false); - return hub; - } - - private static void Texts() - { - var on = NewHub("InfiniteLeaftide", "texts-on"); - Check.Eq(on.GetText(RynthIltHub.TextServerId), "ilt", "its tabs belong to RynthCore's 'ilt'"); - string tail = on.GetText(RynthIltHub.TextSessionReport); - Check.True(tail.StartsWith(", Coins ") && tail.Contains("/h, Pyr "), "the session report's tail: coins and pyreals per hour"); - Check.Eq(on.GetText("no-such-text"), string.Empty, "an unknown id: nothing"); - - var off = NewHub("Aeshnidae", "texts-off"); - Check.Eq(off.GetText(RynthIltHub.TextSessionReport), string.Empty, "off ILT: no coins in RynthAi's report"); - } - - private static void Switches() - { - var on = NewHub("InfiniteLeaftide", "switches"); - Check.True(on.State.Remote.ShowBank && on.State.Remote.ShowGuardian, "both on by default"); - on.State.Remote.ShowBank = false; - on.State.Remote.ShowGuardian = false; - Check.False(on.RenderSection(RynthIltHub.SectionRemoteBank), "Bank switched off: nothing drawn"); - Check.False(on.RenderSection(RynthIltHub.SectionRemoteGuardian), "Guardian switched off: nothing drawn"); - - var off = NewHub("Aeshnidae", "switches-off"); - Check.False(off.RenderSection(RynthIltHub.SectionRemoteStats) || off.RenderSection(RynthIltHub.SectionRemoteOptions) - || off.RenderSection(RynthIltHub.SectionRemoteBank) || off.RenderSection(RynthIltHub.SectionRemoteGuardian), - "off ILT: none of the Remote tab's ILT parts draws (checked before any ImGui call)"); - } - - private static void FollowsSession() - { - var hub = NewHub("InfiniteLeaftide", "session"); - long t1 = DateTime.UtcNow.AddMinutes(-10).Ticks; - FakeAiHub.SessionStartTicks = t1; - long now = Environment.TickCount64; - hub.Rates.Tick(now); - DateTime first = hub.Rates.SessionStartUtc; - System.Threading.Thread.Sleep(30); - hub.Rates.Tick(now + 100); - Check.Eq(hub.Rates.SessionStartUtc, first, "the same shared session: no restart"); - FakeAiHub.SessionStartTicks = DateTime.UtcNow.Ticks; // RynthAi's Reset XP - hub.Rates.Tick(now + 200); - Check.True(hub.Rates.SessionStartUtc > first, "RynthAi's session restarted: the coins start over too"); - } - - private static void ImportsSwitches() - { - string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Remoter"); - Directory.CreateDirectory(legacy); - File.WriteAllText(Path.Combine(legacy, "Default.json"), "{}"); - File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyHudsFile), "{ \"ShowMiniRemote\": true, \"MiniShowBank\": false }"); - var state = new IltHubState(); - IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Remoter"); - Check.False(state.Remote.ShowBank, "Bank was hidden in RynthAi: hidden here"); - Check.True(state.Remote.ShowGuardian, "Guardian wasn't in the file: the default (shown)"); - } -} diff --git a/Tools/RynthILT.Tests/RingChainTests.cs b/Tools/RynthILT.Tests/RingChainTests.cs deleted file mode 100644 index 25b225f..0000000 --- a/Tools/RynthILT.Tests/RingChainTests.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// The Rings inscription chain's pure parts (Hub/IltRingChain.cs, SilentKelpie's RynthAi -// Crafting > Rings moved to RynthILT): ingredient names, the craft queue and the scroll pairing. -internal static class RingChainTests -{ - public static void Register(Runner r) - { - r.Add("rings: ingredients match by name, with alternates and an exclude", Ingredients); - r.Add("rings: the queue runs every Step 1, then Step 2, then the glyphs, capped per recipe", Queue); - r.Add("rings: scrolls are known by their glyph and paired with targets the UB-IT way", Scrolls); - r.Add("rings: the recipe list holds the three steps and eight glyphs", RecipeList); - } - - private static IltRingRecipe Recipe(string id) => IltRingChain.Recipes.Single(r => r.Id == id); - - private static void Ingredients() - { - var step1 = Recipe("ring2_step1_quill_trophy"); - Check.True(IltRingChain.Matches("Quill of Infliction", step1.Tool), "the quill"); - Check.True(IltRingChain.Matches("infliction quill", step1.Tool), "an alternate name, any case"); - Check.False(IltRingChain.Matches("Enlightened Quill of Infliction", step1.Tool), "the enlightened quill is Step 2's, not Step 1's"); - Check.True(IltRingChain.Matches("Empyrean Trophy", step1.Target), "a trophy"); - Check.False(IltRingChain.Matches("Trophy Scroll", step1.Target), "plain 'Trophy' isn't enough (scrolls carry the word)"); - Check.False(IltRingChain.Matches(null, step1.Tool), "no name"); - Check.False(IltRingChain.Matches("", step1.Tool), "empty name"); - - var step2 = Recipe("ring2_step2_ink"); - Check.True(IltRingChain.Matches("Enlightened Quill of Infliction", step2.Tool), "Step 2 takes Step 1's quill"); - Check.False(IltRingChain.Matches("Enlightened Infliction Quill of Partition", step2.Tool), "but not the partition quill"); - - var flame = Recipe("ring2_glyph_flame"); - Check.True(IltRingChain.Matches("Enlightened Infliction Quill of Partition", flame.Tool), "Step 3 takes the partition quill"); - Check.True(IltRingChain.Matches("Glyph of Flame", flame.Target), "the full glyph name"); - Check.False(IltRingChain.Matches("Glyph of Frost", flame.Target), "another glyph is not"); - } - - private static void Queue() - { - var runs = new Dictionary - { - ["ring2_glyph_frost"] = 1, - ["ring2_step2_ink"] = 2, - ["ring2_step1_quill_trophy"] = 2, - ["ring2_glyph_bludgeoning"] = 1, - }; - List q = IltRingChain.Expand(id => runs.TryGetValue(id, out int n) ? n : 0); - Check.Eq(string.Join(",", q.Select(r => r.Id)), - "ring2_step1_quill_trophy,ring2_step1_quill_trophy,ring2_step2_ink,ring2_step2_ink,ring2_glyph_bludgeoning,ring2_glyph_frost", - "tier order, then the definition order within a tier"); - Check.Eq(IltRingChain.Expand(_ => 0).Count, 0, "nothing queued"); - Check.Eq(IltRingChain.Expand(id => id == "ring2_step2_ink" ? -5 : 0).Count, 0, "negative runs count as none"); - Check.Eq(IltRingChain.Expand(id => id == "ring2_step2_ink" ? 500 : 0).Count, IltRingChain.MaxRuns, "capped at MaxRuns"); - } - - private static void Scrolls() - { - Check.True(IltRingChain.IsInscriptionScroll("Inscription of Halo of Frost"), "an inscription scroll"); - Check.False(IltRingChain.IsInscriptionScroll("Scroll of Frost Bolt"), "a spell scroll is not"); - Check.False(IltRingChain.IsInscriptionScroll(null), "no name"); - Check.Eq(IltRingChain.GlyphOf("Inscription of Halo of Frost")?.Id, "ring2_glyph_frost", "known by its scroll name"); - Check.Eq(IltRingChain.GlyphOf("Inscription of Cassius' Ring of Fire")?.Id, "ring2_glyph_flame", "apostrophes too"); - Check.True(IltRingChain.GlyphOf("Inscription of Something New") == null, "an unknown scroll has no glyph"); - - var scrolls = new[] - { - (Id: 50, Name: "Inscription of Something New"), - (Id: 40, Name: "Inscription of Halo of Frost"), - (Id: 30, Name: "Inscription of Tectonic Rifts"), - (Id: 20, Name: "Inscription of Halo of Frost"), - }; - var pairs = IltRingChain.PairScrolls(scrolls, new[] { 900, 700, 800, 700 }); - // Scrolls by glyph id (bludgeoning < frost; unknown last), then by id; targets by id, once each. - Check.Eq(string.Join(" ", pairs.Select(p => p.Scroll + ">" + p.Target)), "30>700 20>800 40>900", "pairing order"); - Check.Eq(IltRingChain.PairScrolls(scrolls.Take(1), new[] { 1, 2, 3 }).Count, 1, "one scroll per target, no more pairs than scrolls"); - Check.Eq(IltRingChain.PairScrolls(scrolls, Array.Empty()).Count, 0, "no targets, no pairs"); - } - - private static void RecipeList() - { - Check.Eq(IltRingChain.Recipes.Length, 10, "Step 1, Step 2 and eight glyphs"); - Check.Eq(IltRingChain.Recipes.Count(r => r.Tier == 3), 8, "eight glyphs"); - Check.True(IltRingChain.Recipes.Select(r => r.Id).Distinct().Count() == IltRingChain.Recipes.Length, "ids are unique"); - foreach (var r in IltRingChain.Recipes.Where(r => r.Tier == 3)) - Check.True(r.ScrollMarkers.Length > 0, r.Id + " knows its scroll's name"); - } -} diff --git a/Tools/RynthILT.Tests/RingEvadeTests.cs b/Tools/RynthILT.Tests/RingEvadeTests.cs deleted file mode 100644 index df992a7..0000000 --- a/Tools/RynthILT.Tests/RingEvadeTests.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.Plugin.Shared; -using RynthCore.RynthAiHostTests.Fakes; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// The Empyrean Handler's lethal ring (Hub/IltRingEvade.cs), RynthAi's CombatManager's until 2026-10-20 -// (Silentkelpie's PR 12). The line "The handler briefly channels infused Empyrean hatred to release a -// lethal ring." on an ILT world, with a Handler near, makes RynthILT ask RynthAi to back away from it -// (RynthAi.Hub BackAwayFrom, 12 yards, a 750 ms jump). The setting (on by default) is RynthILT's now, -// copied once from the RynthAi profile. -internal static class RingEvadeTests -{ - private const uint Player = 0x50000B01; - private const uint Handler = 0x80000B02; - private const uint Lb = 0xA9B40000; - private const string RingLine = "The handler briefly channels infused Empyrean hatred to release a lethal ring."; - - public static void Register(Runner r) - { - r.Add("ring evade (RynthILT): the Handler's line, and not a player's copy of it", ChannelLine); - r.Add("ring evade (RynthILT): on ILT with a Handler near, RynthAi is asked to back away (once per cooldown)", AsksRynthAi); - r.Add("ring evade (RynthILT): not with the setting off, no Handler near, off ILT, or without RynthAi", NotThese); - r.Add("migration: the RynthAi profile's Handler ring evade comes over once (on by default)", ImportsSetting); - } - - private static IltHubController NewHub(string world, string folder, bool handler = true, bool withAi = true, string handlerName = "Empyrean Handler") - { - FakeHost.Reset(); - FakeAiHub.Reset(); - FakeHost.WorldName = world; - FakeHost.ContentsCalls = true; - FakeHost.LiveObjectsCalls = true; - FakeHost.Names[Player] = "Evader"; - FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f); - if (handler) - { - FakeHost.Names[Handler] = handlerName; - FakeHost.ItemTypes[Handler] = 0x10; - FakeHost.Positions[Handler] = (Lb | 0x1C, 96f, 101f, 0f); - } - var host = FakeHost.Create(Player); - var ai = new RynthAiClient(host); - if (withAi) ai.UseTableForTests(FakeAiHub.Table); - string dir = Path.Combine(Program.TempRoot, "ring-" + folder); - if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); - Directory.CreateDirectory(dir); - var hub = new IltHubController(host, dir, new IltSettings(), ai); - hub.OnLoginComplete("Evader", forceFromMigration: false); - return hub; - } - - private static void ChannelLine() - { - Check.True(IltRingEvade.IsChannelLine(RingLine, ChatSource.Emote), "the Handler's emote"); - Check.True(IltRingEvade.IsChannelLine("handler briefly channels infused Empyrean hatred to release a lethal ring.", 0x00), - "mid-line on a system line (a client that strips 'The ')"); - Check.False(IltRingEvade.IsChannelLine("Someone says, \"" + RingLine + "\"", ChatSource.Speech), "a player saying it"); - Check.False(IltRingEvade.IsChannelLine("Bob tells you, \"" + RingLine + "\"", 0x00), "a tell repeating it"); - Check.False(IltRingEvade.IsChannelLine("The handler waves.", ChatSource.Emote), "another Handler emote"); - } - - private static void AsksRynthAi() - { - var hub = NewHub("InfiniteLeaftide", "asks"); - hub.OnChat(RingLine, ChatSource.Emote); - Check.Eq(FakeAiHub.BackAways.Count, 1, "one back-away request"); - var (id, radius, hold) = FakeAiHub.BackAways[0]; - Check.Eq(id, Handler, "away from the Handler"); - Check.Eq(radius, IltRingEvade.DangerYards, "12 yards (RynthAi widens it to Ring Range)"); - Check.Eq(hold, IltRingEvade.JumpHoldMs, "a 750 ms jump"); - Check.True(hub.RingEvade.LastOutcome.Contains("backs away"), "logged"); - hub.OnChat(RingLine, ChatSource.Emote); - Check.Eq(FakeAiHub.BackAways.Count, 1, "a second line inside the cooldown asks nothing"); - - var outside = NewHub("InfiniteLeaftide", "outside"); - FakeAiHub.BackAwayResult = RynthAiHub.BackAwayOutside; - outside.OnChat(RingLine, ChatSource.Emote); - Check.Eq(FakeAiHub.BackAways.Count, 1, "RynthAi decides the radius"); - Check.True(outside.RingEvade.LastOutcome.Contains("outside"), "and its answer is logged"); - - var notFighting = NewHub("InfiniteLeaftide", "notnow"); - FakeAiHub.BackAwayResult = RynthAiHub.BackAwayNotNow; - notFighting.OnChat(RingLine, ChatSource.Emote); - Check.True(notFighting.RingEvade.LastOutcome.Contains("isn't fighting"), "RynthAi not fighting: it says so"); - } - - private static void NotThese() - { - var off = NewHub("InfiniteLeaftide", "setting-off"); - off.State.Combat.HandlerRingEvade = false; - off.OnChat(RingLine, ChatSource.Emote); - Check.Eq(FakeAiHub.BackAways.Count, 0, "setting off: nothing asked"); - - var none = NewHub("InfiniteLeaftide", "none", handlerName: "Drudge Skulker"); - none.OnChat(RingLine, ChatSource.Emote); - Check.Eq(FakeAiHub.BackAways.Count, 0, "no Empyrean Handler near: nothing asked"); - - var said = NewHub("InfiniteLeaftide", "said"); - said.OnChat("Someone says, \"" + RingLine + "\"", ChatSource.Speech); - Check.Eq(FakeAiHub.BackAways.Count, 0, "a player's copy: nothing asked"); - - var retail = NewHub("Aeshnidae", "retail"); - retail.OnChat(RingLine, ChatSource.Emote); - Check.Eq(FakeAiHub.BackAways.Count, 0, "off ILT: nothing asked"); - - var noAi = NewHub("InfiniteLeaftide", "noai", withAi: false); - noAi.OnChat(RingLine, ChatSource.Emote); - Check.True(noAi.RingEvade.LastOutcome.Contains("RynthAi"), "without RynthAi: said in the log, no crash"); - } - - private static void ImportsSetting() - { - Check.True(new IltHubState().Combat.HandlerRingEvade, "on by default"); - string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Evader"); - Directory.CreateDirectory(legacy); - File.WriteAllText(Path.Combine(legacy, "active_profile.txt"), "Farm"); - File.WriteAllText(Path.Combine(legacy, "Farm.json"), "{ \"HandlerRingEvade\": false, \"MonsterRange\": 30 }"); - var state = new IltHubState(); - IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Evader"); - Check.False(state.Combat.HandlerRingEvade, "the active profile had it off: off here too"); - - string legacy2 = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Oldie"); - Directory.CreateDirectory(legacy2); - File.WriteAllText(Path.Combine(legacy2, "Default.json"), "{ \"MonsterRange\": 30 }"); - var old = new IltHubState(); - IltMigration.ImportRynthAiSettings(old, "InfiniteLeaftide", "Oldie"); - Check.True(old.Combat.HandlerRingEvade, "a profile from before the setting: on (the default)"); - } -} diff --git a/Tools/RynthILT.Tests/RynthILT.Tests.csproj b/Tools/RynthILT.Tests/RynthILT.Tests.csproj deleted file mode 100644 index 47e875b..0000000 --- a/Tools/RynthILT.Tests/RynthILT.Tests.csproj +++ /dev/null @@ -1,71 +0,0 @@ - - - - - Exe - net10.0-windows - x86 - win-x86 - false - enable - true - true - RynthILT.Tests - RynthILT.Tests - x86 - $(DefineConstants);RYNTHILT_TESTS - $(NoWarn);CS1591 - - - - - - - - - - - - - - - - - $(DefineConstants);ENGINE_BOUNTIES - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/RynthILT.Tests/SigilChainTests.cs b/Tools/RynthILT.Tests/SigilChainTests.cs deleted file mode 100644 index 4641eab..0000000 --- a/Tools/RynthILT.Tests/SigilChainTests.cs +++ /dev/null @@ -1,83 +0,0 @@ -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// Enlightenment 301-325 sigil craft chain (2026-10-07). Each target level T costs T - 5 sigils and -// T x 2B luminance (ACECustom tier 5). Sigil = Lifeblood Elixir + Ascension Coin; Ascension Coin = -// E-coin + Ancient Yalani Trinket; Elixir = Lifebloom Resin + Necrolytic Extract; Resin = Life -// Splitter + Plant. Stock is used from the top of the chain down. -internal static class SigilChainTests -{ - public static void Register(Runner r) - { - r.Add("sigil chain: 301-325 tier rates and sigil counts", TierRates); - r.Add("sigil chain: shortfall uses stock top-down", ShortfallTopDown); - r.Add("sigil chain: fulfillable count and shared e-coin pool", FulfillableAndCoins); - r.Add("sigil chain: item names (plural stacks, Plant exact)", Names); - } - - private static void TierRates() - { - var t301 = IltProgression.EnlStepCost(301); - Check.Eq(t301.Item, "Enlightenment Sigils", "301 takes sigils"); - Check.Eq(t301.Count, 296, "301 takes T - 5 sigils"); - Check.Eq(t301.Lum, 301 * 2_000_000_000m, "301 costs T x 2B luminance (no step multiplier yet)"); - Check.Eq(IltProgression.EnlStepCost(325).Lum, 325 * 2_000_000_000m, "325 still has no step multiplier"); - Check.Eq(IltProgression.EnlStepCost(326).Item, "Enlightenment Crests", "326 moves to crests"); - Check.Eq(IltSigilChain.SigilsForRange(300, 302), 296L + 297L, "range 300 -> 302 sums both levels"); - Check.Eq(IltSigilChain.SigilsForRange(324, 330), 320L, "range clamps at 325"); - Check.Eq(IltSigilChain.SigilsForRange(200, 300), 0L, "no sigils below 301"); - } - - private static void ShortfallTopDown() - { - var empty = IltSigilChain.Shortfall(10, new IltSigilStock()); - Check.Eq(empty.CoinsShort, 10L, "empty pack: one e-coin per sigil"); - Check.Eq(empty.PlantsShort, 10L, "empty pack: one plant per sigil"); - Check.True(!empty.Covered, "empty pack is not covered"); - - var stock = new IltSigilStock - { - Sigils = 2, AscensionCoins = 3, LifebloodElixirs = 1, LifebloomResins = 4, - EnlightenedCoins = 100, YalaniTrinkets = 1, NecrolyticExtracts = 2, LifeSplitters = 0, Plants = 5, - }; - var s = IltSigilChain.Shortfall(10, stock); - Check.Eq(s.SigilsToCraft, 8L, "2 finished sigils used first"); - Check.Eq(s.AscensionToCraft, 5L, "3 Ascension Coins on hand"); - Check.Eq(s.ElixirsToCraft, 7L, "1 Elixir on hand"); - Check.Eq(s.CoinsShort, 0L, "100 e-coins cover 5 crafts"); - Check.Eq(s.TrinketsShort, 4L, "1 trinket on hand"); - Check.Eq(s.ExtractsShort, 5L, "2 extracts on hand"); - Check.Eq(s.ResinsToCraft, 3L, "4 resins on hand"); - Check.Eq(s.SplittersShort, 3L, "no splitters"); - Check.Eq(s.PlantsShort, 0L, "5 plants cover 3 resins"); - - Check.True(IltSigilChain.Shortfall(5, new IltSigilStock { Sigils = 9 }).Covered, "finished sigils cover the demand"); - } - - private static void FulfillableAndCoins() - { - var stock = new IltSigilStock - { - Sigils = 1, AscensionCoins = 1, EnlightenedCoins = 10, YalaniTrinkets = 2, - LifebloomResins = 1, LifeSplitters = 10, Plants = 10, NecrolyticExtracts = 4, - }; - Check.Eq(IltSigilChain.Fulfillable(stock), 4L, "1 finished + min(3 coins, 4 elixirs)"); - - IltSigilChain.EcoinDemand(50, 30, 2, 20, out long fromCoins, out long still, out long need); - Check.Eq(fromCoins, 1L, "20 coins left after Ascension crafts make 1 token"); - Check.Eq(still, 1L, "one token still short"); - Check.Eq(need, 20L, "one more token's worth of coins"); - IltSigilChain.EcoinDemand(10, 25, 0, 20, out _, out _, out need); - Check.Eq(need, 15L, "Ascension crafts alone exceed the pool"); - } - - private static void Names() - { - Check.True(IltSigilChain.NameIs("Ascension Coins", IltSigilChain.AscensionCoin), "plural stack name"); - Check.True(IltSigilChain.NameIs(" plant ", IltSigilChain.Plant), "case and spaces ignored"); - Check.True(!IltSigilChain.NameIs("Plant Fiber", IltSigilChain.Plant), "Plant must be the whole name"); - Check.True(!IltSigilChain.NameIs("Lifebloom Resin", IltSigilChain.LifebloodElixir), "Lifebloom is not Lifeblood"); - } -} diff --git a/Tools/RynthILT.Tests/T11Tests.cs b/Tools/RynthILT.Tests/T11Tests.cs deleted file mode 100644 index 686edda..0000000 --- a/Tools/RynthILT.Tests/T11Tests.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using RynthCore.Loot.T11; -using RynthCore.Plugin.RynthILT; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.RynthAiHostTests.Fakes; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// T11 (ACECustom tier 11+ gear) moved from RynthAi on 2026-10-20 (Hub/IltT11.cs): RynthILT reads the -// "/aug" reply's wield counters, applies its item-aug override and reports them to RynthAi's loot rules -// (RynthAi.Hub SetPlayerCounter); "/ilt t11" (and RynthAi's "/ra t11", passed on) shows and sets them. -internal static class T11Tests -{ - private const uint Player = 0x50000E01; - - public static void Register(Runner r) - { - r.Add("t11 (RynthILT): the /aug reply's counters go to RynthAi, with the item-aug override applied", ReportsCounters); - r.Add("t11 (RynthILT): /ilt t11 and /ra t11 are RynthILT's verbs; augs sets the override", Commands); - r.Add("t11 (RynthILT): off ILT nothing is read or reported", DormantOffIlt); - r.Add("migration: the RynthAi profile's T11 item-aug override comes over once", ImportsOverride); - } - - private static IltHubController NewHub(string world, string folder) - { - FakeHost.Reset(); - FakeAiHub.Reset(); - FakeHost.WorldName = world; - var host = FakeHost.Create(Player); - var ai = new RynthAiClient(host); - ai.UseTableForTests(FakeAiHub.Table); - string dir = Path.Combine(Program.TempRoot, "t11-" + folder); - if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); - Directory.CreateDirectory(dir); - var hub = new IltHubController(host, dir, new IltSettings(), ai); - hub.OnLoginComplete("Augger", forceFromMigration: false); - return hub; - } - - private static void ReportsCounters() - { - var hub = NewHub("InfiniteLeaftide", "report"); - hub.T11.Tick(Environment.TickCount64); - Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], -1L, "unknown before /aug (reported as -1)"); - Check.Eq(hub.T11.LastReported, T11Catalog.CounterNames.Length, "every counter is reported"); - - hub.OnChat("Advanced Augmentation Levels:"); - hub.OnChat("Item:2,400"); - hub.OnChat("Triune Weave: 5 (adds 5 to your aug counts)"); - hub.T11.Tick(Environment.TickCount64); - Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2400L, "Item: 2,400 reported"); - Check.Eq(FakeAiHub.Counters[(uint)T11Counter.TriuneWeave], 5L, "Triune Weave: 5 reported"); - - hub.State.T11.ItemAugsOverride = 2500; - hub.T11.Tick(Environment.TickCount64); - Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2500L, "the override replaces /aug's item count"); - hub.State.T11.ItemAugsOverride = -1; - hub.T11.Tick(Environment.TickCount64); - Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2400L, "auto again: /aug's count"); - - hub.OnLogout(); - hub.T11.Tick(Environment.TickCount64); - Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], -1L, "after logout: unknown again"); - } - - private static void Commands() - { - Check.True(RynthILTPlugin.IsIltVerb(new[] { "t11" }), "/ra t11 is RynthILT's (RynthAi passes it on)"); - Check.True(RynthILTPlugin.IsIltVerb(new[] { "t11", "augs", "5" }), "with its arguments"); - Check.True(RynthILTPlugin.IsIltVerb(new[] { "ub", "qblist" }) && RynthILTPlugin.IsIltVerb(new[] { "ub", "augs" }), - "ub-IT's /ub qblist and /ub augs (ACECustom commands RynthAi passes on) are RynthILT's"); - Check.False(RynthILTPlugin.IsIltVerb(new[] { "ub", "wear" }) || RynthILTPlugin.IsIltVerb(new[] { "ub" }), "no other /ub verb"); - - var hub = NewHub("InfiniteLeaftide", "cmd"); - FakeHost.Chat.Clear(); - hub.T11.HandleCommand(new[] { "augs", "3,000" }); - Check.Eq(hub.State.T11.ItemAugsOverride, 3000, "augs 3,000 fixes the override"); - Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 3000L, "and reports it at once"); - hub.T11.HandleCommand(new[] { "augs", "auto" }); - Check.Eq(hub.State.T11.ItemAugsOverride, -1, "augs auto clears it"); - FakeHost.Chat.Clear(); - hub.T11.HandleCommand(Array.Empty()); - Check.True(FakeHost.Chat.Any(l => l.Contains("=== T11 loot")), "no argument: the status"); - Check.True(FakeHost.Chat.Any(l => l.Contains("Item Augmentations") || l.Contains("unknown")), "lists the counters"); - FakeHost.Chat.Clear(); - hub.T11.HandleCommand(new[] { "augs", "-5" }); - Check.True(FakeHost.Chat.Any(l => l.Contains("Usage")), "a bad count: usage"); - } - - private static void DormantOffIlt() - { - var off = NewHub("Aeshnidae", "off"); - off.OnChat("Advanced Augmentation Levels:"); - off.OnChat("Item:2,400"); - for (int i = 0; i < 3; i++) off.Tick(); - Check.Eq(FakeAiHub.Counters.Count, 0, "off ILT: no counter is reported to RynthAi"); - Check.True(off.T11.Player.Get(T11Counter.ItemAugmentations) == null, "nor read"); - } - - private static void ImportsOverride() - { - string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Augger"); - Directory.CreateDirectory(legacy); - File.WriteAllText(Path.Combine(legacy, "Default.json"), "{ \"T11ItemAugsOverride\": 2750 }"); - var state = new IltHubState(); - Check.Eq(state.T11.ItemAugsOverride, -1, "automatic by default"); - IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Augger"); - Check.Eq(state.T11.ItemAugsOverride, 2750, "the RynthAi profile's override came over"); - } -} diff --git a/Tools/RynthILT.Tests/VaultedDungeonsTests.cs b/Tools/RynthILT.Tests/VaultedDungeonsTests.cs deleted file mode 100644 index a9c9a6e..0000000 --- a/Tools/RynthILT.Tests/VaultedDungeonsTests.cs +++ /dev/null @@ -1,527 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.Plugin.Shared; -using RynthCore.PluginSdk; -using RynthCore.RynthAiHostTests.Fakes; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// The Vaulted Dungeons keeper (Hub/IltVaultedDungeons.cs, Silentkelpie's, taken in with the owner's -// safety rules): ILT only, a master switch (RynthAi's setting, off by default) that gates everything, -// no resume of Active from the saved file, a recall that waits out combat / buffing, /rc quit once per -// activation and never while gated, and a no-kill timer that restarts on kills and captures. -// The clock, the master switch, RynthAi's activity and the gem use are the module's test seams. -internal static class VaultedDungeonsTests -{ - private const uint Player = 0x50000C01; - private const uint Quarry = 0x01F7; // dungeon 1: Tyrant's Quarry - private const uint Elsewhere = 0x0001; - private const string Luminance = "You've banked 1,234 Luminance."; - - public static void Register(Runner r) - { - r.Add("vaulted: not an ILT world -> inert (no tick work, no recall, no quit, a 'not available' reply)", NotIlt); - r.Add("vaulted: master off -> inert even with a saved Active, Auto Start and Kill Client", MasterOff); - r.Add("vaulted: master on + explicit start -> recalls at 1 s then every 5 s outside, stops inside; a saved Active is not resumed", ExplicitStartRecalls); - r.Add("vaulted: Auto Start On Arrival is honoured only with the master on", AutoStart); - r.Add("vaulted: Kill Client fires once per activation and restarts on luminance, a killing blow and a capture", QuitOnceAndResets); - r.Add("vaulted: Kill Client is never sent once the master goes off, even between the timer and the send", QuitNeverWhenGated); - r.Add("vaulted: a busy bot (combat, buffing, server wait, client busy) defers the recall; the warning keeps its cadence", BusyDefers); - r.Add("vaulted: turning the master off mid-run stops it at once and says so once; turning it on starts Off", MasterOffMidRun); - r.Add("vaulted: the tab and /ra hub open vaulted follow ILT + the master; settings file format kept", TabAndFile); - r.Add("vaulted: capture lines are the Pets tab's own success replies", CaptureLines); - r.Add("vaulted: settings go through the source-generated JSON context (NativeAOT has no reflection serializer)", SourceGeneratedContext); - } - - // ── Rig ────────────────────────────────────────────────────────────────── - - private sealed class Rig - { - public IltHubController Hub = null!; - public IltVaultedDungeons V = null!; - public string Dir = ""; - public long T = 1_000_000; - public bool Master; - public RynthAiActivity? Act = RynthAiActivity.None; - public int MasterCalls, AllowCalls = int.MaxValue; - public readonly List GemsUsed = new(); - public bool HasGem = true; - - public int Quits => FakeHost.ChatCommands.Count(c => c == "/rc quit"); - public int ChatCount(string part) => FakeHost.Chat.Count(c => c.Contains(part, StringComparison.OrdinalIgnoreCase)); - - public void Step(long ms) { T += ms; V.Tick(T); } - public void Inside() => FakeHost.PlayerPose = ((Quarry << 16) | 0x0100u, 0, 0, 0); - public void Outside() => FakeHost.PlayerPose = ((Elsewhere << 16) | 0x0100u, 0, 0, 0); - public string SettingsFile => Path.Combine(Dir, "VaultedDungeons", "settings.json"); - public void WriteSettings(string json) - { - Directory.CreateDirectory(Path.GetDirectoryName(SettingsFile)!); - File.WriteAllText(SettingsFile, json); - } - } - - private static Rig NewRig(string world, string folder, bool master, bool busyCalls = false) - { - FakeHost.Reset(); - FakeHost.WorldName = world; - FakeHost.BusyCalls = busyCalls; - var host = FakeHost.Create(Player); - var rig = new Rig { Master = master, Dir = Path.Combine(Program.TempRoot, folder) }; - Directory.CreateDirectory(rig.Dir); - rig.Hub = new IltHubController(host, rig.Dir, new IltSettings(), new RynthAiClient(host)); - rig.V = rig.Hub.VaultedDungeons; - rig.V.Clock = () => rig.T; - rig.V.MasterEnabled = () => { rig.MasterCalls++; return rig.Master && rig.MasterCalls <= rig.AllowCalls; }; - rig.V.Activity = () => rig.Act; - rig.V.UseGem = name => { if (!rig.HasGem) return false; rig.GemsUsed.Add(name); return true; }; - rig.Outside(); - return rig; - } - - /// Dungeon 1 (Tyrant's Quarry), the primary gem, the given extras. "active": true is on disk to prove it is ignored. - private static string Settings(string extras = "") - => "{ \"active\": true, \"dungeon\": 1, \"gem\": 1" + (extras.Length > 0 ? ", " + extras : "") + " }"; - - // ── ILT only ───────────────────────────────────────────────────────────── - - private static void NotIlt() - { - var rig = NewRig("Aelrynth", "vd-notilt", master: true); - rig.WriteSettings(Settings("\"autoStart\": true, \"quit\": true, \"quitMinutes\": 1")); - string before = File.ReadAllText(rig.SettingsFile); - - rig.Outside(); - for (int i = 0; i < 20; i++) rig.Step(1000); - rig.Inside(); - for (int i = 0; i < 10; i++) rig.Step(30_000); - Check.False(rig.V.IsActive, "not running on another world, though the master is on and Auto Start was saved"); - Check.Eq(rig.GemsUsed.Count, 0, "no recall gem"); - Check.Eq(rig.Quits, 0, "no /rc quit"); - Check.Eq(FakeHost.ChatCommands.Count, 0, "no command of any kind (no /vt, /ub or /rc)"); - Check.Eq(rig.ChatCount("[Vaulted Dungeons]"), 0, "and not a word in chat"); - Check.Eq(File.ReadAllText(rig.SettingsFile), before, "the settings file wasn't even read or rewritten"); - - rig.V.HandleCommand(new[] { "on" }); - Check.False(rig.V.IsActive, "/ilt vaulted on is refused"); - Check.Eq(rig.ChatCount("Not available on this server"), 1, "with the 'not available on this server' reply"); - FakeHost.Chat.Clear(); - rig.V.HandleCommand(new[] { "status" }); - Check.Eq(rig.ChatCount("Not available on this server"), 1, "status says the same"); - Check.False(rig.Hub.TabShown(IltSection.VaultedDungeons), "no tab"); - Check.False(rig.Hub.SectionAvailable(IltSection.VaultedDungeons), "not available"); - - // The controller doesn't tick it either (and the module would refuse anyway). - rig.Hub.Tick(); - Check.Eq(rig.GemsUsed.Count, 0, "the controller's tick does nothing here"); - } - - // ── Master switch ──────────────────────────────────────────────────────── - - private static void MasterOff() - { - var rig = NewRig("InfiniteLeaftide", "vd-masteroff", master: false); - rig.WriteSettings(Settings("\"autoStart\": true, \"quit\": true, \"quitMinutes\": 1, \"disableMeta\": true")); - string before = File.ReadAllText(rig.SettingsFile); - - rig.Outside(); - for (int i = 0; i < 20; i++) rig.Step(1000); - rig.Inside(); - for (int i = 0; i < 10; i++) rig.Step(30_000); // five minutes inside: a one-minute Kill Client would have fired - Check.False(rig.V.IsActive, "off: a saved Active and Auto Start start nothing"); - Check.Eq(rig.GemsUsed.Count, 0, "no recall gem"); - Check.Eq(rig.Quits, 0, "no /rc quit"); - Check.Eq(FakeHost.ChatCommands.Count, 0, "no arrival commands (/vt opt set ...) either"); - Check.Eq(rig.ChatCount("[Vaulted Dungeons]"), 0, "silent"); - Check.Eq(File.ReadAllText(rig.SettingsFile), before, "settings untouched"); - Check.True(rig.Hub.Options.IsIltLikeWorld, "(it is an ILT world: the master switch is what holds it)"); - Check.False(rig.Hub.TabShown(IltSection.VaultedDungeons), "the tab is hidden"); - Check.False(rig.Hub.SectionAvailable(IltSection.VaultedDungeons), "and not available"); - - rig.V.HandleCommand(new[] { "on" }); - Check.False(rig.V.IsActive, "/ilt vaulted on is refused"); - Check.Eq(rig.ChatCount("Settings > Navigation"), 1, "and says where the switch is"); - rig.V.HandleCommand(new[] { "toggle" }); - Check.False(rig.V.IsActive, "toggle too"); - - // Through the controller, the real wiring: nothing either. - for (int i = 0; i < 5; i++) rig.Hub.Tick(); - Check.Eq(rig.GemsUsed.Count, 0, "the controller's tick does nothing while off"); - - // The lines that restart the timer are ignored too (nothing is running). - rig.V.OnChat(Luminance); - rig.V.OnKillNotification(); - Check.Eq(rig.Quits, 0, "still nothing"); - } - - // ── Recalls ────────────────────────────────────────────────────────────── - - private static void ExplicitStartRecalls() - { - var rig = NewRig("InfiniteLeaftide", "vd-recall", master: true); - rig.WriteSettings(Settings()); // "active": true on disk: ignored - rig.Outside(); - rig.Step(0); - Check.False(rig.V.IsActive, "a saved Active is not resumed after login"); - for (int i = 0; i < 10; i++) rig.Step(1000); - Check.Eq(rig.GemsUsed.Count, 0, "so nothing is recalled until the player starts it"); - - rig.V.HandleCommand(new[] { "on" }); - Check.True(rig.V.IsActive, "an explicit start"); - rig.Step(0); // first tick outside: the clock starts - rig.Step(500); - Check.Eq(rig.GemsUsed.Count, 0, "0.5 s out: too early"); - rig.Step(500); // 1 s - Check.Eq(rig.GemsUsed.Count, 1, "the first recall comes 1 s after leaving"); - Check.Eq(rig.GemsUsed[0], "Primary Portal Recall Gem", "the chosen gem"); - rig.Step(4000); - Check.Eq(rig.GemsUsed.Count, 1, "4 s later: not yet"); - rig.Step(1000); // 5 s since the last use - Check.Eq(rig.GemsUsed.Count, 2, "then every 5 s"); - rig.Step(5000); - Check.Eq(rig.GemsUsed.Count, 3, "again"); - - rig.Inside(); - rig.Step(1000); - for (int i = 0; i < 12; i++) rig.Step(1000); - Check.Eq(rig.GemsUsed.Count, 3, "inside the dungeon: no more gems"); - - FakeHost.Portaling = true; - rig.Outside(); - rig.Step(10_000); - Check.Eq(rig.GemsUsed.Count, 3, "portal space: nothing used"); - FakeHost.Portaling = false; - rig.Step(0); - rig.Step(1000); - Check.Eq(rig.GemsUsed.Count, 4, "out again: 1 s, then a recall"); - - rig.HasGem = false; - rig.Step(5000); - Check.Eq(rig.GemsUsed.Count, 4, "no gem in the pack: none used"); - Check.True(rig.ChatCount("No Primary Portal Recall Gem") >= 1, "and it says so"); - } - - private static void AutoStart() - { - // Master on: arriving in the chosen dungeon switches it on, and the arrival commands go out. - var on = NewRig("InfiniteLeaftide", "vd-auto-on", master: true); - on.WriteSettings(Settings("\"autoStart\": true, \"disableMeta\": true")); - on.Inside(); - on.Step(0); - Check.True(on.V.IsActive, "Auto Start On Arrival switches the keeper on (master on)"); - Check.True(FakeHost.ChatCommands.Contains("/vt opt set EnableMeta False"), "and runs the arrival commands"); - - // Auto Start off, master on: a relog inside does not resume a saved Active. - var manual = NewRig("InfiniteLeaftide", "vd-auto-off", master: true); - manual.WriteSettings(Settings("\"disableMeta\": true")); - manual.Inside(); - manual.Step(0); - Check.False(manual.V.IsActive, "no Auto Start: not resumed"); - Check.Eq(FakeHost.ChatCommands.Count, 0, "and the arrival commands wait for an Active keeper"); - - // Master off, Auto Start saved: nothing; then the master comes on while inside. - var gated = NewRig("InfiniteLeaftide", "vd-auto-gated", master: false); - gated.WriteSettings(Settings("\"autoStart\": true")); - gated.Inside(); - gated.Step(0); - Check.False(gated.V.IsActive, "master off: Auto Start does nothing"); - gated.Master = true; - gated.Step(1000); - Check.True(gated.V.IsActive, "with the master on, Auto Start (the player's own saved choice) applies"); - } - - // ── Kill Client ────────────────────────────────────────────────────────── - - private static Rig QuitRig(string folder, int minutes = 2) - { - var rig = NewRig("InfiniteLeaftide", folder, master: true); - rig.WriteSettings(Settings("\"quit\": true, \"quitMinutes\": " + minutes)); - rig.Inside(); - rig.Step(0); - rig.V.HandleCommand(new[] { "on" }); - rig.Step(0); // inside: the no-kill clock starts here - return rig; - } - - private static void QuitOnceAndResets() - { - // Luminance line. - var rig = QuitRig("vd-quit-lum"); - rig.Step(119_000); - Check.Eq(rig.Quits, 0, "just under 2 minutes: no quit"); - rig.V.OnChat(Luminance); - rig.Step(119_000); - Check.Eq(rig.Quits, 0, "the luminance line restarted the timer"); - rig.Step(2_000); - Check.Eq(rig.Quits, 1, "2 minutes after the last kill: /rc quit"); - for (int i = 0; i < 10; i++) rig.Step(60_000); - Check.Eq(rig.Quits, 1, "and only once"); - // A kill after the quit went out doesn't arm a second one (once per activation). - rig.V.OnChat(Luminance); - for (int i = 0; i < 10; i++) rig.Step(60_000); - Check.Eq(rig.Quits, 1, "still once"); - - // The player's own killing blow. - rig = QuitRig("vd-quit-kill"); - rig.Step(110_000); - rig.V.OnKillNotification(); - rig.Step(110_000); - Check.Eq(rig.Quits, 0, "a killing blow restarted the timer"); - rig.Step(15_000); - Check.Eq(rig.Quits, 1, "and it fires after the next idle stretch"); - - // A pet capture. - rig = QuitRig("vd-quit-capture"); - rig.Step(110_000); - rig.V.OnChat("You have successfully siphoned the essence of the Olthoi Warrior."); - rig.Step(110_000); - Check.Eq(rig.Quits, 0, "a capture restarted the timer"); - rig.V.OnChat("The echo resonates perfectly."); - rig.Step(110_000); - Check.Eq(rig.Quits, 0, "so does the other success reply"); - rig.Step(15_000); - Check.Eq(rig.Quits, 1, "then it fires"); - - // Lines that are not kills don't restart it. - rig = QuitRig("vd-quit-noise"); - rig.Step(110_000); - rig.V.OnChat("You hit the Olthoi Warrior for 50 points of damage."); - rig.V.OnChat("The essence is not ready yet."); - rig.V.OnChat("Bob says, \"You've banked 5 Luminance.\""); // a player's chat, not the system line - rig.Step(15_000); - Check.Eq(rig.Quits, 1, "damage lines, a refused capture and someone else's chat don't count"); - - // The minutes are the player's setting: 1 minute here. - rig = QuitRig("vd-quit-1m", minutes: 1); - rig.Step(59_000); - Check.Eq(rig.Quits, 0, "1 minute setting: not yet"); - rig.Step(2_000); - Check.Eq(rig.Quits, 1, "fires at 1 minute"); - - // Off -> on again is a new activation: one more quit may be sent. - rig.V.HandleCommand(new[] { "off" }); - rig.V.HandleCommand(new[] { "on" }); - rig.Step(0); - rig.Step(61_000); - Check.Eq(rig.Quits, 2, "a new activation gets its own single quit"); - } - - private static void QuitNeverWhenGated() - { - // The master goes off, the timer would have fired: nothing is sent, and it stopped. - var rig = QuitRig("vd-quit-gated"); - rig.Step(100_000); - rig.Master = false; - rig.Step(30_000); - Check.Eq(rig.Quits, 0, "master off before the timer: no /rc quit"); - Check.False(rig.V.IsActive, "and the keeper is off"); - rig.Step(600_000); - Check.Eq(rig.Quits, 0, "ever"); - - // The master goes off between the timer firing and the send (asked again right before sending). - rig = QuitRig("vd-quit-race"); - rig.Step(100_000); - rig.AllowCalls = rig.MasterCalls + 1; // true at the top of the next tick, false when it re-checks - rig.Step(21_000); // the timer fires in this tick - Check.Eq(rig.Quits, 0, "master off between the timer firing and the send: not sent"); - Check.False(rig.V.IsActive, "the keeper stopped"); - Check.Eq(rig.ChatCount("Stopped"), 1, "said once"); - - // Not an ILT world any more (the world name changes): same. - rig = QuitRig("vd-quit-world"); - rig.Step(100_000); - FakeHost.WorldName = "Aelrynth"; - rig.Step(30_000); - Check.Eq(rig.Quits, 0, "world no longer ILT: no /rc quit"); - Check.False(rig.V.IsActive, "stopped"); - - // Not Active: the timer has nothing to do (the player turned it off). - rig = QuitRig("vd-quit-off"); - rig.V.HandleCommand(new[] { "off" }); - for (int i = 0; i < 10; i++) rig.Step(60_000); - Check.Eq(rig.Quits, 0, "Off: no quit"); - } - - // ── Combat / buff guard ────────────────────────────────────────────────── - - private static void BusyDefers() - { - var rig = NewRig("InfiniteLeaftide", "vd-busy", master: true, busyCalls: true); - rig.WriteSettings(Settings()); - rig.Outside(); - rig.Step(0); - rig.V.HandleCommand(new[] { "on" }); - rig.Act = RynthAiActivity.MacroRunning | RynthAiActivity.Combat; - rig.Step(0); - rig.Step(1000); - rig.Step(4000); - Check.Eq(rig.GemsUsed.Count, 0, "in combat: the recall is deferred"); - Check.Eq(rig.ChatCount("Waiting to use the Primary Portal Recall Gem"), 1, "and says why, once"); - rig.Step(20_000); - Check.Eq(rig.ChatCount("Waiting to use"), 1, "no repeat inside the 30 s warning cadence"); - rig.Step(10_000); - Check.Eq(rig.ChatCount("Waiting to use"), 2, "the warning comes again after 30 s"); - Check.Eq(rig.GemsUsed.Count, 0, "still nothing used"); - - rig.Act = RynthAiActivity.MacroRunning; // clear - rig.Step(100); - Check.Eq(rig.GemsUsed.Count, 1, "the first clear tick recalls (it was due all along)"); - - // Buffing, the server wait, looting, salvaging, crafting and RynthAi not answering all defer too. - foreach (RynthAiActivity? busy in new RynthAiActivity?[] - { RynthAiActivity.Buffing, RynthAiActivity.ServerAction, RynthAiActivity.Looting, RynthAiActivity.Salvaging, RynthAiActivity.Crafting, null }) - { - int before = rig.GemsUsed.Count; - rig.Act = busy; - rig.Step(6000); - Check.Eq(rig.GemsUsed.Count, before, $"busy ({(busy.HasValue ? busy.Value.ToString() : "RynthAi not ready")}): deferred"); - rig.Act = RynthAiActivity.None; - rig.Step(100); - Check.Eq(rig.GemsUsed.Count, before + 1, "and used once it is clear"); - } - - // The client's own busy hourglass. - FakeHost.BusyStateValue = 1; - int n = rig.GemsUsed.Count; - rig.Step(6000); - Check.Eq(rig.GemsUsed.Count, n, "the client is busy: deferred"); - FakeHost.BusyStateValue = 0; - rig.Step(100); - Check.Eq(rig.GemsUsed.Count, n + 1, "used when it clears"); - - // Busy never blocks the Kill Client (it is not a game action that can be lost). - var q = NewRig("InfiniteLeaftide", "vd-busy-quit", master: true); - q.WriteSettings(Settings("\"quit\": true, \"quitMinutes\": 1")); - q.Inside(); - q.Step(0); - q.V.HandleCommand(new[] { "on" }); - q.Step(0); - q.Act = RynthAiActivity.Combat; - q.Step(61_000); - Check.Eq(q.Quits, 1, "a busy bot still gets its Kill Client"); - } - - // ── Master off mid-run ─────────────────────────────────────────────────── - - private static void MasterOffMidRun() - { - var rig = NewRig("InfiniteLeaftide", "vd-midrun", master: true); - rig.WriteSettings(Settings("\"quit\": true, \"quitMinutes\": 1")); - rig.Outside(); - rig.Step(0); - rig.V.HandleCommand(new[] { "on" }); - rig.Step(0); - rig.Step(1000); - Check.Eq(rig.GemsUsed.Count, 1, "running: a recall went out"); - - rig.Master = false; - rig.Step(10); - Check.False(rig.V.IsActive, "the master went off: stopped on that very tick"); - Check.Eq(rig.ChatCount("Stopped"), 1, "and it said so"); - for (int i = 0; i < 20; i++) rig.Step(5000); - Check.Eq(rig.GemsUsed.Count, 1, "no more recalls"); - Check.Eq(rig.ChatCount("Stopped"), 1, "and the notice wasn't repeated"); - Check.Eq(rig.Quits, 0, "no quit"); - - rig.Master = true; - rig.Step(10); - Check.False(rig.V.IsActive, "turned back on: it starts Off, nothing resumes by itself"); - rig.Step(10_000); - Check.Eq(rig.GemsUsed.Count, 1, "nothing recalled"); - rig.V.HandleCommand(new[] { "on" }); - rig.Step(0); - rig.Step(1000); - Check.Eq(rig.GemsUsed.Count, 2, "until the player starts it again"); - - // The Mini Remote button path (posted to the pump) re-checks the switch as well. - rig.V.HandleCommand(new[] { "off" }); - rig.Master = false; - rig.Hub.Context.Post(() => rig.V.HandleCommand(new[] { "on" })); - rig.Hub.Tick(); - Check.False(rig.V.IsActive, "an On click that lands after the switch went off is refused"); - } - - // ── Tab, commands, file ────────────────────────────────────────────────── - - private static void TabAndFile() - { - var rig = NewRig("InfiniteLeaftide", "vd-tab", master: true); - Check.True(rig.Hub.TabShown(IltSection.VaultedDungeons), "ILT + master on: the tab is shown"); - Check.True(IltSections.Tabs.Contains(IltSection.VaultedDungeons), "it is one of the tab-bar tabs"); - Check.True(IltSections.IsTab(IltSection.VaultedDungeons), "a Mini Remote tab"); - Check.Eq(IltSections.TabId(IltSection.VaultedDungeons), "vaulted", "tab id"); - Check.True(IltSections.TryParse("vaulted", out var s) && s == IltSection.VaultedDungeons, "/ra hub open vaulted parses"); - Check.True(IltSections.TryParse("vaulted-dungeons", out s) && s == IltSection.VaultedDungeons, "and the long names"); - Check.True(RynthCore.Plugin.RynthILT.RynthILTPlugin.IsIltVerb(new[] { "hub", "open", "vaulted" }), "RynthILT takes '/ra hub open vaulted'"); - rig.Master = false; - Check.False(rig.Hub.TabShown(IltSection.VaultedDungeons), "master off: hidden"); - - // The file: the format Silentkelpie's keeper wrote, kept. A start is saved. - rig = NewRig("InfiniteLeaftide", "vd-file", master: true); - rig.WriteSettings("""{ "dungeon": 3, "gem": 2, "quit": true, "quitMinutes": 7, "autoStart": false, "attackPower": 0.5 }"""); - rig.V.HandleCommand(new[] { "status" }); - Check.Eq(rig.ChatCount("dungeon=Wailing Cells, gem=Secondary Portal Recall Gem, kill-client=7m"), 1, "dungeon list and gem names as upstream"); - rig.V.HandleCommand(new[] { "on" }); - rig.Step(0); - string saved = File.ReadAllText(rig.SettingsFile); - Check.True(saved.Contains("\"active\": true") && saved.Contains("\"quitMinutes\": 7") && saved.Contains("\"dungeon\": 3"), - "saved in the same camelCase layout"); - - // A new session (relog) reads it back with Active Off. - var again = NewRig("InfiniteLeaftide", "vd-file", master: true); - FakeHost.Chat.Clear(); - again.V.HandleCommand(new[] { "status" }); - Check.True(again.ChatCount("Off — dungeon=Wailing Cells") == 1 && !again.V.IsActive, "the next session starts Off, with the same choices"); - } - - // The NativeAOT build (what ships) turns reflection-based System.Text.Json off, so the keeper's - // settings must use IltVaultedDungeonsJsonContext. This project runs on the normal runtime where - // reflection would still work, so assert the generated metadata exists and that the file layout - // is what the context (not an options object) produces. - private static void SourceGeneratedContext() - { - var ctx = IltVaultedDungeonsJsonContext.Default; - Check.True(ctx.Cfg != null, "the context has metadata for the settings type (IltVaultedDungeonsJsonContext.Default.Cfg)"); - Check.True(ctx.GetTypeInfo(typeof(IltVaultedDungeons.Cfg)) != null, "and resolves it by type"); - - var cfg = new IltVaultedDungeons.Cfg - { - Active = true, Dungeon = 3, Gem = 2, Quit = true, QuitMinutes = 7, ShowInDungeon = true, - AutoStart = true, DisableMeta = true, DisableNav = false, RepeatAttack = true, SetPower = true, AttackPower = 0.5f, - }; - string json = System.Text.Json.JsonSerializer.Serialize(cfg, ctx.Cfg); - Check.True(json.Contains("\"active\": true") && json.Contains("\"quitMinutes\": 7") && json.Contains("\"attackPower\": 0.5"), - "serializes indented with camelCase names"); - Check.True(json.Contains("\n"), "indented"); - - var back = System.Text.Json.JsonSerializer.Deserialize(json, ctx.Cfg); - Check.True(back != null, "round-trips"); - Check.True(back!.Active && back.Dungeon == 3 && back.Gem == 2 && back.Quit && back.QuitMinutes == 7 && back.ShowInDungeon - && back.AutoStart && back.DisableMeta && !back.DisableNav && back.RepeatAttack && back.SetPower && back.AttackPower == 0.5f, - "every field survives"); - - // The shape of the file Silentkelpie's keeper wrote (camelCase, partial) still reads. - var upstream = System.Text.Json.JsonSerializer.Deserialize( - """{ "dungeon": 2, "gem": 1, "quit": true, "quitMinutes": 5 }""", ctx.Cfg); - Check.True(upstream != null && upstream.Dungeon == 2 && upstream.Gem == 1 && upstream.Quit && upstream.QuitMinutes == 5 && !upstream.Active, - "a partial upstream file reads, missing fields keep their defaults"); - - bool threw = false; - try { System.Text.Json.JsonSerializer.Deserialize("{ not json", ctx.Cfg); } catch (System.Text.Json.JsonException) { threw = true; } - Check.True(threw, "a corrupt file still throws, which the keeper's bad-file copy relies on"); - } - - private static void CaptureLines() - { - Check.True(PetCaptureLines.IsSuccess("You have successfully siphoned the essence."), "siphoned"); - Check.True(PetCaptureLines.IsSuccess("The echo resonates perfectly."), "echo"); - Check.True(PetCaptureLines.IsSuccess("The essence is captured!"), "captured"); - Check.False(PetCaptureLines.IsSuccess("The creature is too strong to be siphoned."), "a refusal is not a success"); - Check.False(PetCaptureLines.IsSuccess("siphon failed"), "nor a failure"); - Check.False(PetCaptureLines.IsSuccess(""), "empty"); - } -} diff --git a/Tools/RynthILT.Tests/VaultedSwitchTests.cs b/Tools/RynthILT.Tests/VaultedSwitchTests.cs deleted file mode 100644 index bf19e76..0000000 --- a/Tools/RynthILT.Tests/VaultedSwitchTests.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System; -using System.IO; -using RynthCore.Plugin.RynthILT.Hub; -using RynthCore.Plugin.Shared; -using RynthCore.RynthAiHostTests.Fakes; -using RynthCore.RynthAiTests.Harness; - -namespace RynthILT.Tests; - -// The Vaulted Dungeons keeper's master switch moved from RynthAi's profile to RynthILT on 2026-10-20 -// (IltHubState.VaultedDungeonsEnabled, the ILT settings view). RynthAi mirrors it into the engine's -// Settings > Navigation row through RynthILT.Hub GetSetting / SetSetting, which offer it on ILT only. -internal static class VaultedSwitchTests -{ - public static void Register(Runner r) - { - r.Add("vaulted switch: RynthILT's own (off by default), what the keeper reads, offered to the engine row on ILT only", OwnSwitch); - r.Add("migration: the RynthAi profile's Vaulted Dungeons switch comes over once", ImportsSwitch); - } - - private static IltHubController NewHub(string world, string folder) - { - FakeHost.Reset(); - FakeHost.WorldName = world; - var host = FakeHost.Create(0x50000C01); - string dir = Path.Combine(Program.TempRoot, "vswitch-" + folder); - if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); - Directory.CreateDirectory(dir); - var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host)); - hub.OnLoginComplete("Vaulter", forceFromMigration: false); - return hub; - } - - private static void OwnSwitch() - { - var hub = NewHub("InfiniteLeaftide", "own"); - Check.False(hub.State.VaultedDungeonsEnabled, "off by default"); - Check.False(hub.VaultedDungeons.MasterEnabled(), "the keeper reads RynthILT's own switch (no RynthAi needed)"); - Check.False(hub.SectionAvailable(IltSection.VaultedDungeons), "no tab while off"); - Check.Eq(hub.GetSetting(RynthIltHub.SettingVaultedDungeons), 0, "offered to the engine row: off"); - Check.True(hub.SetSetting(RynthIltHub.SettingVaultedDungeons, 1), "the engine row (through RynthAi) sets it"); - Check.True(hub.State.VaultedDungeonsEnabled && hub.VaultedDungeons.MasterEnabled(), "on"); - Check.True(hub.SectionAvailable(IltSection.VaultedDungeons), "the tab shows on ILT"); - Check.Eq(hub.GetSetting("no-such-setting"), -1, "an unknown key isn't offered"); - Check.False(hub.SetSetting("no-such-setting", 1), "nor taken"); - - var off = NewHub("Aeshnidae", "off"); - Check.Eq(off.GetSetting(RynthIltHub.SettingVaultedDungeons), -1, "off ILT: not offered (the engine row hides)"); - } - - private static void ImportsSwitch() - { - string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Vaulter"); - Directory.CreateDirectory(legacy); - File.WriteAllText(Path.Combine(legacy, "Default.json"), "{ \"EnableVaultedDungeons\": true }"); - var state = new IltHubState(); - var lines = IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Vaulter"); - Check.True(state.VaultedDungeonsEnabled, "on in the RynthAi profile: on here"); - Check.True(lines.Exists(l => l.Contains("Vaulted Dungeons master switch on")), "logged"); - state.VaultedDungeonsEnabled = false; - IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Vaulter"); - Check.False(state.VaultedDungeonsEnabled, "copied once: RynthILT's later change stays"); - } -} diff --git a/Tools/RynthInventory.Tests/Program.cs b/Tools/RynthInventory.Tests/Program.cs index 0f9496f..ccb3a75 100644 --- a/Tools/RynthInventory.Tests/Program.cs +++ b/Tools/RynthInventory.Tests/Program.cs @@ -64,8 +64,7 @@ namespace RynthInventory.Tests Run("scheduler: unchanged content is not rewritten", SchedulerUnchanged); Run("window display lists parse in the engine", Pages); Run("window events", Events); - Run("banking: roster, totals and amounts", BankRosterTests); - Run("banking: the tab draws and sends RynthILT's verbs", BankingTab); + Run("banking: no Banking tab (it is RynthILT's own, 2026-10-21)", NoBankingTab); Run("storage from other plugins (StorageFeed)", StorageFeedTests); } finally @@ -635,101 +634,31 @@ namespace RynthInventory.Tests ParseAll(host, "after forget", out _); } - // ── Banking (the Mini Remote's Banking tab moved here 2026-10-13) ─── + // ── Banking: RynthILT's own tab since 2026-10-21 ─────────────────────── - /// RynthILT's bank JSON for the sample index: Buffy (here) and Ghost (another account, no inventory file). - private const string BankJson = "{\"available\":true,\"enabled\":1,\"world\":\"Aelrynth\",\"character\":\"Buffy\"," - + "\"characters\":[{\"name\":\"Buffy\",\"current\":true,\"pyreals\":100,\"luminance\":2000,\"legendaryKeys\":1,\"mythicalKeys\":0," - + "\"enlightenedCoins\":3,\"weaklyEnlightenedCoins\":0,\"prestigeCoins\":0,\"updated\":\"2026-10-03T11:00:00Z\"}," - + "{\"name\":\"Ghost\",\"current\":false,\"pyreals\":50,\"luminance\":0,\"legendaryKeys\":2,\"mythicalKeys\":1," - + "\"enlightenedCoins\":0,\"weaklyEnlightenedCoins\":4,\"prestigeCoins\":5,\"updated\":\"2026-10-01T11:00:00Z\"}]," - + "\"deposits\":[\"Everything\",\"Pyreals\"],\"withdrawals\":[{\"label\":\"Pyreals\",\"notes\":false},{\"label\":\"Trade notes\",\"notes\":true}]," - + "\"transfers\":[{\"label\":\"Pyreals\",\"notes\":false}],\"notes\":[{\"label\":\"MMD\",\"value\":250000}]," - + "\"result\":\"Deposited everything.\",\"transactions\":[{\"when\":\"2026-10-03 11:30\",\"type\":\"Sent\",\"amount\":10,\"currency\":\"Pyreals\",\"player\":\"Willow\"}]}"; - - private static void BankRosterTests() + /// + /// Every character's Infinite Leaftide bank was a tab of this window (SilentKelpie's, reading RynthILT's + /// data); it moved to RynthILT's Banking tab with its tests (RynthILT.Tests BankRosterTests). The window + /// has its two pages on every world, and RynthInventory reads nothing of RynthILT's. + /// + private static void NoBankingTab() { - InventoryIndex index = SampleIndex(out _); - var bank = RynthCore.Plugin.Shared.IltBankView.Parse(BankJson); - List roster = BankRoster.Build(bank, index); - Eq(string.Join(",", roster.Select(e => e.Name)), "Buffy,Ghost,Willow", "you first, then by name; Conquest's characters left out"); - Check(roster[0].Current && roster[0].Bank != null && roster[0].Account == "tom", "Buffy: RynthILT's balance and the inventory's account"); - Check(roster[1].Bank != null && roster[1].Account == "", "Ghost: only RynthILT knows it (another account on this PC)"); - Check(roster[2].Bank == null && roster[2].Account == "tom", "Willow: in the inventory, no bank read yet"); - var total = BankRoster.Totals(roster); - Check(total.Pyreals == 150 && total.Luminance == 2000 && total.LegendaryKeys == 3 && total.PrestigeCoins == 5, "totals add every balance"); + const System.Reflection.BindingFlags All = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static + | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic; + foreach (string field in new[] { "IltData", "Bank", "BankCommand" }) + Check(typeof(InventoryContext).GetField(field, All) == null, "InventoryContext has no " + field); + Check(typeof(InventoryView).GetField("TabBanking", All) == null && typeof(InventoryView).GetMethod("ShowBanking", All) == null, "no Banking tab"); + var iltTypes = typeof(InventoryView).Assembly.GetTypes().Where(t => t.Name.StartsWith("Ilt", StringComparison.Ordinal) + || t.Name.StartsWith("RynthIlt", StringComparison.Ordinal) || t.Name.StartsWith("BankRoster", StringComparison.Ordinal)).Select(t => t.Name).ToList(); + Check(iltTypes.Count == 0, "no RynthILT reader or bank roster in RynthInventory: " + string.Join(",", iltTypes)); - Eq(BankRoster.Build(RynthCore.Plugin.Shared.IltBankView.None, null).Count, 0, "nothing without RynthILT or the index"); - var noWorld = RynthCore.Plugin.Shared.IltBankView.Parse("{\"available\":true,\"characters\":[]}"); - Eq(string.Join(",", BankRoster.Build(noWorld, index).Select(e => e.Name)), "Buffy,Willow", "no world named: the server you're on"); - - Eq(BankRoster.ParseAmount("1,000"), 1000L, "commas allowed"); - Eq(BankRoster.ParseAmount(" 25 "), 25L, "spaces trimmed"); - foreach (string bad in new[] { "", "0", "-5", "1.5", "abc", "1e6" }) - Eq(BankRoster.ParseAmount(bad), 0L, $"'{bad}' isn't an amount"); - } - - private static void BankingTab() - { InventoryContext c = Context(false); - var sent = new List(); - c.BankCommand = v => { sent.Add(v); return true; }; var view = new InventoryView(c); var host = new UiHost(); UiWindow w = host.Add(new UiWindow("RynthInventory/Main", "Global Inventory") { Visible = true }); - - // Without RynthILT the tab button stays hidden; /ginv bank still opens it and says why. Draw(w, view); - Check(!BodyText(w).Contains("###tab.bank"), "no Banking button without RynthILT"); - view.ShowBanking(); - Draw(w, view); - Check(BodyText(w).Contains("Load RynthILT"), "asked for: says RynthILT is needed"); - w.MarkSubmitted(true); - - c.Bank = RynthCore.Plugin.Shared.IltBankView.Parse(BankJson); - view.Tab = InventoryView.TabSearch; - Draw(w, view); - Check(BodyText(w).Contains("###tab.bank"), "the Banking button shows on an ILT world"); - Apply(host, Event(1, 1, w.Hash, w.KeyOf("tab.bank"), new byte[] { 1, 0 })); - Check(view.Tab == InventoryView.TabBanking, "a click opens it"); - Draw(w, view); - ParseAll(host, "banking tab", out int ops); string body = BodyText(w); - Check(ops > 5 && ops <= 1500, $"banking tab: {ops} ops"); - Check(body.Contains("Buffy (you)") && body.Contains("Ghost") && body.Contains("Willow") && !body.Contains("Spike"), - "every character on this server, none from another"); - Check(body.Contains("not read yet"), "a character without a balance says so"); - Check(body.Contains("150") && body.Contains("Deposited everything."), "the total and RynthILT's last reply"); - - Apply(host, Event(1, 2, w.Hash, w.KeyOf("b.dep.go"), new byte[] { 1, 0 })); - Eq(sent.LastOrDefault(), "deposit 0", "Deposit sends the chosen deposit"); - - Apply(host, Event(5, 3, w.Hash, w.KeyOf("b.wd.amt"), TextPayload("5"))); - Draw(w, view); - Apply(host, Event(1, 4, w.Hash, w.KeyOf("b.wd.go"), new byte[] { 1, 0 })); - Eq(sent.LastOrDefault(), "withdraw 0 5 0", "Withdraw sends currency, amount and note"); - - // A transfer asks first; only "Yes, send" sends it. - Apply(host, Event(5, 5, w.Hash, w.KeyOf("b.tx.amt"), TextPayload("1,000"))); - Apply(host, Event(5, 6, w.Hash, w.KeyOf("b.tx.to"), TextPayload("Willow"))); - Draw(w, view); - int before = sent.Count; - Apply(host, Event(1, 7, w.Hash, w.KeyOf("b.tx.go"), new byte[] { 1, 0 })); - Check(sent.Count == before, "one click doesn't transfer"); - Draw(w, view); - Check(BodyText(w).Contains("Send 1,000 Pyreals to Willow?"), "it asks, naming amount and recipient"); - Apply(host, Event(1, 8, w.Hash, w.KeyOf("b.tx.yes"), new byte[] { 1, 0 })); - Eq(sent.LastOrDefault(), "transfer 0 1000 0 Willow", "confirmed: the transfer verb"); - - // A bad amount is refused here, nothing sent. - Apply(host, Event(5, 9, w.Hash, w.KeyOf("b.wd.amt"), TextPayload("lots"))); - Draw(w, view); - before = sent.Count; - Apply(host, Event(1, 10, w.Hash, w.KeyOf("b.wd.go"), new byte[] { 1, 0 })); - Check(sent.Count == before, "a bad amount isn't sent"); - Draw(w, view); - Check(BodyText(w).Contains("Type a whole number"), "and it says why"); - ParseAll(host, "banking after actions", out _); + Check(!body.Contains("###tab.bank") && body.Contains("###tab.search") && body.Contains("###tab.chars"), "Search and Characters, no Banking button"); } // ── Helpers ───────────────────────────────────────────────────────── diff --git a/Tools/RynthInventory.Tests/RynthInventory.Tests.csproj b/Tools/RynthInventory.Tests/RynthInventory.Tests.csproj index f97d7eb..d6f2029 100644 --- a/Tools/RynthInventory.Tests/RynthInventory.Tests.csproj +++ b/Tools/RynthInventory.Tests/RynthInventory.Tests.csproj @@ -31,8 +31,6 @@ - - diff --git a/Tools/RynthNet.Tests/Program.cs b/Tools/RynthNet.Tests/Program.cs new file mode 100644 index 0000000..4cd2d76 --- /dev/null +++ b/Tools/RynthNet.Tests/Program.cs @@ -0,0 +1,254 @@ +using RynthCore.Plugin.RynthNet.Characters; + +namespace RynthNet.Tests; + +/// +/// RynthNet's Characters window (moved from RynthCore 2026-10-21): the model (snapshot parsing, +/// where another character is from you, what it is doing, the row order; these checks were +/// RynthCore's tools/CharactersPanelTests), the rows built from a fake game, the Atlas names, +/// the manifest RynthCore hosts the window from, and the icon list against the engine's. +/// +internal static partial class Program +{ + private static int _checks, _failed; + + private static int Main() + { + ParsesCurrentSnapshot(); + ParsesOlderEntries(); + RejectsBadJson(); + DistanceSameLandblock(); + DistanceAcrossLandblocks(); + DungeonRules(); + SurfaceBuildings(); + CoordsText(); + CompassPoints(); + States(); + Stale(); + StableOrder(); + Vitals(); + WindowChecks(); + + Console.WriteLine($"{_checks} checks, {_failed} failed"); + return _failed == 0 ? 0 : 1; + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine("FAIL: " + what); + } + + private static bool Near(double a, double b, double tol = 0.01) => Math.Abs(a - b) <= tol; + + // RynthNet 0.1.1's shape: id and cmode in the status, RynthAi's bot object, age after status. + private const string Current = """ + {"version":"0.1.1","online":true,"node":"n1","char":"Drakkon","world":"Aelrynth","login":true,"tags":["main"], + "acceptRemote":true,"clients":[ + {"node":"n2","pid":4242,"char":"Zed Healer","world":"Aelrynth","login":true,"tags":["heal","box"],"rtt":3, + "status":{"hp":300,"hpMax":400,"st":150,"stMax":200,"mp":50,"mpMax":500,"cell":2847146009,"x":40.5,"y":50.25,"z":12.0, + "ns":42.1,"ew":33.3,"heading":90.0,"portal":false,"busy":0,"vitae":1.0,"id":1342177281,"cmode":2, + "bot":{"macro":true,"action":"Combat","state":"Default","combat":true}},"age":420}, + {"node":"n3","pid":5151,"char":"Alpha","world":"Aelrynth","login":true,"tags":[],"rtt":2,"status":null} + ]} + """; + + private static void ParsesCurrentSnapshot() + { + NetCharSnapshot? s = CharactersModel.Parse(Current); + Check(s != null, "current snapshot parses"); + if (s == null) return; + Check(s.Online && s.Version == "0.1.1" && s.MyName == "Drakkon" && s.MyWorld == "Aelrynth", "snapshot header"); + Check(s.Clients.Count == 2, "two clients"); + NetCharEntry z = s.Clients[0]; + Check(z.Name == "Zed Healer" && z.Pid == 4242 && z.World == "Aelrynth" && z.LoggedIn, "client identity"); + Check(z.Tags.Length == 2 && z.Tags[0] == "heal", "client tags"); + Check(z.HasStatus && z.AgeMs == 420, "status age"); + Check(z.HasVitals && z.Hp == 300 && z.HpMax == 400 && z.St == 150 && z.StMax == 200 && z.Mp == 50 && z.MpMax == 500, "vitals"); + Check(z.HasPose && z.Cell == 2847146009u && Near(z.X, 40.5) && Near(z.Y, 50.25) && Near(z.Z, 12), "pose"); + Check(z.HasCoords && Near(z.Ns, 42.1) && Near(z.Ew, 33.3), "coords"); + Check(z.Id == 1342177281u && z.CombatMode == 2, "id and cmode (0.1.1)"); + Check(z.HasBot && z.Macro && z.Action == "Combat", "bot state"); + NetCharEntry a = s.Clients[1]; + Check(a.LoggedIn && !a.HasStatus && !a.HasVitals && !a.HasPose && a.AgeMs == -1, "null status"); + Check(CharactersModel.State(a).Kind == CharStateKind.NoStatus, "null status reads 'no status yet'"); + } + + private static void ParsesOlderEntries() + { + // RynthNet 0.1.0 (no id / cmode), a client without RynthAi (no bot), one at character + // select (no char, status {} sent as null), and an entry with odd types. + const string old = """ + {"online":true,"char":"Me","world":"W","clients":[ + {"node":"a","pid":1,"char":"Old","world":"W","login":true,"tags":[],"rtt":-1, + "status":{"hp":10,"hpMax":20,"st":5,"stMax":5,"mp":0,"mpMax":0,"cell":16777217,"x":1,"y":2,"z":3},"age":100}, + {"node":"b","pid":2,"char":"","world":"","login":false,"tags":[],"rtt":5,"status":null}, + {"node":"c","pid":3,"char":"Odd","login":true,"tags":"notarray","status":{"hp":"lots","cell":0}} + ]} + """; + NetCharSnapshot? s = CharactersModel.Parse(old); + Check(s != null && s.Clients.Count == 3, "old snapshot parses"); + if (s == null || s.Clients.Count != 3) return; + NetCharEntry o = s.Clients[0]; + Check(o.HasVitals && o.Hp == 10 && o.HpMax == 20, "old vitals"); + Check(o.Id == 0 && o.CombatMode == 0 && !o.HasBot, "old entry: no id, no cmode, no bot"); + Check(o.HasPose && o.Cell == 0x01000001u, "old pose"); + Check(!o.HasCoords, "no ns/ew -> no coords"); + Check(CharactersModel.State(o) == ("idle", CharStateKind.Idle), "no bot, peace -> idle"); + NetCharEntry b = s.Clients[1]; + Check(!b.LoggedIn && CharactersModel.State(b).Kind == CharStateKind.LoggedOut, "character select -> logged out"); + NetCharEntry c = s.Clients[2]; + Check(c.Tags.Length == 0 && !c.HasVitals && !c.HasPose && c.World == "", "wrong types are ignored, cell 0 is no pose"); + Check(CharactersModel.Parse("{\"online\":false,\"clients\":[]}") is { Online: false, Clients.Count: 0 }, "RynthNet's fallback string"); + Check(CharactersModel.Parse("{\"online\":false,\"offline\":\"pipe busy\",\"version\":\"0.1.1\"}") is { Offline: "pipe busy" }, "offline reason"); + } + + private static void RejectsBadJson() + { + Check(CharactersModel.Parse(null) == null, "null"); + Check(CharactersModel.Parse("") == null, "empty"); + Check(CharactersModel.Parse("{\"clients\":[") == null, "truncated"); + Check(CharactersModel.Parse("[1,2]") == null, "array root"); + } + + private const uint Outdoor = 0xA9B40001; // landblock A9B4, outdoor cell 1 + + private static void DistanceSameLandblock() + { + CharPlace p = CharactersModel.Locate(Outdoor, 10, 10, 0, Outdoor, 40, 50, 0, null, null); + Check(p.Measured && Near(p.Distance, 50), "3-4-5 distance"); + Check(Near(p.Bearing, 36.87, 0.05) && p.Compass == "NE", "bearing NE"); + Check(p.DistanceText == "50 yd", "distance text"); + Check(p.Location == CharactersModel.Coords(Outdoor, 40, 50), "outdoor location is map coords"); + CharPlace up = CharactersModel.Locate(Outdoor, 10, 10, 0, Outdoor, 10, 10, 20, null, null); + Check(up.Measured && Near(up.Distance, 20) && up.Compass == "here", "straight above: here, 3D distance"); + } + + private static void DistanceAcrossLandblocks() + { + CharPlace east = CharactersModel.Locate(Outdoor, 10, 10, 0, 0xAAB40001, 10, 10, 0, null, null); + Check(east.Measured && Near(east.Distance, 192) && east.Compass == "E", "one landblock east"); + CharPlace north = CharactersModel.Locate(Outdoor, 10, 10, 0, 0xA9B50001, 10, 10, 0, null, null); + Check(north.Measured && Near(north.Distance, 192) && north.Compass == "N", "one landblock north"); + CharPlace sw = CharactersModel.Locate(Outdoor, 100, 100, 0, 0xA8B30001, 100, 100, 0, null, null); + Check(sw.Measured && Near(sw.Distance, 192 * Math.Sqrt(2), 0.1) && sw.Compass == "SW", "diagonal south-west"); + CharPlace far = CharactersModel.Locate(Outdoor, 0, 0, 0, 0x10100001, 0, 0, 0, null, null); + Check(far.Measured && far.Distance > 10000, "far across the map is still a distance"); + } + + private static void DungeonRules() + { + Func names = lb => lb == 0x01D9 ? "Hive" : ""; + const uint dungeonA = 0x01D90105, dungeonA2 = 0x01D90142, dungeonB = 0x02AB0110; + CharPlace same = CharactersModel.Locate(dungeonA, 10, 10, -6, dungeonA2, 10, 30, -6, null, names); + Check(same.Measured && Near(same.Distance, 20) && same.Compass == "N", "same dungeon landblock: measured"); + Check(same.Location == "Hive", "dungeon location is its name"); + CharPlace fromOutside = CharactersModel.Locate(Outdoor, 10, 10, 0, dungeonA, 10, 10, 0, null, names); + Check(!fromOutside.Measured && fromOutside.Location == "Hive" && fromOutside.DistanceText == "", "outdoors -> dungeon: elsewhere"); + Check(float.IsPositiveInfinity(fromOutside.Distance) && float.IsNaN(fromOutside.Bearing), "elsewhere has no distance or bearing"); + CharPlace other = CharactersModel.Locate(dungeonA, 0, 0, 0, dungeonB, 0, 0, 0, null, names); + Check(!other.Measured && other.Location == "dungeon LB 02AB", "another, unnamed dungeon"); + CharPlace outFromDungeon = CharactersModel.Locate(dungeonA, 0, 0, 0, Outdoor, 12, 12, 0, null, names); + Check(!outFromDungeon.Measured && outFromDungeon.Location == "42.1N 33.3E", "dungeon -> outdoors: elsewhere with coords"); + CharPlace noPose = CharactersModel.Locate(0, 0, 0, 0, Outdoor, 12, 12, 0, null, null); + Check(!noPose.Measured && noPose.Location == "42.1N 33.3E", "no own pose: location only"); + } + + private static void SurfaceBuildings() + { + // An indoor cell of a landblock the caller knows is overworld (a cottage): same space as outdoors. + const uint cottage = 0xAAB40102; + Func over = lb => lb == 0xAAB4; + CharPlace p = CharactersModel.Locate(Outdoor, 10, 10, 0, cottage, 10, 10, 0, over, null); + Check(p.Measured && Near(p.Distance, 192) && p.Compass == "E", "surface building next door: measured"); + Check(p.Location == CharactersModel.Coords(cottage, 10, 10), "surface building location is coords"); + CharPlace q = CharactersModel.Locate(Outdoor, 10, 10, 0, cottage, 10, 10, 0, null, null); + Check(!q.Measured, "unknown indoor landblock counts as a dungeon"); + CharPlace r = CharactersModel.Locate(cottage, 10, 10, 0, Outdoor, 10, 10, 0, over, null); + Check(r.Measured && r.Compass == "W", "from inside the building out"); + } + + private static void CoordsText() + { + Check(CharactersModel.Coords(Outdoor, 12, 12) == "42.1N 33.3E", "Coords NE quadrant"); + Check(CharactersModel.Coords(0x10100001, 12, 12) == "89.1S 89.1W", "Coords SW quadrant"); + Check(CharactersModel.CoordsText(-0.04, 0.04) == "0.0S 0.0E", "near zero keeps its sign letter"); + } + + private static void CompassPoints() + { + (float b, string c)[] cases = + { + (0, "N"), (22.4f, "N"), (22.6f, "NE"), (44, "NE"), (90, "E"), (135, "SE"), (180, "S"), + (225, "SW"), (270, "W"), (315, "NW"), (337.4f, "NW"), (337.6f, "N"), (359, "N"), (-90, "W"), (450, "E"), + }; + foreach (var (b, c) in cases) + Check(CharactersModel.Compass(b) == c, $"compass {b} -> {c} (got {CharactersModel.Compass(b)})"); + } + + private static NetCharEntry Entry(string name = "A", bool macro = false, string action = "", int cmode = 0, uint hp = 10, + bool bot = true, bool portal = false) => new() + { + Name = name, LoggedIn = true, HasStatus = true, AgeMs = 100, + HasVitals = true, Hp = hp, HpMax = 20, St = 1, StMax = 1, Mp = 1, MpMax = 1, + HasBot = bot, Macro = macro, Action = action, CombatMode = cmode, Portal = portal, + }; + + private static void States() + { + Check(CharactersModel.State(Entry(hp: 0, macro: true)) == ("dead", CharStateKind.Dead), "hp 0 -> dead (before botting)"); + Check(CharactersModel.State(Entry(portal: true, macro: true)) == ("portal space", CharStateKind.Portal), "portal space"); + Check(CharactersModel.State(Entry(macro: true, action: "Combat")) == ("botting: fighting", CharStateKind.Fighting), "fighting"); + Check(CharactersModel.State(Entry(macro: true, action: "Navigating")) == ("botting: navigating", CharStateKind.Botting), "navigating"); + Check(CharactersModel.State(Entry(macro: true, action: "Default")) == ("botting", CharStateKind.Botting), "botting, default"); + Check(CharactersModel.State(Entry(macro: false, cmode: 2)) == ("idle, melee", CharStateKind.CombatMode), "macro off, melee stance"); + Check(CharactersModel.State(Entry(macro: false, cmode: 8)) == ("idle, magic", CharStateKind.CombatMode), "macro off, magic stance"); + Check(CharactersModel.State(Entry(macro: false, cmode: 1)) == ("idle (macro off)", CharStateKind.Idle), "macro off, peace"); + Check(CharactersModel.State(Entry(bot: false)) == ("idle", CharStateKind.Idle), "no RynthAi"); + var maxZero = Entry(hp: 0); + maxZero.HpMax = 0; + Check(CharactersModel.State(maxZero).Kind != CharStateKind.Dead, "0/0 vitals (not known yet) isn't dead"); + } + + private static void Stale() + { + var e = Entry(); + e.AgeMs = 1000; + Check(!CharactersModel.IsStale(e), "1 s old: fresh"); + e.AgeMs = 6000; + Check(CharactersModel.IsStale(e), "6 s old: stale"); + e.LoggedIn = false; + Check(!CharactersModel.IsStale(e), "logged out: not stale"); + } + + private static void StableOrder() + { + var zed = Entry("zed"); zed.Cell = Outdoor; zed.X = 1; + var alpha = Entry("Alpha"); alpha.Cell = Outdoor; alpha.X = 100; + var bob = Entry("bob"); bob.Cell = 0x01D90105; + var nobody = new NetCharEntry { Name = "", LoggedIn = false, Pid = 7 }; + var nobody2 = new NetCharEntry { Name = "", LoggedIn = false, Pid = 3 }; + var list = new List { nobody, zed, bob, nobody2, alpha }; + list.Sort(CharactersModel.CompareRows); + Check(string.Join(",", list.Select(e => e.Name.Length > 0 ? e.Name : "pid" + e.Pid)) == "Alpha,bob,zed,pid3,pid7", + "alphabetical (case-insensitive), clients without a character last by pid"); + // Moving characters around never changes the order. + alpha.X = 0; zed.X = 500; bob.Cell = Outdoor; + list.Sort(CharactersModel.CompareRows); + Check(list[0] == alpha && list[1] == bob && list[2] == zed, "positions don't reorder rows"); + // A new character slots in; a gone one just disappears. + list.Add(Entry("Carl")); + list.Remove(bob); + list.Sort(CharactersModel.CompareRows); + Check(string.Join(",", list.Take(3).Select(e => e.Name)) == "Alpha,Carl,zed", "new character slots in alphabetically"); + } + + private static void Vitals() + { + Check(CharactersModel.VitalText(300, 400) == "300/400", "vital text"); + Check(Near(CharactersModel.Fraction(300, 400), 0.75), "fraction"); + Check(CharactersModel.Fraction(5, 0) == 0 && CharactersModel.Fraction(500, 400) == 1, "fraction clamps"); + } +} diff --git a/Tools/RynthNet.Tests/RynthNet.Tests.csproj b/Tools/RynthNet.Tests/RynthNet.Tests.csproj new file mode 100644 index 0000000..04676ff --- /dev/null +++ b/Tools/RynthNet.Tests/RynthNet.Tests.csproj @@ -0,0 +1,30 @@ + + + + + Exe + net10.0 + enable + enable + true + RynthNet.Tests + + + + + + + + + + + diff --git a/Tools/RynthNet.Tests/WindowTests.cs b/Tools/RynthNet.Tests/WindowTests.cs new file mode 100644 index 0000000..ee80b84 --- /dev/null +++ b/Tools/RynthNet.Tests/WindowTests.cs @@ -0,0 +1,153 @@ +using System.Text.Json; +using System.Text.RegularExpressions; +using RynthCore.Plugin.RynthNet.Characters; +using RynthCore.Plugin.Shared.RynthUi; + +namespace RynthNet.Tests; + +// The parts of the Characters window that moved from RynthCore with it (2026-10-21). +internal static partial class Program +{ + private static void WindowChecks() + { + Rows(); + RowsOutOfWorld(); + Atlas(); + Manifest(); + IconsMatchEngine(); + } + + private sealed class FakeGame : ICharacterGame + { + public uint PlayerId { get; set; } = 0x50000001; + public bool InWorld { get; set; } = true; + public bool Portaling { get; set; } + public uint SelectedId { get; set; } + public uint Cell = 0xA9B40019; + public float X = 100, Y = 100, Z = 10; + public readonly Dictionary Objects = new(); + + public bool TryGetPose(out uint cell, out float x, out float y, out float z) + { + cell = Cell; x = X; y = Y; z = Z; + return Cell != 0; + } + + public bool TryGetVitals(out uint hp, out uint hpMax, out uint st, out uint stMax, out uint mp, out uint mpMax) + { + hp = 300; hpMax = 400; st = 100; stMax = 200; mp = 50; mpMax = 100; + return true; + } + + public bool TryGetName(uint id, out string name) + { + bool ok = Objects.TryGetValue(id, out var o); + name = ok ? o.Name : ""; + return ok; + } + + public bool TryGetPosition(uint id, out uint cell, out float x, out float y, out float z) + { + bool ok = Objects.TryGetValue(id, out var o); + cell = o.Cell; x = o.X; y = o.Y; z = o.Z; + return ok; + } + } + + private static NetCharEntry Peer(string name, uint id, uint cell, float x, float y, string world = "Aelrynth") => new() + { + Name = name, LoggedIn = true, World = world, HasStatus = true, AgeMs = 400, Id = id, + HasPose = true, Cell = cell, X = x, Y = y, Z = 10, + HasVitals = true, Hp = 10, HpMax = 20, St = 5, StMax = 10, Mp = 1, MpMax = 2, + }; + + private static void Rows() + { + var game = new FakeGame { SelectedId = 0x50000002 }; + var snap = new NetCharSnapshot { Online = true, Version = "0.1.1", MyName = "Freya", MyWorld = "Aelrynth" }; + snap.Clients.Add(Peer("Zed", 0x50000002, 0xA9B40019, 100, 130)); // 30 m north, same landblock + snap.Clients.Add(Peer("Alpha", 0x50000003, 0xA9B40019, 100, 100, "Coldeve")); + snap.Clients.Add(Peer("Bob", 0x50000004, 0xA9B40019, 0, 0)); // the status says the corner... + game.Objects[0x50000004] = ("Bob", 0xA9B40019, 160, 100, 10); // ...but this client sees it 60 m east + CharactersView v = CharactersRows.Build(snap, game); + + Check(v.Rows.Length == 4 && v.Rows[0].IsSelf && v.Rows[0].Name == "Freya", "this client first, by its name"); + Check(v.Rows[0].HasVitals && v.Rows[0].Hp.Text == "300/400" && v.Rows[0].Location == "42.5N 33.7E", "self: vitals and where: " + v.Rows[0].Location); + Check(string.Join(",", v.Rows.Skip(1).Select(r => r.Name)) == "Alpha,Bob,Zed", "the others alphabetically"); + CharacterRow alpha = v.Rows[1], bob = v.Rows[2], zed = v.Rows[3]; + Check(alpha.OtherWorld == "Coldeve" && alpha.Location == "on Coldeve" && !alpha.Measured, "another server: its name, no distance"); + Check(bob.InView && bob.Measured && bob.DistanceText == "60 yd" && bob.Compass == "E", $"in view: this client's own position wins ({bob.DistanceText} {bob.Compass})"); + Check(zed.Measured && zed.DistanceText == "30 yd" && zed.Compass == "N" && !zed.InView, "from the status: 30 yd N"); + Check(v.SelectedId == 0x50000002, "the game's selection rides along"); + Check(v.Status == "3 other characters" && v.MyName == "Freya", "status line: " + v.Status); + + game.Portaling = true; + CharactersView p = CharactersRows.Build(snap, game); + Check(p.Rows[0].Location == "portal space" && !p.Rows[3].Measured, "in portal space nothing is measured"); + } + + private static void RowsOutOfWorld() + { + var game = new FakeGame { InWorld = false }; + CharactersView v = CharactersRows.Build(new NetCharSnapshot { Online = true, Version = "0.1.1" }, game); + Check(v.Rows.Length == 0 && v.Status == "No other RynthCore clients with RynthNet on this PC.", "not in the world, alone: no rows, why"); + CharactersView off = CharactersRows.Build(new NetCharSnapshot { Online = false, Version = "0.1.1", Offline = "pipe busy" }, game); + Check(off.Status == "RynthNet is offline: pipe busy", "offline says why: " + off.Status); + } + + private static void Atlas() + { + AtlasNames.LoadForTests(""" + { "locations": [ + { "name": "Holtburg", "type": "Town", "cell": "A9B40019", "ns": 42.1, "ew": 33.6 }, + { "name": "Matron Hive East", "type": "Dungeon", "lb": "6146" }, + { "name": "Nameless", "type": "Dungeon", "lb": "zz" } ] } + """); + Check(AtlasNames.IsMapLandblock(0xA9B4) && !AtlasNames.IsMapLandblock(0x6146), "surface landblocks from places on the map"); + Check(AtlasNames.DungeonLabel(0x6146) == "Matron Hive East" && AtlasNames.DungeonLabel(0x0123) == "LB 0123", "dungeon names, else the landblock"); + + // A surface building (indoor cell in a map landblock) counts as the overworld: a distance. + var game = new FakeGame(); + var snap = new NetCharSnapshot { Online = true, Version = "0.1.1", MyName = "Freya" }; + snap.Clients.Add(Peer("Inside", 0x50000009, 0xA9B40105, 100, 160)); + snap.Clients.Add(Peer("Deep", 0x5000000A, 0x61460110, 10, 10)); + CharactersView v = CharactersRows.Build(snap, game); + CharacterRow deep = v.Rows.First(r => r.Name == "Deep"), inside = v.Rows.First(r => r.Name == "Inside"); + Check(inside.Measured && inside.DistanceText == "60 yd", "a surface building is measured: " + inside.DistanceText); + Check(!deep.Measured && deep.DistanceText == "elsewhere" && deep.Location == "Matron Hive East", "a dungeon: elsewhere, named"); + } + + private static void Manifest() + { + using JsonDocument doc = JsonDocument.Parse(CharactersManifest.Json); + JsonElement w = doc.RootElement.GetProperty("windows")[0]; + Check(doc.RootElement.GetProperty("version").GetInt32() == 1, "manifest version 1"); + Check(w.GetProperty("id").GetString() == "characters" && w.GetProperty("title").GetString() == "Characters", "the window's id and title (the panel key players' saved places use)"); + Check(w.GetProperty("surface").GetString() == CharactersManifest.Surface && CharactersManifest.Surface == "window:characters", "its surface"); + Check(w.GetProperty("icon").GetString() == RynthIcons.UsersThree, "its bar icon: UsersThree"); + Check(w.GetProperty("bar").GetBoolean() && w.GetProperty("edgeToEdge").GetBoolean(), "a bar button; edge to edge"); + Check(w.GetProperty("width").GetInt32() == 420 && w.GetProperty("minWidth").GetInt32() == 280, "the old panel's sizes"); + } + + /// Shared\RynthUi\RynthIcons.cs is the engine's Baked set (Tools\gen-rynthui-icons.py writes it). + private static void IconsMatchEngine() + { + string? dir = AppContext.BaseDirectory; + string? engine = null; + while (dir != null && engine == null) + { + string p = Path.Combine(dir, "RynthCore", "src", "RynthCore.Engine", "ImGui", "PhosphorIcons.cs"); + if (File.Exists(p)) engine = p; + dir = Path.GetDirectoryName(dir); + } + if (engine == null) { Console.WriteLine(" (no sibling RynthCore: the icon list isn't compared)"); return; } + string text = File.ReadAllText(engine); + var consts = Regex.Matches(text, @"public const string (\w+) = ""\\u([0-9A-Fa-f]{4})"";") + .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value.ToUpperInvariant()); + string baked = Regex.Match(text, @"public const string Baked =(.*?);", RegexOptions.Singleline).Groups[1].Value; + var names = Regex.Matches(baked, @"[A-Z]\w*").Select(m => m.Value).ToHashSet(); + var ours = typeof(RynthIcons).GetFields().ToDictionary(f => f.Name, f => ((int)((string)f.GetRawConstantValue()!)[0]).ToString("X4")); + Check(ours.Count == names.Count && names.All(ours.ContainsKey), $"RynthIcons has the engine's {names.Count} baked icons (has {ours.Count}); run Tools\\gen-rynthui-icons.py"); + Check(names.All(n => consts.TryGetValue(n, out string? cp) && ours.TryGetValue(n, out string? o) && cp == o), "and the same code points"); + } +} diff --git a/Tools/RynthOracle.QuestPackGen/Program.cs b/Tools/RynthOracle.QuestPackGen/Program.cs deleted file mode 100644 index 7a29e36..0000000 --- a/Tools/RynthOracle.QuestPackGen/Program.cs +++ /dev/null @@ -1,337 +0,0 @@ -using System.Globalization; -using System.IO.Compression; -using System.Text; - -namespace RynthOracle.QuestPackGen; - -/// -/// Generates a server quest pack for RynthOracle from an ACE world-database dump. -/// -/// Every row of the world's `quest` table (the flags /myquests can show: ACE leaves out flags -/// without a row) becomes a pack row with its timer (min_Delta, seconds, before the server's -/// quest_mindelta_rate), its solve limit, its message, and who sets it (NPCs whose emotes -/// stamp, increment or update the flag; else NPCs that check it). The curated text stays -/// Advis's: for a flag in the base list the pack leaves Quest, Url and Hint empty (the plugin -/// keeps the base row's text and only fills empty fields), and a flag that only another -/// server's pack knows takes that pack's text. Base flags missing from the quest table get a -/// NotOnServer row, so the plugin hides them on this server (their status can never be read). -/// -internal static class Program -{ - // EmoteType (ACE.Entity.Enum.EmoteType) - private static readonly HashSet SetTypes = new() { 20, 22, 33, 60, 61, 70, 79, 81, 85, 86 }; - private static readonly HashSet CheckTypes = new() { 21, 30, 58, 80, 82 }; - - private static int Main(string[] args) - { - try - { - string server = Arg(args, "-server") ?? "Aelrynth"; - string resources = Arg(args, "-resources") ?? FindResources(); - string dump = Arg(args, "-dump") ?? NewestDump(); - string output = Arg(args, "-out") ?? Path.Combine(resources, $"quests.{server.ToLowerInvariant()}.csv"); - Console.WriteLine($"dump: {dump}"); - Console.WriteLine($"resources: {resources}"); - Console.WriteLine($"out: {output}"); - - var db = WorldDump.Read(dump); - Console.WriteLine($"read {db.Quests.Count} quests, {db.Names.Count} weenie names, {db.EmoteOwner.Count} emotes, {db.Actions.Count} quest emote actions"); - - Dictionary baseRows = Curated.Load(Path.Combine(resources, "quests.csv")); - var otherPacks = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (string pack in Directory.GetFiles(resources, "quests.*.csv")) - { - if (Path.GetFullPath(pack).Equals(Path.GetFullPath(output), StringComparison.OrdinalIgnoreCase)) continue; - foreach (var kv in Curated.Load(pack)) - otherPacks.TryAdd(kv.Key, kv.Value); - } - - // Who sets / checks each flag. - var setters = new Dictionary>(StringComparer.OrdinalIgnoreCase); - var checkers = new Dictionary>(StringComparer.OrdinalIgnoreCase); - foreach ((uint emoteId, int type, string message) in db.Actions) - { - var map = SetTypes.Contains(type) ? setters : CheckTypes.Contains(type) ? checkers : null; - if (map == null || !db.EmoteOwner.TryGetValue(emoteId, out uint wcid)) continue; - string flag = QuestName(message); - if (flag.Length == 0) continue; - string who = db.Names.TryGetValue(wcid, out string? n) && n.Length > 0 ? n - : db.ClassNames.TryGetValue(wcid, out string? c) ? c : $"wcid {wcid}"; - if (!map.TryGetValue(flag, out var set)) map[flag] = set = new SortedSet(StringComparer.OrdinalIgnoreCase); - set.Add(who); - } - - var sb = new StringBuilder(); - sb.Append("QuestFlag,Server,Quest,Url,Info,Hint,Repeatable,MinDelta,MaxSolves,Source,NotOnServer\n"); - int fromBase = 0, fromOther = 0, generated = 0, notOn = 0; - foreach (var q in db.Quests.OrderBy(q => q.Key, StringComparer.Ordinal)) - { - string flag = q.Key; - (uint minDelta, int maxSolves, string message) = q.Value; - string name = "", url = "", info = message, hint = ""; - if (baseRows.ContainsKey(flag)) fromBase++; - else if (otherPacks.TryGetValue(flag, out CuratedRow? o)) - { - fromOther++; - name = o.Name; url = o.Url; hint = o.Hint; - if (o.Info.Length > 0) info = o.Info; - } - else generated++; - - bool repeatable = minDelta > 0 || maxSolves == -1 || maxSolves > 1; - string source = setters.TryGetValue(flag, out var s) ? "set by " + Join(s) - : checkers.TryGetValue(flag, out var c) ? "checked by " + Join(c) : ""; - Row(sb, flag, server, name, url, info, hint, repeatable ? "TRUE" : "FALSE", - minDelta.ToString(CultureInfo.InvariantCulture), maxSolves.ToString(CultureInfo.InvariantCulture), source, ""); - } - foreach (string flag in baseRows.Keys.Where(f => !db.Quests.ContainsKey(f)).OrderBy(f => f, StringComparer.Ordinal)) - { - notOn++; - Row(sb, flag, server, "", "", "", "", "", "", "", "", "TRUE"); - } - - Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(output))!); - File.WriteAllText(output, sb.ToString(), new UTF8Encoding(false)); - Console.WriteLine($"wrote {db.Quests.Count} quests: {fromBase} in the base list (Advis's text kept), {fromOther} named from another server's pack, {generated} new; {notOn} base flags not on {server}"); - return 0; - } - catch (Exception ex) - { - Console.Error.WriteLine("error: " + ex.Message); - return 1; - } - } - - /// ACE QuestManager.GetQuestName: everything before the first '@', lower case. - private static string QuestName(string message) - { - int at = message.IndexOf('@'); - return (at >= 0 ? message[..at] : message).Trim().ToLowerInvariant(); - } - - private static string Join(SortedSet names) => - names.Count <= 3 ? string.Join(", ", names) : string.Join(", ", names.Take(3)) + $" and {names.Count - 3} more"; - - private static void Row(StringBuilder sb, params string[] fields) - { - for (int i = 0; i < fields.Length; i++) - { - if (i > 0) sb.Append(','); - string f = fields[i].Replace("\r", " ").Replace("\n", " "); - if (f.IndexOfAny(new[] { ',', '"' }) >= 0) sb.Append('"').Append(f.Replace("\"", "\"\"")).Append('"'); - else sb.Append(f); - } - sb.Append('\n'); - } - - private static string? Arg(string[] args, string name) - { - for (int i = 0; i < args.Length - 1; i++) - if (args[i].Equals(name, StringComparison.OrdinalIgnoreCase)) return args[i + 1]; - return null; - } - - private static string FindResources() - { - foreach (string start in new[] { Directory.GetCurrentDirectory(), AppContext.BaseDirectory }) - { - var dir = new DirectoryInfo(start); - while (dir != null) - { - string p = Path.Combine(dir.FullName, "Plugins", "RynthCore.Plugin.RynthOracle", "Resources"); - if (Directory.Exists(p)) return p; - dir = dir.Parent; - } - } - throw new InvalidOperationException("can't find Plugins\\RynthCore.Plugin.RynthOracle\\Resources; pass -resources"); - } - - private static string NewestDump() - { - const string dir = @"C:\Aeshnidae\backups"; - string? f = Directory.Exists(dir) - ? Directory.GetFiles(dir, "aeshnidae_world-*.sql.gz").OrderByDescending(p => p, StringComparer.Ordinal).FirstOrDefault() - : null; - return f ?? throw new InvalidOperationException($"no aeshnidae_world-*.sql.gz in {dir}; pass -dump"); - } -} - -internal sealed record CuratedRow(string Name, string Url, string Info, string Hint); - -internal static class Curated -{ - public static Dictionary Load(string path) - { - var map = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (!File.Exists(path)) return map; - using var r = new StreamReader(path); - string? header = r.ReadLine(); - if (header == null) return map; - string[] h = CsvLine.Parse(header); - int Col(string n) => Array.FindIndex(h, x => x.Trim().Equals(n, StringComparison.OrdinalIgnoreCase)); - int flag = Col("QuestFlag"), name = Col("Quest"), url = Col("Url"), info = Col("Info"), hint = Col("Hint"); - if (flag < 0) return map; - while (r.ReadLine() is string line) - { - if (string.IsNullOrWhiteSpace(line)) continue; - string[] f = CsvLine.Parse(line); - string F(int i) => i >= 0 && i < f.Length ? f[i].Trim() : ""; - string key = F(flag).ToLowerInvariant(); - if (key.Length > 0) map.TryAdd(key, new CuratedRow(F(name), F(url), F(info), F(hint))); - } - return map; - } -} - -internal static class CsvLine -{ - public static string[] Parse(string line) - { - var fields = new List(); - var sb = new StringBuilder(); - bool q = false; - for (int i = 0; i < line.Length; i++) - { - char c = line[i]; - if (q) - { - if (c == '"') { if (i + 1 < line.Length && line[i + 1] == '"') { sb.Append('"'); i++; } else q = false; } - else sb.Append(c); - } - else if (c == '"') q = true; - else if (c == ',') { fields.Add(sb.ToString()); sb.Clear(); } - else sb.Append(c); - } - fields.Add(sb.ToString()); - return fields.ToArray(); - } -} - -/// The few world tables the pack needs, read from a mysqldump file (.sql or .sql.gz). -internal sealed class WorldDump -{ - public readonly Dictionary Quests = new(StringComparer.OrdinalIgnoreCase); - public readonly Dictionary ClassNames = new(); - public readonly Dictionary Names = new(); // PropertyString 1 (Name) - public readonly Dictionary EmoteOwner = new(); // emote id -> wcid - public readonly List<(uint EmoteId, int Type, string Message)> Actions = new(); - - public static WorldDump Read(string path) - { - var db = new WorldDump(); - using Stream file = File.OpenRead(path); - using Stream s = path.EndsWith(".gz", StringComparison.OrdinalIgnoreCase) ? new GZipStream(file, CompressionMode.Decompress) : file; - using var reader = new StreamReader(s, Encoding.UTF8); - - var columns = new Dictionary>(StringComparer.Ordinal); - string? creating = null; - string? inserting = null; - while (reader.ReadLine() is string line) - { - if (line.StartsWith("CREATE TABLE `", StringComparison.Ordinal)) - { - creating = line.Substring(14, line.IndexOf('`', 14) - 14); - columns[creating] = new List(); - continue; - } - if (creating != null) - { - string t = line.TrimStart(); - if (t.StartsWith("`", StringComparison.Ordinal)) columns[creating].Add(t.Substring(1, t.IndexOf('`', 1) - 1)); - else if (t.StartsWith(")", StringComparison.Ordinal)) creating = null; - continue; - } - if (line.StartsWith("INSERT INTO `", StringComparison.Ordinal)) - { - string table = line.Substring(13, line.IndexOf('`', 13) - 13); - inserting = IsWanted(table) ? table : null; - int v = line.IndexOf(" VALUES", StringComparison.Ordinal); - if (inserting != null && v >= 0) db.Take(inserting, columns, line[(v + 7)..]); - if (line.TrimEnd().EndsWith(";", StringComparison.Ordinal)) inserting = null; - continue; - } - if (inserting != null) - { - db.Take(inserting, columns, line); - if (line.TrimEnd().EndsWith(";", StringComparison.Ordinal)) inserting = null; - } - } - return db; - } - - private static bool IsWanted(string t) => - t is "quest" or "weenie" or "weenie_properties_string" or "weenie_properties_emote" or "weenie_properties_emote_action"; - - private void Take(string table, Dictionary> columns, string text) - { - if (!columns.TryGetValue(table, out List? cols)) return; - foreach (List row in Tuples(text)) - { - string? Get(string c) { int i = cols.IndexOf(c); return i >= 0 && i < row.Count ? row[i] : null; } - switch (table) - { - case "quest": - string name = (Get("name") ?? "").Trim().ToLowerInvariant(); - if (name.Length == 0) break; - uint.TryParse(Get("min_Delta"), NumberStyles.None, CultureInfo.InvariantCulture, out uint md); - int.TryParse(Get("max_Solves"), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int ms); - Quests[name] = (md, ms, (Get("message") ?? "").Trim()); - break; - case "weenie": - if (uint.TryParse(Get("class_Id"), out uint id)) ClassNames[id] = Get("class_Name") ?? ""; - break; - case "weenie_properties_string": - if (Get("type") == "1" && uint.TryParse(Get("object_Id"), out uint oid)) Names[oid] = Get("value") ?? ""; - break; - case "weenie_properties_emote": - if (uint.TryParse(Get("id"), out uint eid) && uint.TryParse(Get("object_Id"), out uint owner)) EmoteOwner[eid] = owner; - break; - case "weenie_properties_emote_action": - string? msg = Get("message"); - if (msg == null || !int.TryParse(Get("type"), out int type)) break; - if (uint.TryParse(Get("emote_Id"), out uint emote)) Actions.Add((emote, type, msg)); - break; - } - } - } - - /// The value tuples in a VALUES list fragment: "(1,'a\'b',NULL),(2,...);". - private static IEnumerable> Tuples(string text) - { - int i = 0; - while (true) - { - while (i < text.Length && text[i] != '(') i++; - if (i >= text.Length) yield break; - i++; - var row = new List(); - var sb = new StringBuilder(); - bool quoted = false, wasQuoted = false; - for (; i < text.Length; i++) - { - char c = text[i]; - if (quoted) - { - if (c == '\\' && i + 1 < text.Length) - { - char n = text[++i]; - sb.Append(n switch { 'n' => '\n', 'r' => '\r', 't' => '\t', '0' => '\0', _ => n }); - } - else if (c == '\'') quoted = false; - else sb.Append(c); - } - else if (c == '\'') { quoted = true; wasQuoted = true; } - else if (c == ',' || c == ')') - { - string v = sb.ToString(); - row.Add(!wasQuoted && v.Trim() == "NULL" ? null : v); - sb.Clear(); - wasQuoted = false; - if (c == ')') { i++; break; } - } - else sb.Append(c); - } - yield return row; - } - } -} diff --git a/Tools/RynthOracle.QuestPackGen/RynthOracle.QuestPackGen.csproj b/Tools/RynthOracle.QuestPackGen/RynthOracle.QuestPackGen.csproj deleted file mode 100644 index 541c9b1..0000000 --- a/Tools/RynthOracle.QuestPackGen/RynthOracle.QuestPackGen.csproj +++ /dev/null @@ -1,22 +0,0 @@ - - - - - Exe - net10.0 - enable - enable - true - RynthOracle.QuestPackGen - - - diff --git a/Tools/RynthOracle.Tests/MergedQuestsTests.cs b/Tools/RynthOracle.Tests/MergedQuestsTests.cs index 215aff0..53e0fba 100644 --- a/Tools/RynthOracle.Tests/MergedQuestsTests.cs +++ b/Tools/RynthOracle.Tests/MergedQuestsTests.cs @@ -8,16 +8,15 @@ using RynthCore.Plugin.RynthOracle; using RynthCore.Plugin.RynthOracle.Data; using RynthCore.Plugin.RynthOracle.Ui; using RynthCore.Plugin.RynthOracle.Views; -using IltBreedingView = RynthCore.Plugin.Shared.IltBreedingView; -using IltGuardianView = RynthCore.Plugin.Shared.IltGuardianView; namespace RynthOracle.Tests { // The 0.3.0 port of SilentKelpie's RynthOracle 0.6.0 (RynthSuite PR 12): the merged Quests list - // (Legendary, Markers, Dynamic Stamps and Temple guardians), Go to, the Give Parchment gate, the two - // CSV loaders, the RynthILT profile and the Charms / Pet Breeding pieces. Ported from his tests where - // they fit, adapted where our tree differs (the Refresh row, the Mini Remote keeping its tabs), and - // added for what the merge must keep (favourites, click-to-print, the Markers tab's content). + // (Legendary, Markers), Go to and the CSV loaders. Ported from his tests where they fit, adapted where + // our tree differs (the Refresh row, the Mini Remote keeping its tabs), and added for what the merge + // must keep (favourites, click-to-print, the Markers tab's content). Its Infinite Leaftide parts (the + // Dynamic Stamps, the Temple guardians, the Give Parchment gate, the RynthILT profile, Charms and Pet + // Breeding) moved to RynthILT on 2026-10-21, their tests to RynthILT.Tests (StampTests). internal static partial class Program { // ── Helpers ────────────────────────────────────────────────────────── @@ -51,12 +50,12 @@ namespace RynthOracle.Tests Apply(host, Event(5, ++_seq, w.Hash, w.KeyOf(id), payload)); } - /// A context on a given server (a tag, or "" for retail) with the retail catalog loaded. - private static OracleContext On(string tag) + /// A context on a given server (its id, or "" for retail) with its catalog loaded. + private static OracleContext On(string id) { OracleContext c = Context(); - c.Server.Force(tag, tag.Length > 0 ? tag : "Coldeve"); - c.Catalog.Load(tag, null); + c.Server.Force(id, id.Length > 0 ? id : "Coldeve"); + c.Catalog.Load(TestPacks.ById(id), null); c.Catalog.SyncDiscoveries(c.Flags); return c; } @@ -71,7 +70,7 @@ namespace RynthOracle.Tests "legendary groups: " + string.Join(",", LegendaryList.Groups)); Check(LegendaryList.All.All(q => q.Flags.Length > 0 && q.Luminance > 0), "every legendary quest has a flag and luminance"); var catalog = new QuestCatalog(); - catalog.Load("", _ => { }); + catalog.Load(null, _ => { }); var unknown = LegendaryList.All.SelectMany(q => q.Flags).Where(f => !catalog.TryGet(f, out _)).ToList(); Check(unknown.Count == 0, "every legendary flag is a known quest flag: " + string.Join(",", unknown)); LegendaryQuest rtw = LegendaryList.All.First(q => q.CommonName == "RTW"); @@ -106,56 +105,6 @@ namespace RynthOracle.Tests Check(erqLeft is { } e && e.TotalHours > 7.9 && e.TotalHours < 8.1, $"ERQ: key pickup timer decides (~8 h): {erqLeft}"); } - /// The Dynamic Stamps list (dynstamps.csv), its have / missing rules, RynthNav targets and the Go to parser. - private static void DynamicStamps() - { - var all = DynamicStampList.All; - Check(all.Count == 243, $"dynamic stamps: {all.Count} (243 expected from the ExtraDyn sheet)"); - Check(DynamicStampList.Areas.Count == 17 && DynamicStampList.Areas[0] == "Facility Hub" && DynamicStampList.Areas[^1] == "Candeth Keep", - "dynamic areas: " + string.Join(",", DynamicStampList.Areas)); - Check(all.All(s => s.Stamp.StartsWith("dynamic_") && s.Stamp == s.Stamp.ToLowerInvariant()), "every stamp is a lower-case dynamic_ flag"); - Check(all.Select(s => s.Stamp).Distinct().Count() == all.Count, "no stamp listed twice"); - Check(all.All(s => s.Label.Length > 0), "every row names an NPC or a place"); - - DynamicStamp felscuda = all.First(s => s.Npc == "Felscuda"); - Check(felscuda.Stamp == "dynamic_1_&9jiytb!" && felscuda.Place == "Folthid Cellar" && felscuda.Reward == "Healing Rabbit Pie" - && felscuda.Note == "8.8S, 53.1E", $"Felscuda row: {felscuda.Place} / {felscuda.Reward} / {felscuda.Note}"); - - // /myquests keys flags as \S+ lower case, so the stamps' ! & # ^ $ survive. - var f = new QuestFlagStore(); - long t = 900_000, at = DateTimeOffset.UtcNow.AddDays(-1).ToUnixTimeSeconds(); - f.OnChatLine($"Dynamic_1_&9jiyTB! - 1 solves ({at})\"Dynamic\" 1 0", t); - f.OnChatLine($"Dynamic_1_ANND! - 1 solves ({at})\"Dynamic\" 1 0", t + 1); // the sheet lost the closing ! - f.OnChatLine($"Dynamic_1_ZZZnewNPC! - 1 solves ({at})\"Dynamic\" 1 0", t + 2); // not on the sheet - f.OnChatLine($"rtwcompleted_1013 - 1 solves ({at})\"RTW\" -1 72000", t + 3); - f.Tick(t + 5_000); - Check(felscuda.Have(f), "Felscuda's stamp read from /myquests"); - DynamicStamp annd = all.First(s => s.Stamp == "dynamic_1_annd"); - Check(annd.Have(f) && annd.MatchedFlag(f) == "dynamic_1_annd!", "a stamp the sheet lost its ! on still matches"); - Check(!all.First(s => s.Npc == "Raxanza Folthid").Have(f), "an NPC not done is missing"); - List extra = DynamicStampList.Unlisted(f); - Check(extra.Count == 1 && extra[0] == "dynamic_1_zzznewnpc!", "unlisted: only the stamp the sheet doesn't have: " + string.Join(",", extra)); - DynamicStamp shortStamp = all.First(s => s.Stamp == "dynamic_1_s"); - var sf = new QuestFlagStore(); - sf.OnChatLine($"Dynamic_1_SomethingElse! - 1 solves ({at})\"Dynamic\" 1 0", t); - sf.Tick(t + 5_000); - Check(!shortStamp.Have(sf), "a cut-short stem under 14 characters isn't matched by prefix"); - - // RynthNav targets, best first (RynthNav takes the first on its map). - Check(string.Join(" | ", felscuda.NavCandidates()) == "8.8S, 53.1E | Folthid Cellar | Felscuda | Facility Hub", - "Felscuda nav: " + string.Join(" | ", felscuda.NavCandidates())); - var gerent = new DynamicStamp { Area = "Graveyard", Place = "Gerent's Compound at 87.2S, 17.5W", Npc = "Gerent" }; - Check(string.Join(" | ", gerent.NavCandidates()) == "87.2S, 17.5W | Gerent's Compound | Gerent | Graveyard", - "coordinates inside the place, 'at' dropped: " + string.Join(" | ", gerent.NavCandidates())); - var lost = new DynamicStamp { Area = "Odd Stamps", Place = "Lost Wish Cottages (Arwic) 42.6n 62.4e", Npc = "Bob" }; - Check(string.Join(" | ", lost.NavCandidates()) == "42.6N, 62.4E | Lost Wish Cottages (Arwic) | Lost Wish Cottages | Arwic", - "lower-case n/e, a bracketed town, no grouping area, a 3-letter NPC left out: " + string.Join(" | ", lost.NavCandidates())); - var mhoire = new DynamicStamp { Area = "Looking Around", Place = "Mhoire Castle - Great Hall" }; - Check(string.Join(" | ", mhoire.NavCandidates()) == "Mhoire Castle - Great Hall | Mhoire Castle | Great Hall", - "a place's parts: " + string.Join(" | ", mhoire.NavCandidates())); - Check(all.Count(s => s.NavCandidates().Count > 0) >= 200, "most stamps have somewhere to go: " + all.Count(s => s.NavCandidates().Count > 0)); - } - /// Coordinates in a quest's notes become RynthNav targets (Go to). private static void GoToParsing() { @@ -177,11 +126,11 @@ namespace RynthOracle.Tests Check(NavTargets.Place(" Holtburg ").Target == "Holtburg", "a named place is its own target"); } - /// Both CSV loaders: counts from the shipped files, and a malformed file doesn't cost the good rows. + /// The Legendary loader: counts from the shipped file, and a malformed file doesn't cost the good rows. private static void Loaders() { // The shipped files: counts, and they are embedded resources (the way the other lists are). - Check(LegendaryList.All.Count == 40 && DynamicStampList.All.Count == 243, "the shipped lists load: 40 Legendary quests, 243 stamps"); + Check(LegendaryList.All.Count == 40, "the shipped list loads: 40 Legendary quests"); Check(MarkerList.All.Count == 100, "the shipped marker list still has its 100 markers"); var rows = LegendaryList.Parse(new StringReader( @@ -201,250 +150,13 @@ namespace RynthOracle.Tests "legendary: an empty file is an empty list"); Check(LegendaryList.Parse(new StringReader("Quest\r\nCRLF Quest\r\n")).Single().Name == "CRLF Quest", "legendary: CRLF lines"); - var stamps = DynamicStampList.Parse(new StringReader( - "Area,Place,Npc,Reward,Stamp,Note\n" - + "\"A\",\"P\",\"Npc1\",\"R\",\"Dynamic_1_Abc!\",\"8.8S, 53.1E\"\n" - + "\"A\",\"P\",\"Dup\",\"R\",\"dynamic_1_abc!\",\"\"\n" // the same stamp again: skipped - + "\"A\",\"P\",\"NotDyn\",\"R\",\"something_else\",\"\"\n" // not a dynamic_ flag: skipped - + "\"A\",\"P\",\"Short\"\n" // no stamp column: skipped - + "\n" - + "\"B\",\"\",\"\",\"\",\"Dynamic_2_x\",\"\"\n")); - Check(stamps.Count == 2 && stamps[0].Stamp == "dynamic_1_abc!" && stamps[1].Stamp == "dynamic_2_x", - "dynamic: bad and repeated rows skipped, the rest kept: " + string.Join(",", stamps.Select(s => s.Stamp))); - Check(stamps[0].Npc == "Npc1" && stamps[0].Note == "8.8S, 53.1E" && stamps[1].Label == "", "dynamic: fields read, a missing NPC and place leave an empty label"); - Check(DynamicStampList.Parse(new StringReader("")).Count == 0, "dynamic: an empty file is an empty list"); - // The markers file is the existing loader; a marker row still parses to its flag bit. Marker m = MarkerList.All[0]; Check(m.Number == 1 && m.Flag.StartsWith("explorationmarkersfoundingroup") && m.BitMask == 1, "marker 1 keeps its quest flag bit"); } - // ── RynthILT's profile, charms and pet breeding ────────────────────── - - private const string QbProfileJson = "{\"ilt\":true,\"world\":\"InfiniteLeaftide\",\"fellowship\":{\"maxMembers\":29}," - + "\"questBonus\":{\"disabled\":false,\"generation\":3,\"count\":41,\"status\":\"2 completed, 1 incomplete\"," - + "\"completed\":[\"qbflagone\",\"qbflagtwo\"],\"incomplete\":[\"qbflagthree\"]}}"; - - /// RynthILT's "RynthILT.Server" profile JSON as the Quests, About and Pet Breeding pages read it. - private static void IltProfile() - { - const string json = "{\"ilt\":true,\"world\":\"InfiniteLeaftide\",\"forced\":false,\"source\":\"probe\",\"checked\":\"2026-10-13T21:25:37Z\"," - + "\"features\":[{\"key\":\"bank\",\"label\":\"Banking\",\"group\":\"Character\",\"state\":1,\"where\":\"Mini Remote > Banking tab\"}," - + "{\"key\":\"zone_share\",\"label\":\"Zone Share\",\"group\":\"Fellowship\",\"state\":1,\"where\":\"server\"}," - + "{\"key\":\"fellowship_blackjack\",\"label\":\"Fellowship Blackjack\",\"group\":\"Fellowship\",\"state\":0,\"where\":\"/fblackjack\"}]," - + "\"fellowship\":{\"maxMembers\":29,\"zoneShare\":1,\"blackjack\":0,\"luminanceShare\":-1},\"later\":{\"x\":1}}"; - IltServerProfile p = IltServerProfile.Parse(json); - Check(p.Available && p.Ilt && p.World == "InfiniteLeaftide" && p.Source == "probe", "ILT profile header"); - Check(p.FellowshipMax == 29 && p.ZoneShare == 1 && p.Blackjack == 0 && p.LuminanceShare == -1, "ILT fellowship rules"); - Check(p.Features.Count == 3 && p.InGroup("Fellowship").Count() == 2, $"ILT features: {p.Features.Count}"); - Check(p.CheckedUtc == new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc), "checked time is UTC: " + p.CheckedUtc.ToString("o")); - - IltServerProfile none = IltServerProfile.Parse(""); - Check(!none.Available && none.FellowshipMax == 9, "no RynthILT: a retail fellowship"); - Check(!IltServerProfile.Parse("not json").Available, "garbage is ignored"); - Check(IltServerProfile.Parse("{\"ilt\":false}").FellowshipMax == 9, "an older profile without fellowship rules: retail size"); - Check(IltServerProfile.Parse("{\"fellowship\":{\"maxMembers\":5000}}").FellowshipMax == 9, "an absurd size is not believed"); - Check(IltServerProfile.StateText(1) == "on" && IltServerProfile.StateText(0) == "off" && IltServerProfile.StateText(-1) == "checking", "state words"); - - Check(p.QuestBonus == null, "no questBonus object: no /qb list"); - IltServerProfile qb = IltServerProfile.Parse(QbProfileJson); - Check(qb.QuestBonus is { Disabled: false, Generation: 3, Count: 41 } b && b.Completed.Count == 2 && b.Incomplete.Count == 1 - && b.Incomplete[0] == "qbflagthree" && b.Status == "2 completed, 1 incomplete", "quest bonus list parsed"); - - // The identity: a Leaftide world name, RynthILT's own verdict, and RynthCore's "ilt" server all give the ILT tag. - Check(ServerIdentity.TagForWorld("InfiniteLeaftide") == ServerTags.InfiniteLeaftide, "InfiniteLeaftide"); - Check(ServerIdentity.TagForWorld("Infinite Leaftide Staging") == ServerTags.InfiniteLeaftide, "a Leaftide staging world is ILT"); - Check(ServerIdentity.TagForEngineId("ilt") == ServerTags.InfiniteLeaftide && ServerIdentity.EngineIdForTag(ServerTags.InfiniteLeaftide) == "ilt", - "RynthCore's ilt server <-> the ILT tag"); - } - - /// The About page's "Server features" list comes from RynthILT's profile. - private static void ServerFeatures() - { - OracleContext c = On(ServerTags.InfiniteLeaftide); - c.Settings.TabName = OracleView.TabAbout; - var view = new OracleView(c); - var host = new UiHost(); - UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); - string body = Frame(host, main, view, "About, no RynthILT"); - Check(body.Contains("Load RynthILT to list the Infinite Leaftide features here."), "ILT without RynthILT: says to load it"); - c.Ilt.SetJson("{\"ilt\":true,\"world\":\"InfiniteLeaftide\",\"checked\":\"2026-10-13T21:25:37Z\"," - + "\"features\":[{\"key\":\"bank\",\"label\":\"Banking\",\"group\":\"Character\",\"state\":1,\"where\":\"Mini Remote > Banking tab\"}," - + "{\"key\":\"pet_breeding\",\"label\":\"Pet breeding\",\"group\":\"Pets\",\"state\":0,\"where\":\"Pets\"}]}"); - body = Frame(host, main, view, "About, with RynthILT"); - Check(body.Contains("Server features") && body.Contains("1 of 2 on.") && body.Contains("Character") && body.Contains("###o.feat.h.Pets"), - "the features RynthILT lists, grouped, with a count on"); - Check(body.Contains("o.alert") && body.Contains("o.alertall") && body.Contains("o.readlogin"), "the About settings (quest alerts too) are all still there"); - Check(body.Contains("/ro trackers") && body.Contains("/ro legendary") && body.Contains("/ro markers") && body.Contains("/ro guardians") && body.Contains("/ro breeding"), - "the About page lists the new commands on ILT"); - } - - private static string BreedingJson(int essences) - { - var sb = new StringBuilder("{\"available\":true,\"world\":\"InfiniteLeaftide\",\"enabled\":\"on\",\"maturity\":\"on\",\"bond\":\"on\"," - + "\"room\":\"landblock 0x0106 variant 2\",\"freeSlots\":12,\"message\":\"\",\"essences\":["); - for (int i = 0; i < essences; i++) - { - if (i > 0) sb.Append(','); - bool male = i % 2 == 0, ready = i < 2; - sb.Append("{\"id\":").Append(1000 + i).Append(",\"name\":\"Essence ").Append(i).Append("\",\"sex\":\"").Append(male ? 'M' : 'F') - .Append("\",\"tier\":125,\"bond\":100,\"ready\":").Append(ready ? "true" : "false") - .Append(",\"status\":\"").Append(ready ? "Ready" : "Rest 1h 05m").Append("\",\"readyIn\":").Append(ready ? 0 : 3900) - .Append(",\"charges\":7,\"chargesMax\":10,\"juvenile\":false,\"stage\":\"\",\"kills\":0,\"killsRequired\":300,") - .Append("\"mutations\":1,\"potencyMutations\":0,\"problems\":").Append(ready ? "[]" : "[\"resting after a breed\"]") - .Append(",\"boosters\":").Append(i == 0 ? "[\"Incense +10%\"]" : "[]").Append('}'); - } - sb.Append("],\"pairs\":[{\"stud\":\"Essence 0\",\"dam\":\"Essence 1\",\"chanceBest\":0.13636,\"chanceWorst\":0.05,\"inheritMin\":1,\"inheritMax\":2}],") - .Append("\"supplies\":[{\"key\":\"incense1\",\"name\":\"Breeding Incense\",\"effect\":\"+10% mutation chance\",\"count\":2,\"price\":250000,\"apply\":true,\"targets\":[1000,1001]},") - .Append("{\"key\":\"neuter\",\"name\":\"Neutering Kit\",\"effect\":\"Permanent\",\"count\":1,\"price\":0,\"apply\":false,\"targets\":[]}],") - .Append("\"rules\":[{\"label\":\"Stud charges\",\"value\":\"10/day\",\"source\":\"seen on server\",\"help\":\"Breeds per refill.\"},") - .Append("{\"label\":\"Mutation decay\",\"value\":\"0.1\",\"source\":\"ILT profile\",\"help\":\"\"}],") - .Append("\"events\":[{\"when\":\"10-15 12:00\",\"kind\":\"birth\",\"text\":\"Congratulations! A baby pet has been born: Pup\"}],") - .Append("\"debug\":{\"when\":\"10-15 12:01\",\"enabled\":\"on\",\"location\":\"0x0106 variant 2\",\"match\":\"valid\",\"pet\":\"Essence 0\",\"sex\":\"M\",\"partners\":1}}"); - return sb.ToString(); - } - - /// - /// The Pet Breeding tab: Infinite Leaftide only and only where the server has pet breeding; RynthILT's - /// breeding JSON drawn within the op budget; Dance and supply uses asked first, then sent as RynthILT's verbs. - /// - private static void Breeding() - { - OracleContext c = Context(); - var view = new OracleView(c); - Check(!view.VisibleTabs().Contains(OracleView.TabBreeding), "Aelrynth: no Pet Breeding tab"); - c.Server.Force("", "Coldeve"); - Check(!view.VisibleTabs().Contains(OracleView.TabBreeding), "other servers: no Pet Breeding tab"); - c.Server.Force(ServerTags.InfiniteLeaftide, "InfiniteLeaftide"); - Check(view.VisibleTabs().Contains(OracleView.TabBreeding), "Infinite Leaftide: the Pet Breeding tab"); - c.Ilt.SetJson("{\"ilt\":true,\"features\":[{\"key\":\"pet_breeding\",\"label\":\"Pet breeding\",\"group\":\"Pets\",\"state\":0,\"where\":\"\"}]}"); - Check(!view.VisibleTabs().Contains(OracleView.TabBreeding), "ILT with pet breeding off on the server: no Pet Breeding tab"); - c.Ilt.SetJson("{\"ilt\":true,\"features\":[{\"key\":\"pet_breeding\",\"label\":\"Pet breeding\",\"group\":\"Pets\",\"state\":1,\"where\":\"\"}]}"); - Check(view.VisibleTabs().Contains(OracleView.TabBreeding), "ILT with pet breeding on: the tab"); - c.Ilt.SetJson("{\"ilt\":true,\"features\":[{\"key\":\"pet_breeding\",\"label\":\"Pet breeding\",\"group\":\"Pets\",\"state\":-1,\"where\":\"\"}]}"); - Check(view.VisibleTabs().Contains(OracleView.TabBreeding), "ILT with pet breeding not known yet: the tab (it says what it is waiting for)"); - c.Ilt.SetJson(""); - - IltBreedingView v = IltBreedingView.Parse(BreedingJson(2)); - Check(v.Loaded && v.Available && v.Enabled == "on" && v.Room == "landblock 0x0106 variant 2" && v.FreeSlots == 12, "breeding JSON header"); - Check(v.Essences.Count == 2 && v.Essences[0].Male && !v.Essences[1].Male && v.Essences[0].Ready && v.Essences[0].Boosters.Count == 1, - "breeding essences with sex, readiness and boosters"); - Check(v.Pairs.Count == 1 && Math.Abs(v.Pairs[0].ChanceBest - 0.13636) < 1e-9 && v.Pairs[0].InheritMax == 2, "breeding pair odds"); - Check(v.Supplies.Count == 2 && v.Supplies[0].Targets.Count == 2 && !v.Supplies[1].Apply, "breeding supplies and their targets"); - Check(v.Debug is { Match: "valid", Partners: 1 }, "breeding diagnostics"); - Check(!IltBreedingView.Parse("not json").Loaded && !IltBreedingView.Parse("").Loaded && !IltBreedingView.Parse("[1]").Loaded, - "bad breeding JSON is not loaded"); - Check(IltBreedingView.ApplyVerb(" incense1 ", 1000) == "apply incense1 1000" && IltBreedingView.DanceVerb() == "dance", "breeding verbs"); - - // Nothing from RynthILT yet: the tab says to load it. - var host = new UiHost(); - UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); - c.Settings.TabName = OracleView.TabBreeding; - Check(Frame(host, main, view, "Pet Breeding empty").Contains("Load RynthILT (0.3.1 or later)"), "without RynthILT: says to load it"); - - // 50 essences with every section open: rows cut at 40, the page still fits. - var sent = new List(); - string ran = ""; - c.BreedingCommand = verb => { sent.Add(verb); return true; }; - c.RunCommand = cmd => { ran = cmd; return true; }; - c.Breeding = IltBreedingView.Parse(BreedingJson(50)); - Frame(host, main, view, "Pet Breeding opening"); - foreach (string header in new[] { "br.sup", "br.rules", "br.events" }) - Apply(host, Event(6, ++_seq, main.Hash, main.KeyOf(header), new byte[] { 1 })); - string body = Frame(host, main, view, "Pet Breeding with 50 essences", out int ops); - Check(ops > 5 && ops < 1400, $"Pet Breeding with 50 essences: {ops} ops"); - Console.WriteLine($" InfiniteLeaftide/Pet Breeding (50 essences, all open): {ops} ops, {body.Length} bytes"); - Check(body.Contains("Essences (2 ready of 50)") && body.Contains("... and 10 more"), "essence rows cut at 40 with a count"); - Check(body.Contains("Essence 0 x Essence 1") && body.Contains("5%-13.6%"), "the ready pair with its odds"); - Check(body.Contains("Supplies (3 carried)") && body.Contains("250,000 pyreals"), "supplies with Ivo's price"); - Check(body.Contains("Stud charges") && body.Contains("seen on server") && body.Contains("In the breeding room"), "rules and diagnostics"); - Check(body.Contains("A baby pet has been born"), "recent events"); - Check(body.Contains("###refresh.Pet Breeding"), "the page has the Refresh row every page has"); - - // Dance asks first; No drops it, Yes sends it. - Click(host, main, "br.dance"); - Check(sent.Count == 0, "Dance asks before sending"); - body = Frame(host, main, view, "Pet Breeding asking"); - Check(body.Contains("Dance now?") && body.Contains("###br.yes") && body.Contains("###br.no"), "the question with Yes / No"); - Click(host, main, "br.no"); - body = Frame(host, main, view, "Pet Breeding no"); - Check(sent.Count == 0 && !body.Contains("###br.yes"), "No drops the question"); - Click(host, main, "br.dance"); - Frame(host, main, view, "Pet Breeding asking again"); - Click(host, main, "br.yes"); - Check(sent.Count == 1 && sent[0] == "dance", "Yes sends the dance verb"); - - // A supply use on the selected essence (the first) asks first as well. - body = Frame(host, main, view, "Pet Breeding supplies"); - Check(body.Contains("###br.use.0") && !body.Contains("###br.use.1"), "only a usable, carried supply has Use"); - Click(host, main, "br.use.0"); - Check(sent.Count == 1, "a supply use asks before sending"); - Frame(host, main, view, "Pet Breeding supply question"); - Click(host, main, "br.yes"); - Check(sent.Count == 2 && sent[1] == "apply incense1 1000", "Use then Yes sends apply with the essence id: " + string.Join("|", sent)); - - Click(host, main, "br.debug"); - Check(sent.Count == 3 && sent[2] == "debug", "Diagnostics is sent straight away (it only reads)"); - Click(host, main, "br.remote"); - Check(ran == "/ra hub open breeding", "Mini Remote opens Pets > Breeding: " + ran); - - // The page's Refresh row asks RynthILT to appraise again. - Click(host, main, "refresh.Pet Breeding"); - Check(sent.Count == 4 && sent[3] == "refresh", "Refresh sends refresh: " + string.Join("|", sent)); - - // Breeding switched off on the server: said in red, page still drawn. - c.Breeding = IltBreedingView.Parse("{\"available\":true,\"enabled\":\"off\",\"essences\":[]}"); - Check(Frame(host, main, view, "Pet Breeding off").Contains("Pet breeding is off on this server."), "breeding off is shown"); - } - - /// The Character tab's Charms section (RynthILT's list, Toggle routed back to it). - private static void Charms() - { - const string charmsJson = "{\"available\":true,\"world\":\"InfiniteLeaftide\",\"acquiredCount\":2,\"activeCount\":1," - + "\"charms\":[{\"name\":\"Mana Barrier\",\"effect\":\"Absorbs damage\",\"acquired\":\"carried\",\"count\":1,\"tier\":3,\"maxTier\":5," - + "\"active\":\"on\",\"server\":\"on\",\"toggleId\":5001}," - + "{\"name\":\"Swift Feet\",\"acquired\":\"seen\",\"lastSeen\":\"2026-10-12\",\"active\":\"unknown\",\"server\":\"off\"}]," - + "\"hands\":[{\"id\":7001,\"name\":\"Guardian Hand\",\"active\":\"off\",\"server\":\"on\"}]}"; - - OracleContext c = Context(); - c.Server.Force(ServerTags.InfiniteLeaftide, "InfiniteLeaftide"); - c.Settings.TabName = OracleView.TabCharacter; - var view = new OracleView(c); - var host = new UiHost(); - UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); - - string empty = Frame(host, main, view, "Character, no RynthILT"); - Check(empty.Contains("Load RynthILT to list your Infinite Leaftide charms"), "ILT without RynthILT: says to load it"); - - uint toggled = 0; - c.ToggleCharm = id => { toggled = id; return true; }; - c.Charms = RynthCore.Plugin.Shared.IltCharmsView.Parse(charmsJson); - string body = Frame(host, main, view, "Character with charms", out int ops); - Check(ops > 5 && ops < 1400, $"Character with charms: {ops} ops"); - Check(body.Contains("Charms (2)") && body.Contains("Mana Barrier") && body.Contains("T3/5") && body.Contains("seen 2026-10-12"), - "the charms RynthILT listed, with tier and acquired state"); - Check(body.Contains("server off"), "a charm the server switched off is marked"); - Check(body.Contains("Guardian Hands (1)"), "the Guardian Hands are listed"); - Check(body.Contains("###c.charm.0") && !body.Contains("###c.charm.1"), "an uncarried charm has no Toggle"); - Click(host, main, "c.charm.0"); - Check(toggled == 5001, "the carried charm's Toggle goes to RynthILT with its id"); - Click(host, main, "c.hand.0"); - Check(toggled == 7001, "the Guardian Hand's Toggle goes to RynthILT with its id"); - - // Another world: RynthILT answers "not available", so no charms section at all. - c.Server.Force("", ""); - c.Charms = RynthCore.Plugin.Shared.IltCharmsView.Parse("{\"available\":false,\"charms\":[]}"); - Check(!Frame(host, main, view, "Character off ILT").Contains("Charms ("), "off ILT: no charms section"); - } - // ── The merged Quests list ─────────────────────────────────────────── - private const string GuardianJson = "{\"available\":true,\"world\":\"InfiniteLeaftide\",\"chat\":true,\"auto\":false,\"buy\":true," - + "\"cooldownHours\":20,\"answer\":\"Pyreal\",\"npc\":\"Guardian of Attribute Enlightenment\",\"answerAgeSec\":30," - + "\"heard\":\"What is the coin of the realm?\",\"running\":false,\"status\":\"idle\",\"synced\":\"2026-10-18T19:05:00Z\"," - + "\"rows\":[{\"attribute\":\"Strength\",\"npc\":\"Fiun Strongarm\",\"count\":3,\"status\":\"Ready\",\"eta\":\"\",\"ready\":true,\"exact\":true}," - + "{\"attribute\":\"Focus\",\"npc\":\"Fiun Thinker\",\"count\":1,\"status\":\"Cooldown\",\"eta\":\"in 5h 2m\",\"ready\":false,\"exact\":false}]}"; - /// The "N shown" count in a page body. private static int Shown(string body) { @@ -465,7 +177,7 @@ namespace RynthOracle.Tests UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); c.Settings.TabName = OracleView.TabQuests; int quests = c.Catalog.Quests.Count; - int leg = LegendaryList.All.Count, mrk = MarkerList.All.Count, dyn = DynamicStampList.All.Count; + int leg = LegendaryList.All.Count, mrk = MarkerList.All.Count; Check(view.AvailableKinds().SequenceEqual(new[] { QuestKind.Quest, QuestKind.Legendary, QuestKind.Marker }), "retail kinds: quests, Legendary, markers"); string body = Frame(host, main, view, "Quests, retail, everything"); @@ -553,37 +265,19 @@ namespace RynthOracle.Tests Check(Shown(body) == leg + mrk, $"sort {sort} keeps every row ({Shown(body)})"); } - // Infinite Leaftide: stamps and guardians join; the area picker narrows the stamps. - OracleContext ic = On(ServerTags.InfiniteLeaftide); - var iv = new OracleView(ic); - var ihost = new UiHost(); - UiWindow imain = ihost.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); - ic.Settings.TabName = OracleView.TabQuests; - ic.Guardian = IltGuardianView.Parse(GuardianJson); - ic.GuardianRevision++; - int iq = ic.Catalog.Quests.Count; - body = Frame(ihost, imain, iv, "Quests, ILT, everything"); - Check(Shown(body) == iq + leg + mrk + dyn + 2, $"ILT: quests + Legendary + markers + {dyn} stamps + 2 guardians ({Shown(body)}, {iq + leg + mrk + dyn + 2} expected)"); - foreach ((QuestKind kind, int want, string tag) in new[] { (QuestKind.Dynamic, dyn, "DYN"), (QuestKind.Guardian, 2, "GRD") }) - { - iv.ShowTrackers(kind); - body = Frame(ihost, imain, iv, "Quests, ILT, " + kind); - Check(Shown(body) == want && body.Contains(tag), $"ILT Show {kind}: {Shown(body)} shown ({want} expected)"); - } - iv.ShowTrackers(QuestKind.Dynamic); - Frame(ihost, imain, iv, "Quests, ILT, stamps"); - Apply(ihost, Event(3, ++_seq, imain.Hash, imain.KeyOf("dy.area"), BitConverter.GetBytes(1))); - body = Frame(ihost, imain, iv, "Quests, ILT, one area"); - int areaCount = DynamicStampList.All.Count(s => s.Area == DynamicStampList.Areas[0]); - Check(Shown(body) == areaCount, $"the area picker narrows the stamps to {DynamicStampList.Areas[0]}: {Shown(body)} ({areaCount} expected)"); + // Infinite Leaftide's stamps and guardians are RynthILT's own page (2026-10-21): the list keeps the + // same three kinds on every server, and nothing of theirs is drawn. + Check(view.AvailableKinds().Count == 3 && Enum.GetValues().Length == 3, "three kinds of row, on every server"); - // A saved tab name of an old tab opens Quests; the Markers / Legendary / Dynamic Stamps tabs are gone. - ic.Settings.TabName = "Markers"; - Check(iv.Tab == OracleView.TabQuests, "a saved \"Markers\" tab opens Quests"); - ic.Settings.TabName = "Dynamic Stamps"; - Check(iv.Tab == OracleView.TabQuests, "a saved \"Dynamic Stamps\" tab opens Quests"); - string[] tabs = iv.VisibleTabs(); - Check(!tabs.Contains("Markers") && !tabs.Contains("Legendary") && !tabs.Contains("Dynamic Stamps"), "no separate tracker tabs: " + string.Join(",", tabs)); + // A saved tab name of an old tab opens Quests; the Markers / Legendary / Dynamic Stamps / Pet Breeding tabs are gone. + foreach (string old in new[] { "Markers", "Dynamic Stamps", "Pet Breeding" }) + { + c.Settings.TabName = old; + Check(view.Tab == OracleView.TabQuests, $"a saved \"{old}\" tab opens Quests"); + } + string[] tabs = view.VisibleTabs(); + Check(!tabs.Contains("Markers") && !tabs.Contains("Legendary") && !tabs.Contains("Dynamic Stamps") && !tabs.Contains("Pet Breeding"), + "no separate tracker tabs, no Pet Breeding: " + string.Join(",", tabs)); } /// Everything the old Markers tab showed is reachable from the Quests list. @@ -717,140 +411,6 @@ namespace RynthOracle.Tests } } - /// The guardians as rows, their controls sending RynthILT's verbs, and the stamps' opened box. - private static void Trackers() - { - var g = IltGuardianView.Parse(GuardianJson); - Check(g.Loaded && g.Chat && !g.Auto && g.Buy && g.Answer == "Pyreal" && g.AnswerAgeSec == 30 && g.SyncedUtc.Year == 2026, "guardian JSON header"); - Check(g.Rows.Count == 2 && g.Rows[0].Ready && g.Rows[0].Exact && g.Rows[1].Eta == "in 5h 2m" && !g.Rows[1].Exact, "guardian rows"); - Check(!IltGuardianView.Parse("nope").Loaded && !IltGuardianView.Parse("").Loaded, "bad guardian JSON is not loaded"); - Check(IltGuardianView.SwitchVerb(" Auto ", true) == "auto on" && IltGuardianView.SwitchVerb("buy", false) == "buy off" - && IltGuardianView.HandInVerb() == "handin", "guardian verbs"); - - OracleContext c = On(ServerTags.InfiniteLeaftide); - var view = new OracleView(c); - var host = new UiHost(); - UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); - c.Settings.TabName = OracleView.TabQuests; - - view.ShowTrackers(QuestKind.Guardian); - string body = Frame(host, main, view, "Guardians without RynthILT"); - Check(body.Contains("RynthILT isn't loaded"), "guardians without RynthILT: says to load it"); - - var sent = new List(); - c.GuardianCommand = verb => { sent.Add(verb); return true; }; - c.Guardian = g; - c.GuardianRevision++; - body = Frame(host, main, view, "Guardians"); - Check(body.Contains("Temple guardians") && body.Contains("1 of 2 attribute turn-ins ready") && body.Contains("Pyreal") - && body.Contains("###gd.handin") && body.Contains("GRD") && body.Contains("Strength (Fiun Strongarm)") && body.Contains("in 5h 2m"), - "guardian controls, answer and rows"); - Click(host, main, "gd.handin"); - Tick(host, main, "gd.auto", true); - Tick(host, main, "gd.buy", false); - Click(host, main, "gd.refresh"); - Check(string.Join("|", sent) == "handin|auto on|buy off|refresh", "guardian controls send their verbs: " + string.Join("|", sent)); - - // Open a guardian row, then every kind at once under the engine's ops limit. - Click(host, main, "q.r.gd:Strength"); - view.ShowTrackers(null); - body = Frame(host, main, view, "ILT trackers, a guardian opened", out int ops); - int rows = LegendaryList.All.Count + MarkerList.All.Count + DynamicStampList.All.Count + 2; - Check(Shown(body) == rows && body.Contains("Temple guardian: Strength") && body.Contains("###gd.sel.close"), $"every ILT tracker listed ({Shown(body)}), a guardian opened below"); - Check(ops > 40 && ops < 1400, $"ILT Quests with every tracker and a guardian opened: {ops} ops"); - Console.WriteLine($" InfiniteLeaftide/Quests, trackers only ({rows} rows, guardian opened): {ops} ops, {body.Length} bytes"); - - // A stamp: the nav box with Go / Arrow / Chat, RynthNav asked for the route at once. - var navs = new List(); - c.SendNav = line => { navs.Add(line); return true; }; - var printed = new List(); - c.PrintSink = printed.Add; - view.ShowTrackers(QuestKind.Dynamic); - DynamicStamp felscuda = DynamicStampList.All.First(s => s.Npc == "Felscuda"); - Frame(host, main, view, "Stamps"); - Click(host, main, "q.r.dy:" + felscuda.Stamp); - Check(navs.Count == 1 && navs[0] == "route 8.8S, 53.1E || Folthid Cellar || Felscuda || Facility Hub", "clicking a stamp asks RynthNav for its route: " + string.Join("|", navs)); - body = Frame(host, main, view, "Stamp opened"); - Check(body.Contains("Navigate to Felscuda") && body.Contains("###dy.nav.go") && body.Contains("###dy.nav.arrow") && body.Contains("###dy.nav.chat"), "the stamp's box"); - Click(host, main, "dy.nav.go"); - Check(navs.Count == 2 && navs[1].StartsWith("go 8.8S, 53.1E || "), "Go sends a go with every candidate"); - Click(host, main, "dy.nav.chat"); - Check(printed.Count >= 1 && printed[0].Contains("Felscuda") && printed[0].Contains("missing"), "Chat prints the stamp: " + string.Join(" | ", printed.Take(2))); - } - - /// Give Parchment sends /ub give, and is disabled with a tooltip when RynthAi can't take it. - private static void GiveParchment() - { - OracleContext c = On(ServerTags.InfiniteLeaftide); - c.ParchmentFinder = () => "Parchment of Learning"; - var ran = new List(); - c.RunCommand = cmd => { ran.Add(cmd); return true; }; - c.SendNav = _ => true; - var view = new OracleView(c); - var host = new UiHost(); - UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true }); - c.Settings.TabName = OracleView.TabQuests; - DynamicStamp felscuda = DynamicStampList.All.First(s => s.Npc == "Felscuda"); - view.ShowTrackers(QuestKind.Dynamic); - Frame(host, main, view, "Stamps"); - Click(host, main, "q.r.dy:" + felscuda.Stamp); - - // RynthAi isn't there: no button, a greyed line and the reason. - c.UbGiveAvailable = () => false; - string body = Frame(host, main, view, "Give, no RynthAi"); - Check(!body.Contains("###dy.nav.give") && body.Contains("[Give Parchment of Learning]") && body.Contains("Needs RynthAi"), - "no RynthAi: Give Parchment is disabled with a tooltip"); - Check(ran.Count == 0, "nothing was sent"); - - // RynthAi there: the button sends /ub give 1. - c.UbGiveAvailable = () => true; - body = Frame(host, main, view, "Give, RynthAi"); - Check(body.Contains("###dy.nav.give") && body.Contains("Hands one Parchment of Learning to Felscuda"), "RynthAi loaded: the Give button and its tooltip"); - c.NowMs = 50_000; - Click(host, main, "dy.nav.give"); - Check(ran.Count == 0, "one click doesn't give anything away"); - body = Frame(host, main, view, "Give, asking"); - Check(body.Contains("Give one Parchment of Learning to Felscuda?") && body.Contains("###dy.nav.give.yes") && body.Contains("###dy.nav.give.no"), - "it asks, naming the item and the NPC"); - Click(host, main, "dy.nav.give.no"); - body = Frame(host, main, view, "Give, cancelled"); - Check(ran.Count == 0 && body.Contains("###dy.nav.give") && !body.Contains("###dy.nav.give.yes"), "Cancel drops the question, nothing sent"); - Click(host, main, "dy.nav.give"); - Frame(host, main, view, "Give, asking again"); - Click(host, main, "dy.nav.give.yes"); - Check(ran.Count == 1 && ran[0] == "/ub give 1 Parchment of Learning to Felscuda", "Yes sends /ub give 1: " + string.Join("|", ran)); - Check(c.UbGiveSentMs == 50_000, "the send is stamped, so a rejection can be tied to it"); - - // The loaded RynthAi answers "Unrecognized /ub command": the button turns itself off. - Check(!c.NoteChatLineForGive("[RynthAi] some other line", 52_000) && !c.UbGiveMissing, "an unrelated line changes nothing"); - Check(!c.NoteChatLineForGive("[RynthAi] Unrecognized /ub command.", 60_000) && !c.UbGiveMissing, "a rejection long after the send is not tied to it"); - Check(c.NoteChatLineForGive("[RynthAi] Unrecognized /ub command.", 52_000) && c.UbGiveMissing, "a rejection right after the send disables Give"); - body = Frame(host, main, view, "Give, rejected"); - Check(!body.Contains("###dy.nav.give") && body.Contains("[Give Parchment of Learning]") && body.Contains("Unrecognized /ub command"), - "rejected: disabled, the tooltip says why"); - Click(host, main, "q.r.dy:" + felscuda.Stamp); // close - Click(host, main, "q.r.dy:" + felscuda.Stamp); // open again - ran.Clear(); - Frame(host, main, view, "Give, rejected again"); - Check(ran.Count == 0, "no further /ub give goes out"); - - // No Parchment carried: said, no button either way. - c.UbGiveMissing = false; - c.ParchmentFinder = () => null; - body = Frame(host, main, view, "Give, none carried"); - Check(body.Contains("No Parchment in your packs") && !body.Contains("###dy.nav.give"), "no Parchment: no button, says so"); - - // A name with a control character can't smuggle a second command. - c.ParchmentFinder = () => "Parchment\nof /quit"; - c.UbGiveAvailable = () => true; - Frame(host, main, view, "Give, odd name"); - ran.Clear(); - Click(host, main, "dy.nav.give"); - Frame(host, main, view, "Give, odd name asking"); - Click(host, main, "dy.nav.give.yes"); - Check(ran.Count == 1 && !ran[0].Contains('\n') && ran[0].StartsWith("/ub give 1 "), "control characters are stripped from the command: " + (ran.Count > 0 ? ran[0].Replace("\n", "\\n") : "")); - } - /// The throttle line, and the Refresh bar on the Quests page. private static void Throttle() { diff --git a/Tools/RynthOracle.Tests/Program.cs b/Tools/RynthOracle.Tests/Program.cs index b76bc1a..e7f6977 100644 --- a/Tools/RynthOracle.Tests/Program.cs +++ b/Tools/RynthOracle.Tests/Program.cs @@ -46,24 +46,19 @@ namespace RynthOracle.Tests Catalog(); Servers(); EngineServers(); - IltProfile(); - ServerFeatures(); + QuestPackHook(); + NoServerNames(); QuestNotes(); Void(); TimerAlerts(); Pages(); CharacterExtras(); - Charms(); - Breeding(); Legendary(); - DynamicStamps(); GoToParsing(); Loaders(); MergedList(); MarkersReachable(); GoToButtons(); - Trackers(); - GiveParchment(); Throttle(); Events(); QuestTexts(); @@ -207,24 +202,25 @@ namespace RynthOracle.Tests private static void Catalog() { var retail = new QuestCatalog(); - retail.Load("", msg => Console.WriteLine(msg)); + retail.Load(null, msg => Console.WriteLine(msg)); bool bundled = retail.UsingBundled; Check(bundled || System.IO.File.Exists(QuestCatalog.DownloadedPath), "bundled list used (no download present)"); if (bundled) { Check(retail.RetailCount == 3565 && retail.ServerCount == 0 && retail.PackServer == "", $"another server: retail only ({retail.RetailCount}+{retail.ServerCount})"); + // The same quests on the same servers as before the packs moved into their server plugins. var lev = new QuestCatalog(); - lev.Load("Levistras", null); - Check(lev.RetailCount == 3565 && lev.ServerCount == 464 && lev.PackServer == "Levistras", $"Levistras pack: {lev.RetailCount}+{lev.ServerCount}"); + lev.Load(TestPacks.Levistras, null); + Check(lev.RetailCount == 3565 && lev.ServerCount == 464 && lev.PackServer == "Levistras" && lev.PackSource == "from RynthLevistras", + $"Levistras pack (RynthLevistras's): {lev.RetailCount}+{lev.ServerCount}"); var cq = new QuestCatalog(); - cq.Load("Conquest", null); - Check(cq.RetailCount == 3565 && cq.ServerCount == 546, $"Conquest pack: {cq.RetailCount}+{cq.ServerCount}"); - Check(!retail.TryGet("trigram4", out _) && cq.TryGet("trigram4", out Quest tq) && tq.Server == "Conquest", "a Conquest-only quest only loads on ConquestAC"); + cq.Load(TestPacks.Conquest, null); + Check(cq.RetailCount == 3565 && cq.ServerCount == 546, $"Conquest pack (RynthConquest's): {cq.RetailCount}+{cq.ServerCount}"); + Check(!retail.TryGet("trigram4", out _) && cq.TryGet("trigram4", out Quest tq) && tq.Server == "Conquest", "a Conquest-only quest only loads with Conquest's pack"); } - Check(QuestCatalog.EmbeddedPacks().OrderBy(x => x).SequenceEqual(new[] { "aelrynth", "conquest", "levistras" }), "embedded packs: " + string.Join(",", QuestCatalog.EmbeddedPacks())); var cat = new QuestCatalog(); - cat.Load("Aelrynth", msg => Console.WriteLine(msg)); + cat.Load(TestPacks.Aelrynth, msg => Console.WriteLine(msg)); if (bundled) { Check(cat.PackServer == "Aelrynth" && cat.ServerCount == 712 && cat.HiddenCount == 38 && cat.RetailCount == 3565 - 38, @@ -268,63 +264,56 @@ namespace RynthOracle.Tests Check(st != null && st.HasActive && st.IsActive("ILT") && st.ActivePlugin == "RynthILT" && !st.Picked, "engine state: active ILT, detected"); Check(st!.Servers.Count == 2 && st.Find("aelrynth") != null && st.Find("x") == null && st.Revision == 3, "engine state: rows"); - // Identity from it. - ServerIdentity.FromEngine(st, "Launcher Profile", out string tag, out string world, out string source); - Check(tag == ServerTags.InfiniteLeaftide && world == "InfiniteLeaftide", "engine: ILT active is the ILT tag: " + source); + // Identity from it: the active server, its name and the plugin asked for its quest pack. + ServerIdentity.FromEngine(st, "Launcher Profile", out string id, out string name, out string plugin, out string world, out string source); + Check(id == "ilt" && name == "Infinite Leaftide" && plugin == "RynthILT" && world == "InfiniteLeaftide", "engine: the active server and its plugin: " + source); Check(source.Contains("host matches"), "engine: the reason is shown: " + source); var picked = RynthCore.Plugin.Shared.EngineServerState.Parse(EngineJson("conquest", "ConquestAC", "RynthConquest", "conquest", "", EngineRow("ilt", false, "off"), EngineRow("conquest", true, "on", "RynthConquest")))!; - ServerIdentity.FromEngine(picked, "Leaftide Box", out tag, out world, out source); - Check(tag == ServerTags.Conquest && world == "Leaftide Box", "engine: a pick beats the world name (and the world falls back): " + source); + ServerIdentity.FromEngine(picked, "Leaftide Box", out id, out _, out plugin, out world, out source); + Check(id == "conquest" && plugin == "RynthConquest" && world == "Leaftide Box", "engine: a pick beats the world name (and the world falls back): " + source); Check(source.Contains("picked by hand"), "engine: a pick says so: " + source); var off = RynthCore.Plugin.Shared.EngineServerState.Parse(EngineJson("", "", "", "mixed", "InfiniteLeaftide", EngineRow("ilt", false, "off")))!; - ServerIdentity.FromEngine(off, "", out tag, out _, out source); - Check(tag == "", "engine: ILT forced off stays off despite the Leaftide world name: " + source); + ServerIdentity.FromEngine(off, "", out id, out _, out plugin, out _, out source); + Check(id == "" && plugin == "" && source.Contains("no server active"), "engine: ILT forced off stays off despite the Leaftide world name: " + source); var unknown = RynthCore.Plugin.Shared.EngineServerState.Parse(EngineJson("", "", "", "auto", "Levistras", EngineRow("ilt", false, "auto")))!; - ServerIdentity.FromEngine(unknown, "", out tag, out _, out source); - Check(tag == ServerTags.Levistras, "engine: a world the engine has no server for still tags by name: " + source); + ServerIdentity.FromEngine(unknown, "", out id, out _, out _, out world, out source); + Check(id == "" && world == "Levistras", "engine: a world the engine has no server for is no server (no plugin, so no pack): " + source); + ServerIdentity.FromEngine(null, "Levistras", out id, out _, out _, out world, out source); + Check(id == "" && world == "Levistras" && source.Contains("older than API v86"), "no server list (an older engine): no server: " + source); var coldeve = RynthCore.Plugin.Shared.EngineServerState.Parse(EngineJson("coldeve", "Coldeve", "RynthColdeve", "auto", "Coldeve", EngineRow("coldeve", true, "auto", "RynthColdeve")))!; - ServerIdentity.FromEngine(coldeve, "", out tag, out _, out source); - Check(tag == "" && source.Contains("Coldeve"), "engine: a server without Oracle pages has no tag: " + source); - - Check(ServerIdentity.TagForEngineId("AELRYNTH") == ServerTags.Aelrynth && ServerIdentity.TagForEngineId(null) == "", "engine id to tag"); - Check(ServerIdentity.EngineIdForTag(ServerTags.Aelrynth) == "aelrynth" && ServerIdentity.EngineIdForTag("") == "", "tag to engine id"); + ServerIdentity.FromEngine(coldeve, "", out id, out _, out plugin, out _, out source); + Check(id == "coldeve" && plugin == "RynthColdeve" && source.Contains("Coldeve"), "engine: any active server is the server, with its plugin: " + source); // The owner's profile, read leniently (a server plugin's, and RynthILT's). var prof = RynthCore.Plugin.Shared.ServerProfileView.Parse( "{\"schema\":1,\"id\":\"coldeve\",\"name\":\"Coldeve\",\"plugin\":\"RynthColdeve\",\"ruleset\":\"PvE\",\"emulator\":\"ACE\",\"botting\":\"forbidden\",\"bottingNote\":\"no bots\",\"accountLimit\":\"3 accounts\"}"); Check(prof != null && prof.Botting == "forbidden" && prof.Summary() == "PvE, ACE; botting forbidden - no bots; accounts: 3 accounts", "profile: server plugin: " + prof?.Summary()); - var iltProf = RynthCore.Plugin.Shared.ServerProfileView.Parse("{\"ilt\":true,\"features\":[{\"key\":\"bank\",\"state\":1},{\"key\":\"x\",\"state\":0},{\"key\":\"y\",\"state\":1}]}"); - Check(iltProf != null && iltProf.Ilt && iltProf.FeaturesOn == 2 && iltProf.Summary() == "ILT world, 2 Leaftide features on", "profile: RynthILT: " + iltProf?.Summary()); + var iltProf = RynthCore.Plugin.Shared.ServerProfileView.Parse("{\"ilt\":true,\"features\":[{\"key\":\"bank\",\"state\":1}]}"); + Check(iltProf != null && iltProf.Summary() == "no details", "profile: a server's own fields are its plugin's, not the shared view's: " + iltProf?.Summary()); Check(RynthCore.Plugin.Shared.ServerProfileView.Parse("") == null && RynthCore.Plugin.Shared.ServerProfileView.Parse("[1]") == null, "profile: junk is null"); - // A user's server-name list (ub-Rythai's ILT Auto list) against the engine's verdict. - string[] list = { "InfiniteLeaftide", "Conquest" }; - Check(RynthCore.Plugin.Shared.EngineServerState.MatchesNameList(null, "Infinite Leaftide", list), "names: no engine, the world name decides (spaces ignored)"); - Check(!RynthCore.Plugin.Shared.EngineServerState.MatchesNameList(null, "Coldeve", list), "names: no engine, another world"); - Check(RynthCore.Plugin.Shared.EngineServerState.MatchesNameList(st, "Launcher Profile", list), "names: ILT active matches a Leaftide name whatever the world"); - Check(RynthCore.Plugin.Shared.EngineServerState.MatchesNameList(picked, "", list), "names: a picked Conquest matches by id"); - Check(!RynthCore.Plugin.Shared.EngineServerState.MatchesNameList(coldeve, "InfiniteLeaftide", list), "names: Coldeve active beats a Leaftide world name"); - Check(!RynthCore.Plugin.Shared.EngineServerState.MatchesNameList(off, "InfiniteLeaftide", list), "names: ILT listed and off stays off"); - Check(RynthCore.Plugin.Shared.EngineServerState.MatchesNameList(unknown, "Conquest", list), "names: a server the engine doesn't list still matches by world"); } private static void Servers() { - Check(ServerIdentity.TagForWorld("Aeshnidae") == ServerTags.Aelrynth, "Aeshnidae (the live world name) is Aelrynth"); - Check(ServerIdentity.TagForWorld("Aelrynth Staging") == ServerTags.Aelrynth, "Aelrynth Staging"); - Check(ServerIdentity.TagForWorld("Conquest") == ServerTags.Conquest, "Conquest"); - Check(ServerIdentity.TagForWorld("Levistras") == ServerTags.Levistras, "Levistras"); - Check(ServerIdentity.TagForWorld("Coldeve") == "" && ServerIdentity.TagForWorld("") == "", "other servers have no tag"); - Check(ServerIdentity.TagForWorld("InfiniteLeaftide") == ServerTags.InfiniteLeaftide, "Infinite Leaftide is the ILT tag (the Quests tab's stamps and guardians, Pet Breeding)"); + // RynthOracle has no server tags or world-name rules of its own since 2026-10-21: RynthCore's list decides. + Check(typeof(ServerIdentity).Assembly.GetType("RynthCore.Plugin.RynthOracle.Data.ServerTags") == null, "no server tags in RynthOracle"); + Check(typeof(ServerIdentity).GetMethod("TagForWorld", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic) == null, + "no world-name detection in RynthOracle"); var id = new ServerIdentity(); id.Force("", "Coldeve"); - Check(id.Allows(null) && id.Allows("") && !id.Allows(ServerTags.Conquest) && !id.Allows(ServerTags.Aelrynth), "untagged everywhere, tagged nowhere else"); - id.Force(ServerTags.Conquest, "Conquest"); - Check(id.Allows(ServerTags.Conquest) && !id.Allows(ServerTags.Aelrynth), "Conquest features only on ConquestAC"); + Check(id.ServerId == "" && id.DisplayName == "no server" && id.WorldName == "Coldeve" && id.Known, "no server active: retail"); + id.Force("conquest", "Conquest", "RynthConquest"); + Check(id.ServerId == "conquest" && id.Plugin == "RynthConquest" && id.DisplayName == "conquest", "a server and the plugin asked for its pack"); + int rev = id.Revision; + id.Force("conquest", "Conquest", "RynthConquest"); + Check(id.Revision == rev, "the same identity again: no change"); + id.Reset(); + Check(!id.Known && id.ServerId == "", "logout: forgotten"); // Tabs per server. var c = new OracleContext { InWorld = true }; @@ -333,10 +322,10 @@ namespace RynthOracle.Tests string[] none = view.VisibleTabs(); Check(!none.Contains("Leaderboards") && !none.Contains("Conquest"), "no server tabs on other servers: " + string.Join(",", none)); // A server's own pages are its server plugin's since 2026-10-20 (RynthConquest, RynthAelrynth). - c.Server.Force(ServerTags.Aelrynth, "Aeshnidae"); + c.Server.Force("aelrynth", "Aeshnidae"); string[] ael = view.VisibleTabs(); Check(!ael.Contains("Leaderboards") && !ael.Contains("Conquest"), "Aelrynth: no leaderboards in RynthOracle: " + string.Join(",", ael)); - c.Server.Force(ServerTags.Conquest, "Conquest"); + c.Server.Force("conquest", "Conquest"); string[] cq = view.VisibleTabs(); Check(!cq.Contains("Leaderboards") && !cq.Contains("Conquest"), "Conquest: no Conquest tab and no leaderboards in RynthOracle: " + string.Join(",", cq)); foreach (string old in new[] { "Conquest", "Leaderboards" }) @@ -437,8 +426,8 @@ namespace RynthOracle.Tests private static OracleContext Context() { var c = new OracleContext { InWorld = true, NowMs = 10_000_000, UtcNow = DateTime.UtcNow }; - c.Server.Force(ServerTags.Aelrynth, "Aeshnidae"); - c.Catalog.Load("Aelrynth", null); + c.Server.Force("aelrynth", "Aeshnidae", "RynthAelrynth"); + c.Catalog.Load(TestPacks.Aelrynth, null); c.Flags.OnChatLine("30minattributes - 4 solves (1719432000)\"x\" -1 1800", 0); c.Flags.OnChatLine("societyribbonsperdaytimer - 1 solves (" + DateTimeOffset.UtcNow.ToUnixTimeSeconds() + ")\"x\" -1 72000", 0); c.Flags.OnChatLine("societyribbonsperdaycounter - 30 solves (1719432000)\"x\" 200 0", 0); @@ -482,7 +471,7 @@ namespace RynthOracle.Tests // Every tab on each server, including the server-specific ones (with data in them). c.EarnedTitles.Add(1); c.TitlesKnown = true; - foreach (string server in new[] { ServerTags.Aelrynth, ServerTags.Conquest, ServerTags.InfiniteLeaftide, "" }) + foreach (string server in new[] { "aelrynth", "conquest", "" }) { c.Server.Force(server, server); foreach (string tab in view.VisibleTabs()) @@ -493,7 +482,7 @@ namespace RynthOracle.Tests main.End(); ParseAll(host, $"{server}/{tab}", out int ops); Check(ops > 5 && ops < 1400, $"{server}/{tab}: {ops} ops"); - if (server == ServerTags.Aelrynth) Console.WriteLine($" {(server.Length > 0 ? server : "other")}/{tab}: {ops} ops, {main.Body.Length} bytes"); + if (server == "aelrynth") Console.WriteLine($" {(server.Length > 0 ? server : "other")}/{tab}: {ops} ops, {main.Body.Length} bytes"); main.MarkSubmitted(true); } } @@ -668,7 +657,7 @@ namespace RynthOracle.Tests OracleView.TabTitles, OracleView.TabVoid, OracleView.TabFellowship, OracleView.TabAbout }; OracleContext c = Context(); var view = new OracleView(c); - foreach (string server in new[] { ServerTags.Aelrynth, ServerTags.Conquest, ServerTags.InfiniteLeaftide, "" }) + foreach (string server in new[] { "aelrynth", "conquest", "" }) { c.Server.Force(server, server); string[] tabs = view.VisibleTabs(); @@ -814,7 +803,7 @@ namespace RynthOracle.Tests void Press(string scope) => Click("refresh." + scope); // A Refresh button on every tab, on every server. - foreach (string server in new[] { ServerTags.Aelrynth, ServerTags.Conquest, ServerTags.InfiniteLeaftide, "" }) + foreach (string server in new[] { "aelrynth", "conquest", "" }) { c.Server.Force(server, server); foreach (string tab in view.VisibleTabs()) diff --git a/Tools/RynthOracle.Tests/QuestPackTests.cs b/Tools/RynthOracle.Tests/QuestPackTests.cs new file mode 100644 index 0000000..0adbfdb --- /dev/null +++ b/Tools/RynthOracle.Tests/QuestPackTests.cs @@ -0,0 +1,164 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Text.RegularExpressions; +using RynthCore.Plugin.RynthOracle; +using RynthCore.Plugin.RynthOracle.Data; +using RynthCore.Plugin.Shared; + +namespace RynthOracle.Tests +{ + /// + /// The server plugins' quest packs (2026-10-21: Conquest's, Levistras's and Aelrynth's left RynthOracle + /// for RynthConquest, RynthLevistras and RynthAelrynth), embedded into this test exe from those projects + /// as the plugins offer them through "RynthServer.QuestPack". + /// + internal static class TestPacks + { + public static string Csv(string id) + { + using Stream? s = Assembly.GetExecutingAssembly().GetManifestResourceStream("TestPack." + id + ".csv") + ?? throw new FileNotFoundException("test pack " + id); + using var r = new StreamReader(s, Encoding.UTF8); + return r.ReadToEnd(); + } + + /// The pack as RynthOracle takes it from the active server's plugin. + public static ServerQuestPack Offer(string id, string tag, string plugin) => + new(plugin, id, tag, 0, 1, Csv(id)); + + public static QuestPackSource Source(string id, string tag, string plugin) => new(id, tag, Csv(id), plugin); + + public static QuestPackSource Conquest => Source("conquest", "Conquest", "RynthConquest"); + public static QuestPackSource Levistras => Source("levistras", "Levistras", "RynthLevistras"); + public static QuestPackSource Aelrynth => Source("aelrynth", "Aelrynth", "RynthAelrynth"); + + /// The pack for a server id ("" or an unknown id: none, retail only). + public static QuestPackSource? ById(string id) => id switch + { + "conquest" => Conquest, + "levistras" => Levistras, + "aelrynth" => Aelrynth, + _ => null, + }; + } + + internal static partial class Program + { + /// A RynthCore server list with one active server owned by (or none). + private static EngineServerState Engine(string active, string plugin) => + EngineServerState.Parse(EngineJson(active, active.ToUpperInvariant(), plugin, "auto", "World", + active.Length > 0 ? new[] { EngineRow(active, true, "auto", plugin) } : Array.Empty()))!; + + /// + /// The generic quest-pack hook: RynthOracle merges the pack the active server's plugin offers, only + /// while that plugin owns the active server, under the pack's own tag, and names no server itself. + /// + private static void QuestPackHook() + { + // The info JSON a server plugin answers (ServerPackQuestPack.BuildInfoJson), read leniently. + ServerQuestPackInfo? info = ServerQuestPackInfo.Parse( + "{\"schema\":1,\"server\":\"conquest\",\"tag\":\"Conquest\",\"plugin\":\"RynthConquest\",\"version\":\"0.2.0\",\"rows\":546,\"bytes\":48939,\"revision\":1,\"later\":[1]}"); + Check(info is { ServerId: "conquest", Tag: "Conquest", Plugin: "RynthConquest", Rows: 546, Bytes: 48939, Revision: 1 }, "pack info: parsed"); + Check(ServerQuestPackInfo.Parse(null) == null && ServerQuestPackInfo.Parse("junk") == null && ServerQuestPackInfo.Parse("[1]") == null, + "pack info: junk is no pack"); + Check(ServerQuestPackInfo.Parse("{\"schema\":2,\"bytes\":5}") == null, "pack info: another schema is no pack"); + Check(ServerQuestPackInfo.Parse("{\"schema\":1,\"server\":\"x\"}") == null, "pack info: a pack without a size is no pack"); + + // Whose pack counts: only the active server's plugin's. + ServerQuestPack conquest = TestPacks.Offer("conquest", "Conquest", "RynthConquest"); + Check(ServerQuestPackClient.ForActive(Engine("conquest", "RynthConquest"), conquest) == conquest, "the active server's plugin's pack is merged"); + Check(ServerQuestPackClient.ForActive(Engine("conquest", "rynthconquest"), conquest) == conquest, "plugin names compare in any case"); + Check(ServerQuestPackClient.ForActive(Engine("ilt", "RynthILT"), conquest) == null, "another server active: its pack isn't"); + Check(ServerQuestPackClient.ForActive(Engine("conquest", ""), conquest) == null, "a server without its plugin loaded: no pack"); + Check(ServerQuestPackClient.ForActive(Engine("", ""), conquest) == null, "no server active: no pack"); + Check(ServerQuestPackClient.ForActive(null, conquest) == null, "no server list (an engine older than v86): no pack"); + Check(ServerQuestPackClient.ForActive(Engine("conquest", "RynthConquest"), null) == null, "nothing offered: nothing merged"); + Check(ServerQuestPackClient.OwnerOf(Engine("levistras", "RynthLevistras")) == "RynthLevistras" && ServerQuestPackClient.OwnerOf(Engine("", "")) == "" + && ServerQuestPackClient.OwnerOf(null) == "", "the plugin asked for a pack is the active server's owner"); + + // What the catalog loads for the server it's on. + var id = new ServerIdentity(); + Check(QuestCatalog.SourceFor(id, conquest) == null, "no server: retail only, whatever was offered"); + id.Force("conquest", "Conquest", "RynthConquest"); + QuestPackSource? src = QuestCatalog.SourceFor(id, conquest); + Check(src is { ServerId: "conquest", Tag: "Conquest", From: "RynthConquest" } && src.Csv.Length > 40_000, "the offered pack, under its tag"); + src = QuestCatalog.SourceFor(id, null); + Check(src is { ServerId: "conquest", Csv: "", From: "" }, "a server whose plugin offers no pack: only its id (an override file can still apply)"); + + // End to end: RynthConquest's pack on Conquest; the same pack while Infinite Leaftide is active is not merged. + var cat = new QuestCatalog(); + cat.Load(QuestCatalog.SourceFor(id, ServerQuestPackClient.ForActive(Engine("conquest", "RynthConquest"), conquest)), null); + bool bundled = cat.UsingBundled; + if (bundled) + Check(cat.PackServer == "Conquest" && cat.ServerCount == 546 && cat.PackSource == "from RynthConquest" && cat.TryGet("trigram4", out _), + $"on Conquest with RynthConquest: its 546 quests ({cat.ServerCount}, {cat.PackSource})"); + var ilt = new ServerIdentity(); + ilt.Force("ilt", "InfiniteLeaftide", "RynthILT"); + cat.Load(QuestCatalog.SourceFor(ilt, ServerQuestPackClient.ForActive(Engine("ilt", "RynthILT"), conquest)), null); + Check(cat.PackServer == "" && cat.ServerCount == 0 && !cat.TryGet("trigram4", out _), "on another server: none of Conquest's quests"); + Check(cat.LastSource is { ServerId: "ilt", Csv: "" }, "the catalog remembers what it was loaded for (Reload uses it)"); + + // A pack that isn't one: retail only, nothing thrown. + cat.Load(new QuestPackSource("odd", "Odd", "not a quest list", "RynthOdd"), null); + Check(cat.PackServer == "" && cat.ServerCount == 0 && (!bundled || cat.RetailCount == 3565), "a junk pack: retail quests only"); + + // The override file is named for the server's id, and an odd id can't leave the packs folder. + Check(QuestCatalog.PackOverridePath("conquest").EndsWith(Path.Combine("packs", "quests.conquest.csv"), StringComparison.Ordinal), "override: packs\\quests..csv"); + Check(QuestCatalog.PackOverridePath("..\\x/y").EndsWith(Path.Combine("packs", "quests.___x_y.csv"), StringComparison.Ordinal), "override: an odd id stays in the folder"); + + // RynthOracle embeds no server's pack any more. + string[] embedded = typeof(QuestCatalog).Assembly.GetManifestResourceNames() + .Where(n => n.StartsWith("RynthOracle.quests.", StringComparison.Ordinal) && n != "RynthOracle.quests.csv").ToArray(); + Check(embedded.Length == 0, "RynthOracle embeds no server's quest pack: " + string.Join(",", embedded)); + } + + /// + /// RynthOracle's own code names no server (comments describing history may): the layer rule + /// (CLAUDE.md, 2026-10-21). Read from the plugin's source files. + /// + private static void NoServerNames() + { + string? dir = AppContext.BaseDirectory; + while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "RynthCore.Plugin.RynthOracle"))) dir = Path.GetDirectoryName(dir); + Check(dir != null, "the RynthOracle sources are found"); + if (dir == null) return; + string root = Path.Combine(dir, "Plugins", "RynthCore.Plugin.RynthOracle"); + var names = new Regex(@"Ilt[A-Z]|RynthIlt|Leaftide|Conquest|Aelrynth|Levistras|DreamWeave", RegexOptions.CultureInvariant); + int files = 0; + var found = new System.Collections.Generic.List(); + foreach (string file in Directory.GetFiles(root, "*.cs", SearchOption.AllDirectories)) + { + if (file.Contains(Path.DirectorySeparatorChar + "obj" + Path.DirectorySeparatorChar) || file.Contains(Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar)) continue; + files++; + string[] lines = File.ReadAllLines(file); + for (int i = 0; i < lines.Length; i++) + { + Match m = names.Match(CodeOf(lines[i])); + if (m.Success) found.Add($"{Path.GetRelativePath(root, file)}:{i + 1} ({m.Value})"); + } + } + Check(files > 30, $"RynthOracle's sources were read ({files})"); + Check(found.Count == 0, "RynthOracle's code names no server: " + string.Join(", ", found)); + Check(CodeOf("x = 1; // Conquest's") == "x = 1; " && CodeOf("s = \"a // b\"; // c") == "s = \"a // b\"; ", "comments are told from code"); + } + + /// A line without its comment ("//" outside a string literal). + internal static string CodeOf(string line) + { + bool str = false, chr = false; + for (int i = 0; i < line.Length; i++) + { + char c = line[i]; + if (str) { if (c == '\\') i++; else if (c == '"') str = false; continue; } + if (chr) { if (c == '\\') i++; else if (c == '\'') chr = false; continue; } + if (c == '"') str = true; + else if (c == '\'') chr = true; + else if (c == '/' && i + 1 < line.Length && line[i + 1] == '/') return line[..i]; + } + return line; + } + } +} diff --git a/Tools/RynthOracle.Tests/RynthOracle.Tests.csproj b/Tools/RynthOracle.Tests/RynthOracle.Tests.csproj index a2284a4..871a608 100644 --- a/Tools/RynthOracle.Tests/RynthOracle.Tests.csproj +++ b/Tools/RynthOracle.Tests/RynthOracle.Tests.csproj @@ -28,29 +28,32 @@ - - + + + - - - + + + + - diff --git a/Tools/RynthOracle.Tests/ServerMoveTests.cs b/Tools/RynthOracle.Tests/ServerMoveTests.cs index 7eec22e..5bea750 100644 --- a/Tools/RynthOracle.Tests/ServerMoveTests.cs +++ b/Tools/RynthOracle.Tests/ServerMoveTests.cs @@ -17,6 +17,37 @@ namespace RynthOracle.Tests SettingsKeepUnknown(); ConquestGone(); AelrynthGone(); + IltGone(); + } + + /// + /// Infinite Leaftide without RynthOracle (2026-10-21): its charms, pet breeding, Temple guardians, + /// Dynamic Stamps, /qb list and feature list are RynthILT's own pages, so RynthOracle has none of + /// their types, readers, tabs, tracker kinds or tag, on any world. + /// + private static void IltGone() + { + const System.Reflection.BindingFlags All = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static + | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic; + Type[] types = typeof(RynthOraclePlugin).Assembly.GetTypes(); + string[] iltTypes = Array.ConvertAll(Array.FindAll(types, t => + t.Name.StartsWith("Ilt", StringComparison.Ordinal) || t.Name.StartsWith("RynthIlt", StringComparison.Ordinal) + || t.Name.StartsWith("DynamicStamp", StringComparison.Ordinal)), t => t.FullName ?? t.Name); + Check(iltTypes.Length == 0, "ilt: no RynthILT reader, view or Dynamic Stamp type in RynthOracle: " + string.Join(",", iltTypes)); + foreach (string field in new[] { "Ilt", "IltData", "Charms", "Breeding", "Guardian", "ToggleCharm", "BreedingCommand", "GuardianCommand", "UbGiveAvailable" }) + Check(typeof(OracleContext).GetField(field, All) == null, "ilt: OracleContext has no " + field); + Check(typeof(OracleContext).Assembly.GetType("RynthCore.Plugin.RynthOracle.Data.ServerTags") == null, "ilt: no server tags at all"); + Check(typeof(OracleView).GetField("TabBreeding", All) == null, "ilt: no Pet Breeding tab"); + Check(Enum.GetNames().Length == 3 && Enum.IsDefined(QuestKind.Marker), "ilt: the Quests list has quests, Legendary quests and markers only"); + + var c = new OracleContext { InWorld = true }; + var view = new OracleView(c); + foreach ((string tag, string world) in new[] { ("", "InfiniteLeaftide"), ("", "Coldeve") }) + { + c.Server.Force(tag, world); + string[] tabs = view.VisibleTabs(); + Check(Array.IndexOf(tabs, "Pet Breeding") < 0 && tabs.Length == 11, $"ilt: {world}: the same eleven tabs: " + string.Join(",", tabs)); + } } /// Aelrynth without RynthAelrynth: no leaderboards or Trials in RynthOracle (the quest pack stays, as data). @@ -27,11 +58,13 @@ namespace RynthOracle.Tests Check(typeof(OracleContext).GetField("Boards") == null, "aelrynth: RynthOracle keeps no leaderboard data"); var c = new OracleContext { InWorld = true }; var view = new OracleView(c); - c.Server.Force(ServerTags.Aelrynth, "Aeshnidae"); + c.Server.Force("aelrynth", "Aeshnidae", "RynthAelrynth"); string[] tabs = view.VisibleTabs(); Check(Array.IndexOf(tabs, "Leaderboards") < 0, "aelrynth: no Leaderboards tab in RynthOracle on Aelrynth: " + string.Join(",", tabs)); - c.Catalog.Load(ServerTags.Aelrynth, null); - Check(c.Catalog.PackServer == ServerTags.Aelrynth && c.Catalog.ServerCount > 0, "aelrynth: the quest pack is still RynthOracle's (data)"); + // The quest pack is RynthAelrynth's since 2026-10-21; RynthOracle merges it as offered. + c.Catalog.Load(QuestCatalog.SourceFor(c.Server, TestPacks.Offer("aelrynth", "Aelrynth", "RynthAelrynth")), null); + Check(c.Catalog.PackServer == "Aelrynth" && c.Catalog.ServerCount > 0 && c.Catalog.PackSource == "from RynthAelrynth", + "aelrynth: RynthAelrynth's quest pack, merged as offered"); } /// @@ -52,7 +85,7 @@ namespace RynthOracle.Tests // Conquest tagged by its world name (RynthConquest not installed): retail tabs only. var c = new OracleContext { InWorld = true }; var view = new OracleView(c); - c.Server.Force(ServerTags.Conquest, "Conquest"); + c.Server.Force("conquest", "Conquest"); string[] tabs = view.VisibleTabs(); Check(Array.IndexOf(tabs, "Conquest") < 0 && Array.IndexOf(tabs, "Leaderboards") < 0, "conquest: no Conquest pages in RynthOracle on Conquest: " + string.Join(",", tabs)); diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Resources/quests.aelrynth.csv b/Tools/RynthOracle.Tests/TestData/quests.aelrynth.csv similarity index 100% rename from Plugins/RynthCore.Plugin.RynthOracle/Resources/quests.aelrynth.csv rename to Tools/RynthOracle.Tests/TestData/quests.aelrynth.csv diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Resources/quests.conquest.csv b/Tools/RynthOracle.Tests/TestData/quests.conquest.csv similarity index 100% rename from Plugins/RynthCore.Plugin.RynthOracle/Resources/quests.conquest.csv rename to Tools/RynthOracle.Tests/TestData/quests.conquest.csv diff --git a/Plugins/RynthCore.Plugin.RynthOracle/Resources/quests.levistras.csv b/Tools/RynthOracle.Tests/TestData/quests.levistras.csv similarity index 100% rename from Plugins/RynthCore.Plugin.RynthOracle/Resources/quests.levistras.csv rename to Tools/RynthOracle.Tests/TestData/quests.levistras.csv diff --git a/Tools/RynthServerPack.Tests/AelrynthTests.cs b/Tools/RynthServerPack.Tests/AelrynthTests.cs deleted file mode 100644 index c305988..0000000 --- a/Tools/RynthServerPack.Tests/AelrynthTests.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using RynthCore.Engine.UI.Sections; -using RynthCore.Plugin.RynthAelrynth; -using RynthCore.Plugin.ServerPack; -using RynthCore.RynthAiTests.Harness; - -namespace RynthServerPack.Tests; - -// RynthAelrynth's own features (Plugins\RynthCore.Plugin.RynthAelrynth\Aelrynth), moved out of -// RynthOracle on 2026-10-20: the /top and /trial reply parser (RynthOracle.Tests' old -// AelrynthReplies), the own-reply hiding, the setting taken over from rynthoracle.json and its page. -internal static class AelrynthTests -{ - public static void Register(Runner r) - { - r.Add("aelrynth: the replies of /top, /top me and /trial parse", Replies); - r.Add("aelrynth: replies to RynthAelrynth's own requests are hidden, typed ones show", HideOwnReplies); - r.Add("aelrynth: RynthOracle's reply-hiding choice is taken over once", Migration); - r.Add("aelrynth: its Leaderboards page is an Aelrynth-only view of the Server section", Pages); - } - - private static void Replies() - { - var a = new AelrynthBoards(); - long now = 2_000_000; - a.RequestTop("", now); - Check.True(a.OnChatLine("Leaderboards - 37 characters, refreshed 4 min ago. /top for the top ten, /top me for yourself.", now, out bool ours) && ours, "overview header"); - a.OnChatLine(" kills Creature kills: Buffy, 1,234,567", now, out _); - a.OnChatLine(" pk PK kills: nobody yet", now, out _); - Check.True(a.Overview.Count == 2 && a.Overview[0].Key == "kills" && a.Overview[0].Leader == "Buffy" && a.Overview[0].Value == "1,234,567" - && a.Overview[1].Leader == "nobody yet", "overview rows"); - - a.RequestTop("kills", now); - a.OnChatLine("Creature kills - top 10 of 37:", now, out _); - a.OnChatLine(" 1. Buffy 1,234,567 <- you", now, out _); - a.OnChatLine(" 2. Dargoth 987,654", now, out _); - a.OnChatLine(" 3. Sal 500 12 kills per death", now, out _); - Check.True(a.BoardTitle == "Creature kills" && a.BoardRows.Count == 3 && a.BoardRows[0].IsYou && a.BoardRows[1].Value == "987,654" - && a.BoardRows[2].Extra == "12 kills per death", "board rows: " + string.Join(" | ", a.BoardRows.Select(r => $"{r.Rank} {r.Name} {r.Value} [{r.Extra}] {r.IsYou}"))); - - a.RequestTop("me", now); - a.OnChatLine("Buffy on the boards:", now, out _); - a.OnChatLine(" Creature kills #1 of 37, 1,234,567", now, out _); - a.OnChatLine(" PK kills -", now, out _); - Check.True(a.Standings.Count == 2 && a.Standings[0].Rank == 1 && a.Standings[1].Rank == 0, "/top me"); - - Check.False(a.OnChatLine(" 9. Nobody 12", now + 30_000, out _), "an entry long after its header is ignored"); - - a.RequestTrial("", now); - a.OnChatLine("Trials - a fresh personal copy of a listed dungeon, entered through its portal, is a timed course: ...", now, out _); - a.OnChatLine(" The Citadel Below - Trial (02F0): tier 0 12:34 by Buffy | you: tier 0 12:34 | this week: Buffy 12:34 (tier 0)", now, out _); - a.OnChatLine(" your next attempt here: in 12 min", now, out _); - a.OnChatLine("Trophy: the week's fastest clear of each dungeon, any tier - a trophy and 1,000 experience, Sunday 20:00 (2026-W40). /trial for the top 10 of one dungeon.", now, out _); - Check.True(a.Trials.Count == 1 && a.Trials[0].Landblock == "02F0" && a.TrialLines.Count == 3, $"/trial overview ({a.Trials.Count} dungeons, {a.TrialLines.Count} lines)"); - - a.RequestTrial("citadel", now); - a.OnChatLine("The Citadel Below - Trial (02F0) - top 10, best per character, any tier:", now, out _); - a.OnChatLine(" 1. 12:34 Buffy (tier 0, 105 kills, 3 Oct)", now, out _); - a.OnChatLine(" you: tier 0 12:34 (105 kills)", now, out _); - Check.True(a.TrialRows.Count == 1 && a.TrialRows[0].Name == "Buffy" && a.TrialRows[0].Value == "12:34" && a.TrialNotes.Count == 1, "/trial dungeon top 10"); - Check.False(a.OnChatLine("Bob tells you, \"hello\"", now, out _), "ordinary chat is never taken"); - } - - private static void HideOwnReplies() - { - var f = new AelrynthFeature(); - long now = 3_000_000; - f.Boards.RequestTop("", now); - Check.True(f.OnChatLine("Leaderboards - 3 characters, refreshed just now. /top ...", 0, now), "a reply to RynthAelrynth's /top is hidden"); - Check.True(f.OnChatLine(" kills Creature kills: Buffy, 12", 0, now), "and its rows"); - Check.False(f.OnChatLine("Leaderboards - 3 characters, refreshed just now. /top ...", 0, now + 60_000), "a typed /top's reply shows"); - Check.False(f.OnChatLine(" kills Creature kills: Ann, 14", 0, now + 60_000), "and its rows"); - Check.True(f.Boards.Overview.Count == 1 && f.Boards.Overview[0].Leader == "Ann", "read either way"); - f.HideOwnReplies = false; - f.Boards.RequestTrial("", now); - Check.False(f.OnChatLine("Trials - a fresh personal copy of a listed dungeon ...", 0, now), "with hiding off, own replies show too"); - Check.False(f.OnChatLine("Bob says, \"hi\"", 0, now), "ordinary chat shows"); - f.Reset(); - Check.True(f.Boards.Overview.Count == 0 && f.Boards.Trials.Count == 0, "login/logout clears the boards"); - } - - private static void Migration() - { - string dir = ServerPackHooksTests.TempDir(); - try - { - string oracle = Path.Combine(dir, "rynthoracle.json"), mine = Path.Combine(dir, "rynthaelrynth.json"); - File.WriteAllText(oracle, "{ \"hideOwnQuestReplies\": false }"); - var s = new ServerPackSettings(mine); - s.Load(); - Check.True(AelrynthFeature.Migrate(s, oracle), "taken over the first time"); - var f = new AelrynthFeature(); - f.LoadSettings(s); - Check.False(f.HideOwnReplies, "the player's choice (shown) came over"); - Check.False(AelrynthFeature.Migrate(s, oracle), "never twice"); - var fresh = new ServerPackSettings(Path.Combine(dir, "fresh.json")); - fresh.Load(); - AelrynthFeature.Migrate(fresh, Path.Combine(dir, "none.json")); - var g = new AelrynthFeature(); - g.LoadSettings(fresh); - Check.True(g.HideOwnReplies, "default: hidden"); - } - finally { try { Directory.Delete(dir, true); } catch { } } - } - - private static void Pages() - { - var pages = ServerPackPages.Validate(AelrynthFeature.PageList.Select(p => new ServerPage(p.Id, p.Label, p.Tooltip, () => { }))); - Check.Eq(pages.Count, 1, "one page"); - ServerPackInfo info = new("aelrynth", "Aelrynth", new[] { "aelrynth.com" }, new[] { "Aelrynth*", "Aeshnidae*" }); - SectionManifest m = SectionManifestParser.Parse("RynthAelrynth", ServerPackModel.BuildSectionsJson(info, "RynthAelrynth", pages), out string error); - Check.Eq(error, "", "RynthCore parses the manifest"); - SectionContribution view = m.Contributions.Single(c => c.Primary); - Check.True(view.Server == "aelrynth" && view.Label == "Leaderboards" && view.Surface == "section:server-aelrynth.boards", - "Leaderboards, only while Aelrynth is active"); - } -} diff --git a/Tools/RynthServerPack.Tests/ConquestTests.cs b/Tools/RynthServerPack.Tests/ConquestTests.cs deleted file mode 100644 index 3c08bc8..0000000 --- a/Tools/RynthServerPack.Tests/ConquestTests.cs +++ /dev/null @@ -1,216 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using RynthCore.Engine.UI.Sections; -using RynthCore.Plugin.RynthConquest; -using RynthCore.Plugin.RynthOracle.Data; -using RynthCore.Plugin.ServerPack; -using RynthCore.RynthAiTests.Harness; - -namespace RynthServerPack.Tests; - -// RynthConquest's own features (Plugins\RynthCore.Plugin.RynthConquest\Conquest), moved out of -// RynthOracle on 2026-10-20: the reply parser (RynthOracle.Tests' old ConquestReplies), the -// own-reply hiding, the login /augs, the auto-deposit, the settings taken over from rynthoracle.json, -// the Void DoT rule it publishes, the custom quest list and its pages. -internal static class ConquestTests -{ - public static void Register(Runner r) - { - r.Add("conquest: the replies of /b, /augs, /enl augs, /bonus, /fship list and /top parse", Replies); - r.Add("conquest: replies to RynthConquest's own requests are hidden, typed ones show", HideOwnReplies); - r.Add("conquest: /augs once after login, then never again", LoginAugs); - r.Add("conquest: the auto-deposit is off unless turned on, then once per ten-minute mark", AutoDeposit); - r.Add("conquest: RynthOracle's settings are taken over once (defaults kept without them)", Migration); - r.Add("conquest: the Void DoT rule for RynthOracle's timers", VoidRule); - r.Add("conquest: the custom quest worklist and its status", CustomQuests); - r.Add("conquest: its pages are Conquest-only views of the Server section", Pages); - } - - private static void Replies() - { - var d = new ConquestData(); - long now = 1_000_000; - d.RequestBank(now); - Check.True(d.OnChatLine("[BANK] Your balances:", now, out bool ours) && ours, "bank heading (ours)"); - d.OnChatLine("[BANK] Pyreals: 1,039,678,533", now, out _); - d.OnChatLine("[BANK] Event Tokens [Dragon Coins] (x): 12", now, out _); - Check.True(d.Bank.Any(b => b.Name == "Pyreals" && b.Value.Contains("4,158 MMDs")), "pyreals with MMDs"); - Check.True(d.Bank.Any(b => b.Name == "Dragon Coins (x)"), "event token name"); - Check.False(d.OnChatLine("Bob says, \"[BANK] Pyreals: 999\"", now, out _), "a pasted balance is ignored"); - d.OnChatLine("[BANK] Pyreals: 5", now + 60_000, out bool late); - Check.False(late, "a reply long after the request isn't ours (shows in chat)"); - - d.RequestAugs(now); - d.OnChatLine("Creature: 25", now, out _); - d.OnChatLine("Duration: 3", now, out _); - ConquestAug creature = d.Augs.First(a => a.Name == "Creature"); - Check.True(creature.Count == 25 && creature.NextLuminanceCost() == 6_229_500, $"Creature 25 next costs 6,229,500 ({creature.NextLuminanceCost()})"); - Check.True(d.DurationAugs == 3 && Math.Abs(d.VoidDurationMultiplier(5) - 2.15) < 1e-9, "void duration x(1 + 5*0.2 + 3*0.05)"); - - d.RequestEnl(now); - d.OnChatLine("Enlightenment Augmentations:", now, out _); - d.OnChatLine("Skill Credits: 2 (10 max)", now, out _); - d.OnChatLine("Damage: 5 (25 max)", now, out _); - Check.True(d.EnlAugs.Count == 2 && d.EnlAugs[0].Name == "Damage", "enlightenment augs in display order"); - - d.RequestBonus(now); - d.OnChatLine("=== XP Bonuses ===", now, out _); - d.OnChatLine("Quest Bonus: 14.18% (1,418 quests)", now, out _); - d.OnChatLine("Total Bonus (Kills): 0.16%", now, out _); - Check.True(d.Bonuses.First(b => b.Name == "Quest").Value == "14.18% (1,418 quests)" && d.Bonuses.First(b => b.Name == "Total (Kills)").Value == "0.16%", "bonuses"); - - d.RequestFships(now); - d.OnChatLine("Fellowships looking for members:", now, out _); - d.OnChatLine("- Heroes (Leader: Bob) [3/14] @ Bur", now, out _); - d.OnChatLine("- Quiet (Leader: Ann) [1/14]", now, out _); - Check.True(d.Fellowships.Count == 2 && d.Fellowships[0].Location == "Bur" && d.Fellowships[1].MemberCount == 1, "fellowship list"); - - ConquestBoard lvl = d.Boards.First(b => b.Key == "level"); - d.RequestBoard(lvl, now); - d.OnChatLine("Top 2 Players by Level:", now, out _); - d.OnChatLine("1: 300 - Alpha", now, out _); - d.OnChatLine("2: 299 - Beta", now, out _); - d.OnChatLine("57: 250 - Me (You)", now, out _); - Check.True(lvl.Rows.Count == 2 && lvl.You != null && lvl.You.Rank == 57 && lvl.You.Name == "Me", "Conquest /top board"); - - Check.Eq(ConquestData.WithdrawCommand(ConquestData.Withdrawable[ConquestData.DefaultWithdraw], "10"), "/bank withdraw n 10", "withdraw MMDs"); - Check.Null(ConquestData.WithdrawCommand(ConquestData.Withdrawable[0], "-3"), "withdraw refuses a bad amount"); - Check.Eq(ConquestData.TransferCommand(ConquestData.Transferable[2], "4", "Some One"), "/bank transfer p 1000000 \"Some One\"", "transfer MMD notes as pyreals"); - Check.Null(ConquestData.TransferCommand(ConquestData.Transferable[2], "1001", "X"), "transfer cap"); - } - - private static void HideOwnReplies() - { - var f = new ConquestFeature(); - f.Login(0); - long now = 100_000; - f.Data.RequestBank(now); - Check.True(f.OnChatLine("[BANK] Pyreals: 1,000", now), "a reply to RynthConquest's /b is hidden"); - Check.False(f.OnChatLine("[BANK] Pyreals: 1,000", now + 60_000), "the same reply long after (typed /b) shows"); - Check.False(f.OnChatLine("Bob says, \"hello\"", now), "ordinary chat shows"); - f.HideOwnReplies = false; - f.Data.RequestBank(now); - Check.False(f.OnChatLine("[BANK] Pyreals: 1,000", now), "with hiding off, own replies show too"); - f.HideOwnReplies = true; - - // /myquests: only RynthConquest's own request's reply is hidden; the flags are read either way. - Check.True(f.Flags.Request(_ => true, now), "own /myquests sent"); - Check.True(f.OnChatLine("assaultonaimaru - 1 solves (1719432000)\"x\" -1 0", now), "its reply is hidden"); - f.Flags.Tick(now + 2000); - Check.True(f.Flags.TryGet("assaultonaimaru", out _), "and read"); - Check.False(f.OnChatLine("ghostdencompleted - 1 solves (1719432000)\"x\" -1 0", now + 3000), "a reply nobody here asked for shows"); - Check.True(f.Data.AutoDeposit(now).Length > 0 && f.OnChatLine("Deposited 12 items.", now), "the auto-deposit's reply is hidden"); - } - - private static void LoginAugs() - { - var f = new ConquestFeature(); - f.Login(1000); - Check.Null(f.LoginAugsDue(1000 + ConquestFeature.AugsReadDelayMs), "not before the delay"); - Check.Eq(f.LoginAugsDue(1001 + ConquestFeature.AugsReadDelayMs), "/augs", "/augs after it"); - Check.Null(f.LoginAugsDue(5_000_000), "only once"); - f.Login(9_000_000); - Check.Eq(f.LoginAugsDue(9_000_001 + ConquestFeature.AugsReadDelayMs), "/augs", "again for the next login"); - } - - private static void AutoDeposit() - { - var f = new ConquestFeature(); - f.Login(0); - var at = new DateTime(2026, 10, 20, 14, 0, 5, DateTimeKind.Local); - Check.False(f.AutoDeposit, "off by default (as it was in RynthOracle)"); - Check.Null(f.AutoDepositDue(at, 0), "off: no deposit at :00"); - f.AutoDeposit = true; - Check.Eq(f.AutoDepositDue(at, 0), "/bank deposit", "on: /bank deposit at :00"); - Check.Null(f.AutoDepositDue(at.AddSeconds(30), 0), "once per mark"); - Check.Null(f.AutoDepositDue(at.AddMinutes(5), 0), "not at :05"); - Check.Eq(f.AutoDepositDue(at.AddMinutes(10), 0), "/bank deposit", "again at :10"); - long block = -1; - Check.True(ConquestFeature.DepositDue(new DateTime(2026, 1, 1, 0, 20, 0), ref block), "the schedule: :20"); - Check.False(ConquestFeature.DepositDue(new DateTime(2026, 1, 1, 0, 21, 0), ref block), "the schedule: not :21"); - } - - private static void Migration() - { - string dir = ServerPackHooksTests.TempDir(); - try - { - string oracle = Path.Combine(dir, "rynthoracle.json"), mine = Path.Combine(dir, "rynthconquest.json"); - File.WriteAllText(oracle, "{ \"hideOwnQuestReplies\": false, \"conquestAutoDeposit\": true, \"tabName\": \"Conquest\" }"); - var s = new ServerPackSettings(mine); - s.Load(); - Check.True(ConquestFeature.Migrate(s, oracle), "taken over the first time"); - var f = new ConquestFeature(); - f.LoadSettings(s); - Check.True(f.AutoDeposit, "auto-deposit came over (on)"); - Check.False(f.HideOwnReplies, "hiding came over (off)"); - - // Turned off here later: a newer rynthoracle.json never turns it back on. - f.AutoDeposit = false; - f.SaveSettings(s); - var again = new ServerPackSettings(mine); - again.Load(); - Check.False(ConquestFeature.Migrate(again, oracle), "never taken over twice"); - var g = new ConquestFeature(); - g.LoadSettings(again); - Check.False(g.AutoDeposit, "the player's choice here stands"); - - // A new player (no RynthOracle settings): the defaults. - string fresh = Path.Combine(dir, "fresh.json"); - var n = new ServerPackSettings(fresh); - n.Load(); - Check.True(ConquestFeature.Migrate(n, Path.Combine(dir, "missing.json")), "runs (nothing to take)"); - var h = new ConquestFeature(); - h.LoadSettings(n); - Check.True(!h.AutoDeposit && h.HideOwnReplies, "defaults: auto-deposit off, own replies hidden"); - Check.True(new ServerPackSettings(fresh) is var reread && Reload(reread) && reread.GetBool(ConquestFeature.MigrationMarker, false), - "the marker is saved"); - } - finally { try { Directory.Delete(dir, true); } catch { } } - } - - private static bool Reload(ServerPackSettings s) { s.Load(); return true; } - - private static void VoidRule() - { - var f = new ConquestFeature(); - f.Login(0); - Check.Eq(f.VoidScale, 1.0, "no augs, no Archmage's Endurance: x1"); - f.ArchmagesEndurance = 5; - f.Data.RequestAugs(0); - f.Data.OnChatLine("Duration: 3", 0, out _); - Check.Near(f.VoidScale, 2.15, 1e-9, "x(1 + 5*0.2 + 3*0.05)"); - Check.Eq(ConquestFeature.VoidScaleKey, "voidDotDurationScale", "the profile value RynthOracle reads"); - } - - private static void CustomQuests() - { - Check.Eq(CustomQuestList.All.Count, 6, "six custom quests (customquests.csv, embedded)"); - Check.True(CustomQuestList.All.All(q => q.Server == "Conquest" && q.Flag.Length > 0 && q.Flag == q.Flag.ToLowerInvariant()), "Conquest rows, flags in lower case"); - var flags = new QuestFlagStore(); - CustomQuest darsh = CustomQuestList.All.First(q => q.Flag == "assaultonaimaru"); - DateTime now = DateTime.UtcNow; - Check.False(darsh.IsComplete(flags, now), "not done without the flag"); - Check.Eq(darsh.Status(flags, now), "ready", "ready without the flag"); - long done = DateTimeOffset.UtcNow.ToUnixTimeSeconds() - 60; - flags.OnChatLine($"assaultonaimaru - 1 solves ({done})\"x\" -1 3600", 0); - flags.Tick(5000); - Check.True(darsh.IsComplete(flags, now), "a repeatable on cooldown counts as done"); - Check.True(darsh.Status(flags, now) is not ("ready" or "completed") && darsh.Status(flags, now).Contains('m'), "its status is the time left: " + darsh.Status(flags, now)); - } - - private static void Pages() - { - var pages = ServerPackPages.Validate(ConquestFeature.PageList.Select(p => new ServerPage(p.Id, p.Label, p.Tooltip, () => { }))); - Check.Eq(pages.Count, ConquestFeature.PageList.Length, "every page is valid"); - Check.True(pages.Select(p => p.Label).SequenceEqual(new[] { "Conquest", "Leaderboards" }), "the Conquest and Leaderboards pages"); - ServerPackInfo info = new("conquest", "Conquest", new[] { "acconquest.ddns.net" }, new[] { "Conquest", "ConquestAC" }); - SectionManifest m = SectionManifestParser.Parse("RynthConquest", ServerPackModel.BuildSectionsJson(info, "RynthConquest", pages), out string error); - Check.Eq(error, "", "RynthCore parses the manifest"); - SectionContribution[] views = m.Contributions.Where(c => c.Primary).ToArray(); - Check.Eq(views.Length, 2, "two pages in the Mini Remote"); - Check.True(views.All(c => c.Server == "conquest"), "shown only while Conquest is active"); - Check.True(views.Select(c => c.Surface).SequenceEqual(new[] { "section:server-conquest.main", "section:server-conquest.boards" }), "their surfaces"); - } -} diff --git a/Tools/RynthServerPack.Tests/Program.cs b/Tools/RynthServerPack.Tests/Program.cs deleted file mode 100644 index 2ed1d0f..0000000 --- a/Tools/RynthServerPack.Tests/Program.cs +++ /dev/null @@ -1,22 +0,0 @@ -using RynthCore.RynthAiTests.Harness; - -namespace RynthServerPack.Tests; - -// Offline tests for the server plugins: the shared model and every server plugin's detection data. -// -// Run: dotnet run -c Release (all tests) -// dotnet run -c Release -- host (tests whose name contains "host") -internal static class Program -{ - private static int Main(string[] args) - { - var runner = new Runner(); - ServerPackModelTests.Register(runner); - ServerProjectsTests.Register(runner); - ServerPackHooksTests.Register(runner); - ConquestTests.Register(runner); - AelrynthTests.Register(runner); - VaultTests.Register(runner); - return runner.Run("RynthServerPack tests", args.Length > 0 ? args[0] : null); - } -} diff --git a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj deleted file mode 100644 index 27e541c..0000000 --- a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj +++ /dev/null @@ -1,57 +0,0 @@ - - - - - Exe - net10.0 - enable - true - RynthServerPack.Tests - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs b/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs deleted file mode 100644 index f6d75e2..0000000 --- a/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs +++ /dev/null @@ -1,210 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text.Json; -using RynthCore.Engine.UI.Sections; -using RynthCore.Plugin.ServerPack; -using RynthCore.RynthAiTests.Harness; - -namespace RynthServerPack.Tests; - -// The shared hooks a server plugin's own features use (2026-10-20, when RynthOracle's and -// RynthInventory's Conquest and Aelrynth features moved into RynthConquest and RynthAelrynth): -// pages beside the server card, the plugin's own settings file (with a one-time migration), live -// numbers in the "RynthServer.Profile" JSON, and the own-reply window. -internal static class ServerPackHooksTests -{ - public static void Register(Runner r) - { - r.Add("hooks: page ids, surfaces and the surface a page is drawn under", PageNames); - r.Add("hooks: bad, duplicate and surplus pages are left out", PageValidation); - r.Add("hooks: pages are server-only primary views of the Server section, accepted by RynthCore's parser", PagesInManifest); - r.Add("hooks: settings round-trip and keep values the plugin doesn't know", SettingsRoundTrip); - r.Add("hooks: settings migration runs once, and a broken file means defaults", SettingsMigration); - r.Add("hooks: profile values are published, validated and read back", ProfileValues); - r.Add("hooks: the own-reply window opens, stretches and closes", ReplyWindow); - } - - internal static string TempDir() - { - string dir = Path.Combine(Path.GetTempPath(), "RynthServerPack.Tests", Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(dir); - return dir; - } - - private static void PageNames() - { - Check.True(ServerPackPages.IsValidId("bank") && ServerPackPages.IsValidId("top-10"), "plain ids"); - Check.False(ServerPackPages.IsValidId("") || ServerPackPages.IsValidId("Bank") || ServerPackPages.IsValidId("a.b") - || ServerPackPages.IsValidId(new string('a', 17)), "empty, capitals, dots and long ids are refused"); - Check.Eq(ServerPackPages.SurfaceFor("conquest", "bank"), "section:server-conquest.bank", "surface"); - Check.Eq(ServerPackPages.PageIdOf("section:server-conquest.bank", "conquest"), "bank", "page from its surface"); - Check.Eq(ServerPackPages.PageIdOf("section:server-conquest.bank:popout", "conquest"), "bank", "popped out"); - Check.Null(ServerPackPages.PageIdOf("section:server-conquest", "conquest"), "the card is not a page"); - Check.Null(ServerPackPages.PageIdOf("section:server-aelrynth.top", "conquest"), "another server's page"); - Check.Null(ServerPackPages.PageIdOf("section:server-conquest.Bad!", "conquest"), "a malformed page id"); - Check.Null(ServerPackPages.PageIdOf(null, "conquest"), "null"); - string longest = ServerPackPages.SurfaceFor(new string('a', 32), new string('b', ServerPackPages.MaxIdLength)); - Check.True(longest.Length <= SectionManifestParser.MaxSurfaceLength, "the longest surface fits RynthCore's cap: " + longest.Length); - } - - private static void PageValidation() - { - Action draw = () => { }; - var notes = new List(); - var pages = new List - { - new("one", "One", "", draw), new("one", "Again", "", draw), new("Two", "Two", "", draw), - new("three", " ", "", draw), new("four", "Four", "tip", null!), - }; - for (int i = 0; i < 8; i++) pages.Add(new ServerPage("p" + i, "Page " + i, "", draw)); - List kept = ServerPackPages.Validate(pages, notes.Add); - Check.Eq(kept.Count, ServerPackPages.MaxPages, "capped"); - Check.Eq(kept[0].Id, "one", "first kept"); - Check.Eq(kept.Count(p => p.Id == "one"), 1, "a duplicate id is dropped"); - Check.False(kept.Any(p => p.Id is "Two" or "three" or "four"), "bad id, no label, nothing to draw"); - Check.True(notes.Count == pages.Count - kept.Count, "every dropped page is reported: " + string.Join(" | ", notes)); - Check.Eq(ServerPackPages.Validate(null).Count, 0, "no pages"); - string label = new string('x', 60); - Check.Eq(ServerPackPages.Validate(new[] { new ServerPage("x", label, "", draw) })[0].Label.Length, ServerPackPages.MaxLabelLength, "label capped"); - } - - private static void PagesInManifest() - { - ServerPackInfo info = new("conquest", "Conquest", new[] { "acconquest.ddns.net" }, new[] { "Conquest" }); - var pages = ServerPackPages.Validate(new[] - { - new ServerPage("main", "Conquest", "Bank, augs and more", () => { }), - new ServerPage("boards", "Leaderboards", "", () => { }), - }); - string json = ServerPackModel.BuildSectionsJson(info, "RynthConquest", pages); - SectionManifest m = SectionManifestParser.Parse("RynthConquest", json, out string error); - Check.Eq(error, "", "RynthCore parses it"); - Check.Eq(m.Contributions.Length, 3, "the card and two pages"); - SectionContribution card = m.Contributions.Single(c => !c.Primary); - Check.Eq(card.Surface, "section:server-conquest", "the card keeps its surface"); - SectionContribution[] views = m.Contributions.Where(c => c.Primary).ToArray(); - Check.True(views.All(c => c.Section == ServerPackModel.SectionId && c.Server == "conquest" && c.IsSurface), - "pages: primary views of the Server section, only on Conquest"); - Check.Eq(views[0].Surface, "section:server-conquest.main", "page surface"); - Check.Eq(views[0].Label, "Conquest", "page label"); - Check.Eq(views[0].Tooltip, "Bank, augs and more", "page tooltip"); - Check.Eq(views[1].Tooltip, "Leaderboards (RynthConquest)", "a default tooltip"); - Check.True(views[0].Order < views[1].Order, "pages keep their order"); - Check.True(views[0].Width > 0 && views[0].Height > 0, "pages say their size"); - - // Without pages the manifest is byte for byte what it was. - Check.Eq(ServerPackModel.BuildSectionsJson(info, "RynthConquest", null), ServerPackModel.BuildSectionsJson(info, "RynthConquest"), - "no pages: the old manifest"); - Check.Eq(SectionManifestParser.Parse("x", ServerPackModel.BuildSectionsJson(info, "RynthConquest"), out _).Contributions.Length, 1, - "no pages: only the card"); - } - - private static void SettingsRoundTrip() - { - string dir = TempDir(); - try - { - string path = Path.Combine(dir, "rynthtest.json"); - File.WriteAllText(path, "{ \"future\": {\"a\":[1,2]}, \"flag\": false, \"name\": \"x\" }"); - var s = new ServerPackSettings(path); - s.Load(); - Check.Eq(s.LastError, "", "read"); - Check.False(s.GetBool("flag", true), "a stored false"); - Check.True(s.GetBool("missing", true), "a missing value falls back"); - Check.True(s.GetBool("name", true), "a value of another type falls back"); - Check.Eq(s.GetString("name", "?"), "x", "text"); - Check.True(s.SetBool("flag", true), "a change says so"); - Check.False(s.SetBool("flag", true), "the same value is no change"); - s.SetString("quote", "a \"b\" \\ c"); - Check.True(s.Save(), "saved"); - - var again = new ServerPackSettings(path); - again.Load(); - Check.True(again.GetBool("flag", false), "the change was kept"); - Check.Eq(again.GetString("quote", ""), "a \"b\" \\ c", "text escaped and read back"); - using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path)); - Check.Eq(doc.RootElement.GetProperty("future").GetProperty("a").GetArrayLength(), 2, "an unknown value is written back as it was"); - Check.False(File.Exists(path + ".tmp"), "no temporary file left"); - Check.True(ServerPackSettings.DefaultPath("RynthConquest").EndsWith(Path.Combine("RynthCore", "rynthconquest.json"), StringComparison.Ordinal), - "%APPDATA%\\RynthCore\\.json"); - } - finally { try { Directory.Delete(dir, true); } catch { } } - } - - private static void SettingsMigration() - { - string dir = TempDir(); - try - { - string old = Path.Combine(dir, "old.json"), mine = Path.Combine(dir, "mine.json"); - File.WriteAllText(old, "{ \"moved\": true, \"text\": \"t\" }"); - Check.Eq(ServerPackSettings.ReadBoolFrom(old, "moved"), (bool?)true, "the old home's value"); - Check.Null(ServerPackSettings.ReadBoolFrom(old, "text"), "not a true/false value"); - Check.Null(ServerPackSettings.ReadBoolFrom(old, "absent"), "missing value"); - Check.Null(ServerPackSettings.ReadBoolFrom(Path.Combine(dir, "nope.json"), "moved"), "missing file"); - - var s = new ServerPackSettings(mine); - s.Load(); - int runs = 0; - Action migrate = t => { runs++; if (ServerPackSettings.ReadBoolFrom(old, "moved") is bool b) t.SetBool("moved", b); }; - Check.True(s.MigrateOnce("migratedFromOld", migrate), "runs the first time"); - Check.True(s.GetBool("moved", false), "imported"); - File.WriteAllText(old, "{ \"moved\": false }"); - var later = new ServerPackSettings(mine); - later.Load(); - Check.False(later.MigrateOnce("migratedFromOld", migrate), "never again (the marker was saved)"); - Check.True(later.GetBool("moved", false), "later changes to the old home don't come over"); - Check.Eq(runs, 1, "ran once"); - - File.WriteAllText(mine, "{ not json"); - var broken = new ServerPackSettings(mine); - broken.Load(); - Check.True(broken.LastError.Length > 0 && broken.GetBool("moved", true), "a broken file reads as defaults"); - } - finally { try { Directory.Delete(dir, true); } catch { } } - } - - private static void ProfileValues() - { - var v = new ServerProfileValues(); - int r0 = v.Revision; - Check.True(v.Set("voidDotDurationScale", 1.35), "set"); - Check.True(v.Revision > r0, "a change bumps the revision"); - int r1 = v.Revision; - Check.True(v.Set("voidDotDurationScale", 1.35) && v.Revision == r1, "the same value is no change"); - Check.False(v.Set("bad key", 1) || v.Set("", 1) || v.Set("x", double.NaN) || v.Set("y", double.PositiveInfinity), "bad keys and numbers"); - - ServerPackInfo info = new("conquest", "Conquest", new[] { "h" }, new[] { "Conquest" }); - string json = ServerPackProfile.BuildJson(info, "RynthConquest", "0.2.0", true, "Conquest", v.Snapshot(out int rev)); - Check.Eq(rev, v.Revision, "the snapshot's revision"); - Check.Near(RynthCore.Plugin.Shared.ServerProfileView.Value(json, "voidDotDurationScale", 1), 1.35, 1e-12, "a reader gets the value"); - Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value(json, "other", 7), 7.0, "a missing value falls back"); - Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value("", "voidDotDurationScale", 1), 1.0, "no profile falls back"); - Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value("{\"values\":{\"k\":\"2\"}}", "k", 1), 1.0, "text is not a number"); - Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value("{broken", "k", 3), 3.0, "broken JSON falls back"); - using (JsonDocument doc = JsonDocument.Parse(ServerPackProfile.BuildJson(info, "RynthConquest", "0.2.0", true, "Conquest"))) - Check.Eq(doc.RootElement.GetProperty("values").EnumerateObject().Count(), 0, "no values: an empty object"); - - Check.True(v.Remove("voidDotDurationScale") && !v.Remove("voidDotDurationScale"), "remove"); - v.Set("a", 1); - int r2 = v.Revision; - v.Clear(); - Check.True(v.Revision > r2 && v.Snapshot(out _).Length == 0, "clear (logout)"); - } - - private static void ReplyWindow() - { - var req = new ServerChatRequest(); - Check.False(req.Awaiting(0), "nothing asked"); - req.Sent(1000); - Check.True(req.Awaiting(1000 + ServerChatRequest.WindowMs - 1), "inside the window"); - Check.False(req.Awaiting(1000 + ServerChatRequest.WindowMs), "the window closes"); - req.Sent(1000); - req.Extend(5500); - Check.True(req.Awaiting(7000), "a reply line stretches it"); - req.Clear(); - Check.False(req.Awaiting(1001), "cleared"); - } -} diff --git a/Tools/RynthServerPack.Tests/ServerPackModelTests.cs b/Tools/RynthServerPack.Tests/ServerPackModelTests.cs deleted file mode 100644 index f77ac4c..0000000 --- a/Tools/RynthServerPack.Tests/ServerPackModelTests.cs +++ /dev/null @@ -1,243 +0,0 @@ -using System; -using System.Linq; -using System.Text.Json; -using RynthCore.Plugin.ServerPack; -using RynthCore.RynthAiTests.Harness; - -namespace RynthServerPack.Tests; - -// The shared server-plugin model (Plugins\Shared\ServerPack\ServerPackModel.cs): RynthCore's -// "servermenu" verdict for the plugin's own server, the world-name fallback before one arrives, -// the override commands the card sends, and the sections manifest RynthCore reads. -internal static class ServerPackModelTests -{ - public static void Register(Runner r) - { - r.Add("server pack: RynthCore's push gives this server's verdict, override and reason", EnginePush); - r.Add("server pack: a push without this server, or not a push, changes nothing", ForeignPush); - r.Add("server pack: before any push the world name decides", WorldFallback); - r.Add("server pack: override commands are checked before sending", ForceCommands); - r.Add("server pack: the sections manifest declares the server and a server-only card", SectionsJson); - r.Add("server pack: logout clears the verdict", ClearOnLogout); - r.Add("server pack: the card's botting line and address", InfoText); - r.Add("server pack: the RynthServer.Profile JSON carries the server's settings", ProfileJson); - r.Add("server pack: the profile JSON is plain ASCII and escaped", ProfileJsonAscii); - } - - private static void ProfileJson() - { - ServerPackInfo info = new("Coldeve", "Coldeve", new[] { "play.coldeve.ac" }, new[] { "Coldeve" }) - { - Port = 9050, Ruleset = "PvP", Status = "Stable", Botting = BottingPolicy.Restricted, BottingNote = "attended only", - AccountLimit = "3 accounts", Facts = new[] { "fact one" }, Commands = new[] { new ServerCommand("/x", "does x") }, - Discord = "https://discord.gg/x", - }; - string json = ServerPackProfile.BuildJson(info, "RynthColdeve", "0.1.2", true, "Coldeve"); - using JsonDocument doc = JsonDocument.Parse(json); - JsonElement root = doc.RootElement; - Check.Eq(root.GetProperty("schema").GetInt32(), ServerPackProfile.Schema, "schema"); - Check.Eq(root.GetProperty("id").GetString(), "coldeve", "id (lower-cased)"); - Check.Eq(root.GetProperty("plugin").GetString(), "RynthColdeve", "plugin"); - Check.Eq(root.GetProperty("version").GetString(), "0.1.2", "version"); - Check.True(root.GetProperty("active").GetBoolean(), "active"); - Check.Eq(root.GetProperty("world").GetString(), "Coldeve", "world"); - Check.Eq(root.GetProperty("hosts")[0].GetString(), "play.coldeve.ac", "hosts"); - Check.Eq(root.GetProperty("port").GetInt32(), 9050, "port"); - Check.Eq(root.GetProperty("ruleset").GetString(), "PvP", "ruleset"); - Check.Eq(root.GetProperty("botting").GetString(), "restricted", "botting"); - Check.Eq(root.GetProperty("bottingNote").GetString(), "attended only", "botting note"); - Check.Eq(root.GetProperty("facts")[0].GetString(), "fact one", "facts"); - Check.Eq(root.GetProperty("commands")[0].GetProperty("what").GetString(), "does x", "commands"); - Check.Eq(root.GetProperty("discord").GetString(), "https://discord.gg/x", "links"); - - // What a reader (RynthOracle, RynthAi's /ra server) makes of it. - var view = RynthCore.Plugin.Shared.ServerProfileView.Parse(json); - Check.True(view != null, "the shared reader parses it"); - Check.Eq(view!.Summary(), "PvP, ACE; botting restricted - attended only; accounts: 3 accounts", "the reader's summary"); - - // No salvage defined: an empty list, which the Crafting tab reads as "none defined". - Check.Eq(root.GetProperty("salvage").GetArrayLength(), 0, "no salvage: empty list"); - Check.Eq(RynthCore.Plugin.Shared.ServerSalvageView.ParseList(json).Count, 0, "the reader sees none"); - - // Salvage defined: each row round-trips through the shared reader. - ServerPackInfo withSalvage = new("x", "X", new[] { "x.example" }, new[] { "X" }) - { - Salvage = new[] - { - new ServerSalvage("melee", 52, "+1 tink past the cap", "once", UsesTinkSlot: false), - new ServerSalvage("Armor", 64, "+30 armor level"), - new ServerSalvage("", 64, "no bench: skipped"), - }, - }; - var salvage = RynthCore.Plugin.Shared.ServerSalvageView.ParseList( - ServerPackProfile.BuildJson(withSalvage, "RynthX", "1", true, "X")); - Check.Eq(salvage.Count, 2, "rows without a bench are skipped"); - Check.Eq(salvage[0].Bench, "melee", "bench"); - Check.Eq(salvage[0].Material, 52, "material id"); - Check.Eq(salvage[0].Kind, "once", "kind"); - Check.False(salvage[0].UsesTinkSlot, "no tink slot"); - Check.Eq(salvage[1].Bench, "armor", "bench lower-cased"); - Check.Eq(salvage[1].Kind, "tink", "default kind"); - Check.True(salvage[1].UsesTinkSlot, "slot by default"); - Check.Eq(RynthCore.Plugin.Shared.ServerSalvageView.ParseList("{\"id\":\"x\"}").Count, 0, "a profile without the list (older plugins)"); - - // The optional row fields: absent = off / the default, and the writer leaves them out then. - Check.True(salvage.All(v => v.AppliedInt == 0 && !v.Prepared && v.Order == 0 && !v.AfterCap - && v.StackGroup.Length == 0 && v.StackCap == 0), "optional fields default when absent"); - string plain = ServerPackProfile.BuildJson(withSalvage, "RynthX", "1", true, "X"); - Check.True(!plain.Contains("\"applied\"") && !plain.Contains("\"prepared\"") && !plain.Contains("\"order\"") - && !plain.Contains("\"afterCap\"") && !plain.Contains("\"stackGroup\""), "unset fields are not written"); - - ServerPackInfo withRules = new("x", "X", new[] { "x.example" }, new[] { "X" }) - { - Salvage = new[] - { - new ServerSalvage("melee", 52, "post-cap", "once", UsesTinkSlot: false, Order: 995, AfterCap: true), - new ServerSalvage("jewelry", 71, "stack", UsesTinkSlot: false, Order: 50, StackGroup: "jewelry-stack", StackCap: 10), - new ServerSalvage("trinkets", 20, "tier", "once", UsesTinkSlot: false, AppliedInt: 384, Prepared: true, Order: 10), - }, - }; - var rules = RynthCore.Plugin.Shared.ServerSalvageView.ParseList( - ServerPackProfile.BuildJson(withRules, "RynthX", "1", true, "X")); - Check.Eq(rules.Count, 3, "rows with rules"); - Check.True(rules[0].AfterCap && rules[0].Order == 995 && !rules[0].Prepared && rules[0].StackGroup.Length == 0, "after cap + order"); - Check.Eq(rules[1].StackGroup, "jewelry-stack", "stack group"); - Check.Eq(rules[1].StackCap, 10, "stack cap"); - Check.True(rules[2].Prepared && rules[2].AppliedInt == 384 && rules[2].Order == 10 && !rules[2].AfterCap, "prepared + applied + order"); - Check.Eq(RynthCore.Plugin.Shared.ServerSalvageView.ParseList( - "{\"salvage\":[{\"bench\":\"jewelry\",\"material\":64,\"stackGroup\":\"g\"},{\"bench\":\"jewelry\",\"material\":71,\"stackGroup\":\"g\",\"stackCap\":0}]}") - .Count(v => v.StackGroup.Length > 0), 0, "a stack group without a positive cap is no group"); - var odd = RynthCore.Plugin.Shared.ServerSalvageView.ParseList( - "{\"salvage\":[{\"bench\":\"melee\",\"material\":52,\"applied\":\"x\",\"prepared\":1,\"order\":null,\"afterCap\":\"yes\"}]}"); - Check.True(odd.Count == 1 && odd[0].AppliedInt == 0 && !odd[0].Prepared && odd[0].Order == 0 && !odd[0].AfterCap, - "fields of the wrong type read as absent"); - - string idle = ServerPackProfile.BuildJson(info, "RynthColdeve", "0.1.2", false, null); - using JsonDocument idleDoc = JsonDocument.Parse(idle); - Check.False(idleDoc.RootElement.GetProperty("active").GetBoolean(), "not active"); - Check.Eq(idleDoc.RootElement.GetProperty("world").GetString(), "", "no world before login"); - Check.Eq(ServerPackProfile.BottingName(BottingPolicy.Unknown), "unknown", "unknown botting"); - } - - private static void ProfileJsonAscii() - { - ServerPackInfo info = new("x", "Caf\u00e9 \"Q\"\n", Array.Empty(), Array.Empty()) { Summary = "a\\b\tc \u2014 d" }; - string json = ServerPackProfile.BuildJson(info, "RynthX", "1", false, ""); - bool ascii = true; - foreach (char c in json) if (c > 0x7e || c < 0x20) ascii = false; - Check.True(ascii, "only printable ASCII: " + json); - using JsonDocument doc = JsonDocument.Parse(json); - Check.Eq(doc.RootElement.GetProperty("name").GetString(), "Caf\u00e9 \"Q\"", "name round-trips (trimmed)"); - Check.Eq(doc.RootElement.GetProperty("summary").GetString(), "a\\b\tc \u2014 d", "summary round-trips"); - } - - private static ServerPackInfo Coldeve() => - new("Coldeve", "Coldeve", new[] { "play.coldeve.ac" }, new[] { "Coldeve" }) { Discord = "https://discord.gg/x" }; - - private const string Push = - "V\tcoldeve\tColdeve\t1\ton\t0\tforced on for this character\n" + - "V\tilt\tInfinite Leaftide\t0\tauto\t0\tnot Infinite Leaftide\n" + - "X\tchar\tChar\n" + - "S\tcoldeve\tColdeve\t1\t/rc server coldeve on\n" + - "I\tColdeve server (RynthColdeve)\t/rc miniremote section char\tWhat is known.\tsection:char\n"; - - private static void EnginePush() - { - var model = new ServerPackModel(Coldeve()); - Check.True(model.ApplyEngine(Push, 1234), "taken"); - ServerVerdictView? v = model.Engine; - Check.True(v != null, "this server's verdict"); - Check.True(v!.Active, "active"); - Check.Eq(v.Force, "on", "override"); - Check.False(v.Detected, "forced, not detected"); - Check.Eq(v.Reason, "forced on for this character", "reason"); - Check.Eq(model.EngineAtMs, 1234L, "when"); - Check.True(model.IsActive("SomewhereElse"), "RynthCore's verdict beats the world name"); - } - - private static void ForeignPush() - { - var model = new ServerPackModel(Coldeve()); - Check.False(model.ApplyEngine("X\tchar\tChar\n", 1), "no server lines: not a push"); - Check.False(model.ApplyEngine(null, 1), "null"); - Check.False(model.ApplyEngine(new string('V', ServerPackModel.MaxPayload + 1), 1), "too long"); - Check.True(model.Engine == null, "nothing published"); - - // A push that lists other servers but not this one yet (RynthCore hasn't read the manifest). - Check.True(model.ApplyEngine("V\tilt\tInfinite Leaftide\t1\tauto\t1\thost matches\n", 2), "a push"); - Check.True(model.Engine == null, "no verdict for this server"); - ServerPackModel.ParseEngine("V\tCOLDEVE\tColdeve\t0\tweird\t1\n", "coldeve", out bool listed); - Check.True(listed, "listed"); - Check.Eq(ServerPackModel.ParseEngine("V\tCOLDEVE\tColdeve\t0\tweird\t1\n", "coldeve", out _)!.Force, "auto", - "id case ignored; an unknown override reads as auto; no reason field is fine"); - } - - private static void WorldFallback() - { - var model = new ServerPackModel(Coldeve()); - Check.True(model.IsActive("Coldeve"), "exact world name"); - Check.True(model.IsActive(" coldeve "), "case and spaces"); - Check.False(model.IsActive("ColdeveTwo"), "no partial match without '*'"); - Check.False(model.IsActive(null), "unknown world"); - Check.True(ServerPackModel.WorldMatches("Aeshnidae Live", new[] { "Aelrynth*", "Aeshnidae*" }), "wildcard"); - Check.False(ServerPackModel.WorldMatches("LeafDawn", new[] { "Leafdawning" }), "LeafDawn is not Leafdawning"); - Check.True(ServerPackModel.WorldMatches("Infinite Leaftide", new[] { "*Leaftide*" }), "both ends"); - } - - private static void ForceCommands() - { - Check.Eq(ServerPackModel.ForceCommand("coldeve", "On"), "/rc server coldeve on", "on"); - Check.Eq(ServerPackModel.ForceCommand("coldeve", "auto"), "/rc server coldeve auto", "auto"); - Check.Eq(ServerPackModel.ForceCommand("coldeve", "maybe"), "", "unknown mode"); - Check.Eq(ServerPackModel.ForceCommand("cold eve", "on"), "", "an id with a space"); - Check.Eq(ServerPackModel.ForceCommand("coldeve; /quit", "on"), "", "no command injection through the id"); - Check.False(ServerPackModel.IsSafeId(new string('a', 33)), "too long"); - } - - private static void SectionsJson() - { - string json = ServerPackModel.BuildSectionsJson(Coldeve(), "RynthColdeve"); - using JsonDocument doc = JsonDocument.Parse(json); - JsonElement root = doc.RootElement; - Check.Eq(root.GetProperty("version").GetInt32(), 1, "schema 1"); - JsonElement server = root.GetProperty("servers")[0]; - Check.Eq(server.GetProperty("id").GetString(), "coldeve", "server id lower-cased"); - Check.Eq(server.GetProperty("hosts")[0].GetString(), "play.coldeve.ac", "hosts"); - Check.Eq(server.GetProperty("worldNames")[0].GetString(), "Coldeve", "world names"); - JsonElement card = root.GetProperty("contributions")[0]; - Check.Eq(card.GetProperty("section").GetString(), "server", "in the Server section (not Session Stats)"); - JsonElement section = root.GetProperty("sections")[0]; - Check.Eq(section.GetProperty("id").GetString(), "server", "the Server section is declared"); - Check.Eq(section.GetProperty("label").GetString(), "Server", "its label"); - Check.Eq(section.GetProperty("order").GetInt32(), 50, "after Session Stats, before Map"); - Check.Eq(card.GetProperty("server").GetString(), "coldeve", "only while Coldeve is active"); - Check.Eq(card.GetProperty("surface").GetString(), "section:server-coldeve", "the card's surface"); - - var quoted = new ServerPackInfo("odd", "Odd \"Name\"\n", new[] { "a\\b" }, Array.Empty()); - using JsonDocument odd = JsonDocument.Parse(ServerPackModel.BuildSectionsJson(quoted, "RynthOdd")); - Check.Eq(odd.RootElement.GetProperty("servers")[0].GetProperty("hosts")[0].GetString(), "a\\b", "escaped"); - } - - private static void ClearOnLogout() - { - var model = new ServerPackModel(Coldeve()); - model.ApplyEngine(Push, 5); - model.Clear(); - Check.True(model.Engine == null, "verdict cleared"); - Check.Eq(model.EngineAtMs, 0L, "time cleared"); - Check.False(model.IsActive("Elsewhere"), "back to the world name"); - } - - private static void InfoText() - { - ServerPackInfo c = Coldeve(); - Check.Eq(c.Address, "play.coldeve.ac:9000", "address"); - Check.True(c.BottingText.StartsWith("Not published"), "unknown policy says so"); - Check.True(c.BottingText.Contains("Discord"), "and points at the Discord"); - var lev = new ServerPackInfo("example", "Example", new[] { "play.example.test" }, new[] { "Example" }) - { Botting = BottingPolicy.Forbidden, BottingNote = "no automation" }; - Check.Eq(lev.BottingText, "Forbidden - no automation", "forbidden"); - Check.Eq(new ServerPackInfo("x", "", Array.Empty(), Array.Empty()).Address, "", "no host, no address"); - Check.True(ServerPackModel.LauncherSteps(c)[0].Contains("play.coldeve.ac:9000"), "setup names the address"); - } -} diff --git a/Tools/RynthServerPack.Tests/ServerProjectsTests.cs b/Tools/RynthServerPack.Tests/ServerProjectsTests.cs deleted file mode 100644 index def802b..0000000 --- a/Tools/RynthServerPack.Tests/ServerProjectsTests.cs +++ /dev/null @@ -1,137 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Xml.Linq; -using RynthCore.PluginSdk.Manifest; -using RynthCore.RynthAiTests.Harness; - -namespace RynthServerPack.Tests; - -// Every server plugin's csproj (Plugins\RynthCore.Plugin.Rynth*\ with RynthPluginServerId), read as -// XML: the detection data RynthCore's loader and sections use must be unique and must not overlap, -// or a client would load (or show) the wrong server's plugin. -internal static class ServerProjectsTests -{ - public static void Register(Runner r) - { - r.Add("server projects: every listed server has a plugin", AllServersPresent); - r.Add("server projects: ids, plugin names and hosts are unique", Unique); - r.Add("server projects: no server's host is claimed by another server's list", NoHostOverlap); - r.Add("server projects: each new server plugin has ServerData.cs and imports the shared props", Layout); - r.Add("server projects: RynthOracle and RynthInventory send no server's own commands (they live in its plugin)", SharedPluginsServerFree); - } - - /// - /// Since 2026-10-20 a server's own features live in its server plugin (RynthConquest, RynthAelrynth): - /// the shared plugins' sources hold none of those servers' commands or chat markers, and use the - /// server tags only to pick a quest pack (data, RynthOracle's ServerIdentity.cs). - /// - private static void SharedPluginsServerFree() - { - string[] commands = { "\"/bank", "\"/b\"", "\"/augs", "\"/enl augs", "\"/bonus", "\"/fship list", "\"/top", "\"/trial", "\"/mule-data", "\"~ael1" }; - foreach (string plugin in new[] { "RynthCore.Plugin.RynthOracle", "RynthCore.Plugin.RynthInventory" }) - { - string dir = Path.Combine(PluginsDir(), plugin); - var files = Directory.GetFiles(dir, "*.cs", SearchOption.AllDirectories) - .Where(f => !f.Contains(Path.DirectorySeparatorChar + "obj" + Path.DirectorySeparatorChar) - && !f.Contains(Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar)) - .ToList(); - Check.True(files.Count > 10, plugin + ": its sources were found (" + files.Count + ")"); - foreach (string file in files) - { - string text = File.ReadAllText(file); - string name = plugin + "/" + Path.GetRelativePath(dir, file); - foreach (string c in commands) - Check.False(text.Contains(c, StringComparison.Ordinal), $"{name} sends no server command {c.TrimStart('"')}"); - if (!file.EndsWith("ServerIdentity.cs", StringComparison.Ordinal)) - Check.False(text.Contains("ServerTags.Conquest", StringComparison.Ordinal) || text.Contains("ServerTags.Aelrynth", StringComparison.Ordinal), - $"{name} has no Conquest or Aelrynth feature"); - } - } - } - - private sealed record Project(string Dir, string PluginName, string Id, string Name, string[] Hosts, string[] Worlds, bool Shared); - - /// The servers in the request (the server list's busiest, plus Aelrynth) and their plugins. - private static readonly string[] Expected = - { - "coldeve", "ilt", "frostace", "reefcull", "conquest", "dreamweave", "portalstorm", "sundering", - "achard", "leafdawn", "derptide", "frostcull", "thistlecrown", "eversong", "leafdawning", "aelrynth", - }; - - private static string PluginsDir() - { - string? dir = AppContext.BaseDirectory; - while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack"))) - dir = Path.GetDirectoryName(dir); - if (dir == null) throw new DirectoryNotFoundException("RynthSuite\\Plugins not found above " + AppContext.BaseDirectory); - return Path.Combine(dir, "Plugins"); - } - - private static List Load() - { - var list = new List(); - foreach (string dir in Directory.GetDirectories(PluginsDir(), "RynthCore.Plugin.Rynth*")) - { - string csproj = Path.Combine(dir, Path.GetFileName(dir) + ".csproj"); - if (!File.Exists(csproj)) continue; - XDocument doc = XDocument.Load(csproj); - string Prop(string name) => doc.Descendants(name).FirstOrDefault()?.Value.Trim() ?? ""; - string id = Prop("RynthPluginServerId"); - if (id.Length == 0) continue; - string[] Split(string v) => v.Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - bool shared = doc.Descendants("Import").Any(i => (i.Attribute("Project")?.Value ?? "").EndsWith("ServerPlugin.props")); - string asm = Prop("AssemblyName"); - list.Add(new Project(dir, asm.Replace("RynthCore.Plugin.", ""), id, Prop("RynthPluginServerName"), - Split(Prop("RynthPluginServerHosts")), Split(Prop("RynthPluginServerWorldNames")), shared)); - } - return list; - } - - private static void AllServersPresent() - { - List projects = Load(); - foreach (string id in Expected) - Check.True(projects.Any(p => p.Id == id), "a server plugin for " + id); - Check.Eq(projects.Count, Expected.Length, "no unexpected server plugins"); - } - - private static void Unique() - { - List projects = Load(); - Check.Eq(projects.Select(p => p.Id).Distinct().Count(), projects.Count, "ids unique"); - Check.Eq(projects.Select(p => p.PluginName.ToLowerInvariant()).Distinct().Count(), projects.Count, "plugin names unique"); - var hosts = projects.SelectMany(p => p.Hosts).Select(h => h.ToLowerInvariant()).ToList(); - Check.Eq(hosts.Distinct().Count(), hosts.Count, "hosts unique"); - foreach (Project p in projects) - { - Check.True(p.Hosts.Length > 0, p.PluginName + " lists a host (the loader picks plugins by host)"); - Check.True(p.Worlds.Length > 0, p.PluginName + " lists a world name"); - Check.True(p.Name.Length > 0, p.PluginName + " has a display name"); - } - } - - private static void NoHostOverlap() - { - List projects = Load(); - foreach (Project owner in projects) - foreach (string host in owner.Hosts.Where(h => !h.Contains('*'))) - foreach (Project other in projects.Where(o => o != owner)) - { - var server = new RynthPluginServer { Id = other.Id, Hosts = other.Hosts.ToList() }; - Check.False(server.MatchesHost(host, out string hit), - $"{owner.PluginName}'s host {host} is not claimed by {other.PluginName} ({hit})"); - } - } - - private static void Layout() - { - foreach (Project p in Load().Where(p => p.Id != "ilt")) - { - Check.True(p.Shared, p.PluginName + " imports Shared\\ServerPack\\ServerPlugin.props"); - Check.True(File.Exists(Path.Combine(p.Dir, "ServerData.cs")), p.PluginName + " has ServerData.cs"); - } - } - -} diff --git a/Tools/RynthServerPack.Tests/VaultTests.cs b/Tools/RynthServerPack.Tests/VaultTests.cs deleted file mode 100644 index 59ad0e8..0000000 --- a/Tools/RynthServerPack.Tests/VaultTests.cs +++ /dev/null @@ -1,229 +0,0 @@ -using System.Collections.Generic; -using RynthCore.Plugin.RynthAelrynth; -using RynthCore.Plugin.Shared; -using RynthCore.RynthAiTests.Harness; - -namespace RynthServerPack.Tests; - -// The Aelrynth account vault: /mule-data answers, one "~ael1" line a page (Aeshnidae.Mule MuleData.cs). -// Moved with the feed from RynthInventory.Tests on 2026-10-20: RynthAelrynth reads the vault now and -// hands it to RynthInventory through the storage feed (Plugins/Shared/StorageFeed.cs). -internal static class VaultTests -{ - public static void Register(Runner r) - { - r.Add("vault: pages are asked one after the other and filed as one record", Pages); - r.Add("vault: other plugins' lines and players' imitations are left alone", Imitations); - r.Add("vault: a server without the command is asked once", Unsupported); - r.Add("vault: loading, changed and silent vaults are never filed half or empty", Retries); - r.Add("vault: RynthAelrynth asks after login, every ten minutes and on /rserver vault", Schedule); - r.Add("vault: the record reaches RynthInventory's format intact (plain ASCII)", HandOff); - } - - private const string A = "{\"o\":2147483649,\"w\":100,\"n\":\"Acid Assagai\",\"i\":100667000,\"u\":100667001,\"v\":100667002,\"s\":3,\"m\":100,\"y\":1,\"e\":1}"; - private const string B = "{\"o\":2147483650,\"w\":101,\"n\":\"Pyreal\",\"i\":100667003,\"y\":8192}"; - - private static string VaultPage(int page, int pages, int count, string items, bool ready = true, string why = "") => - ready - ? "~ael1 {\"t\":\"mule\",\"ready\":true,\"page\":" + page + ",\"pages\":" + pages + ",\"count\":" + count + ",\"max\":1000,\"items\":[" + items + "]}" - : "~ael1 {\"t\":\"mule\",\"ready\":false,\"why\":\"" + why + "\"}"; - - private static (VaultFeed Feed, List Sent) NewVault() - { - var sent = new List(); - return (new VaultFeed(t => { sent.Add(t); return true; }), sent); - } - - private static void Pages() - { - (VaultFeed v, List sent) = NewVault(); - Check.True(v.Ask(1000), "ask starts"); - Check.Eq(sent.Count == 1 ? sent[0] : "?", "/mule-data", "page 1 asked first"); - Check.True(v.ShouldEat(VaultPage(1, 2, 2, A)), "page 1 is eaten"); - v.Tick(1100, "Tom"); - Check.Eq(sent.Count == 2 ? sent[1] : "?", "/mule-data 2", "page 2 asked when page 1 came"); - Check.Null(v.Record, "nothing filed before the last page"); - Check.True(v.ShouldEat(VaultPage(2, 2, 2, B)), "page 2 is eaten"); - v.Tick(1200, "Tom"); - StorageFeedRecord? r = v.Record; - Check.True(r != null && v.TakeChanged() && !v.TakeChanged(), "filed once"); - Check.Eq(r?.Items.Count ?? -1, 2, "both pages' items"); - Check.Eq(r?.Id ?? 0, VaultFeed.VaultId("tom"), "id follows the account, case-blind"); - Check.True(StorageFeed.IsStandInId(r?.Id ?? 0), "id is a stand-in, far from real objects"); - Check.Eq(r?.Label ?? "", "Account vault", "label"); - Check.Eq(r?.Name ?? "", "Aelrynth vault", "name"); - StorageFeedItem a = r!.Items[0]; - Check.Eq(a.Name, "Acid Assagai", "name"); Check.Eq(a.Icon, 100667000u, "icon"); Check.Eq(a.Underlay, 100667001u, "underlay"); - Check.Eq(a.Overlay, 100667002u, "overlay"); Check.Eq(a.Stack, 3, "stack"); Check.Eq(a.MaxStack, 100, "max stack"); - Check.Eq(a.ItemType, 1u, "item type"); - Check.Eq(r.Items[1].Stack, 1, "no stack field is a stack of 1"); - Check.Eq(v.Status, VaultFeed.State.Idle, "idle again"); - Check.Eq(VaultFeed.VaultId("Tom"), 0xFF000000u | (FnvOf("tom") & 0x00FFFFFFu), "the id RynthInventory used before the move (no second vault)"); - } - - private static uint FnvOf(string s) - { - uint h = 2166136261u; - foreach (char c in s) { h ^= c; h *= 16777619u; } - return h; - } - - private static void Imitations() - { - { - (VaultFeed v, _) = NewVault(); - v.Ask(0); - Check.False(v.ShouldEat("~ael1 {\"t\":\"inspect\",\"ok\":true}"), "the Companion's line stays visible"); - Check.False(v.ShouldEat("Welcome to Aelrynth"), "ordinary chat stays visible"); - Check.False(v.ShouldEat(null), "null is fine"); - } - { - (VaultFeed v, _) = NewVault(); - v.Ask(0); - Check.False(v.ShouldEat("Bob says, \"" + VaultPage(1, 1, 1, A) + "\"", 2), "spoken data line is not ours"); - Check.False(v.ShouldEat("Bob " + VaultPage(1, 1, 1, A), 12), "an emoted data line is not ours"); - Check.False(v.ShouldEat("Bob " + VaultPage(1, 1, 1, A)), "a data line not at the start is not ours, type unknown"); - Check.False(v.ShouldEat(VaultPage(1, 1, 1, A), 3), "a data line in a tell is not ours"); - Check.False(v.ShouldEat("Bob tells you, \"Unknown command: mule-data\"", 3), "a told unknown-command line is not ours"); - Check.False(v.ShouldEat("Unknown command: mule-data", 2), "unknown-command in speech is not ours"); - Check.False(v.ShouldEat("Unknown command: mule-data-ish"), "another command's refusal is not ours"); - Check.True(v.ShouldEat("Unknown command: mule-data", 15), "ACE's real reply (Help) is ours"); - } - { - (VaultFeed v, _) = NewVault(); - v.Ask(0); - Check.True(v.ShouldEat(" " + VaultPage(1, 1, 1, A), 0), "the server's line (Broadcast), leading space allowed"); - } - { - (VaultFeed v, _) = NewVault(); - Check.True(v.ShouldEat(VaultPage(1, 1, 1, A)), "a line typed by hand while we are not asking is eaten"); - v.Tick(0, "tom"); - Check.Null(v.Record, "but ignored when we did not ask"); - } - } - - private static void Unsupported() - { - { - (VaultFeed v, List sent) = NewVault(); - v.Ask(0); - Check.True(v.ShouldEat("Unknown command: /mule-data"), "the unknown-command reply is eaten while we wait"); - v.Tick(100, "tom"); - Check.Eq(v.Status, VaultFeed.State.Unsupported, "unsupported"); - Check.False(v.Ask(200), "not asked again"); - Check.Eq(sent.Count, 1, "one probe, no more"); - Check.True(v.Ask(300, force: true), "/rserver vault asks anyway"); - } - { - (VaultFeed v, _) = NewVault(); - Check.False(v.ShouldEat("Unknown command: /mule-data"), "an unknown-command line we did not provoke is left alone"); - } - } - - private static void Retries() - { - // A vault the server is still loading is asked again, and never recorded as empty. - { - (VaultFeed v, List sent) = NewVault(); - v.Ask(0); - v.ShouldEat(VaultPage(1, 1, 0, "", ready: false, why: "loading")); - v.Tick(10, "tom"); - Check.Eq(v.Status, VaultFeed.State.Waiting, "waiting"); - v.Tick(2000, "tom"); - Check.Eq(sent.Count, 1, "not before the retry delay"); - v.Tick(3500, "tom"); - Check.Eq(sent.Count, 2, "asked again after it"); - Check.Null(v.Record, "never recorded"); - for (int i = 0; i < 10; i++) - { - v.ShouldEat(VaultPage(1, 1, 0, "", ready: false, why: "loading")); - v.Tick(4000 + i * 4000, "tom"); - } - Check.True(v.Status != VaultFeed.State.Asking || sent.Count < 12, "it gives up after a few tries"); - Check.Null(v.Record, "still never recorded"); - } - // A vault that changed between pages is read again, not filed half and half. - { - (VaultFeed v, _) = NewVault(); - v.Ask(0); - v.ShouldEat(VaultPage(1, 2, 3, A)); - v.Tick(10, "tom"); - v.ShouldEat(VaultPage(2, 2, 3, B)); // 2 read, the server says 3 - v.Tick(20, "tom"); - Check.Null(v.Record, "a mismatched read is not filed"); - Check.Eq(v.Status, VaultFeed.State.Waiting, "and is retried"); - } - // Silence is an idle feed, not a stuck one. - { - (VaultFeed v, _) = NewVault(); - v.Ask(0); - v.Tick(20_000, "tom"); - Check.Eq(v.Status, VaultFeed.State.Idle, "no answer in time"); - Check.True(v.Ask(21_000), "can ask again"); - } - // Garbage inside a mule line does not throw. - { - (VaultFeed v, _) = NewVault(); - v.Ask(0); - v.ShouldEat("~ael1 {\"t\":\"mule\",\"ready\":tru"); - v.Tick(5, "tom"); - Check.True(v.Record == null && v.Status == VaultFeed.State.Idle, "bad JSON drops the read"); - } - } - - private static void Schedule() - { - var sent = new List(); - var f = new AelrynthFeature { SendCommand = t => { sent.Add(t); return true; } }; - f.Reset(); - long login = 50_000; - Check.Null(f.VaultTick(login, "tom"), "nothing at login"); - Check.Eq(sent.Count, 0, "not asked at once"); - f.VaultTick(login + VaultFeed.FirstAskMs - 1, "tom"); - Check.Eq(sent.Count, 0, "not before the first delay"); - f.VaultTick(login + VaultFeed.FirstAskMs, "tom"); - Check.Eq(sent.Count == 1 ? sent[0] : "?", "/mule-data", "asked after the first delay"); - Check.True(f.OnChatLine(VaultPage(1, 1, 1, A), 0, login + VaultFeed.FirstAskMs + 10), "its reply is always hidden"); - StorageFeedRecord? read = f.VaultTick(login + VaultFeed.FirstAskMs + 20, "tom"); - Check.True(read != null && read.Items.Count == 1, "the finished read is handed back once"); - Check.Null(f.VaultTick(login + VaultFeed.FirstAskMs + 30, "tom"), "and only once"); - f.VaultTick(login + VaultFeed.FirstAskMs + VaultFeed.RefreshMs, "tom"); - Check.Eq(sent.Count, 2, "read again ten minutes later"); - f.OnChatLine(VaultPage(1, 1, 1, A), 0, login + VaultFeed.FirstAskMs + VaultFeed.RefreshMs + 1); - f.VaultTick(login + VaultFeed.FirstAskMs + VaultFeed.RefreshMs + 2, "tom"); - Check.True(f.VaultAskNow(login + 700_000) && sent.Count == 3, "/rserver vault reads it now"); - - // A server without the command: one probe per login, then quiet. - var g = new AelrynthFeature { SendCommand = t => { sent.Add(t); return true; } }; - g.Reset(); - int before = sent.Count; - g.VaultTick(0, "tom"); - g.VaultTick(VaultFeed.FirstAskMs, "tom"); - g.OnChatLine("Unknown command: mule-data", 0, VaultFeed.FirstAskMs + 1); - g.VaultTick(VaultFeed.FirstAskMs + 2, "tom"); - g.VaultTick(VaultFeed.FirstAskMs + 3 * VaultFeed.RefreshMs, "tom"); - Check.Eq(sent.Count - before, 1, "no vault on the server: asked once, then never on a timer"); - g.Reset(); - Check.Eq(g.Vault.Status, VaultFeed.State.Idle, "the next login asks again"); - } - - private static void HandOff() - { - var items = new List - { - new(2147483649u, 100, "Acid \"Assagai\" \\ é", 100667000, 100667001, 100667002, 3, 100, 1), - new(2147483650u, 101, "Pyreal", 100667003, 0, 0, 1, 0, 8192), - }; - var rec = new StorageFeedRecord(VaultFeed.VaultId("tom"), VaultFeed.VaultName, VaultFeed.Label, items); - string json = StorageFeed.ToJson(rec); - bool ascii = true; - foreach (char c in json) if (c > 0x7e || c < 0x20) ascii = false; - Check.True(ascii, "plain ASCII (the broker carries ANSI)"); - StorageFeedRecord? back = StorageFeed.Parse(json, out string error); - Check.Eq(error, "", "parsed"); - Check.True(back != null && back.Id == rec.Id && back.Name == rec.Name && back.Label == rec.Label && back.Items.Count == 2, "the record"); - Check.Eq(back!.Items[0], items[0], "an item, name escapes included"); - Check.Eq(back.Items[1], items[1], "another"); - Check.Eq(StorageFeed.TargetPlugin + "/" + StorageFeed.Action, "RynthInventory/storage", "sent to RynthInventory's \"storage\" command"); - } -} diff --git a/Tools/RynthSuite.BoundaryTests/Program.cs b/Tools/RynthSuite.BoundaryTests/Program.cs new file mode 100644 index 0000000..6d3fd01 --- /dev/null +++ b/Tools/RynthSuite.BoundaryTests/Program.cs @@ -0,0 +1,182 @@ +using System.Text.RegularExpressions; +using System.Xml.Linq; + +namespace RynthSuite.BoundaryTests; + +/// +/// RynthCore is the hook layer, RynthAi is a plugin, and one server's features live only in that +/// server's plugin (RynthServers). These checks keep RynthSuite's side of that true: a feature for +/// one server that lands in a shared plugin fails here before it merges. +/// +internal static class Program +{ + private static int _checks, _failed; + + /// Every server with a plugin of its own (RynthServers), as code would name it. + private static readonly Regex ServerNames = new( + @"Ilt[A-Z]|RynthIlt|Leaftide|Conquest|Aelrynth|Levistras|DreamWeave|Coldeve|FrostACE|Reefcull|PortalStorm|" + + @"Sundering|AChard|Derptide|Frostcull|Thistlecrown|Eversong|LeafDawn|Leafdawning", + RegexOptions.CultureInvariant); + + /// Servers' own chat commands and markers: their plugins send and read them. + private static readonly string[] ServerCommands = + { "\"/bank", "\"/b\"", "\"/augs", "\"/enl augs", "\"/bonus", "\"/fship list", "\"/top", "\"/trial", "\"/mule-data", "\"~ael1" }; + + /// + /// Kept on purpose, each with its reason. A file here may name a server in code; nothing else may. + /// + private static readonly Dictionary Allowed = new(StringComparer.OrdinalIgnoreCase) + { + // The DreamWeave owners asked for the Threads patrol block to hold even without RynthDreamWeave, + // and server plugins are opt-in (2026-10-15). + ["Plugins/RynthCore.Plugin.RynthAi/ServerPolicy.cs"] = "DreamWeave's Threads patrol block (owners' request)", + }; + + /// Game words that are also servers' names: allowed in these files only. + private static readonly (string File, string Word, string Why)[] GameWords = + { + ("Plugins/RynthCore.Plugin.RynthLua/LuaEnumData.cs", "PortalStorm", "AC's PlayScript effect of that name"), + ("Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs", "Leafdawning", "a month of Dereth's calendar"), + ("Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs", "Coldeve", "a month of Dereth's calendar"), + }; + + private static int Main() + { + string root = RepoRoot(); + Console.WriteLine("RynthSuite at " + root); + NoServerPlugins(root); + SharedCodeNamesNoServer(root); + NoServerCommands(root); + NoServerOnlyLinks(root); + Console.WriteLine(); + Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); + Console.WriteLine(_failed == 0 ? "ALL BOUNDARY CHECKS PASSED." : $"{_failed} FAILED."); + return _failed == 0 ? 0 : 1; + } + + /// No project here is a server plugin: they are RynthServers' (2026-10-21). + private static void NoServerPlugins(string root) + { + foreach (string proj in Projects(root)) + { + string rel = Rel(root, proj); + XDocument doc = XDocument.Load(proj); + bool serverId = doc.Descendants().Any(e => e.Name.LocalName == "RynthPluginServerId"); + bool serverProps = doc.Descendants().Any(e => e.Name.LocalName == "Import" + && (e.Attribute("Project")?.Value ?? "").Contains("ServerPlugin.props", StringComparison.OrdinalIgnoreCase)); + Check(!serverId && !serverProps, $"{rel} is not a server plugin (they live in RynthServers)"); + } + Check(!Directory.Exists(Path.Combine(root, "Plugins", "Shared", "ServerPack")), "Plugins/Shared/ServerPack is RynthServers'"); + } + + /// The shared plugins' code (comments aside) names no server. + private static void SharedCodeNamesNoServer(string root) + { + var files = Sources(root).ToList(); + Check(files.Count > 200, $"the plugin sources were found ({files.Count})"); + foreach (string file in files) + { + string rel = Rel(root, file); + if (Allowed.ContainsKey(rel)) continue; + var named = new List(); + string[] lines = File.ReadAllLines(file); + bool block = false; + for (int i = 0; i < lines.Length; i++) + { + string code = CodeOf(lines[i], ref block); + foreach (Match m in ServerNames.Matches(code)) + if (!GameWords.Any(g => g.File.Equals(rel, StringComparison.OrdinalIgnoreCase) && g.Word == m.Value)) + named.Add($"line {i + 1} ({m.Value})"); + } + Check(named.Count == 0, $"{rel} names no server in code: {string.Join(", ", named)}"); + } + } + + /// No server's own command or chat marker is sent or read by a shared plugin. + private static void NoServerCommands(string root) + { + foreach (string file in Sources(root)) + { + string rel = Rel(root, file); + if (Allowed.ContainsKey(rel)) continue; + bool block = false; + string code = string.Join("\n", File.ReadAllLines(file).Select(l => CodeOf(l, ref block))); + foreach (string c in ServerCommands) + Check(!code.Contains(c, StringComparison.Ordinal), $"{rel} sends no server command {c.TrimStart('"')}"); + } + } + + /// No project links a server-only source (ILT's contracts, the ServerPack build). + private static void NoServerOnlyLinks(string root) + { + var serverOnly = new Regex(@"RynthIlt[A-Za-z]*Api\.cs|PetCaptureLines\.cs|[\\/]ServerPack[\\/]|RynthCore\.Plugin\.Rynth(ILT|Threads|Aelrynth|Conquest|Levistras)[\\/]", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + foreach (string proj in Projects(root)) + { + string rel = Rel(root, proj); + var links = XDocument.Load(proj).Descendants() + .Select(e => e.Attribute("Include")?.Value ?? e.Attribute("Project")?.Value) + .Where(v => v != null && serverOnly.IsMatch(v!)).ToList(); + Check(links.Count == 0, $"{rel} links no server-only file: {string.Join(", ", links)}"); + } + } + + // ── Helpers ────────────────────────────────────────────────────────── + + private static IEnumerable Projects(string root) => + Directory.EnumerateFiles(root, "*.csproj", SearchOption.AllDirectories).Where(NotBuildOutput); + + /// The plugins' and shared sources (Plugins/, Shared/), not tests or tools. + private static IEnumerable Sources(string root) => + new[] { "Plugins", "Shared" }.Select(d => Path.Combine(root, d)).Where(Directory.Exists) + .SelectMany(d => Directory.EnumerateFiles(d, "*.cs", SearchOption.AllDirectories)) + .Where(NotBuildOutput); + + private static bool NotBuildOutput(string path) + { + string p = path.Replace('\\', '/'); + return !p.Contains("/obj/") && !p.Contains("/bin/"); + } + + private static string Rel(string root, string path) => Path.GetRelativePath(root, path).Replace('\\', '/'); + + /// A line without its comments (// and /* */ outside string and char literals). + private static string CodeOf(string line, ref bool inBlock) + { + var sb = new System.Text.StringBuilder(line.Length); + bool str = false, chr = false; + for (int i = 0; i < line.Length; i++) + { + char c = line[i]; + if (inBlock) + { + if (c == '*' && i + 1 < line.Length && line[i + 1] == '/') { inBlock = false; i++; } + continue; + } + if (str) { sb.Append(c); if (c == '\\' && i + 1 < line.Length) sb.Append(line[++i]); else if (c == '"') str = false; continue; } + if (chr) { sb.Append(c); if (c == '\\' && i + 1 < line.Length) sb.Append(line[++i]); else if (c == '\'') chr = false; continue; } + if (c == '/' && i + 1 < line.Length && line[i + 1] == '/') break; + if (c == '/' && i + 1 < line.Length && line[i + 1] == '*') { inBlock = true; i++; continue; } + if (c == '"') str = true; + else if (c == '\'') chr = true; + sb.Append(c); + } + return sb.ToString(); + } + + private static string RepoRoot() + { + string? dir = AppContext.BaseDirectory; + while (dir != null && !(Directory.Exists(Path.Combine(dir, "Plugins")) && Directory.Exists(Path.Combine(dir, "Tools")))) + dir = Path.GetDirectoryName(dir); + return dir ?? throw new DirectoryNotFoundException("RynthSuite (Plugins + Tools) not found above " + AppContext.BaseDirectory); + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine("FAIL: " + what); + } +} diff --git a/Tools/RynthSuite.BoundaryTests/RynthSuite.BoundaryTests.csproj b/Tools/RynthSuite.BoundaryTests/RynthSuite.BoundaryTests.csproj new file mode 100644 index 0000000..74fbb23 --- /dev/null +++ b/Tools/RynthSuite.BoundaryTests/RynthSuite.BoundaryTests.csproj @@ -0,0 +1,19 @@ + + + + + Exe + net10.0 + enable + enable + true + RynthSuite.BoundaryTests + + + diff --git a/Tools/RynthThreads.Tests/InferenceTests.cs b/Tools/RynthThreads.Tests/InferenceTests.cs deleted file mode 100644 index ce49350..0000000 --- a/Tools/RynthThreads.Tests/InferenceTests.cs +++ /dev/null @@ -1,297 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using RynthCore.Plugin.RynthThreads.Threads; -using RynthCore.RynthAiTests.Harness; - -namespace RynthThreads.Tests; - -// The odds (Threads/PressInference.cs): rates, intervals and comparisons, on the first real presses -// and on made-up ones. -internal static class InferenceTests -{ - public static void Register(Runner r) - { - r.Add("infer: the 4 real Lead Scarab presses (old JSON lines): rates, intervals, Affinity group", RealPresses); - r.Add("infer: with/without a component; 'more likely' only when clear; 'always' only at 10+", WithWithout); - r.Add("infer: Wilson intervals and the Fisher test", Statistics); - r.Add("infer: exact combinations of components", Combinations); - r.Add("infer: No components and All presses rows; incomplete presses left out", NoComponentsAndAll); - r.Add("infer: Affinity grouping and the split by material", AffinityGroup); - r.Add("infer: per-modifier view: overall, no components, each component (0% too)", ModifierView); - r.Add("infer: values by level, tags, results and modifiers per press", ReportDetails); - r.Add("infer: the sample press runs through the whole report", SampleReport); - } - - /// The first 4 presses from presses.jsonl (2026-10-12, all Lead Scarab), exactly as written. - internal static readonly string[] RealLines = - { - """{"v":1,"id":"ccbf1dd788704e08","time":"2026-10-12T23:44:32.8501639Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Radiant","description":"kills pay x1.84 luminance","numbers":[{"value":1.84,"kind":"mult","text":"x1.84"}]},{"name":"Amethyst Affinity","description":"10% of kills leave amethyst to salvage","numbers":[{"value":10,"kind":"pct","text":"10%"}]},{"name":"Precise","description":"monsters have \u002B27 critical strike rating, landing more critical hits","numbers":[{"value":27,"kind":"plus","text":"\u002B27"}]},{"name":"Guarded","description":"the boss has x1.91 health","numbers":[{"value":1.91,"kind":"mult","text":"x1.91"}]},{"name":"Savage","description":"monsters attack with \u002B35 damage rating, hitting harder","numbers":[{"value":35,"kind":"plus","text":"\u002B35"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Radiant - kills pay x1.84 luminance"," Amethyst Affinity - 10% of kills leave amethyst to salvage"," Precise - monsters have \u002B27 critical strike rating, landing more critical hits"," Guarded - the boss has x1.91 health"," Savage - monsters attack with \u002B35 damage rating, hitting harder","Level 175, 3 entries."],"extra":[]}""", - """{"v":1,"id":"6613196a36424f8c","time":"2026-10-12T23:50:31.1229501Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Radiant","description":"kills pay x1.75 luminance","numbers":[{"value":1.75,"kind":"mult","text":"x1.75"}]},{"name":"Iron Affinity","description":"8% of kills leave iron to salvage","numbers":[{"value":8,"kind":"pct","text":"8%"}]},{"name":"Teeming","description":"67% more monsters","numbers":[{"value":67,"kind":"pct","text":"67%"}]},{"name":"Guarded","description":"the boss has x1.83 health","numbers":[{"value":1.83,"kind":"mult","text":"x1.83"}]},{"name":"Swift","description":"monsters move at x1.21 speed","numbers":[{"value":1.21,"kind":"mult","text":"x1.21"}]},{"name":"Shieldbreaker","description":"monsters ignore 54% of your shield","numbers":[{"value":54,"kind":"pct","text":"54%"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Radiant - kills pay x1.75 luminance"," Iron Affinity - 8% of kills leave iron to salvage"," Teeming - 67% more monsters"," Guarded - the boss has x1.83 health"," Swift - monsters move at x1.21 speed"," Shieldbreaker - monsters ignore 54% of your shield","Level 175, 3 entries."],"extra":[]}""", - """{"v":1,"id":"1e960ea87fa64343","time":"2026-10-13T00:22:04.7703741Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Bounteous","description":"kills drop x1.51 loot","numbers":[{"value":1.51,"kind":"mult","text":"x1.51"}]},{"name":"Serpentine Affinity","description":"22% of kills leave serpentine to salvage","numbers":[{"value":22,"kind":"pct","text":"22%"}]},{"name":"Champions","description":"30% of the run\u0027s monsters are elites","numbers":[{"value":30,"kind":"pct","text":"30%"}]},{"name":"Guarded","description":"the boss has x2.18 health","numbers":[{"value":2.18,"kind":"mult","text":"x2.18"}]},{"name":"Enraged","description":"the boss attacks with \u002B54 damage rating, hitting harder","numbers":[{"value":54,"kind":"plus","text":"\u002B54"}]},{"name":"Precise","description":"monsters have \u002B19 critical strike rating, landing more critical hits","numbers":[{"value":19,"kind":"plus","text":"\u002B19"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Bounteous - kills drop x1.51 loot"," Serpentine Affinity - 22% of kills leave serpentine to salvage"," Champions - 30% of the run\u0027s monsters are elites"," Guarded - the boss has x2.18 health"," Enraged - the boss attacks with \u002B54 damage rating, hitting harder"," Precise - monsters have \u002B19 critical strike rating, landing more critical hits","Level 175, 3 entries."],"extra":[]}""", - """{"v":1,"id":"f0bf2c2811904c52","time":"2026-10-13T00:34:08.9352276Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Enlightened","description":"kills pay x1.43 experience","numbers":[{"value":1.43,"kind":"mult","text":"x1.43"}]},{"name":"Obsidian Affinity","description":"7% of kills leave obsidian to salvage","numbers":[{"value":7,"kind":"pct","text":"7%"}]},{"name":"Shieldbreaker","description":"monsters ignore 51% of your shield","numbers":[{"value":51,"kind":"pct","text":"51%"}]},{"name":"Savage","description":"monsters attack with \u002B33 damage rating, hitting harder","numbers":[{"value":33,"kind":"plus","text":"\u002B33"}]},{"name":"Stalwart","description":"monsters have \u002B20 damage resist rating, taking less damage from you","numbers":[{"value":20,"kind":"plus","text":"\u002B20"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Enlightened - kills pay x1.43 experience"," Obsidian Affinity - 7% of kills leave obsidian to salvage"," Shieldbreaker - monsters ignore 51% of your shield"," Savage - monsters attack with \u002B33 damage rating, hitting harder"," Stalwart - monsters have \u002B20 damage resist rating, taking less damage from you","Level 175, 3 entries."],"extra":["[BANK] Debited 1 Trade Notes (250,000) (250,000 pyreals) from your bank."]}""", - }; - - internal static List Real() => RealLines.Select(l => PressStore.FromJson(l)!).ToList(); - - private static int _n; - - /// A complete press with these components and modifiers ("Name" or "Name=x1.5 text"). - internal static Press P(string components, string modifiers, int level = 100, bool complete = true, int? result = null, int? entries = null) - { - var p = new Press - { - Id = "t" + (++_n), - TimeUtc = new DateTime(2026, 10, 12, 19, 0, 0, DateTimeKind.Utc).AddSeconds(_n), - Character = "Tester", - Server = "DreamWeave", - Fragment = "Raw Fragment", - FragmentLevel = level, - Outcome = "Pressed. It holds.", - ComponentsSeen = true, - Components = PressParser.SplitComponents(components), - Complete = complete, - End = complete ? "done" : "timeout", - ResultLevel = result, - Entries = entries, - }; - foreach (string m in modifiers.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) - { - string[] parts = m.Split('=', 2); - string desc = parts.Length > 1 ? parts[1] : "something"; - p.Modifiers.Add(new GemModifier { Name = parts[0], Description = desc, Numbers = PressParser.Numbers(desc) }); - } - return p; - } - - private static List Many(int count, string components, string modifiers) => - Enumerable.Range(0, count).Select(_ => P(components, modifiers)).ToList(); - - private static Odds? Odd(GroupReport? g, string mod) => g?.Find(mod); - - private static void RealPresses() - { - List presses = Real(); - Check.True(presses.All(p => p != null && p.Usable), "all 4 old lines load as complete presses"); - Check.Eq(string.Join(",", presses.Select(p => p.ComponentsText).Distinct()), "Lead Scarab", "all Lead Scarab"); - ThreadsReport r = PressInference.Build(presses); - GroupReport? ls = r.Component("Lead Scarab"); - Check.NotNull(ls, "Lead Scarab row"); - if (ls == null) return; - Check.Eq(ls.Presses, 4, "4 presses"); - - Odds g = Odd(ls, "Guarded")!; - Check.Eq((g.Hits, g.N), (3, 4), "Guarded 3/4"); - Check.Eq(PressInference.OddsText(g), "75% (3/4, 30-95%)", "Guarded text"); - Check.Eq(g.Values, "x1.83 to x2.18", "Guarded values"); - Odds rad = Odd(ls, "Radiant")!; - Check.Eq(PressInference.OddsText(rad), "50% (2/4, 15-85%)", "Radiant 2/4"); - Check.Eq(PressInference.OddsText(Odd(ls, "Champions")!), "25% (1/4, 5-70%)", "Champions 1/4"); - - Odds aff = Odd(ls, PressInference.AffinityGroup)!; - Check.Eq((aff.Hits, aff.N), (4, 4), "Affinity group 4/4"); - Check.Eq(PressInference.OddsText(aff), "100% (4/4, 51-100%)", "Affinity text"); - Check.Eq(PressInference.SplitText(aff), "Amethyst 1, Iron 1, Obsidian 1, Serpentine 1", "split 1 each"); - Check.Eq(aff.Values, "7% to 22%", "affinity values across materials"); - Check.Null(Odd(ls, "Amethyst Affinity"), "materials are not rows of their own"); - Check.Eq(ls.Odds[0].Modifier, PressInference.AffinityGroup, "sorted by rate: Affinity first"); - Check.Eq(ls.Odds[1].Modifier, "Guarded", "then Guarded"); - - Check.Eq(PressInference.OtherText(g, ls.OtherLabel), "without: no data", "nothing without Lead Scarab"); - Check.False(ls.Odds.Any(o => o.MoreLikely), "no 'more likely' with nothing to compare"); - Check.Eq(r.All?.Presses, 4, "All presses row"); - Check.Eq(r.Combinations.Count, 0, "no combinations"); - Check.Null(r.NoComponents, "no No components row"); - Check.Eq(PressInference.ModifiersText(ls), "5.5 modifiers per press (5-6)", "modifiers per press"); - Check.Eq(PressInference.ResultsText(ls), "L185 -> 175, 3 entries: 4", "results"); - Check.Eq(r.Modifier("Affinity")?.Overall.Hits, 4, "modifier view: Affinity 4/4"); - Check.Null(r.Modifier("Iron Affinity"), "no Iron Affinity modifier entry"); - Check.Eq(r.Modifiers.Count, 13, "13 modifiers (affinities as one)"); - } - - private static void WithWithout() - { - var presses = Many(5, "Red Taper", "Bounteous, Hardy"); - presses.Add(P("Red Taper", "Teeming, Hardy")); - presses.AddRange(Many(3, "", "Hardy, Teeming")); - presses.AddRange(Many(3, "", "Savage, Teeming")); - ThreadsReport r = PressInference.Build(presses); - GroupReport red = r.Component("Red Taper")!; - Odds b = Odd(red, "Bounteous")!; - Check.Eq((b.Hits, b.N, b.OtherHits, b.OtherN), (5, 6, 0, 6), "Bounteous 5/6 with, 0/6 without"); - Check.True(b.MoreLikely, "Bounteous more likely with Red Taper"); - Check.Eq(PressInference.LikelyText(b, red), "more likely with Red Taper", "wording"); - Check.Eq(PressInference.OtherText(b, red.OtherLabel), "without: 0% (0/6)", "without text"); - Odds h = Odd(red, "Hardy")!; - Check.Eq((h.Hits, h.OtherHits), (6, 3), "Hardy 6/6 with, 3/6 without"); - Check.False(h.MoreLikely, "Hardy 6/6 vs 3/6: not clear (p ~ 0.09)"); - Check.Eq(red.Odds[0].Modifier, "Hardy", "sorted by rate: Hardy (100%) first"); - - // Few presses: nothing claimed. - r = PressInference.Build(Many(2, "Blue Taper", "Bounteous").Concat(Many(2, "", "Hardy")).ToList()); - Check.False(Odd(r.Component("Blue Taper"), "Bounteous")!.MoreLikely, "2/2 vs 0/2: not claimed"); - - // 'always' only at 100% over 10 or more. - r = PressInference.Build(Many(9, "Green Taper", "Teeming").Concat(Many(9, "", "Hardy")).ToList()); - GroupReport green = r.Component("Green Taper")!; - Check.Eq(PressInference.LikelyText(Odd(green, "Teeming")!, green), "more likely with Green Taper", "9/9: more likely, not always"); - r = PressInference.Build(Many(10, "Green Taper", "Teeming").Concat(Many(10, "", "Hardy")).ToList()); - green = r.Component("Green Taper")!; - Check.Eq(PressInference.LikelyText(Odd(green, "Teeming")!, green), "always with Green Taper so far", "10/10: always so far"); - - // The No components row is compared with presses that had components. - r = PressInference.Build(Many(6, "Red Taper", "Hardy").Concat(Many(6, "", "Teeming")).ToList()); - Odds t = Odd(r.NoComponents, "Teeming")!; - Check.True(t.MoreLikely, "Teeming 6/6 plain vs 0/6 with components"); - Check.Eq(PressInference.LikelyText(t, r.NoComponents!), "more likely with no components", "no-components wording"); - } - - private static void Statistics() - { - var (lo, hi) = PressInference.Wilson(3, 4); - Check.True(Math.Abs(lo - 0.3006) < 0.001 && Math.Abs(hi - 0.9544) < 0.001, $"3/4: 30.1-95.4% ({lo:0.0000}-{hi:0.0000})"); - (lo, hi) = PressInference.Wilson(0, 5); - Check.True(lo == 0 && Math.Abs(hi - 0.4345) < 0.001, $"0/5: 0-43% ({hi:0.0000})"); - (lo, hi) = PressInference.Wilson(0, 0); - Check.True(lo == 0 && hi == 1, "0/0: anything"); - Check.True(Math.Abs(PressInference.FisherGreater(3, 3, 0, 3) - 0.05) < 1e-9, "3/3 vs 0/3: p = 1/20"); - Check.True(Math.Abs(PressInference.FisherGreater(5, 6, 0, 6) - 7.0 / 924) < 1e-9, "5/6 vs 0/6: p = 7/924"); - Check.True(Math.Abs(PressInference.FisherGreater(0, 4, 4, 4) - 1) < 1e-9, "0 hits: p = 1"); - Check.Eq(PressInference.OddsText(new Odds { Hits = 30, N = 60 }), "50% (30/60)", "no interval from 50 presses"); - Check.Eq(PressInference.OddsText(new Odds { Hits = 0, N = 0 }), "no data", "empty"); - } - - private static void Combinations() - { - var presses = Many(3, "Red Taper, Blue Taper", "Bounteous, Savage"); - presses.AddRange(Many(2, "Red Taper", "Bounteous, Hardy")); - presses.Add(P("Blue Taper", "Savage, Hardy")); - presses.AddRange(Many(2, "", "Hardy, Teeming")); - ThreadsReport r = PressInference.Build(presses); - Check.Eq(r.Combinations.Count, 1, "one combination"); - GroupReport? combo = r.Combination("Blue Taper + Red Taper"); - Check.NotNull(combo, "named by its sorted components"); - if (combo == null) return; - Check.Eq(combo.Presses, 3, "3 presses with exactly both"); - Check.Eq(combo.Members.Count, 2, "two members"); - Check.Eq(r.Component("Red Taper")!.Presses, 5, "component row counts every press with it"); - Check.Eq(r.Component("Blue Taper")!.Presses, 4, "Blue Taper 4"); - Odds s = Odd(combo, "Savage")!; - Check.Eq((s.Hits, s.N, s.OtherHits, s.OtherN), (3, 3, 1, 5), "Savage 3/3 in the combination, 1/5 in other presses"); - Check.Eq(PressInference.OtherText(s, combo.OtherLabel), "other presses: 20% (1/5)", "comparison label"); - Check.Eq(PressInference.Build(Many(2, "Blue Taper, Red Taper", "Hardy").Concat(Many(1, "Red Taper, Blue Taper", "Hardy")).ToList()) - .Combination("Blue Taper + Red Taper")?.Presses, 3, "order of components doesn't matter"); - } - - private static void NoComponentsAndAll() - { - var presses = Many(4, "Red Taper", "Bounteous, Hardy"); - presses.AddRange(Many(2, "", "Hardy, Teeming")); - presses.Add(P("", "Teeming")); - presses.Add(P("Red Taper", "Savage", complete: false)); - presses.Add(P("", "")); // finished but no gem block: not usable - ThreadsReport r = PressInference.Build(presses); - Check.Eq((r.Total, r.Usable, r.Incomplete), (9, 7, 1), "totals"); - Check.Eq(r.Component("Red Taper")!.Presses, 4, "incomplete press left out"); - - GroupReport? nc = r.NoComponents; - Check.NotNull(nc, "No components row"); - if (nc == null) return; - Check.Eq((nc.Presses, nc.Kind), (3, GroupKind.NoComponents), "3 plain presses"); - Odds t = Odd(nc, "Teeming")!; - Check.Eq((t.Hits, t.N, t.OtherHits, t.OtherN), (3, 3, 0, 4), "Teeming 3/3 plain, 0/4 with components"); - Check.Eq(PressInference.OtherText(t, nc.OtherLabel), "with components: 0% (0/4)", "comparison label"); - Check.Eq(nc.Odds[0].Modifier, "Teeming", "most common plain draw first"); - - GroupReport all = r.All!; - Check.Eq((all.Presses, all.Kind), (7, GroupKind.All), "All presses: every usable press"); - Odds h = Odd(all, "Hardy")!; - Check.Eq((h.Hits, h.N), (6, 7), "Hardy 6/7 overall"); - Check.False(h.Compared, "the baseline isn't compared"); - Check.Eq(PressInference.OtherText(h, all.OtherLabel), "", "no comparison text"); - Check.False(all.Odds.Any(o => o.MoreLikely), "never flagged"); - } - - private static void AffinityGroup() - { - Check.Eq(PressInference.Material("Green Garnet Affinity"), "Green Garnet", "two-word material"); - Check.Eq(PressInference.Key("Tourmaline Affinity"), PressInference.AffinityGroup, "grouped"); - Check.Null(PressInference.Material("Affinity"), "bare 'Affinity' is not a material"); - Check.Eq(PressInference.Key("Guarded"), "Guarded", "others keep their name"); - Check.Eq(PressInference.Display(PressInference.AffinityGroup), "Affinity (any)", "display name"); - - var presses = new List - { - P("Red Taper", "Iron Affinity=8% of kills leave iron to salvage, Hardy"), - P("Red Taper", "Iron Affinity=10% of kills leave iron to salvage, Teeming"), - P("Red Taper", "Amethyst Affinity=12% of kills leave amethyst to salvage, Gold Affinity=5% of kills leave gold to salvage"), - P("", "Hardy"), - }; - ThreadsReport r = PressInference.Build(presses); - Odds a = Odd(r.Component("Red Taper"), PressInference.AffinityGroup)!; - Check.Eq((a.Hits, a.N, a.OtherHits, a.OtherN), (3, 3, 0, 1), "a press with two affinities counts once"); - Check.Eq(PressInference.SplitText(a), "Iron 2, Amethyst 1, Gold 1", "split counts both, most first"); - ModifierReport m = r.Modifier("Affinity")!; - Check.True(m.IsGroup, "modifier view: the group"); - Check.Eq(m.Tag, "reward", "salvage: reward"); - Check.Eq(m.Values, "8% to 12%", "values over every material (first affinity per press)"); - } - - private static void ModifierView() - { - var presses = Many(3, "Red Taper", "Bounteous, Hardy"); - presses.AddRange(Many(2, "Blue Taper", "Hardy")); - presses.Add(P("Blue Taper, Red Taper", "Bounteous")); - presses.AddRange(Many(2, "", "Teeming, Bounteous")); - ThreadsReport r = PressInference.Build(presses); - ModifierReport b = r.Modifier("Bounteous")!; - Check.Eq((b.Overall.Hits, b.Overall.N), (6, 8), "overall 6/8"); - Check.Eq((b.NoComponents?.Hits, b.NoComponents?.N, b.NoComponents?.OtherHits, b.NoComponents?.OtherN), ((int?)2, (int?)2, (int?)4, (int?)6), "no components 2/2 vs 4/6"); - Check.Eq(string.Join(", ", b.ByGroup.Select(x => $"{x.Group.Name} {x.Odds.Hits}/{x.Odds.N}")), - "Red Taper 4/4, Blue Taper + Red Taper 1/1, Blue Taper 1/3", "each component and combination, likeliest first"); - Odds teemingBlue = r.Modifier("Teeming")!.ByGroup.First(x => x.Group.Name == "Blue Taper").Odds; - Check.Eq((teemingBlue.Hits, teemingBlue.N, teemingBlue.OtherHits, teemingBlue.OtherN), (0, 3, 2, 5), "0% rows are kept, with their comparison"); - } - - private static void ReportDetails() - { - var presses = new List - { - P("Red Taper", "Bounteous=kills drop x1.38 loot, Hardy=monsters have x1.5 health", level: 185, result: 175, entries: 3), - P("Red Taper", "Bounteous=kills drop x1.52 loot", level: 185, result: 175, entries: 3), - P("Red Taper", "Bounteous=kills drop x1.20 loot", level: 120, result: 110, entries: 2), - P("Red Taper", "Hardy=monsters have x2 health", complete: false), - P("", "Hardy=monsters have x1.81 health, Teeming=75% more monsters", level: 120), - P("", "Teeming=60% more monsters", level: 120), - }; - ThreadsReport r = PressInference.Build(presses); - GroupReport red = r.Component("Red Taper")!; - Check.Eq(PressInference.ResultsText(red), "L185 -> 175, 3 entries: 2; L120 -> 110, 2 entries: 1", "results, most common first"); - Check.Eq(PressInference.ModifiersText(red), "1.33 modifiers per press (1-2)", "modifiers per press"); - Check.Eq(Odd(red, "Bounteous")!.Values, "x1.2 to x1.52", "values with the component"); - - ModifierReport b = r.Modifier("Bounteous")!; - Check.Eq(b.Values, "x1.2 to x1.52", "value range"); - Check.Eq(b.ByLevel.Count, 2, "two fragment levels"); - Check.Eq(b.ByLevel[0].Level, 120, "lowest level first"); - Check.Eq(b.ByLevel[1].Values, "x1.38 to x1.52", "level 185 range"); - Check.Eq(b.Tag, "reward", "loot is a reward"); - Check.Eq(r.Modifier("Hardy")!.Tag, "harder", "monster health is harder"); - Check.Eq(PressInference.Tag("something odd"), "", "no tag when the text doesn't say"); - - ThreadsReport empty = PressInference.Build(new List()); - Check.True(empty.Usable == 0 && empty.All == null && empty.Modifiers.Count == 0, "empty input"); - } - - private static void SampleReport() - { - Press p = new PressParser().Feed(string.Join("\n", ParserTests.Sample), 1)![0]; - ThreadsReport r = PressInference.Build(new[] { p }); - Check.Eq(r.Component("Red Taper")?.Presses, 1, "Red Taper counted"); - Check.Eq(r.Modifiers.Count, 6, "six modifiers in the report"); - Check.Eq(r.Modifier("Affinity")?.Tag, "reward", "salvage is a reward"); - Check.Eq(PressInference.SplitText(r.Modifier("Affinity")!.Overall), "Tourmaline 1", "Tourmaline"); - Check.Eq(r.Modifier("Enraged")?.Tag, "harder", "boss damage is harder"); - Check.Eq(PressInference.OddsText(r.Component("Red Taper")!.Find("Hardy")!), "100% (1/1, 21-100%)", "one press: wide range"); - } -} diff --git a/Tools/RynthThreads.Tests/ParserTests.cs b/Tools/RynthThreads.Tests/ParserTests.cs deleted file mode 100644 index 1c749e9..0000000 --- a/Tools/RynthThreads.Tests/ParserTests.cs +++ /dev/null @@ -1,258 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using RynthCore.Plugin.RynthThreads.Threads; -using RynthCore.RynthAiTests.Harness; - -namespace RynthThreads.Tests; - -// The chat parser (Threads/PressParser.cs). The sample is real DreamWeave chat from 2026-10-12 -// (timestamps removed: the plugin sees the text without them), with another player's line in it. -internal static class ParserTests -{ - public static readonly string[] Sample = - { - "Using the Raw Fragment (Level 185) with the Fragment Press", - "Yorick is recalling to the marketplace.", - "Pressed. It holds.", - "Components selected: Red Taper", - "Remaining slots drawn at random.", - "The gem carries:", - " Bounteous - kills drop x1.38 loot", - " Tourmaline Affinity - 12% of kills leave tourmaline to salvage", - " Hardy - monsters have x1.81 health", - " Enraged - the boss attacks with +29 damage rating, hitting harder", - " Teeming - 75% more monsters", - " Savage - monsters attack with +20 damage rating, hitting harder", - "Level 190, 4 entries.", - }; - - public static void Register(Runner r) - { - r.Add("parse: the real sample, line by line, with another player's line in it", SampleLineByLine); - r.Add("parse: the sample as one message with newlines", SampleOneMessage); - r.Add("parse: several components (commas, 'and'), sorted", SeveralComponents); - r.Add("parse: no components (no line, 'none', 'No components ...')", NoComponents); - r.Add("parse: incomplete presses (timeout, next press, other Using line, logout)", Incomplete); - r.Add("parse: unknown and odd lines never throw and never become modifiers", UnknownLines); - r.Add("parse: numbers and their forms", NumberForms); - } - - private static List FeedAll(PressParser parser, IEnumerable lines, long now = 1000) - { - var done = new List(); - foreach (string line in lines) - if (parser.Feed(line, now) is { } d) done.AddRange(d); - return done; - } - - private static void SampleLineByLine() - { - var parser = new PressParser(); - List done = FeedAll(parser, Sample); - Check.Eq(done.Count, 1, "one press"); - if (done.Count != 1) return; - CheckSample(done[0]); - Check.False(parser.Busy, "parser idle after the Level line"); - } - - private static void SampleOneMessage() - { - var parser = new PressParser(); - List? done = parser.Feed(string.Join("\n", Sample) + "\n", 1000); - Check.Eq(done?.Count ?? 0, 1, "one press from one message"); - if (done is { Count: 1 }) CheckSample(done[0]); - // CRLF too. - done = new PressParser().Feed(string.Join("\r\n", Sample), 1000); - Check.Eq(done?[0].Modifiers.Count ?? -1, 6, "CRLF lines: 6 modifiers"); - } - - internal static void CheckSample(Press p) - { - Check.Eq(p.Fragment, "Raw Fragment", "fragment name"); - Check.Eq(p.FragmentLevel, 185, "fragment level"); - Check.Eq(p.Tool, "Fragment Press", "tool"); - Check.Eq(p.Outcome, "Pressed. It holds.", "outcome"); - Check.True(p.Held, "held"); - Check.True(p.ComponentsSeen, "components line seen"); - Check.Eq(string.Join("|", p.Components), "Red Taper", "components"); - Check.Eq(p.RandomNote, "Remaining slots drawn at random.", "random note"); - Check.Eq(p.ResultLevel, 190, "result level"); - Check.Eq(p.Entries, 4, "entries (raw, not the modifier count)"); - Check.True(p.Complete, "complete"); - Check.Eq(p.End, "done", "end reason"); - Check.Eq(p.Modifiers.Count, 6, "six modifiers"); - Check.Eq(p.Raw.Count, 12, "12 own raw lines"); - Check.Eq(string.Join("|", p.Extra), "Yorick is recalling to the marketplace.", "the foreign line is kept apart"); - Check.False(p.Raw.Any(l => l.Contains("Yorick")), "no foreign line in Raw"); - Check.Eq(p.Raw[5], " Bounteous - kills drop x1.38 loot", "raw lines kept as is (indent too)"); - if (p.Modifiers.Count != 6) return; - - (string Name, string Kinds, string Values, string Desc)[] want = - { - ("Bounteous", "mult", "1.38", "kills drop x1.38 loot"), - ("Tourmaline Affinity", "pct", "12", "12% of kills leave tourmaline to salvage"), - ("Hardy", "mult", "1.81", "monsters have x1.81 health"), - ("Enraged", "plus", "29", "the boss attacks with +29 damage rating, hitting harder"), - ("Teeming", "pct", "75", "75% more monsters"), - ("Savage", "plus", "20", "monsters attack with +20 damage rating, hitting harder"), - }; - for (int i = 0; i < want.Length; i++) - { - GemModifier m = p.Modifiers[i]; - Check.Eq(m.Name, want[i].Name, $"modifier {i} name"); - Check.Eq(m.Description, want[i].Desc, $"{want[i].Name} description"); - Check.Eq(string.Join(",", m.Numbers.Select(n => n.Kind)), want[i].Kinds, $"{want[i].Name} number kinds"); - Check.Eq(string.Join(",", m.Numbers.Select(n => n.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))), want[i].Values, $"{want[i].Name} values"); - } - Check.Eq(p.Modifiers[0].Numbers[0].Text, "x1.38", "text as written"); - Check.Eq(p.Modifiers[3].Numbers[0].Text, "+29", "rating text"); - } - - private static string[] Press(string components, params string[] mods) - { - var lines = new List { "Using the Raw Fragment (Level 100) with the Fragment Press", "Pressed. It holds." }; - if (components != null) lines.Add(components); - lines.Add("Remaining slots drawn at random."); - lines.Add("The gem carries:"); - lines.AddRange(mods.Select(m => " " + m)); - lines.Add("Level 104, 2 entries."); - return lines.ToArray(); - } - - private static void SeveralComponents() - { - Press p = FeedAll(new PressParser(), Press("Components selected: Red Taper, Blue Taper, Pyreal", "Hardy - monsters have x1.5 health")).Single(); - Check.Eq(string.Join("|", p.Components), "Blue Taper|Pyreal|Red Taper", "three, sorted"); - p = FeedAll(new PressParser(), Press("Components selected: Red Taper and Yellow Taper.", "Hardy - x")).Single(); - Check.Eq(string.Join("|", p.Components), "Red Taper|Yellow Taper", "'and' splits, trailing dot dropped"); - p = FeedAll(new PressParser(), Press("Components selected: Red Taper, red taper", "Hardy - x")).Single(); - Check.Eq(p.Components.Count, 1, "the same component twice counts once"); - } - - private static void NoComponents() - { - Press p = FeedAll(new PressParser(), Press(null!, "Teeming - 75% more monsters")).Single(); - Check.False(p.ComponentsSeen, "no line: not seen"); - Check.Eq(p.Components.Count, 0, "no line: none"); - Check.True(p.Complete && p.Usable, "still complete and usable"); - - p = FeedAll(new PressParser(), Press("Components selected: none", "Teeming - 75% more monsters")).Single(); - Check.True(p.ComponentsSeen && p.Components.Count == 0, "'none'"); - p = FeedAll(new PressParser(), Press("No components selected.", "Teeming - 75% more monsters")).Single(); - Check.True(p.ComponentsSeen && p.Components.Count == 0, "'No components selected.'"); - Check.Eq(p.ComponentsText, "no components", "shown as 'no components'"); - } - - private static void Incomplete() - { - // Timeout: the Level line never comes. - var parser = new PressParser(); - string[] lines = Sample.Take(Sample.Length - 1).ToArray(); - Check.Eq(FeedAll(parser, lines, 1000).Count, 0, "nothing finished yet"); - Check.Null(parser.Tick(1000 + PressParser.TimeoutMs - 1), "not before the timeout"); - // Other chat doesn't keep it open. - parser.Feed("Someone says, \"hello\"", 1000 + PressParser.TimeoutMs - 1); - Press? t = parser.Tick(1000 + PressParser.TimeoutMs); - Check.NotNull(t, "timed out"); - if (t != null) - { - Check.False(t.Complete, "incomplete"); - Check.Eq(t.End, "timeout", "reason"); - Check.Eq(t.Modifiers.Count, 6, "what was gathered is kept"); - Check.Null(t.ResultLevel, "no result level"); - Check.False(t.Usable, "not used by the inference"); - } - - // The next press starts before this one's Level line. - parser = new PressParser(); - var done = FeedAll(parser, Sample.Take(4).Concat(Sample)); - Check.Eq(done.Count, 2, "two presses"); - if (done.Count == 2) - { - Check.True(!done[0].Complete && done[0].End == "next use", "first: incomplete, next use"); - Check.Eq(done[0].Outcome, "Pressed. It holds.", "first kept its outcome"); - Check.True(done[1].Complete && done[1].Modifiers.Count == 6, "second complete"); - } - - // Some other "Using ..." line ends it and starts nothing. - parser = new PressParser(); - done = FeedAll(parser, Sample.Take(3).Append("Using the Mana Stone on the Robe of Ages")); - Check.Eq(done.Count, 1, "ended by another Using line"); - Check.False(parser.Busy, "no new press from an unrelated Using line"); - Check.Eq(done.Count == 1 ? done[0].End : "", "next use", "reason"); - - // Logout. - parser = new PressParser(); - FeedAll(parser, Sample.Take(2)); - Press? f = parser.Flush("logout"); - Check.True(f != null && f.End == "logout" && !f.Complete, "flush at logout"); - Check.Null(parser.Flush("logout"), "nothing left to flush"); - } - - private static void UnknownLines() - { - var parser = new PressParser(); - string[] junk = - { - "", " ", "\n\n", "Level 190, 4 entries.", "Pressed. It holds.", " Hardy - monsters have x1.81 health", - new string('x', 5000), "Components selected:", "The gem carries:", "☃ éè ???", "Using", "Using the", - "with the Fragment Press", "1234567890123456789012345678901234567890", " - just a dash", "x%+", - }; - int finished = 0; - foreach (string j in junk) - finished += parser.Feed(j, 1000)?.Count ?? 0; - Check.Eq(finished, 0, "nothing comes out of junk while idle"); - Check.False(parser.Busy, "still idle"); - Check.Null(parser.Feed(null, 1000), "null text"); - - // Inside a press: junk goes to Extra, chat-like dash lines don't become modifiers, a failed outcome is kept. - var lines = new List - { - "Using the Woven Shard (Level 12) with the Fragment Press", - "Pressed. It cracks.", - "The gem carries:", - "Bob says, \"Hardy - is that good?\"", - "[Trade] Alice - selling tapers", - "☃☃☃", - " Strange Sigil - something we've never seen, 3 times", - " not a modifier line", - new string('y', 2000), - "Level 12, 1 entry.", - }; - List done = FeedAll(parser, lines); - Check.Eq(done.Count, 1, "one press"); - if (done.Count != 1) return; - Press p = done[0]; - Check.Eq(p.Fragment, "Woven Shard", "other fragment name"); - Check.Eq(p.FragmentLevel, 12, "its level"); - Check.Eq(p.Outcome, "Pressed. It cracks.", "a failed outcome is kept as said"); - Check.False(p.Held, "not held"); - Check.Eq(p.Modifiers.Count, 1, "only the real modifier line"); - Check.Eq(p.Modifiers.Count == 1 ? p.Modifiers[0].Name : "", "Strange Sigil", "unknown modifier name kept"); - Check.Eq(p.Entries, 1, "'1 entry' singular"); - Check.True(p.Extra.Count >= 4, "unfitting lines kept in Extra"); - Check.True(p.Extra.All(l => l.Length <= 400), "long lines cut"); - - // A fragment without a level, and a press that isn't the Fragment Press. - done = FeedAll(new PressParser(), new[] { "Using the Odd Shard with the Fragment Press", "Level 3, 0 entries." }); - Check.True(done.Count == 1 && done[0].FragmentLevel == null && done[0].Fragment == "Odd Shard", "no level in the name"); - Check.True(done.Count == 1 && done[0].Complete && !done[0].Usable, "complete, but no modifiers: not usable"); - done = FeedAll(new PressParser(), new[] { "Using the Pyreal Ingot with the Forge", "Level 3, 0 entries." }); - Check.Eq(done.Count, 0, "not a Press: ignored"); - } - - private static void NumberForms() - { - string Forms(string s) => string.Join(" ", PressParser.Numbers(s).Select(n => n.Kind + ":" + n.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))); - Check.Eq(Forms("kills drop x1.38 loot"), "mult:1.38", "multiplier"); - Check.Eq(Forms("12% of kills"), "pct:12", "percent"); - Check.Eq(Forms("+29 damage rating"), "plus:29", "rating"); - Check.Eq(Forms("attacks with +29."), "plus:29", "rating before a full stop"); - Check.Eq(Forms("-5 damage rating"), "plus:-5", "negative rating"); - Check.Eq(Forms("+12% more"), "pct:12", "signed percent is a percent"); - Check.Eq(Forms("spawns 3 bosses in 10.5 seconds"), "num:3 num:10.5", "plain numbers"); - Check.Eq(Forms("max5 and box2"), "", "digits glued to words aren't numbers"); - Check.Eq(Forms("no numbers here"), "", "none"); - } -} diff --git a/Tools/RynthThreads.Tests/Program.cs b/Tools/RynthThreads.Tests/Program.cs deleted file mode 100644 index 4723f05..0000000 --- a/Tools/RynthThreads.Tests/Program.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.IO; -using RynthCore.RynthAiTests.Harness; - -// The engine parser's only outside dependency: the registry's limits (the engine's values). -namespace RynthCore.Engine.UI.ScriptWindows -{ - internal static class ScriptWindowRegistry - { - public const int MaxOpsPerWindow = 1500; - public const int MaxBytesPerWindow = 64 * 1024; - public const int MaxWindowsPerOwner = 32; - public const int MaxBytesPerSubmit = 256 * 1024; - } -} - -namespace RynthThreads.Tests -{ - // Offline tests for RynthThreads. Each test prints PASS / FAIL. - // - // Run: dotnet run -c Release (all tests) - // dotnet run -c Release -- infer (tests whose name contains "infer") - internal static class Program - { - /// Scratch folder next to the exe for files tests write. Emptied at start. - public static string TempRoot { get; } = Path.Combine(AppContext.BaseDirectory, "scratch"); - - private static int Main(string[] args) - { - if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true); - Directory.CreateDirectory(TempRoot); - - var runner = new Runner(); - ParserTests.Register(runner); - InferenceTests.Register(runner); - StoreTests.Register(runner); - WindowTests.Register(runner); - int rc = runner.Run("RynthThreads tests", args.Length > 0 ? args[0] : null); - try { Directory.Delete(TempRoot, recursive: true); } catch { } - return rc; - } - - /// A fresh empty folder under the scratch root. - public static string NewFolder(string name) - { - string path = Path.Combine(TempRoot, name + "-" + Guid.NewGuid().ToString("N").Substring(0, 6)); - Directory.CreateDirectory(path); - return path; - } - } -} diff --git a/Tools/RynthThreads.Tests/RynthThreads.Tests.csproj b/Tools/RynthThreads.Tests/RynthThreads.Tests.csproj deleted file mode 100644 index 9f48d89..0000000 --- a/Tools/RynthThreads.Tests/RynthThreads.Tests.csproj +++ /dev/null @@ -1,39 +0,0 @@ - - - - - Exe - net10.0-windows - enable - true - true - RynthThreads.Tests - - - - - - - - - - - - - - - - - - diff --git a/Tools/RynthThreads.Tests/StoreTests.cs b/Tools/RynthThreads.Tests/StoreTests.cs deleted file mode 100644 index 78cd25f..0000000 --- a/Tools/RynthThreads.Tests/StoreTests.cs +++ /dev/null @@ -1,181 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using RynthCore.Plugin.RynthThreads.Threads; -using RynthCore.RynthAiTests.Harness; - -namespace RynthThreads.Tests; - -// The shared presses.jsonl (Threads/PressStore.cs). -internal static class StoreTests -{ - public static void Register(Runner r) - { - r.Add("store: a press survives the JSON round trip", RoundTrip); - r.Add("store: another client's presses are read as the file grows; no doubles", FollowsGrowth); - r.Add("store: odd lines are skipped, a half-written line waits", OddLines); - r.Add("store: two writers appending at once lose nothing", ConcurrentAppends); - r.Add("store: CSV export", CsvExport); - } - - private static Press Sample() => new PressParser().Feed(string.Join("\n", ParserTests.Sample), 1)![0]; - - private static void RoundTrip() - { - Press p = Sample(); - p.Server = "DreamWeave"; - p.Character = "Tester \"Quote\""; - string json = PressStore.ToJson(p); - Check.False(json.Contains('\n'), "one line"); - Press? back = PressStore.FromJson(json); - Check.NotNull(back, "reads back"); - if (back == null) return; - ParserTests.CheckSample(back); - Check.Eq(back.Id, p.Id, "id"); - Check.Eq(back.Character, "Tester \"Quote\"", "character (escaped quotes)"); - Check.Eq(back.Server, "DreamWeave", "server"); - Check.Eq(back.TimeUtc, p.TimeUtc, "time"); - Check.Eq(back.Modifiers[3].Numbers[0].Text, "+29", "number text"); - - // Missing fields and unknown ones (a later version) are fine. - Press? minimal = PressStore.FromJson("{\"id\":\"x1\",\"future\":[1,2],\"modifiers\":[{\"name\":\"Hardy\"},{\"description\":\"no name\"}]}"); - Check.True(minimal != null && minimal.Id == "x1" && minimal.Modifiers.Count == 1 && minimal.FragmentLevel == null, - "minimal line reads, nameless modifier dropped"); - Check.Null(PressStore.FromJson("not json"), "garbage"); - Check.Null(PressStore.FromJson("[1,2]"), "not an object"); - } - - private static void FollowsGrowth() - { - string folder = Program.NewFolder("growth"); - var a = new PressStore(folder); - var b = new PressStore(folder); - Check.Eq(b.Poll(), 0, "no file yet"); - - Check.Null(a.Record(Sample()), "client A writes"); - Check.Eq(a.Poll(), 0, "A reading its own press back adds nothing"); - Check.Eq(a.Presses.Count, 1, "A has it once"); - Check.Eq(b.Poll(), 1, "client B sees it"); - Check.Eq(b.Poll(), 0, "and only once"); - - Press second = Sample(); - second.Components = new List { "Blue Taper" }; - a.Record(second); - b.Record(Sample()); - Check.Eq(b.Poll(), 1, "B gets A's second press (its own is already there)"); - Check.Eq(a.Poll(), 1, "A gets B's press"); - Check.Eq(a.Presses.Count, 3, "A: 3"); - Check.Eq(b.Presses.Count, 3, "B: 3"); - - // A fresh client reads them all. - var c = new PressStore(folder); - Check.Eq(c.Poll(), 3, "a new client loads everything"); - int v = c.Version; - c.Poll(); - Check.Eq(c.Version, v, "nothing new: unchanged"); - } - - private static void OddLines() - { - string folder = Program.NewFolder("odd"); - var s = new PressStore(folder); - Directory.CreateDirectory(folder); - string good = PressStore.ToJson(Sample()); - File.WriteAllText(s.FilePath, good + "\n\nnot json at all\n{\"broken\":\n" + good.Substring(0, 20)); - Check.Eq(s.Poll(), 1, "the good line"); - Check.Eq(s.BadLines, 2, "two bad lines counted"); - // The half line gets finished (with a different id: a new press). - Press other = Sample(); - string rest = PressStore.ToJson(other); - File.WriteAllText(s.FilePath, good + "\n\nnot json at all\n{\"broken\":\n" + rest + "\n"); - Check.Eq(s.Poll(), 1, "the finished line is read"); - Check.Eq(s.Presses.Count, 2, "two presses"); - } - - private static void ConcurrentAppends() - { - string folder = Program.NewFolder("concurrent"); - const int perWriter = 250; - var writers = new[] { new PressStore(folder), new PressStore(folder) }; - var errors = new int[2]; - using var stop = new CancellationTokenSource(); - - // A third party holding the file now and then, as another client mid-write would. - var holder = new Thread(() => - { - while (!stop.IsCancellationRequested) - { - try - { - using var fs = new FileStream(Path.Combine(folder, PressStore.FileName), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); - Thread.Sleep(3); - } - catch (IOException) { } - Thread.Sleep(2); - } - }); - holder.Start(); - - var threads = Enumerable.Range(0, 2).Select(w => new Thread(() => - { - for (int i = 0; i < perWriter; i++) - { - Press p = Sample(); - p.Character = "Writer" + w; - p.Components = new List { "C" + i }; - if (writers[w].Record(p) != null) errors[w]++; - } - })).ToList(); - threads.ForEach(t => t.Start()); - threads.ForEach(t => t.Join()); - stop.Cancel(); - holder.Join(); - - // Whatever found the file busy every time is written now. - foreach (PressStore w in writers) - for (int i = 0; i < 50 && w.FlushPending() > 0; i++) Thread.Sleep(10); - Check.Eq(writers[0].PendingCount + writers[1].PendingCount, 0, "nothing left pending"); - - string[] lines = File.ReadAllLines(Path.Combine(folder, PressStore.FileName), Encoding.UTF8) - .Where(l => l.Length > 0).ToArray(); - Check.Eq(lines.Length, 2 * perWriter, "every press is one line"); - List read = lines.Select(PressStore.FromJson).ToList(); - Check.True(read.All(p => p != null && p.Modifiers.Count == 6), "every line is a whole press"); - Check.Eq(read.Select(p => p!.Id).Distinct().Count(), 2 * perWriter, "all ids distinct"); - Check.Eq(read.Count(p => p!.Character == "Writer0"), perWriter, "writer 0's presses all there"); - Check.Eq(read.Count(p => p!.Character == "Writer1"), perWriter, "writer 1's presses all there"); - - var reader = new PressStore(folder); - Check.Eq(reader.Poll(), 2 * perWriter, "a reader loads them all"); - Check.Eq(reader.BadLines, 0, "no bad lines"); - Console.WriteLine($" (appends that found the file busy every try and waited: {errors[0] + errors[1]})"); - } - - private static void CsvExport() - { - string folder = Program.NewFolder("csv"); - var s = new PressStore(folder); - Press p = Sample(); - p.Character = "Tester, Jr."; - s.Record(p); - Press q = Sample(); - q.Components = new List { "=cmd", "Red Taper" }; - q.Complete = false; - q.End = "timeout"; - s.Record(q); - string path = s.ExportCsv(new DateTime(2026, 10, 12, 19, 30, 0)); - Check.True(File.Exists(path) && Path.GetDirectoryName(path) == folder, "written next to presses.jsonl"); - Check.Eq(Path.GetFileName(path), "presses-20261012-193000.csv", "file name"); - string[] rows = File.ReadAllLines(path); - Check.Eq(rows.Length, 3, "header + 2 rows"); - Check.True(rows[0].StartsWith("time_utc,server,character,fragment,fragment_level"), "header"); - Check.True(rows[1].Contains("\"Tester, Jr.\""), "comma value quoted"); - Check.True(rows[1].Contains(",Raw Fragment,185,Pressed. It holds.,Red Taper,190,4,yes,6,"), "columns"); - Check.True(rows[1].Contains("Bounteous: kills drop x1.38 loot | Tourmaline Affinity"), "modifiers joined"); - Check.True(rows[2].Contains("'=cmd; Red Taper"), "a formula-looking cell is defused"); - Check.True(rows[2].Contains("no (timeout)"), "incomplete marked"); - } -} diff --git a/Tools/RynthThreads.Tests/WindowTests.cs b/Tools/RynthThreads.Tests/WindowTests.cs deleted file mode 100644 index b2ff2be..0000000 --- a/Tools/RynthThreads.Tests/WindowTests.cs +++ /dev/null @@ -1,186 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.CompilerServices; -using RynthCore.Engine.UI.ScriptWindows; -using RynthCore.Plugin.RynthThreads; -using RynthCore.Plugin.RynthThreads.Threads; -using RynthCore.Plugin.RynthThreads.Ui; -using RynthCore.Plugin.RynthThreads.Views; -using RynthCore.RynthAiTests.Harness; - -namespace RynthThreads.Tests; - -// The window's display list against the engine's own parser, the server check and /rthreads stats. -internal static class WindowTests -{ - [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "Write")] - private static extern int Write(UiHost h); - - [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_submit")] - private static extern ref byte[] SubmitBuffer(UiHost h); - - public static void Register(Runner r) - { - r.Add("window: every tab, headers open, parses in the engine (bar button set)", EveryTab); - r.Add("window: DreamWeave check and /rthreads stats lines", ServerAndStats); - r.Add("window: Components and Modifiers tab text for the 4 real presses", RealText); - } - - private static List Data() - { - var presses = new List(); - for (int i = 0; i < 3; i++) presses.Add(InferenceTests.P("Red Taper", "Bounteous=kills drop x1.38 loot, Hardy=monsters have x1.5 health", level: 185)); - for (int i = 0; i < 4; i++) presses.Add(InferenceTests.P("", "Hardy=monsters have x1.81 health, Teeming=75% more monsters", level: 185)); - presses.Add(InferenceTests.P("Blue Taper, Red Taper", "Bounteous=kills drop x1.4 loot", level: 120)); - Press raw = new PressParser().Feed(string.Join("\n", ParserTests.Sample), 1)![0]; - presses.Add(raw); - presses.Add(InferenceTests.P("Red Taper", "Hardy", complete: false)); - return presses; - } - - private static unsafe void EveryTab() - { - List presses = Data(); - ThreadsReport report = PressInference.Build(presses); - var panel = new ThreadsPanel { Report = () => report, Presses = () => presses }; - var host = new UiHost(); - UiWindow w = host.Add(new UiWindow("RynthThreads/Main", "RynthThreads") { DefaultWidth = 440f, DefaultHeight = 480f, MinWidth = 320f, MinHeight = 220f }); - - void Pass() - { - w.Begin(); - panel.Draw(w); - w.End(); - } - void OpenAll(IEnumerable ids) - { - foreach (string id in ids) w.Dispatch(w.KeyOf(id), new UiEvent(UiFormat.EvOpen, b: true)); - } - void Click(string id) => w.Dispatch(w.KeyOf(id), new UiEvent(UiFormat.EvClicked)); - - string[] tabs = { "tab.c", "tab.m", "tab.p" }; - foreach (string tab in tabs) - { - Pass(); - Click(tab); - Pass(); - OpenAll(report.Components.Select(c => "c:" + c.Name).Append("c:(none)").Append("c:(all)") - .Concat(report.Combinations.Select(c => "k:" + c.Name)) - .Concat(report.Modifiers.Select(m => "m:" + m.Name)) - .Concat(presses.Select(p => "p:" + p.Id))); - Pass(); - - int n = Write(host); - byte[] buf = SubmitBuffer(host); - int rc; - List windows; - string error; - fixed (byte* p = buf) rc = DisplayListParser.Parse(p, n, 4000f, out _, out windows, out error); - Check.Eq(rc, 0, $"{tab}: the engine accepts the list ({error})"); - if (rc != 0 || windows.Count != 1) continue; - Check.Eq(windows[0].Title, "RynthThreads", "title (the bar button's tooltip)"); - Check.True((windows[0].Flags & WindowFlags.ShowInBar) != 0 && (windows[0].Flags & WindowFlags.BarButton) != 0, "bar button"); - Check.True(windows[0].List!.OpCount > 20, $"{tab}: something drawn ({windows[0].List!.OpCount} ops)"); - } - string body = System.Text.Encoding.UTF8.GetString(w.Body); - Check.True(body.Contains("Level 190, 4 entries."), "presses tab shows raw lines"); - Check.True(body.Contains("Yorick is recalling"), "and the other lines kept beside them"); - - // Empty data still draws. - var empty = new ThreadsPanel(); - w.Begin(); - empty.Draw(w); - w.End(); - Check.True(System.Text.Encoding.UTF8.GetString(w.Body).Contains("No presses yet"), "empty window explains itself"); - } - - private static void ServerAndStats() - { - Check.True(RynthThreadsPlugin.IsDreamWeave("DreamWeave"), "DreamWeave"); - Check.True(RynthThreadsPlugin.IsDreamWeave("dreamweave PvE"), "any case, extra words"); - Check.False(RynthThreadsPlugin.IsDreamWeave("Aelrynth"), "Aelrynth"); - Check.False(RynthThreadsPlugin.IsDreamWeave(""), "empty"); - Check.False(RynthThreadsPlugin.IsDreamWeave(null), "null"); - - List lines = RynthThreadsPlugin.StatsLines(PressInference.Build(Data()), @"C:\x\presses.jsonl"); - Check.True(lines[0].StartsWith("10 presses (9 complete, 1 incomplete)"), "totals line: " + lines[0]); - Check.True(lines.Any(l => l.StartsWith("Red Taper (5): Bounteous 100%+, Hardy 80%")), "Red Taper line"); - Check.True(lines.Any(l => l == "Blue Taper (1): Bounteous 100%"), "Blue Taper line"); - Check.True(lines.Any(l => l.StartsWith("No components (4): Hardy 100%")), "No components line"); - Check.False(lines.Any(l => l.Contains("Affinity")), "the Affinity group is left out"); - Check.True(lines.Contains("+ = more likely with it than without."), "legend"); - Check.Eq(lines[^1], @"File: C:\x\presses.jsonl", "file named last"); - Check.True(lines.Count <= 9, "short"); - } - - /// The window's text ops in order (headers as "== label", indented by Indent ops). - internal static List TextOf(ReadOnlySpan b) - { - var lines = new List(); - int i = 0, indent = 0; - string Str(ReadOnlySpan s, int at) => - System.Text.Encoding.UTF8.GetString(s.Slice(at + 2, s[at] | (s[at + 1] << 8))); - while (i + 4 <= b.Length) - { - byte code = b[i], flags = b[i + 1]; - int len = b[i + 2] | (b[i + 3] << 8), at = i + 4; - if (code == UiFormat.OpEnd && len == 0) break; - string pad = new string(' ', indent * 2); - switch (code) - { - case UiFormat.OpText: case UiFormat.OpTextWrapped: case UiFormat.OpTextDisabled: case UiFormat.OpSeparatorText: - lines.Add(pad + Str(b, at)); break; - case UiFormat.OpBulletText: lines.Add(pad + "- " + Str(b, at)); break; - case UiFormat.OpTextColored: lines.Add(pad + Str(b, at + 4)); break; - case UiFormat.OpCollapsingHeader: - string h = Str(b, at + 4); - int cut = h.IndexOf("###", StringComparison.Ordinal); - lines.Add(pad + "== " + (cut >= 0 ? h.Substring(0, cut) : h)); break; - case UiFormat.OpIndent: indent++; break; - case UiFormat.OpUnindent: indent = Math.Max(0, indent - 1); break; - } - i = at + len + ((flags & UiFormat.OpHasBlock) != 0 ? 4 : 0); - } - return lines; - } - - private static void RealText() - { - List presses = InferenceTests.Real(); - ThreadsReport report = PressInference.Build(presses); - var panel = new ThreadsPanel { Report = () => report, Presses = () => presses }; - var w = new UiWindow("RynthThreads/Main", "RynthThreads"); - void Pass() { w.Begin(); panel.Draw(w); w.End(); } - void Open(string id) => w.Dispatch(w.KeyOf(id), new UiEvent(UiFormat.EvOpen, b: true)); - - Pass(); - Open("c:(all)"); - Open("c:Lead Scarab"); - Pass(); - List comp = TextOf(w.Body); - Check.True(comp.Contains("== Lead Scarab (4 presses)"), "Lead Scarab header"); - Check.True(comp.Any(l => l.Trim() == "- Guarded 75% (3/4, 30-95%); without: no data; x1.83 to x2.18"), "Guarded line"); - Check.True(comp.Any(l => l.Trim() == "- Affinity (any) 100% (4/4, 51-100%); without: no data; 7% to 22%"), "Affinity line"); - Check.True(comp.Any(l => l.Trim() == "Amethyst 1, Iron 1, Obsidian 1, Serpentine 1"), "split line"); - Check.True(comp.Any(l => l.Trim() == "- Guarded 75% (3/4, 30-95%); x1.83 to x2.18"), "All presses: no comparison"); - - w.Dispatch(w.KeyOf("tab.m"), new UiEvent(UiFormat.EvClicked)); - Pass(); - Open("m:Affinity"); - Open("m:Guarded"); - Pass(); - List mods = TextOf(w.Body); - Check.True(mods.Contains("== Guarded 75% (3/4, 30-95%) [harder]") || mods.Contains("== Guarded 75% (3/4, 30-95%)"), "Guarded header"); - Check.True(mods.Any(l => l.Trim() == "- Lead Scarab 75% (3/4, 30-95%); without: no data; x1.83 to x2.18"), "Guarded with Lead Scarab"); - Check.True(mods.Any(l => l.Trim() == "- Amethyst: 25% (1/4, 5-70%)"), "Affinity by material"); - - if (Environment.GetEnvironmentVariable("RYNTHTHREADS_DUMP") == "1") - { - Console.WriteLine("---- Components tab ----"); - foreach (string l in comp) Console.WriteLine(l); - Console.WriteLine("---- Modifiers tab ----"); - foreach (string l in mods) Console.WriteLine(l); - } - } -} diff --git a/Tools/gen-rynthui-icons.py b/Tools/gen-rynthui-icons.py new file mode 100644 index 0000000..9774d81 --- /dev/null +++ b/Tools/gen-rynthui-icons.py @@ -0,0 +1,47 @@ +"""Writes Plugins/Shared/RynthUi/RynthIcons.cs from RynthCore's ImGui/PhosphorIcons.cs. + +Only the icons in the engine's Baked list are in the shared font atlas, so only those are +written: a plugin can't name an icon that would draw as nothing. Run after the engine adds +icons to Baked (Tools/RynthUi.Tests checks the two still match): + + python Tools/gen-rynthui-icons.py [path to RynthCore] (default: the sibling ..\\RynthCore) +""" +import os, re, sys + +here = os.path.dirname(os.path.abspath(__file__)) +suite = os.path.dirname(here) +core = os.path.abspath(sys.argv[1]) if len(sys.argv) > 1 else os.path.join(os.path.dirname(suite), "RynthCore") +src = os.path.join(core, "src", "RynthCore.Engine", "ImGui", "PhosphorIcons.cs") +text = open(src, encoding="utf-8").read() + +consts = dict(re.findall(r'public const string (\w+) = "\\u([0-9A-Fa-f]{4})";', text)) +baked_expr = re.search(r"public const string Baked =(.*?);", text, re.S).group(1) +baked = re.findall(r"[A-Z]\w*", baked_expr) +missing = [n for n in baked if n not in consts] +if missing: + sys.exit("Baked names without a constant: " + ", ".join(missing)) + +names = sorted(set(baked)) +lines = [ + "// ============================================================================", + "// RynthSuite - Plugins/Shared/RynthUi/RynthIcons.cs (GENERATED: do not edit)", + "// The Phosphor icons (MIT) baked into the engine's font atlas, by Phosphor's", + "// names: put one in a label or a button. Written by Tools/gen-rynthui-icons.py", + "// from RynthCore's ImGui/PhosphorIcons.cs (its Baked list); an icon that isn't", + "// baked would draw as nothing, so it isn't here. Tools/RynthUi.Tests checks", + "// this file against the engine's.", + "// ============================================================================", + "", + "namespace RynthCore.Plugin.Shared.RynthUi;", + "", + "internal static class RynthIcons", + "{", +] +for n in names: + lines.append(f' public const string {n} = "\\u{consts[n].upper()}";') +lines += ["}", ""] +out = os.path.join(suite, "Plugins", "Shared", "RynthUi", "RynthIcons.cs") +os.makedirs(os.path.dirname(out), exist_ok=True) +with open(out, "w", encoding="utf-8", newline="\n") as f: + f.write("\n".join(lines)) +print(f"{len(names)} icons -> {out}")