From 04add6c51b9af87bc03bae27e65e2a59dcde3e21 Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Sun, 15 Nov 2026 22:32:01 -0500 Subject: [PATCH] RynthSuite as of 2026-11-15 (internal 907fc16c): release 2026.11.15.3 --- .../Combat/CombatManager.cs | 31 +- .../Dashboard/InstrumentDashboard.cs | 12 +- .../Features/FeatureCatalog.cs | 183 +++++ .../Features/FeatureSearch.cs | 215 ++++++ .../Features/FeatureSearchWindow.cs | 275 ++++++++ .../Huds/SectionsManifest.cs | 30 +- .../LegacyUi/LegacyAdvancedSettingsUi.cs | 6 + .../LegacyUi/LegacyDashboardRenderer.cs | 4 + .../LegacyUi/LegacyUiSettings.cs | 21 + .../LegacyUi/RynthAiJsonContext.cs | 2 + .../MagToolsCommands.cs | 1 + .../Meta/ExpressionEngine.cs | 2 + .../Meta/MetaManager.cs | 1 + .../RynthCore.Plugin.RynthAi/PluginExports.cs | 6 + .../RynthAiCommands.cs | 13 +- .../RynthAiPlugin.AfterDeath.cs | 127 ++++ .../RynthAiPlugin.Dashboard.cs | 1 + .../RynthAiPlugin.FeatureSearch.cs | 176 +++++ .../RynthAiPlugin.LocalFeatures.cs | 2 +- .../RynthAiPlugin.OutdoorHunt.cs | 24 +- .../RynthAiPlugin.Safety.cs | 4 +- .../RynthAiPlugin.VTankHotkeys.cs | 29 + .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 1 + .../RynthCore.Plugin.RynthAi.csproj | 4 + Tools/RynthCore.RynthAiHostTests/Program.cs | 3 + .../Tests/FeatureCatalogTests.cs | 624 ++++++++++++++++++ .../Tests/FeatureSearchTests.cs | 142 ++++ .../Tests/HuntOnLoginTests.cs | 6 +- .../Tests/KeepHuntingAfterDeathTests.cs | 188 ++++++ .../Tests/TargetingTests.cs | 155 +++++ 30 files changed, 2268 insertions(+), 20 deletions(-) create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Features/FeatureCatalog.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Features/FeatureSearch.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Features/FeatureSearchWindow.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.AfterDeath.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.FeatureSearch.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/FeatureCatalogTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/FeatureSearchTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/KeepHuntingAfterDeathTests.cs diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index 75b9fa9..4ebe3f2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -1263,8 +1263,24 @@ public partial class CombatManager : IDisposable // Melee reaches through walls, on both sides: a monster this close is a target when // melee is, or is about to be, the attack (the owner, 2026-11-06). It was left out while // hitting the character, who then read as having nothing to fight. - if (losBlocked && dist <= MeleeIgnoresLosWithin && MeleeIsTheAttackOn(wo, attackType)) + // Not through a building's wall (2026-11-13): Drakkon, outside, locked a sorcerer 3.6 m off + // inside a building and swung at the wall for 12 s with nothing landing either way. One of + // the two in a building's rooms and the other outside: left to the hunt (it walks in + // through a door), and, like the floor above, not counted as out of sight, so the walk to + // that door isn't held for it. + // A setting since 2026-11-15 (Melee through walls, on by default). Off: none of this; a + // blocked monster this close is out of sight like one farther off (counted below, so + // jump-looting waits; it isn't swung at, so it is never blacklisted for a wall; the hunt, + // which needs no line of sight, still walks round to it, and leaves it out if it can't). + if (losBlocked && _settings.MeleeThroughWalls && dist <= MeleeIgnoresLosWithin && MeleeIsTheAttackOn(wo, attackType)) + { + if (hasPlayerPos && AcrossBuildingWall(meCell, (uint)wo.Id)) + { + if (notePassed) NotePassedOver(wo.Id, dist, PassedOverLos); + continue; + } losBlocked = false; + } // Don't blacklist from scan — just exclude from this result. // Blacklisting only happens when an active target fails LOS during attack. @@ -7042,6 +7058,19 @@ public partial class CombatManager : IDisposable /// A monster m away (3D), m above (+) or below (-), /// is out of melee's reach: on another floor, or on a ledge or a roof. + /// True when one of the two cells is a building's room on an outdoor landblock and the other + /// is outside (cells under 0x0100 are the landscape). Two dungeon cells are not: a dungeon has no + /// outdoor cells, and a monster round a dungeon corner is still reached through the wall. + internal static bool InsideVersusOutside(uint cellA, uint cellB) + { + bool aIn = (cellA & 0xFFFF) >= 0x0100, bIn = (cellB & 0xFFFF) >= 0x0100; + return aIn != bIn; + } + + private bool AcrossBuildingWall(uint meCell, uint targetId) + => meCell != 0 && _host.TryGetObjectPosition(targetId, out uint tc, out _, out _, out _) && tc != 0 + && InsideVersusOutside(meCell, tc); + internal static bool OutOfMeleeReachUpOrDown(double dist, double dz) { double rise = Math.Abs(dz); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs b/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs index 7f60188..b1d35a1 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs @@ -107,6 +107,8 @@ internal interface IDashboardHost void ToggleActiveGear(); /// The Timed Commands window (commands sent every N seconds) open or closed. void ToggleTimedCommands(); + /// The Find a Feature window (search every feature: where it is, its command) open, its box ready. + void OpenFeatureSearch(); /// The Classic (retail) look: RynthCore's own face comes back for it. void UseClassicLook(); /// The Mini Remote, drawn into the current window; the size it wants. @@ -341,7 +343,7 @@ internal sealed unsafe class InstrumentDashboard cx += chip + chipGap; bool menuOpen = ImGui.IsPopupOpen(OptionsId); if (ChipButton("##c_menu", RynthIcons.DotsThree, new Vector2(cx, cy), menuOpen ? _text : _faint, - "Options: opacity, size, the Classic look, pop out.", menuOpen)) + "Options: opacity, size, Find a feature, the Classic look, pop out.", menuOpen)) OpenOptions(new Vector2(cx + chip, cy + chip + Px(4)), anchorRight: true); cx += chip + chipGap; if (ChipButton("##c_min", prefs.Minimized ? RynthIcons.ArrowsOutLineVertical : RynthIcons.ArrowsInLineVertical, @@ -1102,6 +1104,14 @@ internal sealed unsafe class InstrumentDashboard dl.AddLine(new Vector2(p.X, p.Y + 0.5f), new Vector2(p.X + w, p.Y + 0.5f), _line); p.Y += Px(5); + // Search every feature (RynthAiPlugin.FeatureSearch.cs): its own window, no bar button. + if (MenuItem(dl, ref p, w, "##m_find", RynthIcons.MagnifyingGlass, "Find a feature", "/ra find", + "Can't find something? Search every RynthSuite feature by a word (death, vendor, buffs...):\n" + + "where it is, its command, and a button that opens it (the Find a Feature window).")) + { + ImGui.CloseCurrentPopup(); + _d.OpenFeatureSearch(); + } if (MenuItem(dl, ref p, w, "##m_classic", RynthIcons.Scroll, "Classic look", "/rc dashboard classic", "The retail-style window with tabs (Main, Monsters, Gear, Buffs, Route, Loot, Meta, Tuning).")) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Features/FeatureCatalog.cs b/Plugins/RynthCore.Plugin.RynthAi/Features/FeatureCatalog.cs new file mode 100644 index 0000000..02afc33 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Features/FeatureCatalog.cs @@ -0,0 +1,183 @@ +// ============================================================================ +// RynthAi - Features/FeatureCatalog.cs +// The feature catalog (2026-11-13): one entry per thing a player would look +// for, across RynthSuite and RynthCore, read from Docs/features/.json +// (the website's search reads the same files; Docs/features/SCHEMA in the +// repo's featsearch notes). Every file there is embedded in RynthAi +// (RynthCore.Plugin.RynthAi.csproj: EmbeddedResource with a wildcard, logical +// names "RynthAi.Features..json") and read once, through the +// source-generated RynthAiJsonContext (NativeAOT: no reflection). +// +// A file that doesn't parse logs one line and is skipped; an entry without an +// id or a name is dropped (counted in the same line). Never throws. +// ============================================================================ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Text.Json; + +namespace RynthCore.Plugin.RynthAi.Features; + +/// One catalog file: Docs/features/<area>.json. +internal sealed class FeatureFile +{ + public string Area { get; set; } = string.Empty; + public List Features { get; set; } = new(); +} + +/// One thing a player would look for (the schema's fields; JSON names are the lower-case ones). +internal sealed class FeatureEntry +{ + /// "<prefix>.<kebab-name>", unique across every file. + public string Id { get; set; } = string.Empty; + /// The name the player sees in the UI, exactly. + public string Name { get; set; } = string.Empty; + /// "RynthAi", "RynthOracle", ... or "RynthCore". + public string Plugin { get; set; } = string.Empty; + /// A short category for browsing (Combat, Buffs, Hunting, ...). + public string Group { get; set; } = string.Empty; + /// One or two plain sentences, 200 characters at most. + public string Summary { get; set; } = string.Empty; + /// Button paths to it, ">" between steps. + public List Where { get; set; } = new(); + /// The typed command with its arguments, or empty. + public string Command { get; set; } = string.Empty; + /// A command that only opens where the feature lives (the window's Open button), or empty. + public string Open { get; set; } = string.Empty; + /// The LegacyUiSettings fields it covers (RynthAi only). + public List Settings { get; set; } = new(); + /// Words a player might type that aren't in the name or summary. + public List Keywords { get; set; } = new(); +} + +/// One embedded file as it was read: its resource name, the file (null when it didn't parse) and the error. +internal sealed record FeatureFileRead(string Resource, FeatureFile? File, string Error, int Dropped); + +/// Every embedded catalog file, read once. +internal sealed class FeatureCatalog +{ + /// The logical-name prefix of the embedded files (the csproj's LogicalName). + public const string ResourcePrefix = "RynthAi.Features."; + + private static readonly object Gate = new(); + private static FeatureCatalog? _loaded; + + /// Every entry, in file order (files by name). + public IReadOnlyList Entries { get; } + + /// What each embedded file gave (tests, and the load's log line). + public IReadOnlyList Files { get; } + + public static readonly FeatureCatalog Empty = new(Array.Empty(), Array.Empty()); + + private FeatureCatalog(IReadOnlyList entries, IReadOnlyList files) + { + Entries = entries; + Files = files; + } + + /// The embedded catalog, read on first use (any thread). gets one line per bad file. + public static FeatureCatalog Shared(Action? log) + { + lock (Gate) + { + return _loaded ??= LoadEmbedded(log); + } + } + + /// The logical names of the embedded catalog files, sorted. + public static List ResourceNames() + { + var names = new List(); + foreach (string n in typeof(FeatureCatalog).Assembly.GetManifestResourceNames()) + if (n.StartsWith(ResourcePrefix, StringComparison.Ordinal) && n.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) + names.Add(n); + names.Sort(StringComparer.Ordinal); + return names; + } + + /// Reads every embedded catalog file. Never throws. + public static FeatureCatalog LoadEmbedded(Action? log) + { + var entries = new List(); + var files = new List(); + List names; + try { names = ResourceNames(); } + catch (Exception ex) + { + log?.Invoke($"[RynthAi] Find a Feature: couldn't list the catalog ({ex.GetType().Name}: {ex.Message})."); + return Empty; + } + Assembly asm = typeof(FeatureCatalog).Assembly; + foreach (string name in names) + { + FeatureFileRead read; + try + { + using Stream? s = asm.GetManifestResourceStream(name); + read = s == null ? new FeatureFileRead(name, null, "not found", 0) : Parse(name, s); + } + catch (Exception ex) { read = new FeatureFileRead(name, null, ex.GetType().Name + ": " + ex.Message, 0); } + files.Add(read); + string shown = name.Substring(ResourcePrefix.Length); + if (read.File == null) + log?.Invoke($"[RynthAi] Find a Feature: skipped {shown}, it doesn't read ({read.Error})."); + else + { + entries.AddRange(read.File.Features); + if (read.Dropped > 0) + log?.Invoke($"[RynthAi] Find a Feature: {shown}: {read.Dropped} entries without an id or a name left out."); + } + } + return new FeatureCatalog(entries, files); + } + + /// One file's JSON (the embedded stream, or a file on disk in the tests). + public static FeatureFileRead Parse(string name, Stream json) + { + try + { + FeatureFile? f = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.FeatureFile); + if (f == null) return new FeatureFileRead(name, null, "empty", 0); + return Clean(name, f); + } + catch (JsonException ex) { return new FeatureFileRead(name, null, "line " + ((ex.LineNumber ?? -1) + 1) + ": " + ex.Message, 0); } + catch (Exception ex) { return new FeatureFileRead(name, null, ex.GetType().Name + ": " + ex.Message, 0); } + } + + /// Nulls (an explicit JSON null) become empty; entries without an id or a name are dropped. + private static FeatureFileRead Clean(string name, FeatureFile f) + { + f.Area ??= string.Empty; + var kept = new List(); + int dropped = 0; + foreach (FeatureEntry? e in f.Features ?? new List()) + { + if (e == null) { dropped++; continue; } + e.Id ??= string.Empty; + e.Name ??= string.Empty; + e.Plugin ??= string.Empty; + e.Group ??= string.Empty; + e.Summary ??= string.Empty; + e.Command ??= string.Empty; + e.Open ??= string.Empty; + e.Where = NoNulls(e.Where); + e.Settings = NoNulls(e.Settings); + e.Keywords = NoNulls(e.Keywords); + if (e.Id.Trim().Length == 0 || e.Name.Trim().Length == 0) { dropped++; continue; } + if (e.Plugin.Length == 0) e.Plugin = f.Area; + kept.Add(e); + } + f.Features = kept; + return new FeatureFileRead(name, f, string.Empty, dropped); + } + + private static List NoNulls(List? list) + { + var r = new List(); + if (list == null) return r; + foreach (string? s in list) if (!string.IsNullOrWhiteSpace(s)) r.Add(s); + return r; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Features/FeatureSearch.cs b/Plugins/RynthCore.Plugin.RynthAi/Features/FeatureSearch.cs new file mode 100644 index 0000000..804f6e3 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Features/FeatureSearch.cs @@ -0,0 +1,215 @@ +// ============================================================================ +// RynthAi - Features/FeatureSearch.cs +// The Find a Feature search (pure; RynthAiHostTests' FeatureSearchTests). +// +// Every typed word must match somewhere in the entry: its name, keywords, +// summary, where paths, command / open, group or plugin. Case doesn't matter; +// a word matches a word of the entry it is the start of ("vend" finds Vendors), +// after light stemming on both sides (a plural s, -ing, -ed: "dying" stays, +// "deaths" finds Death, "looting" finds Loot). Ranked by where each word hit: +// the name over the keywords over the command, group, summary and where. No +// words: every entry, grouped by its group. +// ============================================================================ +using System; +using System.Collections.Generic; +using System.Text; + +namespace RynthCore.Plugin.RynthAi.Features; + +/// One result: the entry and its score (higher first). +internal readonly record struct FeatureHit(FeatureEntry Entry, int Score); + +/// One group of the browse view (no words typed): its name and its entries by name. +internal sealed record FeatureGroup(string Name, List Entries); + +internal static class FeatureSearch +{ + // Weights per field a word hit in (the best one counts for that word). + public const int NameWeight = 100, KeywordWeight = 60, CommandWeight = 45, GroupWeight = 40, + SummaryWeight = 30, WhereWeight = 25, PluginWeight = 20; + /// A word that is a whole word of the field (not just its start) scores this much more. + public const int WholeWordBonus = 10; + + /// The schema's groups, in the order the browse view shows them (others after, by name). + public static readonly string[] GroupOrder = + { + "Help", "Windows", "Combat", "Buffs", "Hunting", "Navigation", "Looting", "Vendors", "Inventory", "Crafting", + "Metas", "Character", "Quests", "Chat", "HUD", "Death", "Fellowship", "Pets", "Scripts", "Server", "Settings", + }; + + /// The query's words, lower case, without punctuation ("/ra hunt" is "ra", "hunt"). + public static List Words(string? text) + { + var words = new List(); + if (string.IsNullOrEmpty(text)) return words; + var sb = new StringBuilder(); + foreach (char ch in text) + { + if (char.IsLetterOrDigit(ch)) sb.Append(char.ToLowerInvariant(ch)); + else if (ch == '\'' || ch == '’') continue; // "don't" is "dont" + else Flush(sb, words); + } + Flush(sb, words); + return words; + } + + private static void Flush(StringBuilder sb, List words) + { + if (sb.Length == 0) return; + words.Add(sb.ToString()); + sb.Clear(); + } + + /// Light stemming: a plural s ("vendors"), -ing ("looting"), -ed ("looted"), a doubled last letter after them ("stopped"). + public static string Stem(string word) + { + string w = word; + if (w.Length > 5 && w.EndsWith("ing", StringComparison.Ordinal)) w = Undouble(w[..^3]); + else if (w.Length > 4 && w.EndsWith("ed", StringComparison.Ordinal)) w = Undouble(w[..^2]); + else if (w.Length > 4 && w.EndsWith("ies", StringComparison.Ordinal)) w = w[..^3] + "y"; + else if (w.Length > 3 && w.EndsWith('s') && !w.EndsWith("ss", StringComparison.Ordinal) && !w.EndsWith("us", StringComparison.Ordinal)) w = w[..^1]; + return w; + } + + /// "stopp" is "stop"; "kill", "pass" and "buzz" keep their double letter. + private static string Undouble(string w) => + w.Length >= 3 && w[^1] == w[^2] && !IsVowel(w[^1]) && w[^1] is not ('l' or 's' or 'z') ? w[..^1] : w; + + private static bool IsVowel(char c) => c is 'a' or 'e' or 'i' or 'o' or 'u'; + + /// + /// How well the typed word matches the field word : + /// 0 no match, 1 the start of it, 2 the whole word (after stemming). + /// + public static int WordMatch(string q, string w) + { + if (q.Length == 0 || w.Length == 0) return 0; + string sq = Stem(q), sw = Stem(w); + if (sq == sw || q == w) return 2; + if (sw.StartsWith(sq, StringComparison.Ordinal) || w.StartsWith(q, StringComparison.Ordinal)) return 1; + return 0; + } + + /// The best match of against any word of . + private static int FieldMatch(string q, List field) + { + int best = 0; + foreach (string w in field) + { + int m = WordMatch(q, w); + if (m > best) { best = m; if (best == 2) break; } + } + return best; + } + + /// An entry's words, by field (built per search; the catalog is a few hundred entries). + private sealed class Fields + { + public readonly List Name, Keywords, Command, Group, Summary, Where, Plugin; + + public Fields(FeatureEntry e) + { + Name = Words(e.Name); + Keywords = new List(); + foreach (string k in e.Keywords) Keywords.AddRange(Words(k)); + Command = Words(e.Command); + Command.AddRange(Words(e.Open)); + Group = Words(e.Group); + Summary = Words(e.Summary); + Where = new List(); + foreach (string p in e.Where) Where.AddRange(Words(p)); + Plugin = Words(e.Plugin); + } + } + + /// The score of for , or 0 when a word matches nowhere. + public static int Score(FeatureEntry e, IReadOnlyList words) + { + var f = new Fields(e); + int total = 0; + foreach (string q in words) + { + int best = 0; + best = Math.Max(best, Weigh(FieldMatch(q, f.Name), NameWeight)); + best = Math.Max(best, Weigh(FieldMatch(q, f.Keywords), KeywordWeight)); + best = Math.Max(best, Weigh(FieldMatch(q, f.Command), CommandWeight)); + best = Math.Max(best, Weigh(FieldMatch(q, f.Group), GroupWeight)); + best = Math.Max(best, Weigh(FieldMatch(q, f.Summary), SummaryWeight)); + best = Math.Max(best, Weigh(FieldMatch(q, f.Where), WhereWeight)); + best = Math.Max(best, Weigh(FieldMatch(q, f.Plugin), PluginWeight)); + if (best == 0) return 0; // every word must match somewhere + total += best; + } + return total; + } + + private static int Weigh(int match, int weight) => match == 0 ? 0 : match == 2 ? weight + WholeWordBonus : weight; + + /// + /// The entries every word of matches, best first (ties by name). No words: + /// every entry in browse order (by group, then name), each with score 0. + /// + public static List Search(IReadOnlyList all, string? query) + { + List words = Words(query); + var hits = new List(); + if (words.Count == 0) + { + foreach (FeatureGroup g in Grouped(all)) + foreach (FeatureEntry e in g.Entries) hits.Add(new FeatureHit(e, 0)); + return hits; + } + foreach (FeatureEntry e in all) + { + int s = Score(e, words); + if (s > 0) hits.Add(new FeatureHit(e, s)); + } + hits.Sort((a, b) => a.Score != b.Score ? b.Score.CompareTo(a.Score) : CompareNames(a.Entry, b.Entry)); + return hits; + } + + /// Every entry by group (the schema's order, then others by name; no group is "Other"), each group by name. + public static List Grouped(IReadOnlyList all) + { + var byName = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (FeatureEntry e in all) + { + string g = e.Group.Trim().Length > 0 ? e.Group.Trim() : "Other"; + if (!byName.TryGetValue(g, out FeatureGroup? group)) byName[g] = group = new FeatureGroup(g, new List()); + group.Entries.Add(e); + } + var groups = new List(byName.Values); + groups.Sort((a, b) => + { + int ia = GroupRank(a.Name), ib = GroupRank(b.Name); + return ia != ib ? ia.CompareTo(ib) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); + }); + foreach (FeatureGroup g in groups) g.Entries.Sort(CompareNames); + return groups; + } + + private static int GroupRank(string g) + { + int i = Array.FindIndex(GroupOrder, x => x.Equals(g, StringComparison.OrdinalIgnoreCase)); + return i >= 0 ? i : GroupOrder.Length; + } + + private static int CompareNames(FeatureEntry a, FeatureEntry b) + { + int c = string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); + return c != 0 ? c : string.Compare(a.Plugin, b.Plugin, StringComparison.OrdinalIgnoreCase); + } + + /// "12 features match 'death'", "1 feature matches 'death'", "No feature matches 'xyz'", "40 features". + public static string CountLine(int count, string? query) + { + string q = (query ?? string.Empty).Trim(); + if (Words(q).Count == 0) return count == 1 ? "1 feature" : $"{count} features"; + return count switch + { + 0 => $"No feature matches '{q}'", + 1 => $"1 feature matches '{q}'", + _ => $"{count} features match '{q}'", + }; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Features/FeatureSearchWindow.cs b/Plugins/RynthCore.Plugin.RynthAi/Features/FeatureSearchWindow.cs new file mode 100644 index 0000000..7e0a78b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Features/FeatureSearchWindow.cs @@ -0,0 +1,275 @@ +// ============================================================================ +// RynthAi - Features/FeatureSearchWindow.cs +// The Find a Feature window (2026-11-13): a search box (focused when the +// window opens), the count line, and the results: each with its name, the +// plugin it is in, what it does, where to find it (the button path), its +// command (Copy puts it on the clipboard) and Open when the catalog says how +// to open it. No words typed: the groups, each a header to fold open. +// +// RynthCore hosts the window (the sections manifest's "featuresearch" window, +// plugin API v89: header, pop-out, resize, remembered place; no bar button) +// and calls Draw through RynthPluginRenderEmbed. AC's render thread: the +// catalog is read once and never changes; Open goes to the tick as a chat +// command. Looks: Shared/RynthUi (the player's theme), as Active Gear. +// ============================================================================ +using System; +using System.Collections.Generic; +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.RynthAi.Features; + +internal sealed class FeatureSearchWindow +{ + private readonly Func> _entries; + private readonly Action _run; + + private string _query = string.Empty; + private string? _builtFor; + private List _hits = new(); + private List _groups = new(); + private readonly HashSet _openGroups = new(StringComparer.OrdinalIgnoreCase); + private bool _focus = true; + private bool _scrollTop; + private string _copied = string.Empty; + private long _copiedAtMs; + + private float _k = 1f; + private float Px(float v) => v * _k; + + private const string HelpText = + "Type what you are looking for: every word has to match, in any order (\"death hunt\", \"vend\", \"loot rares\").\n\n" + + "Each result says where to find it (the buttons to click, from the RynthCore bar, the RynthAi window's ⋯ menu " + + "or a window's title), its chat command, and Open when it can open the place for you.\n\n" + + "Clear the box to browse everything by group.\n\n" + + "/ra find opens this window with the words in the box."; + + /// The catalog (read once). + /// Runs an Open command (a chat command, on the tick). + public FeatureSearchWindow(Func> entries, Action run) + { + _entries = entries; + _run = run; + } + + /// The words in the box (/ra find's words); the box gets the keyboard on the next draw. + public void SetQuery(string query) + { + _query = query ?? string.Empty; + _focus = true; + _scrollTop = true; + } + + /// The window was off screen and is back: the box gets the keyboard. + public void Reopened() => _focus = true; + + /// Draws the window body into the current ImGui window and returns the size it would like. Render thread. + public Vector2 Draw() + { + _k = Math.Max(0.5f, Font(RynthUiFont.Ui11).FontSize / 11f); + Vector2 origin = ImGui.GetCursorScreenPos(); + Vector2 size = ImGui.GetContentRegionAvail(); + var want = new Vector2(Px(560), Px(460)); + if (size.X < 60 || size.Y < 40) return want; + ImDrawListPtr frame = ImGui.GetWindowDrawList(); + frame.AddRectFilled(origin, origin + size, Background, 4); + using (PushFont(RynthUiFont.Ui11)) + { + ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 4)); + ImGui.SetCursorScreenPos(origin + new Vector2(6, 6)); + ImGui.Indent(6); + float w = size.X - 12; + DrawTop(w); + Build(); + ImGui.PushTextWrapPos(ImGui.GetCursorScreenPos().X + w); + Label(FeatureSearch.CountLine(Words() ? _hits.Count : _entries().Count, _query) + ".", Mute); + ImGui.PopTextWrapPos(); + + // 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(10)); + ImGui.PushStyleColor(ImGuiCol.ChildBg, Field); + ImGui.BeginChild("##fs_rows", new Vector2(w, bodyH)); + if (_scrollTop) { ImGui.SetScrollY(0); _scrollTop = false; } + ImGui.Indent(Px(6)); + ImGui.Dummy(new Vector2(0, Px(2))); + if (_entries().Count == 0) Label("The feature list didn't load (the RynthCore log says why).", Highlight); + else if (Words()) DrawHits(); + else DrawGroups(); + ImGui.Unindent(Px(6)); + ImGui.EndChild(); + ImGui.PopStyleColor(); + + ImGui.Unindent(6); + ImGui.PopStyleVar(); + } + frame.AddRect(origin, origin + size, Border, 4); + return want; + } + + private bool Words() => FeatureSearch.Words(_query).Count > 0; + + // ── Top: the box, Clear, help ─────────────────────────────────────── + + private void DrawTop(float w) + { + Vector2 start = ImGui.GetCursorScreenPos(); + float h = Px(22), iconW = Px(22); + float clearW = ButtonWidth("Clear"); + float boxW = Math.Max(Px(60), w - clearW - iconW - Px(8)); + ImGui.SetNextItemWidth(boxW); + ImGui.PushStyleColor(ImGuiCol.FrameBg, Field); + if (_focus) + { + ImGui.SetKeyboardFocusHere(); + _focus = false; + } + if (ImGui.InputTextWithHint("##fs_query", "Find a feature: type a word (death, vendor, buffs, loot...)", ref _query, 96u)) + _scrollTop = true; + ImGui.PopStyleColor(); + float x = start.X + boxW + Px(4); + if (Button("##fs_clear", "Clear", new Vector2(x, start.Y), new Vector2(clearW, h), Text, ButtonFill, enabled: _query.Length > 0)) + { + _query = string.Empty; + _focus = true; + _scrollTop = true; + } + ImGui.SetItemTooltip("Clear the box: every feature, by group."); + x += clearW + Px(4); + IconButton("##fs_help", RynthIcons.Info, new Vector2(x, start.Y), new Vector2(iconW, h), Mute, ButtonFill, font: RynthUiFont.Ui11); + if (ImGui.IsItemHovered()) + { + ImGui.BeginTooltip(); + ImGui.PushTextWrapPos(ImGui.GetFontSize() * 32); + ImGui.TextUnformatted(HelpText); + ImGui.PopTextWrapPos(); + ImGui.EndTooltip(); + } + ImGui.SetCursorScreenPos(new Vector2(start.X, start.Y + h + Px(4))); + ImGui.Dummy(Vector2.Zero); + } + + private void Build() + { + if (_builtFor == _query) return; + _builtFor = _query; + IReadOnlyList all = _entries(); + _hits = FeatureSearch.Search(all, _query); + if (_groups.Count == 0 && all.Count > 0) _groups = FeatureSearch.Grouped(all); + } + + // ── Results ───────────────────────────────────────────────────────── + + private void DrawHits() + { + if (_hits.Count == 0) + { + ImGui.PushTextWrapPos(0); + Label("Nothing matches every word. Try fewer words, or the start of one (\"vend\" finds Vendors).", Mute); + ImGui.PopTextWrapPos(); + return; + } + for (int i = 0; i < _hits.Count; i++) DrawEntry(_hits[i].Entry, i); + } + + private void DrawGroups() + { + int n = 0; + foreach (FeatureGroup g in _groups) + { + ImGui.PushID("g_" + g.Name); + bool open = _openGroups.Contains(g.Name); + Vector2 p = ImGui.GetCursorScreenPos(); + float w = Math.Max(1, ImGui.GetContentRegionAvail().X - Px(4)); + float h = Px(22); + bool clicked = ImGui.InvisibleButton("##hdr", new Vector2(w, h)); + bool hot = ImGui.IsItemHovered(); + if (clicked) + { + if (open) _openGroups.Remove(g.Name); else _openGroups.Add(g.Name); + open = !open; + } + SafeImGui.SetItemTooltip(open ? "Click to fold " + g.Name + " away." : "Click for the " + g.Name + " features."); + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + dl.AddRectFilled(p, p + new Vector2(w, h), hot ? Selected : ButtonFill, 3); + DrawCentered(dl, Font(RynthUiFont.Ui11), open ? RynthIcons.CaretDown : RynthIcons.CaretRight, + new Vector2(p.X + Px(2), p.Y), new Vector2(Px(16), h), Mute); + ImFontPtr bold = Font(RynthUiFont.UiBold11); + dl.AddText(bold, bold.FontSize, new Vector2(p.X + Px(20), p.Y + (h - bold.FontSize) * 0.5f), Text, g.Name); + string count = g.Entries.Count.ToString(System.Globalization.CultureInfo.InvariantCulture); + float cw = ImGui.CalcTextSize(count).X; + dl.AddText(new Vector2(p.X + w - cw - Px(8), p.Y + (h - ImGui.GetFontSize()) * 0.5f), Mute, count); + if (open) + { + ImGui.Dummy(new Vector2(0, Px(2))); + foreach (FeatureEntry e in g.Entries) DrawEntry(e, n++); + } + ImGui.PopID(); + } + } + + /// One feature: name and plugin tag, Copy and Open; what it does; where; the command. + private void DrawEntry(FeatureEntry e, int index) + { + ImGui.PushID(index); + ImGui.PushID(e.Id); + float w = Math.Max(Px(120), ImGui.GetContentRegionAvail().X - Px(4)); + Vector2 p = ImGui.GetCursorScreenPos(); + ImDrawListPtr dl = ImGui.GetWindowDrawList(); + float lineH = Px(22); + + // The buttons on the name's line, at the right: Copy (the command), Open. + bool hasOpen = e.Open.Length > 0, hasCommand = e.Command.Length > 0; + float openW = hasOpen ? ButtonWidth("Open") : 0, copyW = hasCommand ? ButtonWidth("Copy") : 0; + float bx = p.X + w; + if (hasOpen) + { + bx -= openW; + if (Button("##fs_open", "Open", new Vector2(bx, p.Y), new Vector2(openW, lineH), Text, AccentFill)) + _run(e.Open); + SafeImGui.SetItemTooltip("Opens it: runs " + e.Open); + bx -= Px(4); + } + if (hasCommand) + { + bx -= copyW; + if (Button("##fs_copy", "Copy", new Vector2(bx, p.Y), new Vector2(copyW, lineH), Text, ButtonFill)) + { + ImGui.SetClipboardText(e.Command); + _copied = e.Id; + _copiedAtMs = Environment.TickCount64; + } + bool justCopied = _copied == e.Id && Environment.TickCount64 - _copiedAtMs < 2500; + SafeImGui.SetItemTooltip(justCopied ? "Copied: paste it in chat (Ctrl+V)." : "Copy the command: " + e.Command); + bx -= Px(4); + } + + // Name (bold) and the plugin's tag, clipped short of the buttons. + ImFontPtr bold = Font(RynthUiFont.UiBold11); + float ty = p.Y + (lineH - bold.FontSize) * 0.5f; + float textRight = bx - Px(4); + dl.PushClipRect(p, new Vector2(Math.Max(p.X + 1, textRight), p.Y + lineH), true); + dl.AddText(bold, bold.FontSize, new Vector2(p.X, ty), Accent, e.Name); + float nameW = bold.CalcTextSizeA(bold.FontSize, float.MaxValue, 0f, e.Name).X; + if (e.Plugin.Length > 0) + Badge(dl, new Vector2(p.X + nameW + Px(8), p.Y + (lineH - Px(14)) * 0.5f), Px(14), e.Plugin, RowAlt, Mute); + dl.PopClipRect(); + ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + lineH + Px(1))); + + ImGui.PushTextWrapPos(p.X + w); + if (e.Summary.Length > 0) Label(e.Summary, Text); + foreach (string where in e.Where) Label("Where: " + where, Mute); + if (hasCommand) Label("Command: " + e.Command, Highlight); + ImGui.PopTextWrapPos(); + + ImGui.Dummy(new Vector2(0, Px(2))); + Vector2 q = ImGui.GetCursorScreenPos(); + dl.AddLine(new Vector2(p.X, q.Y), new Vector2(p.X + w, q.Y), Border); + ImGui.Dummy(new Vector2(0, Px(4))); + ImGui.PopID(); + ImGui.PopID(); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/SectionsManifest.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/SectionsManifest.cs index 4ac3970..de7ec92 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Huds/SectionsManifest.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/SectionsManifest.cs @@ -98,21 +98,28 @@ internal static class SectionsManifest /// public const string ActiveGearTitle = RynthAiPlugin.ActiveGearTitle, ActiveGearSurface = RynthAiPlugin.ActiveGearSurface; + /// + /// The Find a Feature window (RynthAiPlugin.FeatureSearch.cs, 2026-11-13): searches the feature catalog + /// (Docs/features/*.json), drawn by RynthAi in the engine's frame (plugin API v89). No bar button (the + /// bar is full): the dashboard's options menu (Find a feature) and /ra find open it. + /// + public const string FeatureSearchTitle = RynthAiPlugin.FeatureSearchTitle, FeatureSearchSurface = RynthAiPlugin.FeatureSearchSurface; + /// /// The manifest JSON for (UTF-8 text, schema version 1), with the dashboard /// window when , the Monster Stats window when , - /// the Timed Commands window when and the Active Gear window when - /// . + /// the Timed Commands window when , the Active Gear window when + /// and the Find a Feature window when . /// public static string Build(IReadOnlyList views, IReadOnlyList
sections, bool dashboard = false, bool monsterStats = false, - bool timedCommands = false, bool activeGear = false) + bool timedCommands = false, bool activeGear = false, bool featureSearch = false) { using var stream = new MemoryStream(4096); using (var w = new Utf8JsonWriter(stream)) { w.WriteStartObject(); w.WriteNumber("version", 1); - bool windows = dashboard || monsterStats || timedCommands || activeGear; + bool windows = dashboard || monsterStats || timedCommands || activeGear || featureSearch; if (windows) w.WriteStartArray("windows"); if (dashboard) @@ -178,6 +185,21 @@ internal static class SectionsManifest w.WriteBoolean("edgeToEdge", true); w.WriteEndObject(); } + if (featureSearch) + { + w.WriteStartObject(); + w.WriteString("id", "featuresearch"); + w.WriteString("title", FeatureSearchTitle); + w.WriteString("surface", FeatureSearchSurface); + w.WriteString("icon", RynthCore.Plugin.Shared.RynthUi.RynthIcons.MagnifyingGlass); + w.WriteNumber("width", 560); + w.WriteNumber("height", 460); + w.WriteNumber("minWidth", 360); + w.WriteNumber("minHeight", 200); + w.WriteBoolean("bar", false); + w.WriteBoolean("edgeToEdge", true); + w.WriteEndObject(); + } if (windows) w.WriteEndArray(); w.WriteStartArray("sections"); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index a0f95d2..0726452 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -368,6 +368,9 @@ internal sealed class LegacyAdvancedSettingsUi _settings.PatrolOnLogin = false; if (ImGui.IsItemHovered()) ImGui.SetTooltip(LoginAutoStart.HuntOnLoginTip); + ImGui.Checkbox("Keep Hunting After Death", ref _settings.KeepHuntingAfterDeath); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip(AfterDeath.Tip); ImGui.Checkbox("Resume Meta After Reload", ref _settings.ResumeMetaOnReload); if (ImGui.IsItemHovered()) ImGui.SetTooltip("After a hot reload the meta carries on in the same state, with its variables,\nfired rules and route. A real login still starts in Default."); @@ -806,6 +809,9 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Checkbox("Fight the monster I select", ref _settings.FightSelectedTarget); if (ImGui.IsItemHovered()) ImGui.SetTooltip(LegacyUiSettings.FightSelectedTargetTip); + ImGui.Checkbox("Melee through walls", ref _settings.MeleeThroughWalls); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip(LegacyUiSettings.MeleeThroughWallsTip); ImGui.Spacing(); ImGui.Text("Corpse Acquisition (Yards)"); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index 0c3d5cd..fc41557 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -1387,6 +1387,7 @@ internal sealed partial class LegacyDashboardRenderer TargetSelection = s.TargetSelection, TargetLock = s.TargetLock, FightSelectedTarget = s.FightSelectedTarget, + MeleeThroughWalls = s.MeleeThroughWalls, RingRange = s.RingRange, ApproachRange = s.ApproachRange, CorpseApproachRangeMax = s.CorpseApproachRangeMax, @@ -1679,6 +1680,7 @@ internal sealed partial class LegacyDashboardRenderer if (p.TargetSelection is int targeting) s.TargetSelection = Math.Clamp(targeting, 0, 3); // absent = unchanged if (p.TargetLock is bool targetLock) s.TargetLock = targetLock; // absent = unchanged if (p.FightSelectedTarget is bool fightSel) s.FightSelectedTarget = fightSel; // absent = unchanged + if (p.MeleeThroughWalls is bool meleeWalls) s.MeleeThroughWalls = meleeWalls; // absent = unchanged s.RingRange = p.RingRange; s.ApproachRange = p.ApproachRange; s.CorpseApproachRangeMax = p.CorpseApproachRangeMax; @@ -2205,6 +2207,7 @@ internal sealed partial class LegacyDashboardRenderer dst.TargetSelection = Math.Clamp(tmp.TargetSelection, 0, 3); dst.TargetLock = tmp.TargetLock; dst.FightSelectedTarget = tmp.FightSelectedTarget; + dst.MeleeThroughWalls = tmp.MeleeThroughWalls; dst.RingRange = tmp.RingRange; dst.HandlerRingEvade = tmp.HandlerRingEvade; // obsolete (RynthILT's now): carried so the profile keeps it for RynthILT's one-time import dst.ApproachRange = tmp.ApproachRange; @@ -2373,6 +2376,7 @@ internal sealed partial class LegacyDashboardRenderer dst.StartMacroOnLogin = tmp.StartMacroOnLogin; dst.PatrolOnLogin = tmp.PatrolOnLogin; dst.HuntOnLogin = tmp.HuntOnLogin; + dst.KeepHuntingAfterDeath = tmp.KeepHuntingAfterDeath; dst.ResumeMetaOnReload = tmp.ResumeMetaOnReload; dst.YieldToVTank = tmp.YieldToVTank; dst.FeatureServerNames = tmp.FeatureServerNames; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index bb696a6..75bf20a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -335,6 +335,19 @@ public sealed class LegacyUiSettings "another monster or deselect. The bot's own selections never count. Ignored (Priority 0) and\n" + "never-attack monsters are not followed (/ra targetlock still forces them). Out to Disengage Range.\n" + "/ra fightselected [on|off]"; + // Melee through walls (2026-11-15, on by default, the meta option meleethroughwalls): melee within + // 4 m (CombatManager.MeleeIgnoresLosWithin) ignores a blocked line of sight, except across a + // building's wall (one side in its rooms, the other outside). Off: a blocked monster is never a + // melee target for being close; it is treated like a blocked monster farther off (out of sight, + // left to the hunt). A profile saved before this setting loads it as on. + public bool MeleeThroughWalls = true; + internal const string MeleeThroughWallsTip = + "On: melee reaches a monster within 4 m even when the line of sight test says a wall is in the way\n" + + "(a corner, a pillar, a thin dungeon wall: melee lands where the test is too strict). Not across a\n" + + "building's wall: one of you inside its rooms and the other outside is left to the hunt, which walks\n" + + "in through a door.\n" + + "Off: a monster behind a wall is never a melee target for being close; it is treated like any monster\n" + + "out of sight. On by default. /ra meleewalls [on|off]"; public int RingRange = 5; // Obsolete since 2026-10-20 (unused here, kept so profiles still load and carry it): the Empyrean // Handler lethal-ring evade is Infinite Leaftide's and lives in RynthILT now (its ILT settings, @@ -547,6 +560,13 @@ public sealed class LegacyUiSettings /// public bool HuntOnLogin; /// + /// Keep Hunting After Death (2026-11-13, RynthAiPlugin.AfterDeath.cs): a death pauses the Outdoor Hunt + /// instead of ending it, and it starts again once the character is back up (after Recall On Death and + /// Travel Back To My Corpse); the Dungeon Patrol also follows into a dungeon a death sent it to. Off by + /// default (a death ended the hunt before it). + /// + public bool KeepHuntingAfterDeath; + /// /// Resume Meta After Reload (2026-11-07, Tom: "remembers which meta state you're in and restarts in /// that state so Drakkon doesn't recall back every time"). A hot reload carries the meta's whole /// runtime over (Meta/MetaResume.cs): state, variables, fired rules, call stack, watchdog, route. @@ -1449,6 +1469,7 @@ public sealed class SettingsBridgePayload public int? TargetSelection { get; set; } public bool? TargetLock { get; set; } public bool? FightSelectedTarget { get; set; } + public bool? MeleeThroughWalls { get; set; } // Melee through walls; absent (an engine without the row) = unchanged public int RingRange { get; set; } public int ApproachRange { get; set; } public double CorpseApproachRangeMax { get; set; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs index 516034a..29dc369 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/RynthAiJsonContext.cs @@ -26,6 +26,8 @@ namespace RynthCore.Plugin.RynthAi; [JsonSerializable(typeof(RynthCore.Plugin.RynthAi.MiniRemote.MiniRemoteState))] [JsonSerializable(typeof(RynthCore.Plugin.RynthAi.MiniRemote.LegacyHubFile))] [JsonSerializable(typeof(RynthCore.Plugin.RynthAi.BuffProfile))] +// The feature catalog (Docs/features/*.json, embedded): Find a Feature (Features/FeatureCatalog.cs). +[JsonSerializable(typeof(RynthCore.Plugin.RynthAi.Features.FeatureFile))] [JsonSourceGenerationOptions( WriteIndented = true, IncludeFields = true, diff --git a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs index bebd182..064779d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs @@ -252,6 +252,7 @@ public sealed partial class RynthAiPlugin ["lootpriorityboost"] = "BoostLootPriority", ["pickupmacrooff"] = "LootChestsMacroOff", // Settings > Looting > Pickup with macro off ["lootchestsmacrooff"] = "LootChestsMacroOff", + ["meleethroughwalls"] = "MeleeThroughWalls", // Settings > Combat > Targeting > Melee through walls ["dooropenrange"] = "OpenDoorRange", ["autofellowmanagement"] = "AutoFellowMgmt", ["switchwandstodebuff"] = "UseDispelItems", diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index f13e25f..7101b69 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -3664,6 +3664,7 @@ internal sealed partial class ExpressionEngine ["LootOwnCorpse"] = (() => B(s.LootOwnCorpse), v => s.LootOwnCorpse = ToDouble(v) != 0), ["EscapeHazards"] = (() => B(s.EscapeHazards), v => s.EscapeHazards = ToDouble(v) != 0), ["TravelToOwnCorpse"] = (() => B(s.TravelToOwnCorpse), v => s.TravelToOwnCorpse = ToDouble(v) != 0), + ["KeepHuntingAfterDeath"] = (() => B(s.KeepHuntingAfterDeath), v => s.KeepHuntingAfterDeath = ToDouble(v) != 0), ["ItemInfoOnSelect"] = (() => B(s.ItemInfoSettings.OnSelect), v => s.ItemInfoSettings.OnSelect = ToDouble(v) != 0), // The looter's "Looted" line names the rule and the item's details (salvage: on request). ["ItemInfoLootChat"] = (() => B(s.ItemInfoSettings.LootChat), v => s.ItemInfoSettings.LootChat = ToDouble(v) != 0), @@ -3711,6 +3712,7 @@ internal sealed partial class ExpressionEngine ["TargetSelection"] = (() => I(s.TargetSelection), v => { if (int.TryParse(v, out int i)) s.TargetSelection = Math.Clamp(i, 0, 3); }), ["TargetLock"] = (() => B(s.TargetLock), v => s.TargetLock = ToDouble(v) != 0), ["FightSelectedTarget"] = (() => B(s.FightSelectedTarget), v => s.FightSelectedTarget = ToDouble(v) != 0), + ["MeleeThroughWalls"] = (() => B(s.MeleeThroughWalls), v => s.MeleeThroughWalls = ToDouble(v) != 0), ["RingRange"] = (() => I(s.RingRange), v => { if (int.TryParse(v, out int i)) s.RingRange = i; }), ["ApproachRange"] = (() => I(s.ApproachRange), v => { if (int.TryParse(v, out int i)) s.ApproachRange = i; }), ["MinRingTargets"] = (() => I(s.MinRingTargets), v => { if (int.TryParse(v, out int i)) s.MinRingTargets = i; }), diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs index ed776db..d756098 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs @@ -1598,6 +1598,7 @@ internal sealed partial class MetaManager ["lootpriorityboost"] = "BoostLootPriority", ["pickupmacrooff"] = "LootChestsMacroOff", // Settings > Looting > Pickup with macro off ["lootchestsmacrooff"] = "LootChestsMacroOff", + ["meleethroughwalls"] = "MeleeThroughWalls", // Settings > Combat > Targeting > Melee through walls ["dooropenrange"] = "OpenDoorRange", ["autofellowmanagement"] = "AutoFellowMgmt", ["switchwandstodebuff"] = "UseDispelItems", diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs index c563757..c58bb12 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -184,6 +184,12 @@ public static unsafe class PluginExports int drawn = plugin.RenderActiveGear(popped, out want); if (drawn != 1) return drawn; } + else if (name.SequenceEqual("window:featuresearch"u8)) + { + // The Find a Feature window (RynthAiPlugin.FeatureSearch.cs): 1 drawn, 0 not ready, -2 failed. + int drawn = plugin.RenderFeatureSearch(popped, out want); + if (drawn != 1) return drawn; + } else if (name.StartsWith("section:"u8)) { // Section names are short ASCII ids (Huds/SectionsManifest.cs); anything longer isn't ours. diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index bd7611f..4d30bd5 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -68,10 +68,12 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] === Commands ==="); ChatLine("[RynthAi] /ra fellow — fellowship diagnostics and queries"); ChatLine("[RynthAi] /ra help — show this list"); + ChatLine("[RynthAi] /ra find [words] — Find a Feature: search every RynthSuite feature, where it is and its command"); ChatLine("[RynthAi] /ra version — RynthAi version and build date, and the engine it runs on"); ChatLine("[RynthAi] /ra server - which server RynthCore says this is, its overrides, and the server plugin's settings"); ChatLine("[RynthAi] /ra power <0-100|auto> — set attack power (auto = recklessness-aware)"); ChatLine("[RynthAi] /ra dfheight [on|off|status|window] — Dirty Fighting rotation: attack heights by the effects on the target"); + ChatLine("[RynthAi] /ra meleewalls [on|off] — Melee through walls: melee reaches a monster within 4 m behind a wall (not a building's)"); ChatLine("[RynthAi] /ra cast — cast spell on current target"); ChatLine("[RynthAi] /ra buffs — show active buff timers"); ChatLine("[RynthAi] /ra buffitems [list|allow|block|add|addselected|remove|repeat|open] — the buff items RynthAi may use"); @@ -3779,12 +3781,14 @@ public sealed partial class RynthAiPlugin /// those say how to patrol here instead. /// internal static PatrolFollow DecidePatrolFollow(uint patrolLb, uint playerCell, bool isDungeonLandblock, - bool portaling, uint triedLb, long msSinceDeath, bool arrivedWhileRunning) + bool portaling, uint triedLb, long msSinceDeath, bool arrivedWhileRunning, + bool followAfterDeath = false) { uint lb = playerCell >> 16; if (playerCell == 0 || lb == patrolLb || (playerCell & 0xFFFF) < 0x0100) return PatrolFollow.None; if (portaling || !isDungeonLandblock || lb == triedLb) return PatrolFollow.None; - if (msSinceDeath >= 0 && msSinceDeath < PatrolFollowDeathMs) return PatrolFollow.AfterDeath; + // Keep Hunting After Death: the patrol is the mode through a death too (RynthAiPlugin.AfterDeath.cs). + if (msSinceDeath >= 0 && msSinceDeath < PatrolFollowDeathMs && !followAfterDeath) return PatrolFollow.AfterDeath; return arrivedWhileRunning ? PatrolFollow.Follow : PatrolFollow.CameWhileStopped; } @@ -3805,7 +3809,8 @@ public sealed partial class RynthAiPlugin bool portaling = (Host.HasIsPortaling && Host.IsPortaling()) || _deathHolding; long sinceDeath = _lastDeathAt == 0 ? -1 : Environment.TickCount64 - _lastDeathAt; var what = DecidePatrolFollow(_dunPatrolLandblock, cell, _navPlanner.IsDungeonLandblock(lb, cellDat), portaling, - _dunPatrolFollowTriedLb, sinceDeath, _dunPatrolArrivedRunning); + _dunPatrolFollowTriedLb, sinceDeath, _dunPatrolArrivedRunning, + followAfterDeath: settings.KeepHuntingAfterDeath); if (what == PatrolFollow.None) return false; uint was = _dunPatrolLandblock; @@ -3820,6 +3825,8 @@ public sealed partial class RynthAiPlugin } Host.Log($"[RynthAi] DunNav-Patrol: the character went from dungeon 0x{was:X4} into 0x{lb:X4} - building the patrol here."); + if (sinceDeath >= 0 && sinceDeath < PatrolFollowDeathMs) + ChatLine($"[RynthAi] Dungeon Patrol: in dungeon 0x{lb:X4} after the death; patrolling here (Keep Hunting After Death)."); BuildDunPatrol(isRebuild: true, followedIn: true); if (!_dunPatrolActive || _dunPatrolLandblock != lb) ChatLine($"[RynthAi] Dungeon Patrol: couldn't lay a patrol in dungeon 0x{lb:X4} from here. Press Patrol to try again."); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.AfterDeath.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.AfterDeath.cs new file mode 100644 index 0000000..b73ee17 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.AfterDeath.cs @@ -0,0 +1,127 @@ +// RynthAiPlugin.AfterDeath.cs - Keep Hunting After Death (2026-11-13). +// +// Players asked for the hunt to stay on after a death, and the same for the patrol. Off by default: +// a death still ends the Outdoor Hunt (from the lifestone it would hunt round the lifestone). With +// Keep Hunting After Death on and the macro still running (Stop Macro On Death off): +// - the Outdoor Hunt is paused at the death and starts again once the character is back up and +// the death's own steps are done (the settle after the respawn, Recall On Death, Travel Back To +// My Corpse), from where the character stands then (its Hunt Radius is round that spot); +// - the Dungeon Patrol, which already carries on when the character gets back into its dungeon, +// also follows it into another dungeon a death sent it to (DecidePatrolFollow). +// A route loaded meanwhile (a meta's death handling), the macro stopped, or the box turned off: the +// hunt stays off and says why. Tick thread. +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi; + +/// The decision half of the hunt's restart after a death (pure, for the tests). +internal static class AfterDeath +{ + internal enum HuntStep + { + /// Not yet: the death's steps aren't done, or the character is in portal space. + Wait, + /// Start the hunt again from here. + Start, + /// The box was turned off: forget it quietly. + DropOff, + /// The macro was stopped: forget it and say so. + DropMacro, + /// Another route was loaded meanwhile (a meta's death handling): forget it and say so. + DropRoute, + } + + internal const string Tip = + "After a death, the Outdoor Hunt starts again once you're back up: after Recall On Death and\n" + + "Travel Back To My Corpse when they're on, from where you are then (Hunt Radius is round that spot).\n" + + "The Dungeon Patrol carries on in its dungeon, and also in a dungeon a recall takes you to after the death.\n" + + "Needs the macro to keep running (Stop Macro On Death off). A route a meta loads after the death wins."; + + internal static HuntStep DecideHunt(bool keepOn, bool macroRunning, bool routeReplaced, bool deathStepsBusy, bool portaling) + { + if (!keepOn) return HuntStep.DropOff; + if (!macroRunning) return HuntStep.DropMacro; + if (routeReplaced) return HuntStep.DropRoute; + if (deathStepsBusy || portaling) return HuntStep.Wait; + return HuntStep.Start; + } +} + +public sealed partial class RynthAiPlugin +{ + private bool _huntAfterDeath; // the hunt was on at a death, to start again once back up + private NavRouteParser? _huntAfterDeathRoute; // the empty route the paused hunt left (another one = a meta took over) + + internal const string KeepHuntingUsage = "/ra hunt death [on|off]"; + + /// The death edge (HoldForDeath): the hunt ends, or with Keep Hunting After Death pauses until the character is back up. + private void PauseHuntForDeath() + { + var s = _dashboard?.Settings; + bool keep = (_hunt.Active || _huntAfterDeath) && s is { KeepHuntingAfterDeath: true, IsMacroRunning: true }; + if (_hunt.Active) + StopHunt(keep ? "died; it starts again once you're back up (Keep Hunting After Death)" : "died", say: true); + _huntAfterDeath = keep; + _huntAfterDeathRoute = keep ? s!.CurrentRoute : null; + } + + /// Each tick the hunt is off (TickOutdoorHunt): the paused hunt starts again when the death's steps are done. + private void TickHuntAfterDeath() + { + if (!_huntAfterDeath) return; + var s = _dashboard?.Settings; + if (s == null) return; + bool replaced = !ReferenceEquals(s.CurrentRoute, _huntAfterDeathRoute) || s.CurrentNavPath.Length > 0; + bool busy = _deathHolding || _deathRecall != null || _ownCorpseTravel != OwnCorpseTravelState.None; + bool portaling = Host.HasIsPortaling && Host.IsPortaling(); + var step = AfterDeath.DecideHunt(s.KeepHuntingAfterDeath, s.IsMacroRunning, replaced, busy, portaling); + if (step == AfterDeath.HuntStep.Wait) return; + _huntAfterDeath = false; + _huntAfterDeathRoute = null; + switch (step) + { + case AfterDeath.HuntStep.Start: + StartHunt(afterDeath: true); + break; + case AfterDeath.HuntStep.DropMacro: + ChatLine(KeepHuntingRefusedPrefix + "the macro is off."); + break; + case AfterDeath.HuntStep.DropRoute: + ChatLine(KeepHuntingRefusedPrefix + $"{PatrolReplacementName(s)} is the route now."); + break; + default: + Host.Log("[RynthAi] Hunt: not started again after the death (Keep Hunting After Death was turned off)."); + break; + } + } + + internal const string KeepHuntingRefusedPrefix = "[RynthAi] Keep Hunting After Death: the hunt didn't start again: "; + + /// "/ra hunt death [on|off]": Keep Hunting After Death. No word: says it now. + private void SetKeepHuntingAfterDeath(string value) + { + var s = _dashboard?.Settings; + if (s == null) { ReplyFail("[RynthAi] Settings not ready."); return; } + string v = value.Trim().ToLowerInvariant(); + if (v.Length == 0) + { + ReplyOk($"[RynthAi] Keep Hunting After Death: {(s.KeepHuntingAfterDeath ? "on" : "off")}. {KeepHuntingUsage} to change it."); + return; + } + bool? on = v switch + { + "on" or "true" or "1" or "yes" => true, + "off" or "false" or "0" or "no" => false, + _ => null, + }; + if (on is not bool want) + { + ReplyFail($"[RynthAi] Keep Hunting After Death: '{value.Trim()}' isn't on or off (it is {(s.KeepHuntingAfterDeath ? "on" : "off")} now). Usage: {KeepHuntingUsage}"); + return; + } + s.KeepHuntingAfterDeath = want; + ReplyOk(want + ? "[RynthAi] Keep Hunting After Death set: on. After a death the hunt starts again once you're back up (after Recall On Death and Travel Back To My Corpse), and the Dungeon Patrol carries on." + : "[RynthAi] Keep Hunting After Death set: off. A death ends the hunt."); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Dashboard.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Dashboard.cs index 7896391..f09ab72 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Dashboard.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Dashboard.cs @@ -332,6 +332,7 @@ internal sealed class DashboardBridge : IDashboardHost public void ToggleSpells() => _p.EnqueueRemoteCommand("spells", "toggle"); public void ToggleActiveGear() => Queue(_p.ToggleActiveGearWindow); public void ToggleTimedCommands() => Queue(_p.ToggleTimedCommandsWindow); + public void OpenFeatureSearch() => Queue(_p.OpenFeatureSearchWindow); public void UseClassicLook() => _p.UseClassicLook(); public ProfileFileInfo ProfileInfo(int kind) diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.FeatureSearch.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.FeatureSearch.cs new file mode 100644 index 0000000..852648f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.FeatureSearch.cs @@ -0,0 +1,176 @@ +// RynthAiPlugin.FeatureSearch.cs — the Find a Feature window and /ra find (2026-11-13, approved by the +// owner: players couldn't find RynthSuite's features). +// +// The catalog is Docs/features/*.json (every RynthSuite plugin's features and RynthCore's), embedded in +// RynthAi and read once (Features/FeatureCatalog.cs); the website's search reads the same files. The +// search is Features/FeatureSearch.cs (pure, tested), the window Features/FeatureSearchWindow.cs. +// +// Ways in, buttons first: the dashboard's options menu (⋯ > Find a feature) and /ra find [words], which +// opens the window with the words in the box and says how many match. The window is a plugin window +// (API v89) declared in the sections manifest without a bar button (the bar is full). Without plugin +// windows /ra find prints the best matches in chat instead. +// +// Threads: /ra find runs on the pump thread and leaves its words for the window (a volatile string); +// the window is drawn on the render thread and sends Open's command to the tick (QueueDashCommand). +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Threading; +using ImGuiNET; +using RynthCore.Plugin.RynthAi.Features; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + /// The window's title (its panel key) and surface (Huds/SectionsManifest.cs). + internal const string FeatureSearchTitle = "Find a Feature", FeatureSearchSurface = "window:featuresearch"; + + internal const string FeatureSearchUsage = "Usage: /ra find [words] (no words: browse every feature)"; + + /// The most a /ra find may type (the window's box holds as much). + internal const int FeatureQueryMax = 96; + + /// How many matches /ra find prints in chat when the window can't open. + internal const int FeatureChatMatches = 5; + + private volatile string? _featureQueryPending; // /ra find's words for the window (pump writes, render takes) + private FeatureSearchWindow? _featureWindow; // render thread + private long _featureDrawnMs = long.MinValue / 2; // render thread + private int _featureFailures; // render thread + + /// The window goes in the manifest on an engine with plugin windows (v89). + private bool FeatureSearchWindowWanted => Host.HasUiTheme && Host.HasSetPanelOpen; + + /// The catalog, read on first use (any thread); a bad file logs one line. + internal FeatureCatalog FeatureList => FeatureCatalog.Shared(line => Host.Log(line)); + + /// The words /ra find left for the window (tests). + internal string? FeatureQueryPendingForTests => _featureQueryPending; + + // ── /ra find ───────────────────────────────────────────────────────── + + /// + /// "/ra find [words]": opens the window with the words in the box and says how many features match + /// (no words: how many there are to browse). "?" says the usage. Every form replies. Pump thread. + /// + private void HandleFindCommand(string[] parts) + { + string words = parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2).Trim() : string.Empty; + if (words is "?" or "-?" or "/?") + { + ChatLine("[RynthAi] /ra find — opens Find a Feature with every feature those words match (\"/ra find death\", \"/ra find vend\")"); + ChatLine("[RynthAi] /ra find — opens it to browse every feature by group (also: the RynthAi window's ⋯ menu > Find a feature)"); + return; + } + if (words.Length > FeatureQueryMax) + { + ReplyFail($"[RynthAi] Find a Feature: that's {words.Length} characters to look for, {FeatureQueryMax} at most. {FeatureSearchUsage}"); + return; + } + if (words.Length > 0 && FeatureSearch.Words(words).Count == 0) + { + ReplyFail($"[RynthAi] Find a Feature: '{words}' has no letters or numbers to look for. {FeatureSearchUsage}"); + return; + } + FeatureCatalog catalog = FeatureList; + if (catalog.Entries.Count == 0) + { + ReplyFail("[RynthAi] Find a Feature: the feature list didn't load (the RynthCore log says why)."); + return; + } + + List hits = FeatureSearch.Search(catalog.Entries, words); + _featureQueryPending = words; + int open = OpenFeatureWindow(); + string where = open == 1 ? " (Find a Feature open)" + : open == -2 ? string.Empty + : " (the window isn't there yet: RynthCore adds it a few seconds after login)"; + string count = FeatureSearch.CountLine(hits.Count, words); + if (words.Length > 0 && hits.Count == 0) + ReplyFail($"[RynthAi] Find a Feature: {count}{where}. Try fewer words, or the start of one. {FeatureSearchUsage}"); + else if (words.Length == 0) + ReplyOk($"[RynthAi] Find a Feature: {count} to browse by group{where}."); + else + ReplyOk($"[RynthAi] Find a Feature: {count}{where}."); + // No window to show them in: the best few in chat. + if (open != 1 && words.Length > 0) + for (int i = 0; i < hits.Count && i < FeatureChatMatches; i++) ChatLine("[RynthAi] " + ChatText(hits[i].Entry)); + } + + /// "Name (Plugin): where; /command" for chat. + internal static string ChatText(FeatureEntry e) + { + string text = e.Name + (e.Plugin.Length > 0 ? " (" + e.Plugin + ")" : string.Empty); + if (e.Where.Count > 0) text += ": " + e.Where[0]; + if (e.Command.Length > 0) text += (e.Where.Count > 0 ? "; " : ": ") + e.Command; + return text; + } + + /// + /// The window open: 1 open, 0 closed, -1 not there yet (RynthCore adds plugin windows a few seconds + /// after login), -2 no plugin windows on this RynthCore. Any thread. + /// + private int OpenFeatureWindow() + { + if (!Host.HasSetPanelOpen) return -2; + int r = Host.SetPanelOpen(FeatureSearchTitle, RynthPanelOpen.Open); + return r < 0 ? -1 : r; + } + + /// The dashboard's ⋯ > Find a feature: the window open, the box ready to type in. Any thread. + internal void OpenFeatureSearchWindow() + { + if (OpenFeatureWindow() == -1) + ChatLine("[RynthAi] Find a Feature isn't there yet (RynthCore adds it a few seconds after login). Try again in a moment, or type /ra find ."); + } + + /// The window's Open: a feature's open command, run as typed (on the tick). + private void RunFeatureOpen(string command) + { + if (string.IsNullOrWhiteSpace(command)) return; + if (!Host.HasInvokeChatParser) + { + ChatLine("[RynthAi] Find a Feature: this RynthCore can't run commands for RynthAi; type " + command); + return; + } + QueueDashCommand(command.Trim()); + } + + // ── Window (render thread) ─────────────────────────────────────────── + + /// + /// RynthPluginRenderEmbed "window:featuresearch": the Find a Feature window body, docked or popped out. + /// 1 drawn, 0 not ready, -2 failed (three draws in a row threw). + /// + internal int RenderFeatureSearch(bool popped, out Vector2 want) + { + want = default; + if (!_initialized || Host.ImGuiContext == IntPtr.Zero) return 0; + long now = Environment.TickCount64; + bool reopened = now - _featureDrawnMs > 1000; + _featureDrawnMs = now; + IntPtr previous = ImGui.GetCurrentContext(); + ImGui.SetCurrentContext(EmbedContext()); + try + { + _featureWindow ??= new FeatureSearchWindow(() => FeatureList.Entries, RunFeatureOpen); + string? pending = Interlocked.Exchange(ref _featureQueryPending, null); + if (pending != null) _featureWindow.SetQuery(pending); + else if (reopened) _featureWindow.Reopened(); + want = _featureWindow.Draw(); + _featureFailures = 0; + return 1; + } + catch (Exception ex) + { + RynthLog.Exception(LogCat.UI, ex, "RenderFeatureSearch"); + return ++_featureFailures >= 3 ? -2 : 0; + } + finally + { + ImGui.SetCurrentContext(previous); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs index 25220a8..a06cc30 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs @@ -494,7 +494,7 @@ public sealed partial class RynthAiPlugin if (!_initialized || !_loginComplete) return null; return Huds.SectionsManifest.Build(Huds.SectionsManifest.Views(), Huds.SectionsManifest.OwnSections, dashboard: DashboardWindowWanted, monsterStats: MonsterStatsWindowWanted, timedCommands: TimedCommandsWindowWanted, - activeGear: ActiveGearWindowWanted); + activeGear: ActiveGearWindowWanted, featureSearch: FeatureSearchWindowWanted); } /// Chat Translate window in the dashboard colours (no-op while hidden). private void RenderTranslateWindow() diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs index 36c7889..6079017 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs @@ -62,6 +62,10 @@ public sealed partial class RynthAiPlugin case "login": SetHuntOnLogin(parts.Length > 3 ? parts[3] : ""); break; + case "death": + case "keep": + SetKeepHuntingAfterDeath(parts.Length > 3 ? parts[3] : ""); + break; case "panel": case "settings": ToggleHuntPanel(); @@ -70,7 +74,7 @@ public sealed partial class RynthAiPlugin if (_hunt.Active) StopHunt("stopped", say: true); else StartHunt(); break; default: - ChatLine("[RynthAi] /ra hunt [start|stop|status|panel] | /ra hunt range | /ra hunt radius | " + HuntPickUsage + " | " + HuntLoginUsage); + ChatLine("[RynthAi] /ra hunt [start|stop|status|panel] | /ra hunt range | /ra hunt radius | " + HuntPickUsage + " | " + HuntLoginUsage + " | " + KeepHuntingUsage); break; } } @@ -193,6 +197,8 @@ public sealed partial class RynthAiPlugin string note = _hunt.Note; if (on && note.Length > 0) Wrapped(note, Ui.Text); HuntOnLoginCheckbox(s); + ImGui.Checkbox("Keep Hunting After Death##huntkeepdeath", ref s.KeepHuntingAfterDeath); + if (ImGui.IsItemHovered()) ImGui.SetTooltip(AfterDeath.Tip); ImGui.Separator(); float range = s.OutdoorHuntRange; @@ -259,9 +265,13 @@ public sealed partial class RynthAiPlugin internal const string HuntOnLoginRefusedPrefix = "[RynthAi] Hunt On Login: the hunt didn't start. "; - /// The Hunt button, /ra hunt and Hunt On Login (: its lines say so). - internal void StartHunt(bool onLogin = false) + /// + /// The Hunt button, /ra hunt, Hunt On Login () and Keep Hunting After Death + /// (): their lines say which. + /// + internal void StartHunt(bool onLogin = false, bool afterDeath = false) { + _huntAfterDeath = false; // started now, by whichever: nothing waits for the respawn any more var s = _dashboard?.Settings; uint cell = 0; OutdoorHunt.Vec me = default; @@ -277,7 +287,7 @@ public sealed partial class RynthAiPlugin { string why = OutdoorHunt.StartBlockText(block); if (onLogin) Host.Log("[RynthAi] Hunt On Login: not started (" + block + ")."); - ChatLine((onLogin ? HuntOnLoginRefusedPrefix : "[RynthAi] ") + why); + ChatLine((onLogin ? HuntOnLoginRefusedPrefix : afterDeath ? KeepHuntingRefusedPrefix : "[RynthAi] ") + why); return; } if (!s.IsMacroRunning && RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge) @@ -295,7 +305,9 @@ public sealed partial class RynthAiPlugin s.IsMacroRunning = true; _macroWasRunning = true; // no macro-start "nearest waypoint" pick: the hunt plans its own walks } - ChatLine((onLogin ? "[RynthAi] Hunt On Login: outdoor hunt on: " : "[RynthAi] Outdoor hunt on: ") + ChatLine((onLogin ? "[RynthAi] Hunt On Login: outdoor hunt on: " + : afterDeath ? "[RynthAi] Outdoor hunt on again after the death, from here (Keep Hunting After Death): " + : "[RynthAi] Outdoor hunt on: ") + HuntSettingsText(s) + " /ra hunt range to change."); } @@ -384,7 +396,7 @@ public sealed partial class RynthAiPlugin /// Each plugin tick while logged in: the hunt's next walk, when nothing else wants the character. private void TickOutdoorHunt() { - if (!_hunt.Active) return; + if (!_hunt.Active) { TickHuntAfterDeath(); return; } var s = _dashboard?.Settings; if (s == null) return; if (!s.IsMacroRunning) { StopHunt("the macro stopped"); return; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs index 6715270..7a5a7b1 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs @@ -121,7 +121,9 @@ public sealed partial class RynthAiPlugin _buffManager?.CancelPendingRecall("death"); // no /lifestone or macro restart after the respawn _buffManager?.ForgetPendingWield("death"); // a swap the death cut short is not a failed swap _petManager?.OnPlayerDeath(); // the pet out is left behind with the corpse - StopHunt("died", say: true); // from the lifestone it would walk all the way back to where it started + // From the lifestone it would walk all the way back to where it started: off, or with Keep + // Hunting After Death paused until the character is back up (RynthAiPlugin.AfterDeath.cs). + PauseHuntForDeath(); } else { diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs index 91768cf..12cff58 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs @@ -12,6 +12,7 @@ namespace RynthCore.Plugin.RynthAi; // /ra setmetastate Meta: switch the meta state (no state: list them) // /ra targetlock [off] Target lock attack the selected monster (again / off: release) // /ra fightselected [on|off] Fight the monster I select (no argument: toggle) +// /ra meleewalls [on|off] Melee through walls (no argument: toggle) // /ra meleelow|meleemid|meleehigh melee attack height // /ra navaddpt NavAddPt waypoint at your position (same as /ra addnavpt) // /ra testitem TestItem the selected item against the loot profile @@ -55,6 +56,8 @@ public sealed partial class RynthAiPlugin case "targetlock": HandleTargetLockCommand(parts); return true; case "fightselected": case "fightselect": HandleFightSelectedCommand(parts); return true; + case "meleewalls": + case "meleethroughwalls": HandleMeleeWallsCommand(parts); return true; case "meleelow": SetMeleeAttackHeight(0); return true; case "meleemid": case "meleemedium": SetMeleeAttackHeight(1); return true; @@ -205,6 +208,32 @@ public sealed partial class RynthAiPlugin : "[RynthAi] Fight the monster I select: off."); } + // ── Melee through walls ────────────────────────────────────────────────── + + private void HandleMeleeWallsCommand(string[] parts) + { + var dash = _dashboard; + var s = dash?.Settings; + if (s == null) { ReplyFail("[RynthAi] Settings not ready."); return; } + string arg = parts.Length >= 3 ? parts[2].ToLowerInvariant() : ""; + bool? set = arg switch + { + "" or "toggle" => !s.MeleeThroughWalls, + "on" or "1" or "true" => true, + "off" or "0" or "false" => false, + _ => null, + }; + if (set is not bool on) + { + ReplyFail($"[RynthAi] Melee through walls: unknown '{arg}'. Usage: /ra meleewalls [on|off] (now {(s.MeleeThroughWalls ? "on" : "off")})."); + return; + } + s.MeleeThroughWalls = on; + dash!.SaveSettings(); + ReplyOk(on ? "[RynthAi] Melee through walls: on (melee reaches a monster within 4 m behind a wall, not across a building's wall)." + : "[RynthAi] Melee through walls: off (a monster behind a wall is never a melee target for being close)."); + } + // ── Melee attack height ────────────────────────────────────────────────── private void SetMeleeAttackHeight(int height) diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index 8a5d17a..01a91e7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -4150,6 +4150,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "mstats": HandleMonsterStatsCommand(parts); break; // RynthAiPlugin.MonsterStats.cs case "gear": HandleGearCommand(parts); break; // RynthAiPlugin.ActiveGear.cs case "timed": HandleTimedCommand(parts); break; // RynthAiPlugin.TimedCommands.cs + case "find": HandleFindCommand(parts); break; // RynthAiPlugin.FeatureSearch.cs case "aetheria": HandleAetheriaCommand(parts); break; // RynthAiPlugin.Aetheria.cs case "autoconfirm": HandleAutoConfirmCommand(parts); break; // RynthAiPlugin.AutoConfirm.cs case "why": HandleWhyCommand(); break; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj index 2253e9f..77d64bb 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthCore.Plugin.RynthAi.csproj @@ -106,6 +106,10 @@ C:\Games\RynthSuite\RynthAi\Data wins over the built-in one. --> + + diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 0d6957b..a5b7123 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -101,6 +101,7 @@ internal static class Program HandSwapTests.Register(runner); OutdoorHuntTests.Register(runner); HuntOnLoginTests.Register(runner); + KeepHuntingAfterDeathTests.Register(runner); HuntBuildingTests.Register(runner); FloodPerfTests.Register(runner); LootSalvageTests.Register(runner); @@ -229,6 +230,8 @@ internal static class Program FellowOpenTests.Register(runner); WieldBanTests.Register(runner); ActiveGearTests.Register(runner); + FeatureSearchTests.Register(runner); + FeatureCatalogTests.Register(runner); return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/FeatureCatalogTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/FeatureCatalogTests.cs new file mode 100644 index 0000000..33b60e4 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/FeatureCatalogTests.cs @@ -0,0 +1,624 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; +using RynthCore.Engine.UI.Sections; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.Features; +using RynthCore.Plugin.RynthAi.Huds; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The feature catalog (Docs/features/*.json, embedded in RynthAi; Features/FeatureCatalog.cs), the +// Find a Feature window in the sections manifest, and /ra find. +// +// The catalog's rules (Docs/features schema): every file is embedded and parses; every entry has its +// required fields; ids are unique and carry their plugin's prefix; command and open start with '/'; +// open never toggles anything; summaries are 200 characters at most; settings are LegacyUiSettings +// fields. +// +// Coverage, so the catalog can't fall behind the code: every /ra verb DispatchRaCommand handles, +// every window and view in RynthAi's sections manifest, and every LegacyUiSettings field is in some +// RynthAi entry, or in an ignore list below with its reason. The ignore lists are for what a player +// never uses (developer dumps, internal state); a player's command or setting goes in the catalog. +internal static class FeatureCatalogTests +{ + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + private const string AddIt = "add it to Docs/features/rynthai.json"; + /// The where of a feature with no button (the content's convention). + private const string CommandOnlyWhere = "Chat command (no button)"; + + public static void Register(Runner r) + { + r.Add("feature catalog: every Docs/features file is embedded and parses", EveryFileEmbeddedAndParses); + r.Add("feature catalog: required fields, ids, commands, where, summary, settings", EntriesValid); + r.Add("feature catalog: open commands only open (never start, stop or toggle)", OpenOnlyOpens); + r.Add("feature catalog: a bad file is skipped, nulls and nameless entries cleaned", BadFilesSkipped); + r.Add("feature catalog coverage: every /ra command is in the catalog", CoverageCommands); + r.Add("feature catalog coverage: every RynthAi window and view is in the catalog", CoverageWindows); + r.Add("feature catalog coverage: every RynthAi setting is in the catalog", CoverageSettings); + r.Add("find a feature: the window is in the manifest with no bar button", Manifest); + r.Add("find a feature: /ra find opens the window with the words and says the count", FindCommand); + r.Add("find a feature: /ra find without plugin windows prints the best matches", FindCommandNoWindows); + } + + // ── Where things are ───────────────────────────────────────────────── + + private static string RepoRoot() + { + string? root = AppContext.BaseDirectory; + while (root != null && !(Directory.Exists(Path.Combine(root, "Plugins")) && Directory.Exists(Path.Combine(root, "Docs")))) + root = Path.GetDirectoryName(root); + return root ?? throw new InvalidOperationException("RynthSuite's root (Plugins and Docs) not found above " + AppContext.BaseDirectory); + } + + private static string FeaturesDir => Path.Combine(RepoRoot(), "Docs", "features"); + + private static FeatureCatalog Catalog() => FeatureCatalog.LoadEmbedded(null); + + private static List RynthAiEntries() => + Catalog().Entries.Where(e => e.Plugin.Equals("RynthAi", StringComparison.Ordinal)).ToList(); + + /// The id prefix of each plugin (the schema's list). + private static readonly Dictionary Prefixes = new(StringComparer.Ordinal) + { + ["RynthAi"] = "ai", ["RynthOracle"] = "oracle", ["RynthTracker"] = "tracker", ["RynthLua"] = "lua", + ["RynthSort"] = "sort", ["RynthChat"] = "chat", ["RynthVision"] = "vision", ["RynthInventory"] = "inv", + ["RynthNav"] = "nav", ["RynthNet"] = "net", ["RynthDefective"] = "defective", ["RynthCore"] = "core", + }; + + private static string List(IEnumerable items) => string.Join(", ", items); + + // ── The files ──────────────────────────────────────────────────────── + + private static void EveryFileEmbeddedAndParses() + { + string[] onDisk = Directory.GetFiles(FeaturesDir, "*.json").Select(Path.GetFileName).OrderBy(n => n, StringComparer.Ordinal).ToArray()!; + List embedded = FeatureCatalog.ResourceNames().Select(n => n.Substring(FeatureCatalog.ResourcePrefix.Length)).ToList(); + Check.True(onDisk.Length > 0, "Docs/features has catalog files"); + Check.True(onDisk.SequenceEqual(embedded, StringComparer.OrdinalIgnoreCase), + $"every file is embedded (the csproj's wildcard): on disk {List(onDisk)}; embedded {List(embedded)}"); + Check.True(onDisk.Contains("rynthai.json"), "rynthai.json is there"); + + var log = new List(); + FeatureCatalog c = FeatureCatalog.LoadEmbedded(log.Add); + Check.Eq(log.Count, 0, "no file skipped and no entry dropped: " + string.Join(" | ", log)); + foreach (FeatureFileRead f in c.Files) + { + Check.True(f.File != null, f.Resource + " parses: " + f.Error); + Check.True(f.File == null || f.File.Area.Trim().Length > 0, f.Resource + " has an area"); + Check.True(f.File == null || f.File.Features.Count > 0, f.Resource + " has features"); + } + // The files on disk are the embedded ones byte for byte (a stale build would test old content). + foreach (string name in onDisk) + { + using Stream s = File.OpenRead(Path.Combine(FeaturesDir, name)); + FeatureFileRead disk = FeatureCatalog.Parse(name, s); + FeatureFileRead? emb = c.Files.FirstOrDefault(f => f.Resource.EndsWith("." + name, StringComparison.OrdinalIgnoreCase) + || f.Resource == FeatureCatalog.ResourcePrefix + name); + Check.True(emb?.File != null && disk.File != null && emb.File.Features.Count == disk.File.Features.Count, + name + ": the embedded copy matches the file (rebuild RynthAi)"); + } + Check.True(c.Entries.Count > 0, "the catalog has entries"); + Check.True(ReferenceEquals(FeatureCatalog.Shared(null), FeatureCatalog.Shared(null)), "read once"); + } + + private static void EntriesValid() + { + FeatureCatalog c = Catalog(); + var settingNames = new HashSet(SettingsMembers().Select(m => m.Name), StringComparer.Ordinal); + var ids = new Dictionary(StringComparer.OrdinalIgnoreCase); + var idRule = new Regex("^([a-z]+)\\.[a-z0-9]+(-[a-z0-9]+)*$"); + var problems = new List(); + foreach (FeatureFileRead f in c.Files) + { + if (f.File == null) continue; + string file = f.Resource.Substring(FeatureCatalog.ResourcePrefix.Length); + foreach (FeatureEntry e in f.File.Features) + { + string at = $"{file} {(e.Id.Length > 0 ? e.Id : "'" + e.Name + "'")}"; + if (e.Name.Trim().Length == 0) problems.Add(at + ": no name"); + if (!Prefixes.TryGetValue(e.Plugin, out string? prefix)) problems.Add($"{at}: plugin '{e.Plugin}' isn't one of {List(Prefixes.Keys)}"); + Match m = idRule.Match(e.Id); + if (!m.Success) problems.Add($"{at}: id isn't ."); + else if (prefix != null && m.Groups[1].Value != prefix) problems.Add($"{at}: id prefix should be '{prefix}.' for {e.Plugin}"); + if (ids.TryGetValue(e.Id, out string? other)) problems.Add($"{at}: id also in {other}"); + else ids[e.Id] = file; + if (e.Group.Trim().Length == 0) problems.Add(at + ": no group"); + if (e.Summary.Trim().Length == 0) problems.Add(at + ": no summary"); + if (e.Summary.Length > 200) problems.Add($"{at}: summary is {e.Summary.Length} characters (200 at most)"); + // A feature with no button says so: where ["Chat command (no button)"] (allowed; it counts as a where). + if (e.Where.Count == 0) problems.Add(at + ": no where (a command-only feature says \"" + CommandOnlyWhere + "\")"); + foreach (string w in e.Where) + if (w.Trim().Length == 0) problems.Add(at + ": an empty where"); + if (e.Command.Length > 0 && !e.Command.StartsWith('/')) problems.Add($"{at}: command '{e.Command}' doesn't start with '/'"); + if (e.Open.Length > 0 && !e.Open.StartsWith('/')) problems.Add($"{at}: open '{e.Open}' doesn't start with '/'"); + if (e.Settings.Count > 0 && e.Plugin != "RynthAi") problems.Add($"{at}: settings are for RynthAi entries only"); + foreach (string s in e.Settings) + if (e.Plugin == "RynthAi" && !settingNames.Contains(s)) problems.Add($"{at}: setting '{s}' isn't a LegacyUiSettings field"); + if (Regex.IsMatch(e.Summary + " " + string.Join(" ", e.Where) + " " + e.Name, "\\bTom\\b")) + problems.Add(at + ": a person's name in player text"); + } + } + Check.True(problems.Count == 0, problems.Count + " problem(s):\n " + string.Join("\n ", problems)); + } + + /// + /// Commands that start, stop or switch something, never only open a window: an entry's open must + /// not be one (the window's Open button runs it). "/ra hunt" alone starts or stops the hunt; its + /// window is "/ra hunt panel". + /// + private static readonly string[] NotOpenCommands = + { + "/ra hunt", "/ra hunt start", "/ra hunt stop", "/ra start", "/ra stop", "/ra pause", "/ra resume", "/ra panic", + "/ra forcebuff", "/ra cancelforcebuff", "/ra clearbusy", "/ra quit", "/ra exit", "/ra fightselected", + "/ra targetlock", "/ra dunnav-patrol", "/ra navprio", "/ra lootprio", "/ra navlootprio", "/ra lootthis", + "/ra heal", "/ra stam", "/ra mana", "/ra recharge", "/ra follow", "/ra dfheight on", "/ra dfheight off", + }; + + private static void OpenOnlyOpens() + { + var bad = new List(); + foreach (FeatureEntry e in Catalog().Entries) + { + if (e.Open.Length == 0) continue; + string open = Regex.Replace(e.Open.Trim().ToLowerInvariant(), "\\s+", " "); + if (NotOpenCommands.Contains(open)) bad.Add($"{e.Id}: open '{e.Open}' does more than open a window"); + if (open.EndsWith(" on") || open.EndsWith(" off") || open.EndsWith(" toggle") || open.EndsWith(" start") || open.EndsWith(" stop")) + bad.Add($"{e.Id}: open '{e.Open}' switches something"); + } + Check.True(bad.Count == 0, string.Join("\n ", bad)); + } + + private static void BadFilesSkipped() + { + FeatureFileRead r = Parse("{ \"area\": \"X\", \"features\": [ { \"id\": \"ai.a\", \"name\": \"A\", } ] }"); + Check.True(r.File == null && r.Error.Length > 0, "a trailing comma doesn't parse: " + r.Error); + r = Parse("{ \"area\": \"X\", // a comment\n \"features\": [] }"); + Check.True(r.File == null, "comments don't parse"); + r = Parse("not json"); + Check.True(r.File == null && r.Error.Contains("line"), "the error says where: " + r.Error); + r = Parse("{ \"area\": \"RynthAi\", \"features\": [ { \"id\": \"ai.a\", \"name\": \"A\", \"where\": null, \"keywords\": [\"x\", null] }," + + " { \"id\": \"\", \"name\": \"No id\" }, { \"id\": \"ai.b\" }, null ] }"); + Check.True(r.File != null, "nulls read"); + Check.Eq(r.File?.Features.Count ?? -1, 1, "only the entry with an id and a name is kept"); + Check.Eq(r.Dropped, 3, "three dropped (no id, no name, null)"); + FeatureEntry? a = r.File?.Features.FirstOrDefault(); + Check.True(a != null && a.Where.Count == 0 && a.Keywords.SequenceEqual(new[] { "x" }) && a.Plugin == "RynthAi", + "null lists are empty, null items gone, the plugin from the area"); + Check.True(a != null && a.Command == "" && a.Open == "" && a.Summary == "", "missing strings are empty"); + // Field names in any case, unknown fields ignored (the website may add its own). + r = Parse("{ \"Area\": \"X\", \"Features\": [ { \"ID\": \"ai.c\", \"Name\": \"C\", \"extra\": 1 } ] }"); + Check.True(r.File?.Features.Count == 1 && r.File.Features[0].Id == "ai.c", "any case, unknown fields ignored"); + } + + private static FeatureFileRead Parse(string json) => FeatureCatalog.Parse("test.json", new MemoryStream(Encoding.UTF8.GetBytes(json))); + + // ── Coverage ───────────────────────────────────────────────────────── + + /// /ra verbs a player never types: developer dumps and tests. Each with why. + private static readonly Dictionary IgnoredCommands = new(StringComparer.Ordinal) + { + ["raycast"] = "the raycaster's status, for its developers", + ["lostest"] = "a line-of-sight test for tuning the raycaster", + ["landtest"] = "a terrain heightmap dump", + ["rayland"] = "a landscape raycast test", + ["cache"] = "an object cache dump", + ["cache2"] = "an object cache id dump", + ["attackable"] = "one flag of the selection, for combat's developers", + ["buildinfo"] = "a nearby geometry dump", + ["navdebug"] = "a nav coordinate dump", + ["navstate"] = "the nav engine's state dump", + ["salvstate"] = "the salvage state machine's dump", + ["mapdump"] = "an object position dump", + ["dumpinv"] = "an inventory dump to the log", + ["combat"] = "the combat manager's state dump", + ["busyinfo"] = "the busy-state counters", + ["pace"] = "the action pacer's counters", + ["swaptest"] = "a weapon swap test run", + ["bufftest"] = "the buff cast registry diagnostic", + ["debug"] = "echoes trace and exception lines to chat, for developers", + ["trace"] = "log categories on and off, for developers", + ["corpseinfo"] = "corpse range and open diagnostics", + ["corpseopen"] = "forces the corpse-open flow, a looting test", + ["lootparse"] = "dumps a loot profile's parsed rules", + ["wielded"] = "a wielded-items dump (Active Gear is the player's view)", + ["discord"] = "only says the Discord relay moved into RynthCore's Chat", + ["cast"] = "casts a spell by id at the selection, a spell-data test tool", + ["scan"] = "a nearby-objects line-of-sight dump", + ["videopatch"] = "passed on to RynthCore's /rc videopatch (rynthcore.json lists it)", + ["video"] = "passed on to RynthCore's /rc videopatch (rynthcore.json lists it)", + }; + + /// Verbs that are another verb by another name (separate case labels): covered when that one is. + private static readonly Dictionary SameAs = new(StringComparer.Ordinal) + { + ["fellowinfo"] = "fellow", // /ra fellow status + ["navaddpt"] = "addnavpt", // VTank's name for it + ["testitem"] = "lootcheck", // VTank's TestItem + ["meleemedium"] = "meleemid", // the same height by its long name + ["propertydump"] = "dumpprops", // VTank's PropertyDump + }; + + /// + /// The verbs of DispatchRaCommand's switch and of the VTank-style switch its default branch calls + /// (TryHandleVTankHotkeyCommand), with "jump" (the default branch's jump* verbs). Case labels with + /// nothing between them are one command's names (aliases): one group. + /// + internal static List> RaVerbGroups() + { + var groups = new List>(); + string dir = Path.Combine(RepoRoot(), "Plugins", "RynthCore.Plugin.RynthAi"); + ReadSwitch(File.ReadAllText(Path.Combine(dir, "RynthAiPlugin.cs")), "private void DispatchRaCommand(", groups); + ReadSwitch(File.ReadAllText(Path.Combine(dir, "RynthAiPlugin.VTankHotkeys.cs")), "private bool TryHandleVTankHotkeyCommand(", groups); + groups.Add(new List { "jump" }); + // A verb listed twice (case "itemhud" when ...: before case "huds": case "itemhud": ...) joins its groups. + var merged = new List>(); + foreach (List g in groups) + { + List? into = merged.FirstOrDefault(m => m.Intersect(g, StringComparer.Ordinal).Any()); + if (into == null) merged.Add(new List(g)); + else foreach (string v in g) if (!into.Contains(v)) into.Add(v); + } + return merged; + } + + private static void ReadSwitch(string src, string method, List> groups) + { + int a = src.IndexOf(method, StringComparison.Ordinal); + Check.True(a >= 0, method + " found"); + if (a < 0) return; + int b = src.IndexOf("\n }", a, StringComparison.Ordinal); + string body = src.Substring(a, (b > a ? b : src.Length) - a); + List? group = null; + int lastEnd = -1; + foreach (Match m in Regex.Matches(body, "case\\s+\"([a-z0-9_-]+)\"(?:\\s+when[^:]*)?\\s*:")) + { + string between = lastEnd >= 0 ? body.Substring(lastEnd, m.Index - lastEnd) : "x"; + between = Regex.Replace(between, "//[^\\n]*", ""); + if (group != null && between.Trim().Length == 0) group.Add(m.Groups[1].Value); + else groups.Add(group = new List { m.Groups[1].Value }); + lastEnd = m.Index + m.Length; + } + } + + /// + /// "/ra verb" in a RynthAi entry's command or open. The verb may be written as /ra help writes its + /// families: "/ra give[a][p|xp|pp|r]" or "/ra use[i|l][p]", each bracket an optional part with its + /// choices (so that one names give, givea, givep, giveap, ...). + /// + private static bool Mentions(IEnumerable entries, string verb) + { + foreach (FeatureEntry e in entries) + foreach (string text in new[] { e.Command, e.Open }) + foreach (Match m in Regex.Matches(text, "/ra\\s+([a-z0-9_\\-\\[\\]|]+)", RegexOptions.IgnoreCase)) + if (Expand(m.Groups[1].Value.ToLowerInvariant()).Contains(verb)) return true; + return false; + } + + /// "give[a][p|xp]" is give, givea, givep, givexp, giveap, giveaxp. A token without brackets is itself. + internal static HashSet Expand(string token) + { + var results = new HashSet(StringComparer.Ordinal) { string.Empty }; + int i = 0; + while (i < token.Length) + { + if (token[i] == '[') + { + int close = token.IndexOf(']', i); + if (close < 0) break; + string[] choices = token.Substring(i + 1, close - i - 1).Split('|'); + var next = new HashSet(results, StringComparer.Ordinal); // the part left out + foreach (string r in results) foreach (string c in choices) next.Add(r + c); + results = next; + i = close + 1; + } + else if (token[i] == '|' || token[i] == ']') break; // "on|off" after the verb: not part of it + else + { + int end = i; + while (end < token.Length && token[end] != '[' && token[end] != '|' && token[end] != ']') end++; + string part = token.Substring(i, end - i); + results = new HashSet(results.Select(r => r + part), StringComparer.Ordinal); + i = end; + } + } + results.Remove(string.Empty); + return results; + } + + private static void CoverageCommands() + { + HashSet family = Expand("give[a][p|xp]"); + Check.True(family.SetEquals(new[] { "give", "givea", "givep", "givexp", "giveap", "giveaxp" }), "a bracketed family: " + List(family)); + Check.True(Expand("hunt").SetEquals(new[] { "hunt" }), "a plain verb is itself"); + List ai = RynthAiEntries(); + List> groups = RaVerbGroups(); + Check.True(groups.Count > 50, $"the dispatcher's verbs were read ({groups.Count} commands)"); + var missing = new List(); + foreach (List g in groups) + { + if (g.Any(v => IgnoredCommands.ContainsKey(v))) continue; + if (g.Any(v => Mentions(ai, v) || (SameAs.TryGetValue(v, out string? same) && Mentions(ai, same)))) continue; + missing.Add("/ra " + string.Join(" | /ra ", g)); + } + foreach (string v in IgnoredCommands.Keys) + Check.True(groups.Any(g => g.Contains(v)), $"ignored /ra {v} is still a command (else take it off the ignore list)"); + Check.True(missing.Count == 0, + $"{missing.Count} /ra command(s) in no RynthAi entry's command or open ({AddIt}, or to the test's ignore list if a player never uses it):\n " + + string.Join("\n ", missing)); + } + + /// Every window title and section view label RynthAi declares (the manifest with every window on). + internal static List ManifestSurfaces() + { + string json = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, + dashboard: true, monsterStats: true, timedCommands: true, activeGear: true, featureSearch: true); + SectionManifest m = SectionManifestParser.Parse("RynthAi", json, out string error); + Check.Eq(error, string.Empty, "the manifest parses"); + var names = new List(); + foreach (SectionWindowDecl w in m.Windows) names.Add(w.Title); + foreach (SectionContribution c in m.Contributions) names.Add(c.Label); + foreach (SectionDecl s in m.Sections) names.Add(s.Label); + return names.Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + } + + private static void CoverageWindows() + { + List ai = RynthAiEntries(); + List surfaces = ManifestSurfaces(); + Check.True(surfaces.Count >= 8, "the manifest's windows and views: " + List(surfaces)); + var missing = surfaces.Where(s => !ai.Any(e => + e.Name.Contains(s, StringComparison.OrdinalIgnoreCase) + || e.Where.Any(w => w.Contains(s, StringComparison.OrdinalIgnoreCase)))) + .ToList(); + Check.True(missing.Count == 0, + $"{missing.Count} RynthAi window(s) or view(s) in no RynthAi entry's name or where ({AddIt}):\n " + string.Join("\n ", missing)); + } + + /// Persisted LegacyUiSettings fields a player never sets: internal state. Each with why. + private static readonly Dictionary IgnoredSettings = new(StringComparer.Ordinal) + { + ["CurrentNavPath"] = "the loaded route's path (the Loaded files picker sets it)", + ["CurrentLootPath"] = "the loaded loot profile's path (the Loaded files picker sets it)", + ["CurrentMetaPath"] = "the loaded meta's path (the Loaded files picker sets it)", + ["CurrentBuffProfilePath"] = "the buff profile in use's path (the Loaded files picker sets it)", + ["MacroSettingsIdx"] = "a picker's position", + ["NavProfileIdx"] = "a picker's position", + ["LootProfileIdx"] = "a picker's position", + ["MetaProfileIdx"] = "a picker's position", + ["BuffProfileIdx"] = "a picker's position", + ["SelectedProfile"] = "the settings profile's name (the Profile picker sets it)", + ["MetaUnsaved"] = "a failed meta save's marker", + ["ProfileItemsChecked"] = "the once-per-profile pack check's marker", + ["ActiveNavIndex"] = "how far along the route is", + ["EmbeddedNavs"] = "the loaded meta's own routes", + ["ShowSpellsWindow"] = "whether a window is open", + ["ShowAdvancedWindow"] = "whether a window is open", + ["SelectedAdvancedTab"] = "a window's last tab", + ["DashShowWeapons"] = "whether a window is open", + ["DashShowLua"] = "whether a window is open", + ["DashShowNavigation"] = "whether a window is open", + ["DashShowMacroRules"] = "whether a window is open", + ["DashShowMonsters"] = "whether a window is open", + ["DashShowDungeonMap"] = "whether a window is open", + ["DashboardMinimized"] = "the dashboard's minimize button's state", + ["WindowPosX"] = "a window's place", ["WindowPosY"] = "a window's place", + ["WindowSizeX"] = "a window's size", ["WindowSizeY"] = "a window's size", + ["RadarPosX"] = "a window's place", ["RadarPosY"] = "a window's place", + ["RadarSizeX"] = "a window's size", ["RadarSizeY"] = "a window's size", + ["FeatureServerNames"] = "legacy: read once by RynthILT, no UI", + ["ForceServerFeatures"] = "legacy: read once by RynthILT, no UI", + ["HandlerRingEvade"] = "obsolete (RynthILT's now), kept so old profiles load", + ["EnableVaultedDungeons"] = "obsolete (RynthILT's now), kept so old profiles load", + ["T11ItemAugsOverride"] = "obsolete (RynthILT's now), kept so old profiles load", + ["LootInterItemDelayMs"] = "not read by the looting, kept so old profiles load", + ["LootClosingDelayMs"] = "not read by the looting, kept so old profiles load", + ["LootOnlyRareCorpses"] = "not read by the looting, kept so old profiles load", + ["LootJumpHeight"] = "kept for old profiles and metas (jump-loot's height is fixed)", + ["ShowEditor"] = "not read by RynthAi (copied with the profile only)", + ["AdvancedOptions"] = "not read by RynthAi (copied with the profile only)", + ["DashboardVisible"] = "not read by RynthAi (copied with the profile only)", + ["HealOthersAt"] = "saved but not acted on yet (RynthCore leaves its row out until it is)", + ["RestamOthersAt"] = "saved but not acted on yet (RynthCore leaves its row out until it is)", + ["InfuseOthersAt"] = "saved but not acted on yet (RynthCore leaves its row out until it is)", + ["MapShowDoors"] = "the old plugin map's; RynthCore's Dungeon Map keeps its own settings", + ["MapShowCreatures"] = "the old plugin map's; RynthCore's Dungeon Map keeps its own settings", + ["MapShowToolbar"] = "the old plugin map's; RynthCore's Dungeon Map keeps its own settings", + ["MapBgOpacity"] = "the old plugin map's; RynthCore's Dungeon Map keeps its own settings", + ["MapRotateWithPlayer"] = "the old plugin map's; RynthCore's Dungeon Map keeps its own settings", + ["ShowRynthRadar"] = "RynthAi's own radar window is gone, kept so profiles load", + ["RadarRotateWithPlayer"] = "RynthAi's own radar window is gone, kept so profiles load", + ["RadarOpacity"] = "RynthAi's own radar window is gone, kept so profiles load", + ["RadarZoom"] = "RynthAi's own radar window is gone, kept so profiles load", + ["RadarShowMonsters"] = "RynthAi's own radar window is gone, kept so profiles load", + ["RadarShowNpcs"] = "RynthAi's own radar window is gone, kept so profiles load", + ["RadarShowPortals"] = "RynthAi's own radar window is gone, kept so profiles load", + ["RadarShowDoors"] = "RynthAi's own radar window is gone, kept so profiles load", + ["RadarCircular"] = "RynthAi's own radar window is gone, kept so profiles load", + ["RadarClickThrough"] = "RynthAi's own radar window is gone, kept so profiles load", + ["ShowRadarWalls"] = "RynthAi's own radar window is gone, kept so profiles load", + ["RadarWallWorldRange"] = "RynthAi's own radar window is gone, kept so profiles load", + ["RadarWallPaintRadius"] = "RynthAi's own radar window is gone, kept so profiles load", + ["ShowRynthChat"] = "RynthAi's own chat window is gone (RynthChat's now), kept so profiles load", + ["ChatOpacity"] = "RynthAi's own chat window is gone (RynthChat's now), kept so profiles load", + ["ChatMaxLines"] = "RynthAi's own chat window is gone (RynthChat's now), kept so profiles load", + ["ChatShowTimestamps"] = "RynthAi's own chat window is gone (RynthChat's now), kept so profiles load", + ["ChatClickThrough"] = "RynthAi's own chat window is gone (RynthChat's now), kept so profiles load", + ["AmmoRules"] = "an old list with no editor (its window is gone), kept so profiles load", + ["BuffRules"] = "an old list with no editor, kept so profiles load", + // NO WAY IN (found 2026-11-13): these were only in RynthAi's own Advanced Settings window, which + // isn't drawn since 2026-09-30, and RynthCore's Settings panel has no row for them. Give each a + // Settings row, then catalogue it and take it off this list. + ["HpFailsafeRecall"] = "NO WAY IN YET: needs a Settings row", + ["MonsterNameBlacklist"] = "NO WAY IN YET: needs a Settings row (Never Attack by name)", + ["AllowMetaKeystrokes"] = "NO WAY IN YET: needs a Settings row", + ["StuckCastBreakMs"] = "NO WAY IN YET: needs a Settings row", + ["RecoveryRetryMs"] = "NO WAY IN YET: needs a Settings row", + }; + + /// LegacyUiSettings' public instance fields and properties. + private static List SettingsMembers() => + typeof(LegacyUiSettings).GetFields(BindingFlags.Instance | BindingFlags.Public).Cast() + .Concat(typeof(LegacyUiSettings).GetProperties(BindingFlags.Instance | BindingFlags.Public)) + .ToList(); + + private static void CoverageSettings() + { + List ai = RynthAiEntries(); + var named = new HashSet(ai.SelectMany(e => e.Settings), StringComparer.Ordinal); + List members = SettingsMembers(); + Check.True(members.Count > 300, $"LegacyUiSettings' fields were read ({members.Count})"); + // [JsonIgnore] members are never saved: runtime state (the macro running, the meta state), not settings. + var missing = members + .Where(m => m.GetCustomAttribute() == null) + .Select(m => m.Name) + .Where(n => !named.Contains(n) && !IgnoredSettings.ContainsKey(n)) + .ToList(); + var members2 = new HashSet(members.Select(m => m.Name), StringComparer.Ordinal); + foreach (string n in IgnoredSettings.Keys) + Check.True(members2.Contains(n), $"ignored setting {n} is still a LegacyUiSettings field (else take it off the ignore list)"); + Check.True(missing.Count == 0, + $"{missing.Count} LegacyUiSettings field(s) in no RynthAi entry's settings ({AddIt}, or to the test's ignore list if it is internal state):\n " + + string.Join("\n ", missing)); + } + + // ── The window and /ra find ────────────────────────────────────────── + + private static void Manifest() + { + string json = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, featureSearch: true); + SectionManifest m = SectionManifestParser.Parse("RynthAi", json, out string error); + Check.Eq(error, string.Empty, "no parse error"); + Check.Eq(m.Windows.Length, 1, "the one window"); + SectionWindowDecl w = m.Windows.Single(); + Check.Eq(w.Id, "featuresearch", "id"); + Check.Eq(w.Title, RynthAiPlugin.FeatureSearchTitle, "title (its panel key)"); + Check.Eq(w.Title, "Find a Feature", "the title players see"); + Check.Eq(w.Surface, "window:featuresearch", "the surface PluginExports.RenderEmbed draws"); + Check.False(w.Bar, "no bar button (the bar is full)"); + Check.False(w.TakeOver || w.Frameless, "the engine's frame"); + Check.True(w.Width >= w.MinWidth && w.Height >= w.MinHeight, "sizes"); + Check.True(w.Icon.Length > 0, "an icon (the magnifier)"); + + string all = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, dashboard: true, monsterStats: true, activeGear: true, featureSearch: true); + SectionManifest m4 = SectionManifestParser.Parse("RynthAi", all, out error); + Check.True(error.Length == 0 && m4.Windows.Length == 4, "with the other three"); + string none = SectionsManifest.Build(SectionsManifest.Views(), SectionsManifest.OwnSections, dashboard: true, monsterStats: true, activeGear: true); + Check.False(none.Contains("featuresearch"), "off unless asked"); + } + + private static readonly List<(string Key, int Mode)> PanelCalls = new(); + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static uint FakeUiColor(int token) => 0xFFFFFFFF; + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static IntPtr FakeUiFont(int font) => IntPtr.Zero; + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static unsafe int FakeSetPanelOpen(byte* key, int mode) + { + PanelCalls.Add((Marshal.PtrToStringUTF8((IntPtr)key) ?? "", mode)); + return mode == 0 ? 0 : 1; + } + + private static unsafe void PluginWindows(ref RynthCoreApiNative api) + { + api.Version = Math.Max(api.Version, 89u); + api.GetUiColorFn = (IntPtr)(delegate* unmanaged[Cdecl])&FakeUiColor; + api.GetUiFontFn = (IntPtr)(delegate* unmanaged[Cdecl])&FakeUiFont; + api.SetPanelOpenFn = (IntPtr)(delegate* unmanaged[Cdecl])&FakeSetPanelOpen; + } + + private sealed class Rig + { + public readonly RynthAiPlugin P = new(); + + public Rig(bool windows) + { + FakeHost.Reset(); + PanelCalls.Clear(); + if (windows) FakeHost.ConfigureApi = PluginWindows; + FakeHost.Create(playerId: 0x50000F41); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + Set("_playerId", 0x50000F41u); + Set("_initialized", true); + Set("_loginComplete", true); + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + + public List Typed(string line) + { + int before = FakeHost.Chat.Count; + int eat = 0; + P.OnChatBarEnter(line, ref eat); + return FakeHost.Chat.Skip(before).ToList(); + } + } + + private static string Show(List lines) => string.Join(" | ", lines); + + private static void FindCommand() + { + var rig = new Rig(windows: true); + IReadOnlyList all = rig.P.FeatureList.Entries; + int death = FeatureSearch.Search(all, "death").Count; + Check.True(death > 0, "the catalog has a death feature"); + + List lines = rig.Typed("/ra find death"); + Check.Eq(lines.Count, 1, "one line: " + Show(lines)); + string count = FeatureSearch.CountLine(death, "death"); + Check.True(lines.Count == 1 && lines[0].Contains(count) && lines[0].Contains("Find a Feature open"), "the count and the window: " + Show(lines)); + Check.True(PanelCalls.Count > 0 && PanelCalls[^1] == (RynthAiPlugin.FeatureSearchTitle, (int)RynthPanelOpen.Open), "opened by its panel key"); + Check.Eq(rig.P.FeatureQueryPendingForTests, "death", "the words go to the window's box"); + + lines = rig.Typed("/ra find"); + Check.True(lines.Count == 1 && lines[0].Contains(FeatureSearch.CountLine(all.Count, "")) && lines[0].Contains("browse"), + "no words: how many to browse: " + Show(lines)); + Check.Eq(rig.P.FeatureQueryPendingForTests, "", "the box cleared"); + + lines = rig.Typed("/ra find qqqzzzxxy"); + Check.True(lines.Count == 1 && lines[0].Contains("No feature matches 'qqqzzzxxy'") && lines[0].Contains(RynthAiPlugin.FeatureSearchUsage), + "nothing matches: says so, and the usage: " + Show(lines)); + + lines = rig.Typed("/ra find ???!!"); + Check.True(lines.Count == 1 && lines[0].Contains("no letters or numbers") && lines[0].Contains(RynthAiPlugin.FeatureSearchUsage), + "punctuation only: why, and the usage: " + Show(lines)); + + lines = rig.Typed("/ra find " + new string('a', RynthAiPlugin.FeatureQueryMax + 1)); + Check.True(lines.Count == 1 && lines[0].Contains("at most") && lines[0].Contains(RynthAiPlugin.FeatureSearchUsage), "too long: " + Show(lines)); + + lines = rig.Typed("/ra find ?"); + Check.True(lines.Count == 2 && lines.All(l => l.Contains("/ra find")), "? says the usage: " + Show(lines)); + + lines = rig.Typed("/ra help"); + Check.True(lines.Any(l => l.Contains("/ra find")), "/ra help lists it"); + } + + private static void FindCommandNoWindows() + { + var rig = new Rig(windows: false); + IReadOnlyList all = rig.P.FeatureList.Entries; + List hits = FeatureSearch.Search(all, "hunt"); + Check.True(hits.Count > 0, "the catalog has hunting features"); + List lines = rig.Typed("/ra find hunt"); + int shown = Math.Min(hits.Count, RynthAiPlugin.FeatureChatMatches); + Check.Eq(lines.Count, 1 + shown, "the count, then the best few: " + Show(lines)); + Check.True(lines.Count > 0 && lines[0].Contains(FeatureSearch.CountLine(hits.Count, "hunt")) && !lines[0].Contains("open"), "no window to open: " + Show(lines)); + Check.True(lines.Count > 1 && lines[1].Contains(hits[0].Entry.Name), "the best match first: " + Show(lines)); + Check.Eq(PanelCalls.Count, 0, "no panel asked for"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/FeatureSearchTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/FeatureSearchTests.cs new file mode 100644 index 0000000..c23ff61 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/FeatureSearchTests.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthAi.Features; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The Find a Feature search (Features/FeatureSearch.cs) on a small made-up catalog: every word must +// match somewhere, case and light stemming don't matter, the start of a word counts, the name ranks +// over the keywords over the summary and where, and no words lists everything by group. +internal static class FeatureSearchTests +{ + public static void Register(Runner r) + { + r.Add("feature search: every word must match (AND), in any order and case", AndOfWords); + r.Add("feature search: plural s, -ing and -ed are stemmed", Stemming); + r.Add("feature search: the start of a word matches (vend finds Vendors)", Prefix); + r.Add("feature search: name over keywords over summary and where", Ranking); + r.Add("feature search: no words lists every feature by group", EmptyQuery); + r.Add("feature search: the count line", CountLine); + } + + private static FeatureEntry E(string id, string name, string group, string summary = "", string[]? where = null, + string command = "", string open = "", string[]? keywords = null, string plugin = "RynthAi") => new() + { + Id = id, Name = name, Plugin = plugin, Group = group, Summary = summary, + Where = (where ?? new[] { "RynthAi window" }).ToList(), Command = command, Open = open, + Keywords = (keywords ?? Array.Empty()).ToList(), + }; + + private static readonly List Catalog = new() + { + E("ai.keep-hunting-after-death", "Keep Hunting After Death", "Hunting", + "After a death the Outdoor Hunt starts again once you're back up.", + new[] { "Outdoor Hunt window > Keep Hunting After Death" }, "/ra hunt death [on|off]", "/ra hunt panel", + new[] { "die", "respawn", "lifestone" }), + E("ai.outdoor-hunt", "Outdoor Hunt", "Hunting", "Walks from monster to monster outdoors.", + new[] { "RynthAi window > Hunt" }, "/ra hunt [start|stop]", "/ra hunt panel", new[] { "farm", "grind" }), + E("ai.recall-on-death", "Recall On Death", "Death", "Recalls after you respawn, then runs back to your corpse.", + new[] { "Settings > Misc > Recall On Death" }, keywords: new[] { "portal" }), + E("ai.auto-vendor", "Auto Vendor", "Vendors", "Sells and buys when a vendor opens.", + new[] { "Settings > Vendoring > Auto Vendor" }, "/ub autovendor", keywords: new[] { "merchant", "sell" }), + E("ai.looting", "Looting", "Looting", "Opens corpses and takes what the loot profile keeps.", + new[] { "RynthAi window > Looting" }, keywords: new[] { "pickup", "corpse" }), + E("ai.buff-items", "Buff Items", "Buffs", "Uses gems and rations that buff you.", + new[] { "Spells window > Buff Items" }, "/ra buffitems list", keywords: new[] { "gem" }), + // "death" only in where and summary (never in the name or keywords): ranks under the name hits. + E("ai.death-window", "Corpse Finder", "Death", "Finds your corpse after a death.", + new[] { "Death window > Corpse Finder" }), + // "death" only in a keyword. + E("ai.patrol", "Dungeon Patrol", "Navigation", "Walks every room of a dungeon.", + keywords: new[] { "death", "sweep" }), + E("oracle.quests", "Quests", "Quests", "Your quest timers.", new[] { "RynthCore bar > Oracle > Quests" }, + "/ro quests", plugin: "RynthOracle"), + }; + + private static List Ids(string query) => FeatureSearch.Search(Catalog, query).Select(h => h.Entry.Id).ToList(); + + private static void AndOfWords() + { + List both = Ids("death hunt"); + Check.True(both.Contains("ai.keep-hunting-after-death"), "both words: " + string.Join(",", both)); + Check.False(both.Contains("ai.recall-on-death"), "death but no hunt: out"); + Check.False(both.Contains("ai.outdoor-hunt"), "hunt but no death: out"); + Check.Eq(string.Join(",", Ids("HUNT Death")), string.Join(",", both), "order and case don't matter"); + Check.Eq(Ids("death zzzz").Count, 0, "a word that matches nothing: no results"); + Check.True(Ids("oracle quests").SequenceEqual(new[] { "oracle.quests" }), "the plugin's name counts as a field"); + Check.True(Ids("/ra buffitems").Contains("ai.buff-items"), "a command's words, slash and all"); + Check.True(Ids("vendoring").Contains("ai.auto-vendor"), "a where path's words count"); + } + + private static void Stemming() + { + Check.Eq(FeatureSearch.Stem("vendors"), "vendor", "plural s"); + Check.Eq(FeatureSearch.Stem("looting"), "loot", "-ing"); + Check.Eq(FeatureSearch.Stem("looted"), "loot", "-ed"); + Check.Eq(FeatureSearch.Stem("stopped"), "stop", "-ed with a doubled letter"); + Check.Eq(FeatureSearch.Stem("buffs"), "buff", "buffs"); + Check.Eq(FeatureSearch.Stem("pass"), "pass", "ss isn't a plural"); + Check.Eq(FeatureSearch.Stem("status"), "status", "-us isn't a plural"); + Check.True(Ids("deaths").Contains("ai.recall-on-death"), "deaths finds Death"); + Check.True(Ids("hunting").Contains("ai.outdoor-hunt"), "hunting finds Hunt"); + Check.True(Ids("looted corpses").Contains("ai.looting"), "looted corpses finds Looting (corpse)"); + Check.True(Ids("gems").Contains("ai.buff-items"), "gems finds the keyword gem"); + } + + private static void Prefix() + { + Check.True(Ids("vend").Contains("ai.auto-vendor"), "vend finds Vendors / Vendor"); + Check.True(Ids("merch").Contains("ai.auto-vendor"), "the start of a keyword"); + Check.True(Ids("resp").Contains("ai.keep-hunting-after-death"), "resp finds respawn"); + Check.False(Ids("endor").Contains("ai.auto-vendor"), "the middle of a word doesn't count"); + Check.Eq(FeatureSearch.WordMatch("vend", "vendors"), 1, "a start is a partial match"); + Check.Eq(FeatureSearch.WordMatch("vendors", "vendor"), 2, "the same stem is a whole match"); + } + + private static void Ranking() + { + List hits = FeatureSearch.Search(Catalog, "death"); + List ids = hits.Select(h => h.Entry.Id).ToList(); + int name1 = ids.IndexOf("ai.keep-hunting-after-death"), name2 = ids.IndexOf("ai.recall-on-death"); + int keyword = ids.IndexOf("ai.patrol"), whereOnly = ids.IndexOf("ai.death-window"); + Check.True(name1 >= 0 && name2 >= 0 && keyword >= 0 && whereOnly >= 0, "all four found: " + string.Join(",", ids)); + Check.True(Math.Max(name1, name2) < keyword, "the name hits before the keyword hit: " + string.Join(",", ids)); + Check.True(keyword < whereOnly, "the keyword hit before the summary / where hit: " + string.Join(",", ids)); + Check.True(hits.Zip(hits.Skip(1)).All(p => p.First.Score >= p.Second.Score), "best first"); + // Equal scores: by name. + int a = ids.IndexOf("ai.keep-hunting-after-death"), b = ids.IndexOf("ai.recall-on-death"); + Check.True(a < b, "a tie goes by name (Keep before Recall)"); + Check.True(FeatureSearch.Score(Catalog[1], new[] { "hunt" }) > FeatureSearch.Score(Catalog[1], new[] { "hun" }), + "a whole word scores over its start"); + } + + private static void EmptyQuery() + { + foreach (string q in new[] { "", " ", "--- ..." }) + { + List all = FeatureSearch.Search(Catalog, q); + Check.Eq(all.Count, Catalog.Count, $"'{q}': every feature"); + } + List groups = FeatureSearch.Grouped(Catalog); + Check.Eq(groups.Sum(g => g.Entries.Count), Catalog.Count, "every feature in a group"); + Check.Eq(groups.Count, Catalog.Select(e => e.Group).Distinct().Count(), "one group per group name"); + var order = groups.Select(g => g.Name).ToList(); + Check.True(order.IndexOf("Buffs") < order.IndexOf("Hunting") && order.IndexOf("Hunting") < order.IndexOf("Looting"), + "the schema's group order: " + string.Join(",", order)); + FeatureGroup hunting = groups.Single(g => g.Name == "Hunting"); + Check.True(hunting.Entries.Select(e => e.Name).SequenceEqual(new[] { "Keep Hunting After Death", "Outdoor Hunt" }), "by name inside a group"); + List flat = FeatureSearch.Search(Catalog, "").Select(h => h.Entry.Id).ToList(); + Check.True(flat.SequenceEqual(groups.SelectMany(g => g.Entries).Select(e => e.Id)), "no words: the groups' order"); + Check.Eq(FeatureSearch.Words("/ra hunt, death!").Count, 3, "words without punctuation"); + } + + private static void CountLine() + { + Check.Eq(FeatureSearch.CountLine(12, "death"), "12 features match 'death'", "many"); + Check.Eq(FeatureSearch.CountLine(1, " death "), "1 feature matches 'death'", "one"); + Check.Eq(FeatureSearch.CountLine(0, "xyz"), "No feature matches 'xyz'", "none"); + Check.Eq(FeatureSearch.CountLine(40, ""), "40 features", "no words"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HuntOnLoginTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HuntOnLoginTests.cs index 2c47264..0d2fe54 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/HuntOnLoginTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/HuntOnLoginTests.cs @@ -85,7 +85,7 @@ internal static class HuntOnLoginTests var start = typeof(RynthAiPlugin).GetMethod("StartHunt", Any)!; FakeHost.HasPose = false; FakeHost.Chat.Clear(); - start.Invoke(p, new object[] { true }); + start.Invoke(p, new object[] { true, false }); Check.False(p.HuntActive, "no position: not started"); Check.True(All().Contains(RynthAiPlugin.HuntOnLoginRefusedPrefix.Trim()) && All().Contains("no position yet"), "says Hunt On Login and why: " + All()); @@ -93,14 +93,14 @@ internal static class HuntOnLoginTests FakeHost.HasPose = true; FakeHost.PlayerPose = (0xA9B40021u, 100f, 100f, 50f); FakeHost.Chat.Clear(); - start.Invoke(p, new object[] { true }); + start.Invoke(p, new object[] { true, false }); Check.False(p.HuntActive, "no RynthNav: not started"); Check.False(dash.Settings.IsMacroRunning, "and the macro isn't turned on"); Check.True(All().Contains("Hunt On Login") && All().Contains("needs RynthNav"), "says why: " + All()); // The Hunt button's own wording is unchanged. FakeHost.Chat.Clear(); - start.Invoke(p, new object[] { false }); + start.Invoke(p, new object[] { false, false }); Check.True(All().StartsWith("[RynthAi] Outdoor hunt needs RynthNav") && !All().Contains("Hunt On Login"), "the button says it as before: " + All()); } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/KeepHuntingAfterDeathTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/KeepHuntingAfterDeathTests.cs new file mode 100644 index 0000000..44fd7c5 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/KeepHuntingAfterDeathTests.cs @@ -0,0 +1,188 @@ +using System; +using System.Reflection; +using System.Text.Json; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Keep Hunting After Death (2026-11-13): a death pauses the Outdoor Hunt instead of ending it, and it +// starts again once the character is back up; the Dungeon Patrol follows into a dungeon a death sent it to. +internal static class KeepHuntingAfterDeathTests +{ + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("keep hunting (11-13): the restart waits for the death's steps; the box off, the macro off or another route: it stays off", Decide); + r.Add("keep hunting (11-13): the patrol follows into a dungeon a death sent it to only with the box on", PatrolFollow); + r.Add("keep hunting (11-13): a death with the box on pauses the hunt, back up it starts again (and says so); off, it ends as before", PauseAndRestart); + r.Add("keep hunting (11-13): a meta's route loaded after the death, or the macro stopped: not started again, said in chat", Dropped); + r.Add("keep hunting (11-13): /ra hunt death answers, sets it, says why not with the usage", Command); + r.Add("keep hunting (11-13): KeepHuntingAfterDeath is off by default and round-trips (saved, copied)", Setting); + } + + private static void Decide() + { + var S = AfterDeath.HuntStep.Start; + var W = AfterDeath.HuntStep.Wait; + Check.Eq(AfterDeath.DecideHunt(true, true, false, false, false), S, "back up, nothing else to do: start"); + Check.Eq(AfterDeath.DecideHunt(true, true, false, true, false), W, "a recall or the corpse trip running: wait"); + Check.Eq(AfterDeath.DecideHunt(true, true, false, false, true), W, "portal space: wait"); + Check.Eq(AfterDeath.DecideHunt(false, true, false, false, false), AfterDeath.HuntStep.DropOff, "the box turned off: dropped"); + Check.Eq(AfterDeath.DecideHunt(true, false, false, true, false), AfterDeath.HuntStep.DropMacro, "the macro stopped: dropped, even mid-recall"); + Check.Eq(AfterDeath.DecideHunt(true, true, true, true, false), AfterDeath.HuntStep.DropRoute, "another route: dropped, even mid-recall"); + } + + private static void PatrolFollow() + { + const uint patrolLb = 0x5756, other = 0x00830188; + var D = RynthAiPlugin.PatrolFollow.AfterDeath; + var F = RynthAiPlugin.PatrolFollow.Follow; + Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, other, true, false, uint.MaxValue, 30_000, true), D, "box off: as before, not after a death"); + Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, other, true, false, uint.MaxValue, 30_000, true, followAfterDeath: true), F, "box on: follows"); + Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, 0xC4B60002, false, false, uint.MaxValue, 30_000, true, followAfterDeath: true), + RynthAiPlugin.PatrolFollow.None, "box on, landed outdoors: nothing (the patrol waits for its dungeon)"); + Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, other, true, true, uint.MaxValue, 30_000, true, followAfterDeath: true), + RynthAiPlugin.PatrolFollow.None, "box on, mid-portal: wait"); + } + + private sealed class Rig + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyDashboardRenderer Dash; + public LegacyUiSettings S => Dash.Settings; + + public Rig() + { + FakeHost.Reset(); + var host = FakeHost.Create(); + typeof(RynthCore.PluginCore.RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + Dash = new LegacyDashboardRenderer(host); + typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(P, Dash); + FakeHost.HasPose = true; + FakeHost.PlayerPose = (0xA9B40021u, 100f, 100f, 50f); + } + + public object? Get(string f) => typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P); + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + public void Call(string m) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, null); + + /// A hunt running (its route the current one), the macro on. + public void Hunting() + { + S.IsMacroRunning = true; + var hunt = (OutdoorHunt)Get("_hunt")!; + hunt.Start(DateTime.UtcNow, new OutdoorHunt.Vec(100, 100, 50)); + var route = new NavRouteParser { RouteType = NavRouteType.Once, OutdoorHuntWalk = true }; + Set("_huntRoute", route); + S.CurrentNavPath = string.Empty; + S.CurrentRoute = route; + S.EnableNavigation = true; + } + + public bool Pending => (bool)Get("_huntAfterDeath")!; + public string All => string.Join(" | ", FakeHost.Chat); + } + + private static void PauseAndRestart() + { + var g = new Rig(); + g.Hunting(); + g.S.KeepHuntingAfterDeath = true; + FakeHost.Chat.Clear(); + g.Call("PauseHuntForDeath"); + Check.False(g.P.HuntActive, "the hunt is off while dead"); + Check.True(g.Pending, "and waits to start again"); + Check.True(g.All.Contains("starts again once you're back up"), "said in chat: " + g.All); + + g.Set("_deathHolding", true); + g.Call("TickOutdoorHunt"); + Check.True(g.Pending && !g.P.HuntActive, "still dead or settling: waits"); + g.Call("PauseHuntForDeath"); + Check.True(g.Pending, "died again while waiting: still waits"); + + g.Set("_deathHolding", false); + FakeHost.Chat.Clear(); + g.Call("TickOutdoorHunt"); + Check.False(g.Pending, "back up: no longer waiting"); + // No RynthNav on the fake host: the Hunt button's own check refuses, under this box's name. + Check.True(g.All.Contains(RynthAiPlugin.KeepHuntingRefusedPrefix.Trim()) && g.All.Contains("needs RynthNav"), + "it tried to start the hunt again, from here, and says why it couldn't: " + g.All); + + var off = new Rig(); + off.Hunting(); + FakeHost.Chat.Clear(); + off.Call("PauseHuntForDeath"); + Check.False(off.P.HuntActive || off.Pending, "box off: the death ends the hunt, nothing waits"); + Check.True(off.All.Contains("Outdoor hunt off (died)"), "said as before: " + off.All); + } + + private static void Dropped() + { + var g = new Rig(); + g.Hunting(); + g.S.KeepHuntingAfterDeath = true; + g.Call("PauseHuntForDeath"); + g.S.CurrentRoute = new NavRouteParser(); + g.S.CurrentNavPath = ""; + FakeHost.Chat.Clear(); + g.Call("TickOutdoorHunt"); + Check.False(g.Pending || g.P.HuntActive, "a meta's route after the death: the hunt stays off"); + Check.True(g.All.Contains(RynthAiPlugin.KeepHuntingRefusedPrefix.Trim()) && g.All.Contains("the meta's route 'BackToCamp'"), + "and says whose route it is: " + g.All); + + var m = new Rig(); + m.Hunting(); + m.S.KeepHuntingAfterDeath = true; + m.Call("PauseHuntForDeath"); + m.S.IsMacroRunning = false; + FakeHost.Chat.Clear(); + m.Call("TickOutdoorHunt"); + Check.False(m.Pending || m.P.HuntActive, "the macro stopped: the hunt stays off"); + Check.True(m.All.Contains("the macro is off"), "said: " + m.All); + + var stopped = new Rig(); + stopped.Hunting(); + stopped.S.KeepHuntingAfterDeath = true; + stopped.S.IsMacroRunning = false; // Stop Macro On Death stopped it first + stopped.Call("PauseHuntForDeath"); + Check.False(stopped.Pending, "Stop Macro On Death wins: nothing waits"); + } + + private static void Command() + { + var g = new Rig(); + void Ra(string line) + { + FakeHost.Chat.Clear(); + string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(g.P, new object[] { parts[1].ToLowerInvariant(), parts, 0 }); + } + Ra("/ra hunt death"); + Check.True(g.All.Contains("Keep Hunting After Death: off") && g.All.Contains(RynthAiPlugin.KeepHuntingUsage), "no word: off, and the usage: " + g.All); + Ra("/ra hunt death on"); + Check.True(g.S.KeepHuntingAfterDeath && g.All.Contains("Keep Hunting After Death set: on"), "on, said: " + g.All); + Ra("/ra hunt death sometimes"); + Check.True(g.S.KeepHuntingAfterDeath && g.All.Contains("isn't on or off") && g.All.Contains("Usage: " + RynthAiPlugin.KeepHuntingUsage), + "an unknown word changes nothing, says why: " + g.All); + Ra("/ra hunt death off"); + Check.True(!g.S.KeepHuntingAfterDeath && g.All.Contains("set: off"), "off, said: " + g.All); + Ra("/ra hunt nonsense"); + Check.True(g.All.Contains(RynthAiPlugin.KeepHuntingUsage), "the hunt's usage lists it: " + g.All); + } + + private static void Setting() + { + Check.False(new LegacyUiSettings().KeepHuntingAfterDeath, "off by default"); + var ctx = RynthAiJsonContext.Default.LegacyUiSettings; + var saved = JsonSerializer.Deserialize(JsonSerializer.Serialize(new LegacyUiSettings { KeepHuntingAfterDeath = true }, ctx), ctx)!; + Check.True(saved.KeepHuntingAfterDeath, "saved"); + var live = new LegacyUiSettings(); + typeof(LegacyDashboardRenderer).GetMethod("CopySettings", Any)!.Invoke(null, new object[] { saved, live }); + Check.True(live.KeepHuntingAfterDeath, "copied"); + Check.False(JsonSerializer.Deserialize("{\"HuntOnLogin\":true}", ctx)!.KeepHuntingAfterDeath, "a profile from before the setting: off"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs index 822e941..0f5669d 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/TargetingTests.cs @@ -53,6 +53,160 @@ internal static class TargetingTests FakeHost.WeaponCalls = true; FakeHost.CombatModeValue = CombatMode.Missile; Check.Eq(missile.Tick(), 0u, "missile, 3 yd, a wall between: nor do arrows"); + + // 2026-11-13: not through a building's wall (outside, the monster in the building's rooms, or the other way). + var building = new ScanPick(20); + building.Place(A, "Mob A", north: 3); + building.Blocked.Add(A); + FakeHost.Positions[A] = (Lb | 0x01C9, FakeHost.Positions[A].Item2, FakeHost.Positions[A].Item3, FakeHost.Positions[A].Item4); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(building.Tick(), 0u, "melee outside, 3 yd, the monster inside a building behind its wall: not the target"); + + var inside = new ScanPick(20); + inside.Place(A, "Mob A", north: 3); + inside.Blocked.Add(A); + FakeHost.Positions[Player] = (Lb | 0x0105, 96f, 96f, 0f); + FakeHost.PlayerPose = (Lb | 0x0105, 96f, 96f, 0f); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(inside.Tick(), 0u, "melee inside a building, the monster outside its wall: not the target either"); + + var dungeon = new ScanPick(20); + dungeon.Place(A, "Mob A", north: 3); + dungeon.Blocked.Add(A); + FakeHost.Positions[Player] = (Lb | 0x0105, 96f, 96f, 0f); + FakeHost.PlayerPose = (Lb | 0x0105, 96f, 96f, 0f); + FakeHost.Positions[A] = (Lb | 0x0107, FakeHost.Positions[A].Item2, FakeHost.Positions[A].Item3, FakeHost.Positions[A].Item4); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(dungeon.Tick(), A, "two rooms' cells (a dungeon wall): melee still reaches through"); + + var unblocked = new ScanPick(20); + unblocked.Place(A, "Mob A", north: 3); + FakeHost.Positions[A] = (Lb | 0x01C9, FakeHost.Positions[A].Item2, FakeHost.Positions[A].Item3, FakeHost.Positions[A].Item4); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(unblocked.Tick(), A, "in the building's doorway with a clear line: the target as before"); + + Check.True(CombatManager.InsideVersusOutside(0xE74E0023, 0xE74E01C9), "Drakkon's case: outside 0x0023, the sorcerer in 0x01C9"); + Check.False(CombatManager.InsideVersusOutside(0xE74E0023, 0xE74E001B), "both outside"); + } + + // 2026-11-15: Melee through walls is a setting (MeleeThroughWalls, on by default; the meta option meleethroughwalls). + // On is the rule above, the building's wall included; off, a blocked monster is out of sight however close. + private static void MeleeThroughWallsSetting() + { + Check.True(new LegacyUiSettings().MeleeThroughWalls, "on by default"); + var old = System.Text.Json.JsonSerializer.Deserialize("{\"MonsterRange\":7}", RynthAiJsonContext.Default.LegacyUiSettings); + Check.True(old != null && old.MeleeThroughWalls, "a profile saved before the setting loads it as on"); + Check.True(RynthCore.Plugin.RynthAi.Meta.MetaManager.TryMapVtOption("meleethroughwalls", out string ra) && ra == "MeleeThroughWalls", "the meta option meleethroughwalls is the setting"); + Check.True(RynthCore.Plugin.RynthAi.Meta.MetaManager.TryMapVtOption("MeleeThroughWalls", out _), "any case"); + + // On: today's behaviour. + var on = new ScanPick(20); + on.Place(A, "Mob A", north: 3); + on.Blocked.Add(A); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(on.Tick(), A, "on: melee, 3 yd, a wall between: the target"); + + var onBuilding = new ScanPick(20); + onBuilding.Place(A, "Mob A", north: 3); + onBuilding.Blocked.Add(A); + FakeHost.Positions[A] = (Lb | 0x01C9, FakeHost.Positions[A].Item2, FakeHost.Positions[A].Item3, FakeHost.Positions[A].Item4); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(onBuilding.Tick(), 0u, "on: not through a building's wall"); + Check.False(onBuilding.C.HasNearbyMonsters, "on: and not counted as out of sight (the hunt's walk to the door isn't held)"); + + // Off: a blocked monster within 4 m is like one farther off. + var off = new ScanPick(20); + off.S.MeleeThroughWalls = false; + off.Place(A, "Mob A", north: 3); + off.Blocked.Add(A); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(off.Tick(), 0u, "off: melee, 3 yd, a wall between: not the target"); + Check.True(off.C.HasNearbyMonsters, "off: counted as a monster nearby out of sight, like one 6 yd off"); + Check.Eq(off.C.LastScanLosBlocked, 1, "off: the scan counts it as LOS-blocked"); + Check.Eq(off.C.LastScanPossible, 0, "off: and not as a possible target"); + + var offClose = new ScanPick(20); + offClose.S.MeleeThroughWalls = false; + offClose.Place(A, "Mob A", north: 1); + offClose.Blocked.Add(A); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(offClose.Tick(), 0u, "off: 1 yd, a wall between: still not the target"); + + var offBuilding = new ScanPick(20); + offBuilding.S.MeleeThroughWalls = false; + offBuilding.Place(A, "Mob A", north: 3); + offBuilding.Blocked.Add(A); + FakeHost.Positions[A] = (Lb | 0x01C9, FakeHost.Positions[A].Item2, FakeHost.Positions[A].Item3, FakeHost.Positions[A].Item4); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(offBuilding.Tick(), 0u, "off: the monster in a building behind its wall: not the target"); + Check.True(offBuilding.C.HasNearbyMonsters, "off: counted out of sight like any blocked monster"); + + var offDungeon = new ScanPick(20); + offDungeon.S.MeleeThroughWalls = false; + offDungeon.Place(A, "Mob A", north: 3); + offDungeon.Blocked.Add(A); + FakeHost.Positions[Player] = (Lb | 0x0105, 96f, 96f, 0f); + FakeHost.PlayerPose = (Lb | 0x0105, 96f, 96f, 0f); + FakeHost.Positions[A] = (Lb | 0x0107, FakeHost.Positions[A].Item2, FakeHost.Positions[A].Item3, FakeHost.Positions[A].Item4); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(offDungeon.Tick(), 0u, "off: a dungeon wall between two rooms: not the target either"); + + var offClear = new ScanPick(20); + offClear.S.MeleeThroughWalls = false; + offClear.Place(A, "Mob A", north: 3); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(offClear.Tick(), A, "off: a clear line: the target as always"); + + var offOther = new ScanPick(20); + offOther.S.MeleeThroughWalls = false; + offOther.Place(A, "Mob A", north: 2); + offOther.Place(B, "Mob B", north: -5); + offOther.Blocked.Add(A); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(offOther.Tick(), B, "off: the one in sight 5 yd off, not the one behind a wall 2 yd off"); + + var offTurnOn = new ScanPick(20); + offTurnOn.S.MeleeThroughWalls = false; + offTurnOn.Place(A, "Mob A", north: 3); + offTurnOn.Blocked.Add(A); + FakeHost.WeaponCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Check.Eq(offTurnOn.Tick(), 0u, "off: not the target"); + offTurnOn.S.MeleeThroughWalls = true; + Check.Eq(offTurnOn.Tick(), A, "turned on: the next scan takes it"); + + // Profile copy and the engine's Settings row. + var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!; + var dst = new LegacyUiSettings(); + copy.Invoke(null, new object[] { new LegacyUiSettings { MeleeThroughWalls = false }, dst }); + Check.False(dst.MeleeThroughWalls, "a profile's off is copied"); + copy.Invoke(null, new object[] { old!, dst }); + Check.True(dst.MeleeThroughWalls, "an old profile loads it on"); + + var s = new LegacyUiSettings { MeleeThroughWalls = false }; + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_profileLoaded", BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(dash, true); + typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s); + typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)! + .SetValue(dash, new LegacyAdvancedSettingsUi(s)); + var sent = System.Text.Json.JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload); + Check.True(sent != null && sent.MeleeThroughWalls == false, "sent to the engine's Settings window"); + dash.ApplySettingsJson("{\"PatrolOnLogin\":false}"); + Check.False(s.MeleeThroughWalls, "an engine without the row leaves it alone"); + dash.ApplySettingsJson("{\"MeleeThroughWalls\":true}"); + Check.True(s.MeleeThroughWalls, "the row's tick sets it"); } // 11-12: a test character locked golems on the floor above (d 9.0, h 6.7, dz +6.0; d 7.4, h 3.3, dz +6.6) and @@ -90,6 +244,7 @@ internal static class TargetingTests public static void Register(Runner r) { r.Add("targeting: melee within 4 yd ignores the raycast; beyond it, or with magic or missile, it counts", MeleeThroughWalls); + r.Add("targeting (11-15): Melee through walls: on keeps the 4 yd rule and the building's wall; off, a blocked monster is never the target", MeleeThroughWallsSetting); r.Add("targeting (11-12): melee leaves out a monster on the floor above or below; magic doesn't", MeleeOtherFloor); r.Add("targeting: each scheme picks its monster", SchemesPick); r.Add("targeting: unknown health counts as full; ties go to the closest, then the lower id", UnknownHealthAndTies);