From 688f948c9887d18217631100776ddebf2248e200 Mon Sep 17 00:00:00 2001 From: BlankenshipG Date: Fri, 9 Oct 2026 08:39:39 -0400 Subject: [PATCH] feat(rynthai): track ACECustom bounties for the engine's Bounties window ACECustom keeps bounty progress server-side only, so RynthAi reads "/bounty list" (every active bounty and this character's standing, wherever the player is) and hides the reply from chat. Reads run only while the engine's Bounties window polls the export: on open, ~2 s after kills (at most every MinRefreshSeconds), after bounty chat events, periodically, and on Refresh. Typed /bounty output updates the list too; cooldowns count down locally; "Unknown command: bounty" stops automatic reads. - Bounty/BountyParse.cs: /bounty list, /bounty, status, wait and event lines - Bounty/BountyTracker.cs: schedule, quiet capture, merge, per-character bounties.json, bridge JSON and commands - Exports RynthPluginGetBountiesJson / RynthPluginBountyCommand (UTF-8) - /ra bounty [list|refresh]; remote command "bounty" - Host tests: 8 tests / 150 checks, incl. the engine's JSON reader when the engine side is present --- Changelog/2026-10-09-bounties-window.md | 61 ++ .../Bounty/BountyParse.cs | 229 +++++++ .../Bounty/BountyTracker.cs | 623 ++++++++++++++++++ .../LegacyUi/RynthAiJsonContext.cs | 2 + .../RynthCore.Plugin.RynthAi/PluginExports.cs | 32 + .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 26 + Tools/RynthCore.RynthAiHostTests/Program.cs | 1 + .../RynthCore.RynthAiHostTests.csproj | 10 + .../Tests/BountyTests.cs | 382 +++++++++++ 9 files changed, 1366 insertions(+) create mode 100644 Changelog/2026-10-09-bounties-window.md create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Bounty/BountyParse.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Bounty/BountyTracker.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/BountyTests.cs diff --git a/Changelog/2026-10-09-bounties-window.md b/Changelog/2026-10-09-bounties-window.md new file mode 100644 index 0000000..785605c --- /dev/null +++ b/Changelog/2026-10-09-bounties-window.md @@ -0,0 +1,61 @@ +# RynthAi - ACECustom bounty tracker (Bounties window) + +Date: 2026-10-09 +Pairs with: RynthCore engine PR "Bounties window" (the ImGui face, `/rc bounties`, bar button) + +## What it does + +ACECustom servers now have a bounty system: an area pays a reward every N kills, sometimes with +a cooldown between awards or a minimum QB. The progress is a server-only property, so the client +never sees it. RynthAi now tracks it from what the server prints: + +- `/bounty list` reports every active bounty on the server and this character's standing on + each (kills so far, cooldown left, or the QB needed). The tracker reads it **quietly**: it sends + the command itself and hides the reply from chat. So the window covers every bounty, wherever + the player is standing. +- Reads run only while the engine's Bounties window is open: + - when it opens (if the list is over 30 s old, or kills happened while it was closed); + - about 2 s after each of this character's kills, at most every *MinRefreshSeconds* (default 10 s, minimum 5 s); + - after a bounty chat event ("Bounty complete!", "Bounty unlocked:", "Next bounty ..."); + - every *PeriodicRefreshMinutes* as a backstop (default 5, 0 = off); + - on Refresh or `/ra bounty refresh`. +- `/bounty list` and `/bounty` lines the player prints themselves update the list too. They + stay in chat. +- Cooldowns count down locally. When one ends, the row shows 0 of N kills, which matches the + server: an award resets the count before the cooldown starts. +- A server without the system answers "Unknown command: bounty". Automatic reads then stop + until a manual refresh. +- The list and the window options are saved per character in `bounties.json`, so the window + fills immediately after login. + +## New in the plugin + +- `Bounty/BountyParse.cs`: parsers for the `/bounty list` and `/bounty` lines, status phrases, + waits ("1 hr 15 sec") and award/unlock events. The formats come from ACECustom + `BountyManager`. +- `Bounty/BountyTracker.cs`: the read schedule, the quiet capture (ends on the footer, after + 1.5 s of silence, or after a 10 s timeout), merging (a full read replaces the list, a partial + one updates it), persistence and the bridge JSON. +- Exports: + - `RynthPluginGetBountiesJson` (UTF-8). The engine polls it every second while the window is + open, and those polls are also the plugin's "window is open" signal. + - `RynthPluginBountyCommand` (UTF-8): `refresh`, or `set {option} {value}`. +- `/ra bounty [list|refresh]` (aliases `bounties`, `bountys`); the remote command is `bounty`. +- Hooked into login, logout (save), tick, chat (eats only its own read) and the kill + notification. + +## Tests + +`Tools/RynthCore.RynthAiHostTests/Tests/BountyTests.cs`: 8 tests, 150 checks. + +- Line parsing, events and waits. +- Full and partial merges, and `/bounty` matching only the one reward it can mean. +- Change highlight, cooldown expiry, and the save/load round trip. +- The read loop on a fake clock: open, kill debounce and minimum interval, award re-read, + footer-less replies, closed window, unknown command, and timeout. +- The bridge JSON parsed by the engine's own reader. This links RynthCore's + `UI/Data/BountiesSnapshotJson.cs` when it exists, so the test is compiled out until the engine + PR is merged. + +Full host suite: 558 passed, 4 known failures. One map-bake test makes no checks on a machine +without a live plan for 0x6346, which is environmental and unrelated. diff --git a/Plugins/RynthCore.Plugin.RynthAi/Bounty/BountyParse.cs b/Plugins/RynthCore.Plugin.RynthAi/Bounty/BountyParse.cs new file mode 100644 index 0000000..9478f6d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Bounty/BountyParse.cs @@ -0,0 +1,229 @@ +// 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.RynthAi.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.RynthAi/Bounty/BountyTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Bounty/BountyTracker.cs new file mode 100644 index 0000000..304148d --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Bounty/BountyTracker.cs @@ -0,0 +1,623 @@ +// 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 (at most every MinRefreshSeconds), +// * after a bounty chat event ("Bounty complete!", "Bounty unlocked:", "Next bounty ..."), +// * every PeriodicRefreshMinutes as a backstop, and on Refresh / "/ra bounty refresh". +// Lines the player prints themselves ("/bounty list", "/bounty") update the list too. +// 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.RynthAi.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; + 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 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. + private void Schedule(long nowMs, long delayMs, bool respectMinInterval) + { + long due = nowMs + delayMs; + if (respectMinInterval && _lastSentMs != 0) + due = Math.Max(due, _lastSentMs + _s.MinRefreshSeconds * 1000L); + if (_dueAtMs == 0 || due < _dueAtMs) _dueAtMs = due; + } + + /// Manual refresh (window button, "/ra bounty refresh"): ignores the interval and retries an unsupported server. + public string RequestRefresh() + { + _unsupported = false; + long now = NowMs; + Schedule(now, 0, respectMinInterval: false); + // A closed window does not tick reads, so a manual request sends now. + if (!WindowOpen) Send(now); + return "Reading /bounty list..."; + } + + /// One of this character's kills (RynthAiPlugin.OnKillNotification). + public void OnKill() + { + if (!_s.RefreshOnKills || _unsupported) return; + if (WindowOpen) Schedule(NowMs, KillDebounceMs, respectMinInterval: true); + else _stale = true; + } + + private void Send(long nowMs) + { + _dueAtMs = 0; + if (_capActive) return; + _lastSentMs = nowMs; + _capActive = true; + _capSentMs = nowMs; + _capLastLineMs = 0; + _capLines.Clear(); + try { _send(ListCommand); } + catch (Exception ex) + { + _capActive = false; + _status = "could not send /bounty list"; + _log($"[RynthAi] Bounties: sending {ListCommand} failed: {ex.Message}"); + } + } + + public void Tick() + { + long now = NowMs; + if (_capActive) + { + if (_capLastLineMs == 0 && now - _capSentMs >= FirstLineTimeoutMs) + { + _capActive = false; + _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: false); + _stale = false; + } + + if (_s.PeriodicRefreshMinutes > 0 && _lastSentMs != 0 && now - _lastSentMs >= _s.PeriodicRefreshMinutes * 60_000L) + Schedule(now, 0, respectMinInterval: false); + + if (_dueAtMs != 0 && now >= _dueAtMs && !_unsupported) Send(now); + } + + private void FinishCapture(string? terminator) + { + _capActive = 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) return false; + long now = NowMs; + + if (_capActive) + { + if (BountyParse.IsUnknownCommand(t)) + { + _capActive = false; + _capLines.Clear(); + _unsupported = true; + _status = "this server has no /bounty command"; + _log("[RynthAi] Bounties: server has no /bounty command; automatic reads stopped."); + return true; + } + if (t == BountyParse.ListHeader) { _capLastLineMs = now; return true; } + if (BountyParse.TryParseListLine(t, out var captured)) { _capLines.Add(captured); _capLastLineMs = now; return true; } + if (BountyParse.IsListTerminator(t)) { FinishCapture(t); return true; } + } + + 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) + { + if (WindowOpen) Schedule(now, EventDebounceMs, respectMinInterval: false); + 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, RynthAiJsonContext.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 ──────────────────────────────────────────────────────── + + /// "/ra 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: /rc bounties, or the Bounties button on the RynthCore bar."); + break; + default: + _chat("[Bounties] /ra bounty [list|refresh] - list the tracked bounties, or re-read /bounty list now."); + 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}", + }; + } + + /// "/ra 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. Type /ra bounty refresh."); + 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), RynthAiJsonContext.Default.BountyState) ?? new BountyState(); + } + catch (Exception ex) + { + _log($"[RynthAi] 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; + try + { + string? dir = Path.GetDirectoryName(_filePath); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + string tmp = _filePath + ".tmp"; + File.WriteAllText(tmp, JsonSerializer.Serialize(_s, RynthAiJsonContext.Default.BountyState)); + File.Move(tmp, _filePath, overwrite: true); + } + catch (Exception ex) + { + _log($"[RynthAi] Bounties: saving {_filePath} failed: {ex.Message}"); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs index d0289ee..27fb7a2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs @@ -17,6 +17,8 @@ namespace RynthCore.Plugin.RynthAi; [JsonSerializable(typeof(MetaRuleDto))] [JsonSerializable(typeof(MetaCommand))] [JsonSerializable(typeof(RynthCore.Plugin.RynthAi.Meta.MetaScheduleConfig))] +[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.Bounty.BountyState))] +[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.Bounty.BountyBridgePayload))] [JsonSourceGenerationOptions( WriteIndented = true, IncludeFields = true, diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs index 2487766..25dec0d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -765,6 +765,38 @@ public static unsafe class PluginExports catch { } } + // ── Bounties bridge (engine-side ImGui Bounties window) ───────────────── + // 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. + + private static IntPtr _bountiesPtr = IntPtr.Zero; + + /// The tracked bounties as JSON (BountyBridgePayload); 0 before login. + [UnmanagedCallersOnly(EntryPoint = "RynthPluginGetBountiesJson", 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 = "RynthPluginBountyCommand", 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)) return; + Runtime.Plugin?.Bounties?.Command(text); + } + catch { } + } + [UnmanagedCallersOnly(EntryPoint = "RynthPluginAddSelectedWeapon", CallConvs = new[] { typeof(CallConvCdecl) })] public static void AddSelectedWeapon() { diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index d4dedb8..e8b388a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -95,6 +95,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase private FellowshipTracker? _fellowshipTracker; private MetaManager? _metaManager; private QuestTracker? _questTracker; + private Bounty.BountyTracker? _bountyTracker; + /// The Bounties window's tracker (PluginExports); null until login. + internal Bounty.BountyTracker? Bounties => _bountyTracker; private InventoryManager? _inventoryManager; private SalvageManager? _salvageManager; private ScrollLearner? _scrollLearner; // VTank ReadUnknownScrolls (Loot/ScrollLearner.cs) @@ -398,6 +401,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _metaManager = null; TeardownMetaSchedule(); _questTracker = null; + try { _bountyTracker?.Save(); } catch { } + _bountyTracker = null; _inventoryManager = null; _salvageManager = null; _scrollLearner?.Reset(); @@ -666,6 +671,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase WireMetaSchedule(); // before the refresh: the Meta Manager shows (doesn't eat) that reply _questTracker.Refresh(); // auto-populate quest flags on login + // ACECustom bounties (engine Bounties window); reads only while that window is open. + _bountyTracker?.Save(); + string bountyFile = string.IsNullOrEmpty(_dashboard.CharFolder) + ? string.Empty : Path.Combine(_dashboard.CharFolder, Bounty.BountyTracker.FileName); + _bountyTracker = new Bounty.BountyTracker(cmd => Host.InvokeChatParser(cmd), ChatLine, msg => Host.Log(msg), bountyFile); + _metaManager = new MetaManager(_dashboard.Settings, Host, _vitals); _metaManager.SetPlayerId(_playerId); _metaManager.SetMtCommandHandler(HandleMtCommand); @@ -858,6 +869,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "hideui": _hideUi = on; dash.SetUiHidden(on); break; // applied each tick in OnTick case "sendchat": if (!string.IsNullOrEmpty(value)) HandleRynthChatSubmit(value); break; case "setsetting": ApplyRemoteSetting(value); break; // one advanced setting from the phone (clamped + persisted) + case "bounty": _bountyTracker?.Command(string.IsNullOrEmpty(value) ? "refresh" : value); break; // movestart/movestop are applied DIRECTLY by the RynthRemote plugin (pure Host.SetAutoRun/ // SetMotion + its own dead-man watchdog) and are never forwarded here. } @@ -1405,6 +1417,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // A nav saved into NavProfiles from outside (RynthNav's "save as nav route"): list it. _dashboard?.TickNavFolder(); _questTracker?.Tick(); + _bountyTracker?.Tick(); if (diag) Host.Log("[RynthAi] OnTick: after quest tracker"); DrainGiveQueue(); if (diag) Host.Log("[RynthAi] OnTick: after drain give queue"); @@ -2044,6 +2057,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // The Meta Manager eats the reply to its own /myquests poll (only that). bool mmEat = false; try { mmEat = MetaScheduleChat(text); } catch { } + // The Bounties window's own "/bounty list" read is eaten too. + if (!mmEat) + { + try { mmEat = _bountyTracker?.OnChat(text) == true; } + catch (Exception ex) { Host.Log($"[RynthAi] Bounty chat parse failed: {ex.Message}"); } + } if (mmEat) eat = 1; else _dashboard?.PushChatLine(text, chatType); try { NoteHotspotChat(text, chatType); } catch (Exception ex) { Host.Log($"[RynthAi] Hazard chat check failed: {ex.Message}"); } @@ -2073,6 +2092,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _killClock.RecordKill(); // the only kill source: KillerNotification goes to the killer alone _combatManager?.OnKillNotification(deathMessage); _dashboard?.RecordKill(); // feeds the kills/hour session stat + _bountyTracker?.OnKill(); // re-reads /bounty list while the Bounties window is open } public override void OnCreateObject(uint objectId) @@ -3153,6 +3173,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "follow": HandleFollowCommand(parts); break; case "myquests": case "refreshquests": _questTracker?.Refresh(); ChatLine("[RynthAi] Quest flag refresh requested."); break; + case "bounty": + case "bounties": + case "bountys": + if (_bountyTracker == null) ChatLine("[RynthAi] Bounties not ready (not logged in yet)."); + else _bountyTracker.HandleChatCommand(parts); + break; case "metamgr": QueueMetaMgrCommand(parts); break; // Meta Manager: applied on the next tick case "dunnav": HandleDungeonNavCommand(parts); break; case "dunnav-patrol": HandleDungeonNavPatrolCommand(parts); break; diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index efff52e..6dfb8ee 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -86,6 +86,7 @@ internal static class Program HazardEscapeTests.Register(runner); ManaStoneChoiceTests.Register(runner); CustomDebuffTests.Register(runner); + BountyTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthCore.RynthAiHostTests/RynthCore.RynthAiHostTests.csproj b/Tools/RynthCore.RynthAiHostTests/RynthCore.RynthAiHostTests.csproj index fb2bb24..c04aa38 100644 --- a/Tools/RynthCore.RynthAiHostTests/RynthCore.RynthAiHostTests.csproj +++ b/Tools/RynthCore.RynthAiHostTests/RynthCore.RynthAiHostTests.csproj @@ -55,6 +55,16 @@ + + + $(DefineConstants);ENGINE_BOUNTIES + + + + + diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/BountyTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/BountyTests.cs new file mode 100644 index 0000000..97202f1 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/BountyTests.cs @@ -0,0 +1,382 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using RynthCore.Plugin.RynthAi.Bounty; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.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 RynthAi 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. + 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), 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[] { "/ra", "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 right away. + Run(t, clock, 5000, windowOpen: false); + t.Command("refresh"); + Check.Eq(Reads(sent), 3, "a closed-window refresh sends now"); + + chat.Clear(); + t.HandleChatCommand(new[] { "/ra", "bounty" }); + Check.True(chat.Any(c => c.Contains("/rc bounties")), "'/ra 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(); + } + } +}