feat: SK backlog from test through 2026.11.22.48 (Trade Shop, Oracle, quests, loot, nav)

Squash of test/main-merge-2026-10-25 onto aelrynth main 2026.11.19.1 for the standing sk PR. Includes Trade Shop, Oracle wiki/ILT tracker, quest runs, loot checklist, RynthNav, VTank import. HandWrittenVersion remains 0.5.0-legacy-ui. See Changelog/2026-11-22-sk-backlog-test-merge.md.
This commit is contained in:
BlankenshipG 2026-11-23 00:08:38 -05:00
commit dc08e1abba
521 changed files with 47247 additions and 795 deletions

View file

@ -0,0 +1,245 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>
/// One Infinite Leaftide Dynamic Stamp (dynstamps.csv): an NPC hand-in that puts a
/// "Dynamic_N_..." quest flag on the character. List from the players' "ExtraDyn" sheet
/// (10.13.2026, one sheet per area, the wiki's Dynamic Stamps page); NPCs that give no stamp
/// are left out. A stamp is a one-time flag: having it in /myquests means it's done.
/// </summary>
internal sealed class DynamicStamp
{
public string Area = "";
/// <summary>Where in the area (a town, a dungeon, coordinates), or "".</summary>
public string Place = "";
public string Npc = "";
/// <summary>What the NPC gives back (the sheet's "X gives you Y"), or "".</summary>
public string Reward = "";
/// <summary>The quest flag, lower case (as QuestFlagStore keys it).</summary>
public string Stamp = "";
public string Note = "";
/// <summary>The NPC, else the place (a few sheet rows only name the spot).</summary>
public string Label => Npc.Length > 0 ? Npc : Place;
/// <summary>
/// The stamp without the "!" the sheet copied from the server's "You've stamped {flag}!" line.
/// ACECustom names a stamp "Dynamic_1_" plus random letters, digits and ! @ # $ ^ &amp;
/// (QuestManager.ComputeDynamicQuest), yet 238 of the 243 listed stamps end in "!".
/// </summary>
public string Stem => Stamp.EndsWith('!') ? Stamp[..^1] : Stamp;
/// <summary>
/// The flag this character has for the stamp, or null. Tried in order: the stamp as listed,
/// without the copied closing "!" (the server's flag, almost always), with "!" added (a few
/// rows lost a real one), its errand's delivery flag ("_d"), then, when the stem is at least
/// <see cref="MinPrefixLength"/> long, the one errand whose flag starts with it (a row cut
/// short). <paramref name="qbStamps"/> is the Dynamic flags of RynthILT's /qb list (Infinite
/// Leaftide): /myquests leaves out flags the server holds no quest text for, so a stamp that
/// isn't in /myquests is looked for there too, with the same rules.
/// </summary>
public string? MatchedFlag(QuestFlagStore flags, IReadOnlySet<string>? qbStamps = null)
{
string? mine = Match(k => flags.TryGet(k, out _), flags.Flags.Keys);
if (mine != null || qbStamps == null || qbStamps.Count == 0) return mine;
return Match(qbStamps.Contains, qbStamps);
}
/// <summary>The matching rules over one source (see <see cref="MatchedFlag"/>).</summary>
private string? Match(Func<string, bool> has, IEnumerable<string> keys)
{
string stem = Stem;
if (has(Stamp)) return Stamp;
if (stem != Stamp && has(stem)) return stem;
if (stem == Stamp && has(Stamp + "!")) return Stamp + "!";
if (has(stem + DynamicStampList.DeliverySuffix)) return stem + DynamicStampList.DeliverySuffix;
if (stem.Length < MinPrefixLength) return null;
string? only = null;
foreach (string key in keys)
{
if (!key.StartsWith(stem, StringComparison.OrdinalIgnoreCase)) continue;
// An errand's own flag and its "_d" delivery flag are one stamp; two errands can't be told apart.
if (only != null && !DynamicStampList.ErrandOf(only).Equals(DynamicStampList.ErrandOf(key), StringComparison.OrdinalIgnoreCase))
return null;
if (only == null || key.Length < only.Length) only = key; // the errand's own flag over its "_d"
}
return only;
}
public bool Have(QuestFlagStore flags, IReadOnlySet<string>? qbStamps = null) => MatchedFlag(flags, qbStamps) != null;
// Sheet areas that are groupings, not places on the map.
private static readonly HashSet<string> NotPlaces = new(StringComparer.OrdinalIgnoreCase)
{
"Looking Around", "Odd Stamps", "Odd Stamps 2",
};
/// <summary>
/// Where RynthNav should go for this stamp, best first (RynthNav takes the first that is on its
/// map): the coordinates in the note or the place, the place and its parts ("Mhoire Castle -
/// Great Hall" also tries "Mhoire Castle"), the NPC, then the area. Empty when there is nothing.
/// </summary>
public List<string> NavCandidates()
{
var list = new List<string>();
void Add(string s)
{
s = s.Trim().Trim('.', ',', ';', ':').Trim();
if (s.Length >= 4 && !char.IsDigit(s[0]) && !list.Contains(s, StringComparer.OrdinalIgnoreCase)) list.Add(s);
}
foreach (string text in new[] { Note, Place })
if (NavTargets.FirstCoords(text) is string c && !list.Contains(c)) list.Add(c);
string place = NavTargets.WithoutCoords(Place);
place = System.Text.RegularExpressions.Regex.Replace(place, @"\b(at|in the|nearby)\b", " ", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
place = System.Text.RegularExpressions.Regex.Replace(place, @"\s+", " ").Trim();
Add(place);
foreach (string part in place.Split(new[] { " - ", " / ", "(", ")" }, StringSplitOptions.RemoveEmptyEntries))
Add(part);
Add(Npc);
if (!NotPlaces.Contains(Area)) Add(Area);
return list;
}
/// <summary>A truncated stamp shorter than this is matched exactly only (too many flags share a short stem).</summary>
public const int MinPrefixLength = 14;
}
internal static class DynamicStampList
{
/// <summary>Dynamic stamp quest flags start with this (lower case).</summary>
public const string FlagPrefix = "dynamic_";
/// <summary>
/// A chain errand's second flag: the NPC the item is delivered to stamps the errand's flag
/// with this added (QuestManager.ComputeDynamicQuest, questName + "_d").
/// </summary>
public const string DeliverySuffix = "_d";
/// <summary>The errand a Dynamic flag belongs to: the flag without its "_d" delivery suffix.</summary>
public static string ErrandOf(string flag) =>
flag.EndsWith(DeliverySuffix, StringComparison.OrdinalIgnoreCase) ? flag[..^DeliverySuffix.Length] : flag;
private static readonly List<DynamicStamp> Sheet = Load();
/// <summary>
/// The stamps: the wiki's Dynamic Stamps page when RynthILT has read it (2026-11-21, Silentkelpie: "the dynamic
/// stamp tab should be using" it), else the players' sheet shipped with RynthOracle.
/// </summary>
public static List<DynamicStamp> All { get; private set; } = Sheet;
/// <summary>The areas in list order (the wiki's towns and camps, or the sheet's Facility Hub, Looking Around, ...).</summary>
public static List<string> Areas { get; private set; } = BuildAreas(Sheet);
/// <summary>Where the list comes from: "wiki" or "sheet".</summary>
public static string Source { get; private set; } = "sheet";
/// <summary>Goes up when the list is swapped.</summary>
public static int Revision { get; private set; }
/// <summary>
/// Uses the wiki's Dynamic Stamps (QuestGuide.DynStamps) when there are any, else goes back to the sheet.
/// Pump thread. The wiki's coordinates go into the note, where RynthNav's candidates look first.
/// </summary>
public static void UseWiki(IReadOnlyList<GuideDynStamp>? wiki)
{
if (wiki == null || wiki.Count == 0)
{
if (Source == "sheet") return;
All = Sheet;
Areas = BuildAreas(Sheet);
Source = "sheet";
Revision++;
return;
}
var list = new List<DynamicStamp>(wiki.Count);
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (GuideDynStamp d in wiki)
{
string stamp = d.Stamp.Trim().ToLowerInvariant();
if (!stamp.StartsWith(FlagPrefix, StringComparison.Ordinal) || !seen.Add(stamp)) continue;
string note = d.Coords.Length > 0 && d.Note.Length > 0 ? d.Coords + " - " + d.Note : d.Coords + d.Note;
list.Add(new DynamicStamp { Area = d.Area, Place = d.Place, Npc = d.Npc, Reward = d.Reward, Stamp = stamp, Note = note });
}
if (list.Count == 0) { UseWiki(null); return; }
All = list;
Areas = BuildAreas(list);
Source = "wiki";
Revision++;
}
/// <summary>
/// Dynamic stamps on this character that the list doesn't have (new or unlisted NPCs), so the
/// tab can show them and the count isn't only what the sheet knows.
/// </summary>
public static List<string> Unlisted(QuestFlagStore flags, IReadOnlySet<string>? qbStamps = null)
{
// By errand: a listed stamp's "_d" delivery flag is that stamp, and an unlisted errand shows once.
var matched = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (DynamicStamp s in All)
if (s.MatchedFlag(flags, qbStamps) is string f) matched.Add(ErrandOf(f));
var extra = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string key in flags.Flags.Keys)
if (key.StartsWith(FlagPrefix, StringComparison.OrdinalIgnoreCase) && !matched.Contains(ErrandOf(key)))
extra.Add(ErrandOf(key));
if (qbStamps != null)
foreach (string key in qbStamps)
if (key.StartsWith(FlagPrefix, StringComparison.OrdinalIgnoreCase) && !matched.Contains(ErrandOf(key)))
extra.Add(ErrandOf(key));
var list = extra.ToList();
list.Sort(StringComparer.OrdinalIgnoreCase);
return list;
}
/// <summary>
/// Where this character's stamps come from, for the log: Dynamic flags in /myquests, Dynamic
/// flags in the /qb list, and the listed stamps matched from either.
/// </summary>
public static (int InMyQuests, int InQb, int Matched) Counts(QuestFlagStore flags, IReadOnlySet<string>? qbStamps)
{
int mine = flags.Flags.Keys.Count(k => k.StartsWith(FlagPrefix, StringComparison.OrdinalIgnoreCase));
int qb = qbStamps?.Count(k => k.StartsWith(FlagPrefix, StringComparison.OrdinalIgnoreCase)) ?? 0;
int matched = All.Count(s => s.Have(flags, qbStamps));
return (mine, qb, matched);
}
private static List<DynamicStamp> Load()
{
var list = new List<DynamicStamp>();
using StreamReader r = Csv.OpenEmbedded("dynstamps.csv");
Dictionary<string, int> col = Csv.MapColumns(r.ReadLine() ?? "");
int cArea = Csv.Column(col, "Area"), cPlace = Csv.Column(col, "Place"), cNpc = Csv.Column(col, "Npc"),
cReward = Csv.Column(col, "Reward"), cStamp = Csv.Column(col, "Stamp"), cNote = Csv.Column(col, "Note");
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
while (r.ReadLine() is string line)
{
if (string.IsNullOrWhiteSpace(line)) continue;
string[] f = Csv.ParseLine(line);
string stamp = Csv.Field(f, cStamp).Trim().ToLowerInvariant();
if (!stamp.StartsWith(FlagPrefix, StringComparison.Ordinal) || !seen.Add(stamp)) continue;
list.Add(new DynamicStamp
{
Area = Csv.Field(f, cArea),
Place = Csv.Field(f, cPlace),
Npc = Csv.Field(f, cNpc),
Reward = Csv.Field(f, cReward),
Stamp = stamp,
Note = Csv.Field(f, cNote),
});
}
return list;
}
private static List<string> BuildAreas(List<DynamicStamp> all)
{
var areas = new List<string>();
foreach (DynamicStamp s in all)
if (!areas.Contains(s.Area)) areas.Add(s.Area);
return areas;
}
}

View file

@ -0,0 +1,297 @@
// FandomFeed.cs - RynthOracle's own quest guide from the AC Community Wiki, asheron.fandom.com (2026-11-21,
// Silentkelpie: "under oracle duplicate itl functions for pulling in overall quests ... pull a dynamic feed from
// https://asheron.fandom.com/wiki/Category:Quests for the quests, .../Category:Kill_Tasks for kill task,
// .../Category:Society_Quests for socity quests, .../Category:Contracts for contracts ... should not be gated
// behind any server check"). The same reading as RynthILT's WikiFeed (leaftidewiki.com, a fork of this wiki
// with the same templates), but anonymous and on every server:
// - the quests: every page with the {{Quest Summary}} box, and the pages under Category:Quests (its
// sub-categories followed, the item ones left out);
// - the kill tasks: Category:Kill_Tasks and its sub-categories;
// - the society quests: Category:Society_Quests, each page's rank from the sub-category it is in
// ("Society Quests: Initiate Rank" -> Initiate; "Joining a Society Quests" -> Joining);
// - the contracts: Category:Contracts' item pages (WikiQuestParser.ParseContract).
// Only pages changed since the last read are fetched (their revision ids), unless the page reader is newer
// (WikiQuestParser.Version). Saved to %APPDATA%\RynthCore\RynthOracle\fandom-quests.json, read at load. The
// read runs on a pool thread and only builds a new QuestGuide and writes the file; the pump takes it
// (TakeResult). Read at login when the saved one is a day old (or older reader, or none), and on Refresh.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.Plugin.RynthOracle.Data;
internal sealed class FandomFeed
{
public const string Api = "https://asheron.fandom.com/api.php";
public const string WikiBase = "https://asheron.fandom.com/wiki/";
public const string QuestTemplate = "Template:Quest_Summary";
public const string QuestsCategory = "Category:Quests";
public const string KillTasksCategory = "Category:Kill_Tasks";
public const string SocietyCategory = "Category:Society_Quests";
public const string ContractsCategory = "Category:Contracts";
public const int RefreshHours = 24;
/// <summary>Category:Quests is a tree; this many categories at most are followed.</summary>
internal const int MaxCategories = 400;
private const int RequestGapMs = 250;
public static string DefaultPath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "RynthOracle", "fandom-quests.json");
private readonly string _path;
private CancellationTokenSource? _cts;
private Task? _task;
private volatile QuestGuide? _ready; // a new guide for the pump
private volatile string _status = "";
private bool _autoTried;
/// <summary>The guide in use (pump thread).</summary>
public QuestGuide Guide { get; private set; } = new();
/// <summary>Goes up when <see cref="Guide"/> is replaced.</summary>
public int Revision { get; private set; }
public bool Running => _task is { IsCompleted: false };
public string Status => _status;
public FandomFeed(string? path = null)
{
_path = path ?? DefaultPath;
try
{
if (File.Exists(_path)) Guide = QuestGuide.Parse(File.ReadAllText(_path));
}
catch { Guide = new QuestGuide(); }
_status = Guide.Quests.Count > 0
? $"{Guide.Quests.Count} quests, {Guide.Contracts.Count} contracts (read {Guide.UpdatedUtc.ToLocalTime():MM-dd HH:mm})"
: "not read yet";
}
/// <summary>The saved guide wants reading: none yet, a day old, or made by an older page reader.</summary>
internal static bool Due(QuestGuide g, DateTime utcNow) =>
g.Quests.Count == 0 || g.Parser < WikiQuestParser.Version || utcNow - g.UpdatedUtc >= TimeSpan.FromHours(RefreshHours);
/// <summary>Pump thread, in the world: the read at login, once a session, when the saved guide is due.</summary>
public void Tick(DateTime utcNow)
{
if (_autoTried) return;
_autoTried = true;
if (Due(Guide, utcNow)) Start();
}
/// <summary>Starts a read unless one is running. Pump thread.</summary>
public bool Start()
{
if (Running) return false;
_cts?.Dispose();
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
QuestGuide old = Guide;
_status = "reading...";
_task = Task.Run(async () =>
{
try { _status = await RefreshAsync(old, token).ConfigureAwait(false); }
catch (OperationCanceledException) { _status = "stopped"; }
catch (Exception ex) { _status = "couldn't read the wiki: " + ex.GetType().Name + ": " + ex.Message; }
}, token);
return true;
}
/// <summary>Pump thread: takes a finished read's guide; true when the guide changed.</summary>
public bool TakeResult()
{
QuestGuide? g = _ready;
if (g == null) return false;
_ready = null;
Guide = g;
Revision++;
return true;
}
/// <summary>Uses a guide (the tests).</summary>
internal void Use(QuestGuide g)
{
Guide = g;
Revision++;
}
public void Shutdown()
{
try { _cts?.Cancel(); _task?.Wait(2000); } catch { }
}
// ── The read (pool thread) ──────────────────────────────────────────────
private static readonly Regex RankRx = new(@"(?:^|:\s*)(\w+)\s+Rank\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
/// <summary>The society rank a society sub-category stands for ("Society Quests: Knight Rank" -> Knight), or "".</summary>
internal static string RankOf(string category)
{
Match m = RankRx.Match(category);
if (m.Success) return char.ToUpperInvariant(m.Groups[1].Value[0]) + m.Groups[1].Value.Substring(1).ToLowerInvariant();
return category.Contains("Joining", StringComparison.OrdinalIgnoreCase) ? "Joining" : "";
}
/// <summary>A Category:Quests sub-category not followed: item and NPC lists, not quests.</summary>
internal static bool SkipCategory(string category) =>
category.Contains("Quest Items", StringComparison.OrdinalIgnoreCase)
|| category.Contains("Items", StringComparison.OrdinalIgnoreCase) && !category.Contains("Quest", StringComparison.OrdinalIgnoreCase)
|| category.Contains("NPC", StringComparison.OrdinalIgnoreCase)
|| category.Contains("Brokers", StringComparison.OrdinalIgnoreCase)
|| category.Contains("Images", StringComparison.OrdinalIgnoreCase)
|| category.Contains("Maps", StringComparison.OrdinalIgnoreCase);
private async Task<string> RefreshAsync(QuestGuide old, CancellationToken token)
{
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
http.DefaultRequestHeaders.UserAgent.ParseAdd("RynthOracle/1.0 (RynthCore quest guide; Asheron's Call)");
var titles = new SortedSet<string>(StringComparer.Ordinal);
var killTasks = new SortedSet<string>(StringComparer.Ordinal);
var contracts = new SortedSet<string>(StringComparer.Ordinal);
var society = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
_status = "listing the quest pages...";
await ListAsync(http, "embeddedin", new[] { ("list", "embeddedin"), ("eititle", QuestTemplate), ("einamespace", "0"), ("eilimit", "max") },
p => titles.Add(p), _ => { }, token).ConfigureAwait(false);
await WalkAsync(http, QuestsCategory, (p, _) => titles.Add(p), SkipCategory, token).ConfigureAwait(false);
_status = "listing the kill tasks...";
await WalkAsync(http, KillTasksCategory, (p, _) => { killTasks.Add(p); titles.Add(p); }, SkipCategory, token).ConfigureAwait(false);
_status = "listing the society quests...";
await WalkAsync(http, SocietyCategory, (p, cat) =>
{
titles.Add(p);
string rank = RankOf(cat);
if (rank.Length > 0 && !society.ContainsKey(p)) society[p] = rank;
}, SkipCategory, token).ConfigureAwait(false);
_status = "listing the contracts...";
await ListAsync(http, "categorymembers", new[] { ("list", "categorymembers"), ("cmtitle", ContractsCategory), ("cmlimit", "max"), ("cmtype", "page") },
p => { contracts.Add(p); titles.Add(p); }, _ => { }, token).ConfigureAwait(false);
if (titles.Count == 0) return "the wiki listed no quest pages";
// Which pages changed since the saved guide.
var list = new List<string>(titles);
var revs = new Dictionary<string, long>(StringComparer.Ordinal);
int done = 0;
foreach (string batch in MediaWikiJson.Batches(list))
{
_status = $"checking pages ({done}/{list.Count})...";
string json = await GetAsync(http, MediaWikiJson.Url(Api, ("action", "query"), ("prop", "info"), ("titles", batch)), token).ConfigureAwait(false);
foreach (var kv in MediaWikiJson.LastRevisions(json)) revs[kv.Key] = kv.Value;
done += MediaWikiJson.TitlesPerRequest;
}
List<string> changed = PagesToRead(old, revs);
var fresh = new Dictionary<string, GuideQuest>(StringComparer.Ordinal);
var freshContracts = new Dictionary<string, GuideContract>(StringComparer.Ordinal);
var notQuest = new HashSet<string>(StringComparer.Ordinal);
int read = 0;
foreach (string batch in MediaWikiJson.Batches(changed))
{
_status = $"reading pages ({read}/{changed.Count})...";
string json = await GetAsync(http, MediaWikiJson.Url(Api, ("action", "query"), ("prop", "revisions"), ("rvprop", "content|ids"),
("rvslots", "main"), ("titles", batch)), token).ConfigureAwait(false);
foreach (var (title, rev, text) in MediaWikiJson.Contents(json))
{
if (WikiQuestParser.IsQuestPage(text)) fresh[title] = WikiQuestParser.Parse(title, text, rev, WikiBase);
else if (contracts.Contains(title) && WikiQuestParser.IsContractPage(title, text)) freshContracts[title] = WikiQuestParser.ParseContract(title, text, rev, WikiBase);
else notQuest.Add(title);
}
read += MediaWikiJson.TitlesPerRequest;
}
QuestGuide g = Merge(old, revs, fresh, freshContracts);
g.KillTasks = new List<string>(killTasks);
g.Society = society;
token.ThrowIfCancellationRequested();
try
{
Directory.CreateDirectory(Path.GetDirectoryName(_path)!);
File.WriteAllText(_path + ".tmp", g.ToJson());
File.Move(_path + ".tmp", _path, overwrite: true);
}
catch (Exception ex) { _status = "read, but couldn't save: " + ex.Message; }
_ready = g;
return $"{g.Quests.Count} quests ({fresh.Count} read now), {g.KillTasks.Count} kill tasks, {g.Society.Count} society quests, {g.Contracts.Count} contracts";
}
/// <summary>The pages to read: new or edited since the saved guide; every one when it came from an older reader.</summary>
internal static List<string> PagesToRead(QuestGuide old, IReadOnlyDictionary<string, long> revs)
{
var known = new Dictionary<string, long>(StringComparer.Ordinal);
foreach (GuideQuest q in old.Quests) known[q.Title] = q.Rev;
foreach (GuideContract c in old.Contracts) known[c.Title] = c.Rev;
bool whole = old.Parser < WikiQuestParser.Version;
var changed = new List<string>();
foreach (var kv in revs)
if (whole || kv.Value == 0 || !known.TryGetValue(kv.Key, out long rev) || rev != kv.Value) changed.Add(kv.Key);
return changed;
}
/// <summary>
/// The new guide: the pages listed now, each the fresh read when there is one, else the saved one (a page that
/// is no longer listed goes). Pages that aren't quests or contracts aren't kept, so they are read again next
/// time (cheap: they are few once the item categories are left out).
/// </summary>
internal static QuestGuide Merge(QuestGuide old, IReadOnlyDictionary<string, long> listed,
IReadOnlyDictionary<string, GuideQuest> fresh, IReadOnlyDictionary<string, GuideContract> freshContracts)
{
var oldQuests = new Dictionary<string, GuideQuest>(StringComparer.Ordinal);
foreach (GuideQuest q in old.Quests) oldQuests[q.Title] = q;
var oldContracts = new Dictionary<string, GuideContract>(StringComparer.Ordinal);
foreach (GuideContract c in old.Contracts) oldContracts[c.Title] = c;
var g = new QuestGuide { Source = "fandom", UpdatedUtc = DateTime.UtcNow, Parser = WikiQuestParser.Version, KillTasks = old.KillTasks, Society = old.Society };
foreach (string title in listed.Keys)
{
if (fresh.TryGetValue(title, out GuideQuest? f)) g.Quests.Add(f);
else if (oldQuests.TryGetValue(title, out GuideQuest? o)) g.Quests.Add(o);
if (freshContracts.TryGetValue(title, out GuideContract? fc)) g.Contracts.Add(fc);
else if (oldContracts.TryGetValue(title, out GuideContract? oc)) g.Contracts.Add(oc);
}
g.Quests.Sort((a, b) => string.Compare(a.Title, b.Title, StringComparison.OrdinalIgnoreCase));
g.Contracts.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
return g;
}
/// <summary>A category's pages and, followed breadth first, its sub-categories' (each page with the category it was in).</summary>
private async Task WalkAsync(HttpClient http, string root, Action<string, string> page, Func<string, bool> skip, CancellationToken token)
{
var queue = new Queue<string>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { root.Replace('_', ' '), root };
queue.Enqueue(root);
while (queue.Count > 0 && seen.Count <= MaxCategories)
{
string cat = queue.Dequeue();
await ListAsync(http, "categorymembers", new[] { ("list", "categorymembers"), ("cmtitle", cat), ("cmlimit", "max"), ("cmtype", "page|subcat") },
p => page(p, cat), sub =>
{
if (!skip(sub) && seen.Add(sub)) queue.Enqueue(sub);
}, token).ConfigureAwait(false);
}
}
private static async Task ListAsync(HttpClient http, string listName, (string, string)[] args, Action<string> page, Action<string> sub, CancellationToken token)
{
var cont = new List<(string, string)>();
for (int i = 0; i < 100; i++)
{
var all = new List<(string, string)> { ("action", "query") };
all.AddRange(args);
all.AddRange(cont);
string json = await GetAsync(http, MediaWikiJson.Url(Api, all.ToArray()), token).ConfigureAwait(false);
var (pages, subs, next) = MediaWikiJson.Members(json, listName);
foreach (string p in pages) page(p);
foreach (string s in subs) sub(s);
if (next.Count == 0) return;
cont = next;
}
}
private static async Task<string> GetAsync(HttpClient http, string url, CancellationToken token)
{
await Task.Delay(RequestGapMs, token).ConfigureAwait(false);
using HttpResponseMessage resp = await http.GetAsync(url + "&maxlag=5", token).ConfigureAwait(false);
return await resp.Content.ReadAsStringAsync(token).ConfigureAwait(false);
}
}

View file

@ -0,0 +1,789 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>
/// One item read from the game for the Gear tab: what it is, where it sits, its spells (from the
/// appraisal) and the properties the ratings view shows. Filled by <see cref="GearScanner"/>.
/// </summary>
internal sealed class GearPiece
{
public uint Id;
public string Name = "";
/// <summary>ItemType flags (MeleeWeapon 0x1, Armor 0x2, Clothing 0x4, Jewelry 0x8, MissileWeapon 0x100, Caster 0x8000).</summary>
public uint ItemType;
/// <summary>EquipMask it is worn in; 0 in a pack.</summary>
public uint Location;
public bool Equipped;
/// <summary>The appraisal reached the client (or it was asked for and answered with no spells).</summary>
public bool Appraised;
/// <summary>The item's own spells (cantrips, banes, procs): Decal's Spell list.</summary>
public uint[] Inscribed = Array.Empty<uint>();
/// <summary>Item enchantments active on it right now (appraisal ids with 0x80000000): Decal's ActiveSpell.</summary>
public uint[] OnItem = Array.Empty<uint>();
public int SetId;
public int MaxLevel;
public int XpStyle;
public long BaseXp;
public long TotalXp;
/// <summary>PropertyInt.DamageType (45): the weapon's element (a caster's too).</summary>
public int DamageType;
/// <summary>The gear ratings it carries (PropertyInt 370-389), non-zero only.</summary>
public (int Prop, int Value)[] Ratings = Array.Empty<(int, int)>();
/// <summary>T11+ modifier lines from the appraisal's "Modifiers:" section (<see cref="T11Modifiers"/>); none elsewhere.</summary>
public GearModifier[] Modifiers = Array.Empty<GearModifier>();
/// <summary>The appraisal says "Zone Locked (Power Reduced)": the modifiers are dormant outside their zones.</summary>
public bool ZoneLocked;
/// <summary>The appraised int properties the Mag-style line reads (<see cref="MagFormat.IntProps"/>), present ones only.</summary>
public Dictionary<int, int> Ints = new();
/// <summary>The appraised float properties the Mag-style line reads (<see cref="MagFormat.FloatProps"/>), present ones only.</summary>
public Dictionary<int, double> Floats = new();
public int Int(int prop) => Ints.TryGetValue(prop, out int v) ? v : 0;
public double Float(int prop, double fallback) => Floats.TryGetValue(prop, out double v) ? v : fallback;
/// <summary>Gains levels from experience (ItemBaseXp, ItemMaxLevel and ItemXpStyle all set).</summary>
public bool Leveled => BaseXp > 0 && MaxLevel > 0 && XpStyle > 0;
/// <summary>The item's level from its experience (0 for an item that doesn't level).</summary>
public int Level => Leveled ? GearMath.ItemLevel(TotalXp, BaseXp, MaxLevel, XpStyle) : 0;
}
/// <summary>
/// One T11 modifier line ("Damage Rating +52"): its name, its number, the line as shown, and the
/// gear rating it adds (0 for the lines that aren't ratings: All Attributes, the slot specials...).
/// </summary>
internal readonly record struct GearModifier(string Name, int Value, bool HasValue, string Text, int RatingProp);
/// <summary>
/// T11+ gear's modifier lines (ACECustom "zone modifiers"). The appraisal shows them as a
/// "Modifiers:" section of "- Name value [min-max]" lines: in the Use text on armour, clothing and
/// jewelry, in the long description on weapons (AppraiseInfo.PromoteZoneModifierLines). A line
/// that is a gear rating is taken OUT of the item's appraised ratings so it doesn't show twice,
/// which is why the Ratings view adds them back from here. Servers without these lines show none.
/// </summary>
internal static class T11Modifiers
{
public const string SectionHeader = "Modifiers:";
public const string ZoneLockedLine = "Zone Locked (Power Reduced)";
/// <summary>The lines that are gear ratings, and the PropertyInt each adds (ACECustom ZoneModifiers.Catalog).</summary>
public static readonly (string Name, int Prop)[] RatingLines =
{
("Damage Rating", 370), ("Damage Resist", 371), ("Crit Chance", 372), ("Crit Resist", 373),
("Crit Damage Rating", 374), ("Crit Damage Resist", 375), ("Healing Boost", 376),
("Nether Resist", 377), ("Max Health", 379),
};
/// <summary>The slot specials: the highest single one worn counts (MAX-wins), not the sum.</summary>
public static readonly HashSet<string> MaxWins = new(StringComparer.OrdinalIgnoreCase)
{
"Fortify Vitals", "Battle Mending", "Pct HP Damage", "Cheat Death", "Regeneration",
};
/// <summary>Lines that change only their own piece (its armour), so they have no character total.</summary>
public static readonly HashSet<string> PerPiece = new(StringComparer.OrdinalIgnoreCase) { "Armor Level", "Reinforced" };
/// <summary>Every line name the catalog has, longest first so "Max Health Pct" is not read as "Max Health".</summary>
private static readonly string[] KnownNames = new[]
{
"Max Health", "Armor Level", "Damage Rating", "Crit Damage Rating", "Healing Boost", "Spell Duration",
"Crit Chance", "Fortify Vitals", "Battle Mending", "Pct HP Damage", "Cheat Death", "Regeneration",
"Max Health Pct", "Life on Hit", "Reinforced", "All Attributes", "Damage Resist", "Crit Damage Resist",
"Crit Resist", "Nether Resist",
}.OrderByDescending(n => n.Length).ToArray();
private static readonly System.Text.RegularExpressions.Regex Range =
new(@"\s*\[\s*-?\d+\s*-\s*-?\d+\s*\]\s*$", System.Text.RegularExpressions.RegexOptions.CultureInvariant);
private static readonly System.Text.RegularExpressions.Regex Number =
new(@"[+-]?\d+", System.Text.RegularExpressions.RegexOptions.CultureInvariant);
/// <summary>The modifier lines in any of the appraisal texts given (Use, long description), and the zone lock.</summary>
public static (GearModifier[] Lines, bool ZoneLocked) Parse(params string?[] texts)
{
var lines = new List<GearModifier>();
bool locked = false;
foreach (string? text in texts)
{
if (string.IsNullOrEmpty(text) || text.IndexOf(SectionHeader, StringComparison.Ordinal) < 0) continue;
bool inSection = false;
foreach (string raw in text.Split('\n'))
{
string line = raw.Trim();
if (!inSection)
{
inSection = line == SectionHeader;
continue;
}
if (!line.StartsWith("- ", StringComparison.Ordinal)) break; // the section ends at the first other line
string body = line[2..].Trim();
if (body.Equals(ZoneLockedLine, StringComparison.OrdinalIgnoreCase)) { locked = true; continue; }
if (body.Length == 0) continue;
GearModifier m = ParseLine(body);
if (!lines.Contains(m)) lines.Add(m);
}
}
return (lines.ToArray(), locked);
}
/// <summary>"Damage Rating +52 [14-69]": the name, the first number after it, the line without the roll range.</summary>
internal static GearModifier ParseLine(string body)
{
string shown = Range.Replace(body, "").Trim();
string name = "";
foreach (string known in KnownNames)
if (shown.StartsWith(known, StringComparison.OrdinalIgnoreCase)
&& (shown.Length == known.Length || shown[known.Length] == ' '))
{
name = known;
break;
}
if (name.Length == 0)
{
// A line the catalog didn't have when this was written: its name runs up to the first number.
System.Text.RegularExpressions.Match first = Number.Match(shown);
name = (first.Success ? shown[..first.Index] : shown).Trim();
}
string rest = shown.Length > name.Length ? shown[name.Length..] : "";
System.Text.RegularExpressions.Match num = Number.Match(rest);
int value = num.Success && int.TryParse(num.Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int v) ? v : 0;
int prop = 0;
foreach (var (n, p) in RatingLines)
if (n.Equals(name, StringComparison.OrdinalIgnoreCase)) { prop = p; break; }
return new GearModifier(name, value, num.Success, shown, prop);
}
}
/// <summary>A spell as the Gear tab knows it: from portal.dat, else SpellData.txt, else only its id.</summary>
internal readonly record struct SpellMeta(uint Id, string Name, uint Category, uint Power, bool Enchantment, bool ItemTarget, bool Known)
{
public static SpellMeta Unknown(uint id) => new(id, "Spell " + id.ToString(CultureInfo.InvariantCulture), 0, 0, true, false, false);
}
/// <summary>Where a spell on the character comes from.</summary>
internal enum SpellLayer
{
/// <summary>One of the item's own spells.</summary>
Inscribed,
/// <summary>An item enchantment active on the item (a bane cast on it, Blood Drinker).</summary>
OnItem,
/// <summary>An equipment set's bonus for the pieces worn.</summary>
SetBonus,
/// <summary>An enchantment on the character (spells cast on you, and worn items' cantrips).</summary>
Buff,
}
/// <summary>One spell from one source.</summary>
internal sealed class SpellSource
{
/// <summary>The item (0 for a set bonus or a buff on the character).</summary>
public uint ItemId;
public string ItemName = "";
public SpellLayer Layer;
public SpellMeta Spell;
/// <summary>The equipment set of a set bonus, else 0.</summary>
public int SetId;
public string LayerLabel => GearAnalysis.LayerLabel(Layer);
}
/// <summary>What a family's spells do together.</summary>
internal enum OverlapKind
{
/// <summary>Different spells of one enchantment family: only the highest power works, the rest are wasted.</summary>
Overlap,
/// <summary>The same spell from more than one item: one copy works, the others are wasted.</summary>
Duplicate,
/// <summary>Not enchantments (procs, heals): each works on its own.</summary>
Stacks,
/// <summary>One spell, one source.</summary>
Ok,
}
/// <summary>One family on one target (the character, or one item for item spells).</summary>
internal sealed class OverlapRow
{
public OverlapKind Kind;
public uint Category;
public string Family = "";
/// <summary>The item the spells are on (item spells), or "" for the character.</summary>
public string Scope = "";
public SpellSource Winner = null!;
public List<SpellSource> Sources = new();
/// <summary>"item/layer/power" per source, highest first; "(beat)" on the ones that lose.</summary>
public string Summary = "";
}
/// <summary>Ward and bane tiers, lowest to highest: a higher tier in the family wins.</summary>
internal enum ProtTier { Missing = 0, Lower = 1, Minor = 2, Major = 3, Epic = 4, Legendary = 5 }
/// <summary>One element of the life wards or banes: the spell that wins and what it beats.</summary>
internal sealed class ProtRow
{
public string Element = "";
public uint Category;
public ProtTier Tier;
public string Winner = "";
public string Source = "";
public string Beaten = "";
public bool Missing => Tier == ProtTier.Missing;
}
/// <summary>Life wards (on the character) and banes (on the armour), seven elements each.</summary>
internal sealed class ProtSummary
{
public List<ProtRow> Life = new();
public List<ProtRow> Crit = new();
public int LifeLegendary => Life.Count(r => r.Tier == ProtTier.Legendary);
public int CritLegendary => Crit.Count(r => r.Tier == ProtTier.Legendary);
public string LifeMissing => string.Join(", ", Life.Where(r => r.Missing).Select(r => r.Element));
public string CritMissing => string.Join(", ", Crit.Where(r => r.Missing).Select(r => r.Element));
}
/// <summary>An equipment set worn, its level and the bonus spells it gives.</summary>
internal sealed class SetBonusGroup
{
public int SetId;
public string Name = "";
public int Pieces;
public int Level;
public uint Tier;
public bool LeveledSet;
public string Label = "";
public string PieceNames = "";
public List<SpellSource> Spells = new();
}
/// <summary>The Overlap view's whole picture at one moment.</summary>
internal sealed class GearReport
{
public DateTime CheckedLocal;
public int Equipped;
public int NotAppraised;
public int SpellSources;
public int UnknownSpells;
public List<GearPiece> Pieces = new();
public Dictionary<uint, List<SpellSource>> PieceSpells = new();
public List<SetBonusGroup> Sets = new();
public List<SpellSource> Buffs = new();
public List<SpellSource> Paragon = new();
public List<OverlapRow> Rows = new();
public ProtSummary Protection = new();
public int Count(OverlapKind kind) => Rows.Count(r => r.Kind == kind);
}
/// <summary>One item of the Ratings view (sets, item levels, gear ratings; UB-ILT's Paragon gear, for every server).</summary>
internal sealed class RatingRow
{
public GearPiece Piece = null!;
public string Category = "";
public string TypeLabel = "";
public string SetName = "-";
public bool Paragon;
public string Stats = "";
/// <summary>The ratings with the T11 modifier lines' added (the appraisal leaves those out).</summary>
public (int Prop, int Value)[] Effective = Array.Empty<(int, int)>();
/// <summary>The T11 modifier lines, as the appraisal shows them ("Damage Rating +52, All Attributes +40").</summary>
public string T11 = "";
/// <summary>Has a set, an item level, gear ratings or T11 modifiers (the column view lists only these).</summary>
public bool Rated;
/// <summary>The item as one Mag-Tools ItemInfo line (<see cref="MagFormat"/>).</summary>
public string Mag = "";
}
internal sealed class RatingsReport
{
public DateTime CheckedLocal;
public bool IncludePack;
public List<RatingRow> Rows = new();
/// <summary>Every rating summed over the worn items (T11 modifier ratings included).</summary>
public List<(int Prop, int Value)> WornTotals = new();
/// <summary>The worn T11 modifiers that aren't ratings: summed, the slot specials the highest one.</summary>
public List<(string Name, string Value)> T11Totals = new();
/// <summary>The rows with a set, a level, ratings or modifiers (<see cref="RatingRow.Rated"/>).</summary>
public IEnumerable<RatingRow> RatedRows => Rows.Where(r => r.Rated);
public int EquippedRows => Rows.Count(r => r.Rated && r.Piece.Equipped);
public int T11Rows => Rows.Count(r => r.T11.Length > 0);
}
/// <summary>Item experience to level (ACE ExperienceSystem.ItemTotalXPToLevel).</summary>
internal static class GearMath
{
public static int ItemLevel(long totalXp, long baseXp, int maxLevel, int xpStyle)
{
if (baseXp <= 0 || maxLevel <= 0) return 0;
ulong gained = (ulong)Math.Max(0, totalXp), b = (ulong)baseXp;
int level = 0;
switch (xpStyle)
{
case 1: // Fixed
level = (int)(gained / b);
break;
case 2: // ScalesWithLevel: each level costs twice the last
{
ulong cost = b, left = gained;
while (left >= cost && level < maxLevel)
{
level++;
left -= cost;
if (cost > ulong.MaxValue / 2) break;
cost *= 2;
}
break;
}
case 3: // FixedPlusBase
if (gained >= b && gained < b * 3UL) level = 1;
else if (gained >= b) level = (int)((gained - b) / b);
break;
}
return Math.Min(level, maxLevel);
}
}
/// <summary>
/// The Gear tab's analysis, all of it pure (the tests build pieces by hand). Ported from UB-ILT's
/// EquippedSpellOverlapAnalyzer, EquippedProtectionCoverage, EquippedGearSetBonus and
/// ParagonGearAnalyzer, with the spell facts taken from the client's own spell table instead of
/// a catalog exported from one server, so it reads any server's gear.
/// </summary>
internal static class GearAnalysis
{
public const uint ItemMelee = 0x1, ItemArmor = 0x2, ItemClothing = 0x4, ItemJewelry = 0x8,
ItemMissile = 0x100, ItemContainer = 0x200, ItemCaster = 0x8000;
public const uint ItemWeapons = ItemMelee | ItemMissile | ItemCaster;
public const uint ItemWearables = ItemWeapons | ItemArmor | ItemClothing | ItemJewelry;
/// <summary>ACE's paragon weapon sets (ACECustom EquipmentSet 138-140); harmless where they don't exist.</summary>
public const int ParagonSetFirst = 138, ParagonSetLast = 140;
/// <summary>Luminous Amber puts ItemBaseXp at 2,000,000,000 on a paragon weapon.</summary>
public const long ParagonWeaponBaseXp = 2_000_000_000L;
/// <summary>The life ward families, in UB-ILT's order (ACE SpellCategory).</summary>
public static readonly (uint Category, string Element)[] LifeWards =
{
(403, "Slashing"), (405, "Piercing"), (401, "Bludgeon"), (287, "Fire"), (289, "Cold"), (285, "Acid"), (291, "Storm"),
};
/// <summary>The bane families (ExtraXResistanceRaising: armour against an element).</summary>
public static readonly (uint Category, string Element)[] CritBanes =
{
(395, "Slashing"), (393, "Piercing"), (383, "Bludgeon"), (385, "Fire"), (387, "Cold"), (381, "Acid"), (397, "Storm"),
};
/// <summary>The gear ratings (ACE PropertyInt), short and long names.</summary>
public static readonly (int Prop, string Short, string Long)[] RatingProps =
{
(370, "D", "Damage"), (371, "DR", "Damage resist"), (372, "C", "Crit"), (373, "CR", "Crit resist"),
(374, "CD", "Crit damage"), (375, "CDR", "Crit damage resist"), (376, "HB", "Healing boost"),
(377, "NR", "Nether resist"), (378, "LR", "Life resist"), (379, "V", "Max health"),
(383, "PKD", "PK damage"), (384, "PKDR", "PK damage resist"), (388, "OP", "Overpower"), (389, "OPR", "Overpower resist"),
};
public static string LayerLabel(SpellLayer layer) => layer switch
{
SpellLayer.Inscribed => "Inscribed",
SpellLayer.OnItem => "Active",
SpellLayer.SetBonus => "Set bonus",
_ => "Active buff",
};
private static string LayerShort(SpellLayer layer) => layer switch
{
SpellLayer.Inscribed => "Ins",
SpellLayer.OnItem => "Act",
SpellLayer.SetBonus => "Set",
_ => "Buff",
};
// ── Overlap ──────────────────────────────────────────────────────────────
/// <summary>
/// Everything on the worn gear and the character at once: each piece's spells, the set bonuses,
/// the character's enchantments, the overlap rows and the ward / bane coverage.
/// </summary>
public static GearReport Analyze(IReadOnlyList<GearPiece> equipped, IReadOnlyList<uint> buffSpellIds,
Func<uint, SpellMeta> lookup, Func<int, SpellSetDef?> setOf,
string characterName, DateTime nowLocal)
{
var report = new GearReport { CheckedLocal = nowLocal, Equipped = equipped.Count };
var all = new List<SpellSource>();
var unknown = new HashSet<uint>();
SpellMeta Look(uint id)
{
SpellMeta m = lookup(id);
if (!m.Known) unknown.Add(id);
return m;
}
foreach (GearPiece p in equipped.OrderBy(p => p.Name, StringComparer.OrdinalIgnoreCase))
{
report.Pieces.Add(p);
if (!p.Appraised) report.NotAppraised++;
var list = new List<SpellSource>();
foreach (uint id in p.Inscribed.Distinct())
list.Add(new SpellSource { ItemId = p.Id, ItemName = p.Name, Layer = SpellLayer.Inscribed, Spell = Look(id) });
foreach (uint id in p.OnItem.Distinct())
list.Add(new SpellSource { ItemId = p.Id, ItemName = p.Name, Layer = SpellLayer.OnItem, Spell = Look(id) });
report.PieceSpells[p.Id] = list;
all.AddRange(list);
}
report.Sets = SetBonuses(equipped, setOf, Look);
foreach (SetBonusGroup g in report.Sets) all.AddRange(g.Spells);
string who = characterName.Length > 0 ? characterName : "(character)";
foreach (uint id in buffSpellIds.Distinct())
report.Buffs.Add(new SpellSource { ItemName = who, Layer = SpellLayer.Buff, Spell = Look(id) });
report.Buffs.Sort((a, b) => string.Compare(a.Spell.Name, b.Spell.Name, StringComparison.OrdinalIgnoreCase));
all.AddRange(report.Buffs);
report.SpellSources = all.Count;
report.UnknownSpells = unknown.Count;
report.Rows = BuildRows(all);
report.Protection = Protection(all);
report.Paragon = all.Where(IsParagonSource)
.OrderByDescending(s => s.Spell.Power).ThenBy(s => s.Spell.Name, StringComparer.OrdinalIgnoreCase).ToList();
return report;
}
/// <summary>Spells cast on an item are per item (each piece is its own target); the rest land on the character.</summary>
private static bool ItemScoped(SpellSource s) =>
s.Spell.ItemTarget && s.ItemId != 0 && (s.Layer == SpellLayer.Inscribed || s.Layer == SpellLayer.OnItem);
/// <summary>A family key that keeps spells with no known family apart (each its own row).</summary>
private static long FamilyKey(SpellMeta m) => m.Category != 0 ? m.Category : (1L << 32) | m.Id;
internal static List<OverlapRow> BuildRows(List<SpellSource> sources)
{
var rows = new List<OverlapRow>();
foreach (var g in sources.GroupBy(s => (Family: FamilyKey(s.Spell), Item: ItemScoped(s) ? s.ItemId : 0u)))
rows.Add(MakeRow(g.ToList(), g.Key.Item != 0));
return rows
.OrderBy(r => (int)r.Kind)
.ThenBy(r => r.Family, StringComparer.OrdinalIgnoreCase)
.ThenBy(r => r.Scope, StringComparer.OrdinalIgnoreCase)
.ToList();
}
private static OverlapRow MakeRow(List<SpellSource> group, bool itemScope)
{
var ordered = group.OrderByDescending(s => s.Spell.Power).ThenBy(s => s.Spell.Id)
.ThenBy(s => s.ItemName, StringComparer.OrdinalIgnoreCase).ToList();
SpellSource winner = ordered[0];
int distinctSpells = group.Select(s => s.Spell.Id).Distinct().Count();
// The same spell on two pieces (a worn cantrip also shows as the character's buff: that one
// doesn't count, it is the same copy).
int itemsWithWinner = group.Where(s => s.Spell.Id == winner.Spell.Id && s.Layer != SpellLayer.Buff)
.Select(s => s.Layer == SpellLayer.SetBonus ? 0x8000_0000u | (uint)s.SetId : s.ItemId)
.Distinct().Count();
bool exclusive = group.All(s => s.Spell.Enchantment);
OverlapKind kind = distinctSpells > 1
? (exclusive ? OverlapKind.Overlap : OverlapKind.Stacks)
: (itemsWithWinner > 1 && exclusive ? OverlapKind.Duplicate : OverlapKind.Ok);
return new OverlapRow
{
Kind = kind,
Category = winner.Spell.Category,
Family = GearNames.FamilyLabel(winner.Spell.Category),
Scope = itemScope ? winner.ItemName : "",
Winner = winner,
Sources = ordered,
Summary = Summary(ordered, winner, kind),
};
}
private static string Summary(List<SpellSource> ordered, SpellSource winner, OverlapKind kind)
{
var sb = new StringBuilder();
bool winnerCopySeen = false;
foreach (SpellSource s in ordered)
{
if (sb.Length > 0) sb.Append("; ");
sb.Append(Cut(s.ItemName, 18)).Append('/').Append(LayerShort(s.Layer)).Append("/P").Append(s.Spell.Power.ToString(CultureInfo.InvariantCulture));
if (kind == OverlapKind.Overlap && s.Spell.Id != winner.Spell.Id) sb.Append(" (beat)");
else if (kind == OverlapKind.Duplicate && s.Layer != SpellLayer.Buff)
{
if (winnerCopySeen) sb.Append(" (extra)");
winnerCopySeen = true;
}
}
return sb.ToString();
}
// ── Life wards and banes ─────────────────────────────────────────────────
internal static ProtSummary Protection(IReadOnlyList<SpellSource> sources) => new()
{
Life = LifeWards.Select(s => ProtSlot(s.Element, s.Category, sources, life: true)).ToList(),
Crit = CritBanes.Select(s => ProtSlot(s.Element, s.Category, sources, life: false)).ToList(),
};
private static ProtRow ProtSlot(string element, uint category, IReadOnlyList<SpellSource> sources, bool life)
{
var mine = sources.Where(s => InSlot(s, element, category, life)).ToList();
if (mine.Count == 0) return new ProtRow { Element = element, Category = category, Tier = ProtTier.Missing, Winner = "MISSING" };
var distinct = mine.GroupBy(s => s.Spell.Id).Select(g => g.First())
.OrderByDescending(s => (int)TierOf(s.Spell.Name)).ThenByDescending(s => s.Spell.Power).ThenByDescending(s => s.Spell.Id)
.ToList();
SpellSource winner = distinct[0];
ProtTier tier = TierOf(winner.Spell.Name);
var beaten = distinct.Skip(1).Select(s => Cut(s.Spell.Name, 20)).ToList();
return new ProtRow
{
Element = element,
Category = category,
Tier = tier,
Winner = winner.Spell.Name,
Source = winner.Layer == SpellLayer.SetBonus ? winner.ItemName + " [set]" : winner.ItemName,
Beaten = beaten.Count == 0 ? "" : string.Join(", ", beaten.Take(3)) + (beaten.Count > 3 ? "..." : ""),
};
}
/// <summary>
/// A source fills a ward slot (on the character) or a bane slot (on an item) by its family; a spell
/// the tables don't know is placed by its name ("... Fire Ward", "... Flame Bane").
/// </summary>
private static bool InSlot(SpellSource s, string element, uint category, bool life)
{
if (s.Spell.Known && s.Spell.Category != 0)
return s.Spell.Category == category && s.Spell.ItemTarget != life;
string n = s.Spell.Name;
if (n.IndexOf(life ? " Ward" : " Bane", StringComparison.OrdinalIgnoreCase) < 0) return false;
foreach (string word in ElementWords(element))
if (n.IndexOf(word, StringComparison.OrdinalIgnoreCase) >= 0) return true;
return false;
}
private static string[] ElementWords(string element) => element switch
{
"Slashing" => new[] { "Slashing" },
"Piercing" => new[] { "Piercing" },
"Bludgeon" => new[] { "Bludgeon" },
"Fire" => new[] { "Fire", "Flame" },
"Cold" => new[] { "Cold", "Frost" },
"Acid" => new[] { "Acid" },
"Storm" => new[] { "Storm", "Lightning", "Electric" },
_ => Array.Empty<string>(),
};
/// <summary>A ward or bane's tier from its name ("Legendary ...", "Epic ...").</summary>
public static ProtTier TierOf(string name)
{
if (name.StartsWith("Legendary", StringComparison.OrdinalIgnoreCase)) return ProtTier.Legendary;
if (name.StartsWith("Epic", StringComparison.OrdinalIgnoreCase)) return ProtTier.Epic;
if (name.StartsWith("Major", StringComparison.OrdinalIgnoreCase)) return ProtTier.Major;
if (name.StartsWith("Minor", StringComparison.OrdinalIgnoreCase)) return ProtTier.Minor;
return ProtTier.Lower;
}
public static string TierLabel(ProtTier tier) => tier switch
{
ProtTier.Legendary => "Legendary",
ProtTier.Epic => "Epic",
ProtTier.Major => "Major",
ProtTier.Minor => "Minor",
ProtTier.Lower => "Other",
_ => "MISSING",
};
// ── Equipment sets ───────────────────────────────────────────────────────
/// <summary>
/// The worn pieces grouped by set, as ACE's GetSpellSet: a leveled set's level is the sum of its
/// pieces' item levels, any other set's the number of pieces worn; the set's spells for that level.
/// </summary>
internal static List<SetBonusGroup> SetBonuses(IReadOnlyList<GearPiece> equipped, Func<int, SpellSetDef?> setOf, Func<uint, SpellMeta> look)
{
var groups = new List<SetBonusGroup>();
foreach (var bySet in equipped.Where(p => p.SetId > 0).GroupBy(p => p.SetId))
{
SpellSetDef? def = setOf(bySet.Key);
if (def == null) continue;
var pieces = bySet.ToList();
bool leveled = pieces[0].XpStyle > 0;
int level = leveled ? pieces.Sum(p => p.Level) : pieces.Count;
uint tier = def.TierAt((uint)Math.Max(0, level));
uint[] spells = def.SpellsAt((uint)Math.Max(0, level));
if (spells.Length == 0) continue;
string name = GearNames.SetName(bySet.Key);
string label = leveled ? $"{name} ({pieces.Count} pc, level {level})" : $"{name} ({pieces.Count} pc)";
var g = new SetBonusGroup
{
SetId = bySet.Key,
Name = name,
Pieces = pieces.Count,
Level = level,
Tier = tier,
LeveledSet = leveled,
Label = label,
PieceNames = string.Join(", ", pieces.Select(p => p.Name).OrderBy(n => n, StringComparer.OrdinalIgnoreCase)),
};
foreach (uint id in spells.Where(id => id != 0).Distinct())
g.Spells.Add(new SpellSource { ItemName = label, Layer = SpellLayer.SetBonus, Spell = look(id), SetId = bySet.Key });
groups.Add(g);
}
groups.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
return groups;
}
public static bool IsParagonSet(int setId) => setId >= ParagonSetFirst && setId <= ParagonSetLast;
/// <summary>A paragon mastery spell (family "Paragon...") or a paragon set's bonus.</summary>
private static bool IsParagonSource(SpellSource s) =>
GearNames.FamilyRaw(s.Spell.Category).StartsWith("Paragon", StringComparison.Ordinal)
|| (s.Layer == SpellLayer.SetBonus && IsParagonSet(s.SetId));
// ── Ratings (sets, levels, gear ratings) ─────────────────────────────────
/// <summary>
/// Every wearable, worn first, each with its Mag-style line; the ones with a set, an item level,
/// gear ratings or T11 modifiers marked <see cref="RatingRow.Rated"/>; and the ratings summed over
/// what is worn. UB-ILT's Paragon gear view, without the server's paragon gate: paragon items are
/// marked where they exist. <paramref name="lookup"/> names the spells in the Mag-style lines.
/// </summary>
public static RatingsReport Ratings(IReadOnlyList<GearPiece> items, bool includePack, DateTime nowLocal, Func<uint, SpellMeta>? lookup = null)
{
var report = new RatingsReport { CheckedLocal = nowLocal, IncludePack = includePack };
foreach (GearPiece p in items)
{
if (!includePack && !p.Equipped) continue;
bool rated = p.SetId > 0 || p.Ratings.Length > 0 || p.Modifiers.Length > 0 || (p.MaxLevel > 0 && (p.ItemType & ItemWearables) != 0);
if (!rated && (p.ItemType & ItemWearables) == 0) continue;
string category = CategoryOf(p.ItemType);
string element = (p.ItemType & ItemWeapons) != 0 ? ElementShort(p.DamageType) : "";
var effective = EffectiveRatings(p);
report.Rows.Add(new RatingRow
{
Piece = p,
Rated = rated,
Mag = MagFormat.Describe(p, lookup, effective),
Category = category,
TypeLabel = element.Length > 0 ? category + " " + element : category,
SetName = GearNames.SetName(p.SetId),
Paragon = IsParagonSet(p.SetId) || ((p.ItemType & ItemWeapons) != 0 && p.MaxLevel > 0 && p.BaseXp >= ParagonWeaponBaseXp),
Effective = effective,
Stats = string.Join(", ", effective.Select(r => RatingLong(r.Prop) + " " + r.Value.ToString(CultureInfo.InvariantCulture))),
T11 = string.Join(", ", p.Modifiers.Select(m => m.Text)),
});
}
report.Rows = report.Rows
.OrderByDescending(r => r.Piece.Equipped)
.ThenBy(r => r.Category, StringComparer.OrdinalIgnoreCase)
.ThenBy(r => r.Piece.Name, StringComparer.OrdinalIgnoreCase)
.ToList();
var totals = new Dictionary<int, int>();
foreach (GearPiece p in items.Where(p => p.Equipped))
foreach (var (prop, value) in EffectiveRatings(p))
totals[prop] = totals.TryGetValue(prop, out int t) ? t + value : value;
foreach (var (prop, _, _) in RatingProps)
if (totals.TryGetValue(prop, out int v) && v != 0) report.WornTotals.Add((prop, v));
report.T11Totals = T11Totals(items.Where(p => p.Equipped));
return report;
}
/// <summary>
/// A piece's ratings with its T11 rating lines folded in. A line's rating is only added where
/// the appraisal didn't send that rating: on T11 gear the server removes it (it shows under
/// Modifiers instead); on older pieces it sends both, and the sent value already holds it.
/// </summary>
public static (int Prop, int Value)[] EffectiveRatings(GearPiece p)
{
if (p.Modifiers.Length == 0) return p.Ratings;
var list = p.Ratings.ToList();
foreach (GearModifier m in p.Modifiers)
{
if (m.RatingProp == 0 || !m.HasValue || m.Value == 0) continue;
int at = list.FindIndex(r => r.Prop == m.RatingProp);
if (at < 0) list.Add((m.RatingProp, m.Value));
else if (p.Ratings.All(r => r.Prop != m.RatingProp)) list[at] = (m.RatingProp, list[at].Value + m.Value); // two lines of one rating
}
return list.OrderBy(r => Array.FindIndex(RatingProps, x => x.Prop == r.Prop)).ToArray();
}
/// <summary>
/// The worn T11 modifiers that aren't ratings, by name: summed across pieces (All Attributes,
/// Max Health Pct, Life on Hit), the slot specials the highest single one, and a line with no
/// number (Battle Mending, Cheat Death) as "yes".
/// </summary>
internal static List<(string Name, string Value)> T11Totals(IEnumerable<GearPiece> worn)
{
var sums = new Dictionary<string, (int Value, bool HasValue, string Suffix)>(StringComparer.OrdinalIgnoreCase);
var order = new List<string>();
foreach (GearPiece p in worn)
foreach (GearModifier m in p.Modifiers)
{
if (m.RatingProp != 0 || T11Modifiers.PerPiece.Contains(m.Name)) continue;
string suffix = m.Text.Contains('%') ? "%" : "";
if (!sums.TryGetValue(m.Name, out var cur))
{
sums[m.Name] = (m.Value, m.HasValue, suffix);
order.Add(m.Name);
continue;
}
int next = T11Modifiers.MaxWins.Contains(m.Name) ? Math.Max(cur.Value, m.Value) : cur.Value + m.Value;
sums[m.Name] = (next, cur.HasValue || m.HasValue, cur.Suffix);
}
var list = new List<(string, string)>();
foreach (string name in order)
{
var (value, has, suffix) = sums[name];
string best = T11Modifiers.MaxWins.Contains(name) ? " (best)" : "";
string shown = !has ? "yes"
// Its number is tenths of a percent of the target's maximum health.
: name.Equals("Pct HP Damage", StringComparison.OrdinalIgnoreCase)
? (value / 10.0).ToString("0.#", CultureInfo.InvariantCulture) + "% of max HP per hit" + best
: (value >= 0 ? "+" : "") + value.ToString(CultureInfo.InvariantCulture) + suffix + best;
list.Add((name, shown));
}
return list;
}
public static string RatingShort(int prop)
{
foreach (var r in RatingProps) if (r.Prop == prop) return r.Short;
return prop.ToString(CultureInfo.InvariantCulture);
}
public static string RatingLong(int prop)
{
foreach (var r in RatingProps) if (r.Prop == prop) return r.Long;
return "Rating " + prop.ToString(CultureInfo.InvariantCulture);
}
public static string CategoryOf(uint itemType)
{
if ((itemType & ItemWeapons) != 0) return "Weapon";
if ((itemType & ItemArmor) != 0) return "Armor";
if ((itemType & ItemJewelry) != 0) return "Jewelry";
if ((itemType & ItemClothing) != 0) return "Clothing";
return "Other";
}
/// <summary>A weapon's element, short (PropertyInt.DamageType flags; Nether wins where it is set).</summary>
public static string ElementShort(int damageType)
{
if ((damageType & 0x400) != 0) return "Neth";
return damageType switch
{
0 => "",
0x1 => "Slash",
0x2 => "Pierce",
0x3 => "Sl+Pi",
0x4 => "Bludg",
0x8 => "Cold",
0x10 => "Fire",
0x20 => "Acid",
0x40 => "Storm",
_ => "0x" + damageType.ToString("X", CultureInfo.InvariantCulture),
};
}
private static string Cut(string s, int max) => s.Length <= max ? s : s.Substring(0, Math.Max(0, max - 3)) + "...";
}

View file

@ -0,0 +1,111 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>
/// Names for the numbers the Gear tab reads: spell families (portal.dat SpellBase.Category, ACE
/// SpellCategory) and equipment sets (PropertyInt.EquipmentSetId 265, ACE EquipmentSet), from
/// Resources\spellcategories.csv and equipmentsets.csv (Tools\RynthOracle.QuestPackGen\Make-GearNames.ps1).
/// A number missing from a table still shows ("Family 812", "Set 301").
/// </summary>
internal static class GearNames
{
private static Dictionary<int, string>? _families, _sets, _materials, _masteries, _skills;
/// <summary>A material ("Black Garnet") by PropertyInt.MaterialType (131); "" when unknown or none.</summary>
public static string Material(int id) => Named(ref _materials, "materials.csv", id);
/// <summary>A weapon mastery ("Two Handed") by PropertyInt.WeaponType (353); "" when unknown or none.</summary>
public static string Mastery(int id) => Named(ref _masteries, "masteries.csv", id);
/// <summary>A skill ("Melee Defense") by its number; "" when unknown.</summary>
public static string Skill(int id) => Named(ref _skills, "skills.csv", id);
private static string Named(ref Dictionary<int, string>? table, string file, int id)
{
if (id <= 0) return "";
table ??= Load(file);
return table.TryGetValue(id, out string? n) ? Pretty(n) : "";
}
/// <summary>ACE's name for a spell family ("SlashWardProtection"), or "".</summary>
public static string FamilyRaw(uint category)
{
_families ??= Load("spellcategories.csv");
return _families.TryGetValue((int)category, out string? n) ? n : "";
}
/// <summary>
/// A family for a narrow column: "Slash Ward", "Extra Fire Resistance" as "Fire Resistance",
/// "Strength" for StrengthRaising (UB-ILT's FormatSpellFamilyShort, with the spaces put in).
/// </summary>
public static string FamilyLabel(uint category)
{
if (category == 0) return "?"; // no family known (ACE's 0 is "Undef")
string fam = FamilyRaw(category);
if (fam.Length == 0) return "Family " + category.ToString(CultureInfo.InvariantCulture);
if (fam.EndsWith("Protection", StringComparison.Ordinal) && fam.Length > "Protection".Length)
fam = fam[..^"Protection".Length];
else if (fam.StartsWith("Extra", StringComparison.Ordinal) && fam.EndsWith("ResistanceRaising", StringComparison.Ordinal)
&& fam.Length > "Extra".Length + "ResistanceRaising".Length)
fam = fam["Extra".Length..^"Raising".Length];
else if (fam.EndsWith("Raising", StringComparison.Ordinal) && fam.Length > "Raising".Length)
fam = fam[..^"Raising".Length];
return Pretty(fam);
}
/// <summary>An equipment set's name ("Shimmering Shadows Set", "Paragon Melee"); "-" for none.</summary>
public static string SetName(int setId)
{
if (setId <= 0) return "-";
_sets ??= Load("equipmentsets.csv");
return _sets.TryGetValue(setId, out string? n) ? Pretty(n) : "Set " + setId.ToString(CultureInfo.InvariantCulture);
}
/// <summary>CamelCase to words: "ShimmeringShadowsSet" as "Shimmering Shadows Set", "PKDamage" as "PK Damage".</summary>
public static string Pretty(string camel)
{
if (string.IsNullOrEmpty(camel)) return "";
var sb = new StringBuilder(camel.Length + 8);
for (int i = 0; i < camel.Length; i++)
{
char c = camel[i];
if (i > 0 && c != '_')
{
char p = camel[i - 1];
bool next = i + 1 < camel.Length && char.IsLower(camel[i + 1]);
// A capital after a lower-case letter or a digit, or the last capital of a run before lower case.
if (char.IsUpper(c) && (char.IsLower(p) || char.IsDigit(p) || (char.IsUpper(p) && next))) sb.Append(' ');
else if (char.IsDigit(c) && char.IsLetter(p)) sb.Append(' ');
}
sb.Append(c == '_' ? ' ' : c);
}
return sb.ToString();
}
private static Dictionary<int, string> Load(string file)
{
var map = new Dictionary<int, string>();
try
{
using StreamReader r = Csv.OpenEmbedded(file);
r.ReadLine(); // header
while (r.ReadLine() is string line)
{
int comma = line.IndexOf(',');
if (comma <= 0) continue;
if (int.TryParse(line.AsSpan(0, comma), NumberStyles.None, CultureInfo.InvariantCulture, out int id))
map[id] = line[(comma + 1)..].Trim();
}
}
catch
{
// A missing table only costs names ("Family 287").
}
return map;
}
}

View file

@ -0,0 +1,328 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>
/// The Gear tab's Check: reads the character's worn items (and, for the Ratings view, the packs),
/// gets each one appraised so its spells and properties are known, waits for the answers and for
/// the client's spell table, then builds the Overlap and Ratings reports. Nothing here is
/// server-specific: the items, their appraisals and the character's enchantments come from the
/// client, the spell facts from its portal.dat. Pump thread only.
/// </summary>
internal sealed class GearScanner
{
public enum Phase { Idle, Identifying, Settling, WaitingForSpells, Done }
/// <summary>One RequestId this often, so a full pack doesn't flood the server.</summary>
private const long IdSpacingMs = 150;
/// <summary>After the last RequestId, how long the answers get to arrive.</summary>
private const long SettleMs = 1500;
/// <summary>An item asked about within this long isn't asked about again (one with no spells never caches a list).</summary>
private const long ReaskMs = 5 * 60_000;
/// <summary>At most this many pack items are asked about in one Check.</summary>
private const int MaxPackIds = 200;
public Phase State { get; private set; } = Phase.Idle;
public GearReport? Overlap { get; private set; }
public RatingsReport? Ratings { get; private set; }
/// <summary>Goes up when the state or a report changes (the window re-records).</summary>
public int Revision { get; private set; }
/// <summary>Why the last Check couldn't run, or "".</summary>
public string Problem { get; private set; } = "";
public int IdsQueued { get; private set; }
public int IdsSent { get; private set; }
/// <summary>The book the reports read spells from (tests put their own in).</summary>
internal PortalSpellBook Book = PortalSpellBook.Shared;
private readonly Queue<uint> _idQueue = new();
private readonly Dictionary<uint, long> _askedAt = new();
private List<uint> _equipped = new();
private List<uint> _pack = new();
private bool _includePack;
private long _nextIdAt, _settleUntil;
private Action<string>? _log;
public bool Busy => State is Phase.Identifying or Phase.Settling or Phase.WaitingForSpells;
/// <summary>Tests: show reports built by hand, as if a Check had just finished.</summary>
internal void UseReports(GearReport? overlap, RatingsReport? ratings)
{
Overlap = overlap;
Ratings = ratings;
State = Phase.Done;
Revision++;
}
/// <summary>Forget everything (logout): the next character starts with no report.</summary>
public void Clear()
{
State = Phase.Idle;
Overlap = null;
Ratings = null;
Problem = "";
_idQueue.Clear();
_askedAt.Clear();
_equipped.Clear();
_pack.Clear();
IdsQueued = IdsSent = 0;
Revision++;
}
/// <summary>
/// Starts a Check: lists the items, queues an appraisal for each one the client hasn't seen
/// appraised (or asked about lately), and starts the spell table read. False with
/// <see cref="Problem"/> set when there is nothing to read from.
/// </summary>
public bool Start(RynthCoreHost host, long now, bool includePack, Action<string>? log = null)
{
_log = log;
_includePack = includePack;
Problem = "";
Book.EnsureLoading(log);
uint player = host.GetPlayerId();
if (player == 0) { Problem = "Log in first."; Revision++; return false; }
_equipped = WornItems(host, player);
_pack = includePack ? PackItems(host, player) : new List<uint>();
if (_equipped.Count == 0 && _pack.Count == 0)
{
Problem = host.HasGetWieldedItems || host.GetLiveObjectIds().Length > 0
? "Nothing worn or wielded was found."
: "This RynthCore engine can't list worn items (it needs engine API 69 or newer).";
State = Phase.Idle;
Revision++;
return false;
}
_idQueue.Clear();
var buf = new uint[1];
int packAsked = 0;
foreach (uint id in _equipped) QueueIfNeeded(host, id, now, buf);
foreach (uint id in _pack)
{
if (packAsked >= MaxPackIds) break;
if (QueueIfNeeded(host, id, now, buf)) packAsked++;
}
IdsQueued = _idQueue.Count;
IdsSent = 0;
_nextIdAt = now;
State = _idQueue.Count > 0 ? Phase.Identifying : Phase.WaitingForSpells;
_settleUntil = now;
Revision++;
return true;
}
private bool QueueIfNeeded(RynthCoreHost host, uint id, long now, uint[] buf)
{
if (host.GetObjectSpellIds(id, buf, buf.Length) >= 0) return false; // already appraised this session
if (_askedAt.TryGetValue(id, out long at) && now - at < ReaskMs) return false;
_idQueue.Enqueue(id);
return true;
}
/// <summary>Moves the Check along; true when something the tab shows changed.</summary>
public bool Tick(RynthCoreHost host, long now, string characterName)
{
switch (State)
{
case Phase.Identifying:
if (now < _nextIdAt) return false;
if (_idQueue.Count > 0)
{
uint id = _idQueue.Dequeue();
if (host.HasRequestId) host.RequestId(id);
_askedAt[id] = now;
IdsSent++;
_nextIdAt = now + IdSpacingMs;
Revision++;
return true;
}
State = Phase.Settling;
_settleUntil = now + SettleMs;
Revision++;
return true;
case Phase.Settling:
if (now < _settleUntil) return false;
State = Phase.WaitingForSpells;
Revision++;
return true;
case Phase.WaitingForSpells:
if (!Book.Done) return false;
Build(host, now, characterName);
State = Phase.Done;
Revision++;
return true;
default:
return false;
}
}
private void Build(RynthCoreHost host, long now, string characterName)
{
var worn = new List<GearPiece>();
var all = new List<GearPiece>();
var seen = new HashSet<uint>();
var locations = new Dictionary<uint, uint>();
if (host.TryGetWieldedItems(out var wielded))
foreach (var (id, loc) in wielded) locations[id] = loc;
foreach (uint id in _equipped)
{
if (!seen.Add(id)) continue;
GearPiece p = Read(host, id, now, equipped: true, locations.TryGetValue(id, out uint l) ? l : 0);
worn.Add(p);
all.Add(p);
}
foreach (uint id in _pack)
if (seen.Add(id)) all.Add(Read(host, id, now, equipped: false, 0));
uint[] buffs = PlayerBuffs(host);
DateTime local = DateTime.Now;
Overlap = GearAnalysis.Analyze(worn, buffs, Lookup, SetOf, characterName, local);
Ratings = GearAnalysis.Ratings(all, _includePack, local, Lookup);
_log?.Invoke($"[RynthOracle] Gear check: {worn.Count} worn, {Overlap.SpellSources} spells, "
+ $"{Overlap.Count(OverlapKind.Overlap)} overlap, {Overlap.Count(OverlapKind.Duplicate)} duplicate; "
+ $"{Ratings.RatedRows.Count()} rated item(s), {Ratings.T11Rows} with T11 modifiers; spells from {(Book.HasDat ? "portal.dat" : "SpellData.txt (" + Book.Status + ")")}.");
}
/// <summary>The spell facts: the client's spell table, else SpellData.txt, else only the id.</summary>
internal SpellMeta Lookup(uint id)
{
if (Book.TryGet(id, out PortalSpell s))
return new SpellMeta(id, s.Name, s.Category, s.Power, s.IsEnchantment, s.IsItemTarget, true);
if (SpellTable.TryGet(id, out SpellInfo info))
{
uint cat = (uint)Math.Max(0, info.Category);
return new SpellMeta(id, info.Name, cat, (uint)Math.Max(0, info.Power), true, ItemFamilyGuess(cat), true);
}
return SpellMeta.Unknown(id);
}
private SpellSetDef? SetOf(int setId) => Book.TryGetSet((uint)setId, out SpellSetDef d) ? d : null;
/// <summary>
/// Without portal.dat there is no target type: the families cast on items (weapon buffs, armour,
/// banes) by name, so their per-item rows still form.
/// </summary>
private static bool ItemFamilyGuess(uint category)
{
string fam = GearNames.FamilyRaw(category);
if (fam.StartsWith("Extra", StringComparison.Ordinal) && fam.Contains("ResistanceRaising", StringComparison.Ordinal)) return true;
return fam.StartsWith("DamageRaising", StringComparison.Ordinal) || fam.StartsWith("AttackModRaising", StringComparison.Ordinal)
|| fam.StartsWith("DefenseModRaising", StringComparison.Ordinal) || fam.StartsWith("WeaponTimeRaising", StringComparison.Ordinal)
|| fam.StartsWith("ManaConversionModRaising", StringComparison.Ordinal) || fam.StartsWith("SpellDamageRaising", StringComparison.Ordinal)
|| fam.StartsWith("ArmorValueRaising", StringComparison.Ordinal);
}
private GearPiece Read(RynthCoreHost host, uint id, long now, bool equipped, uint location)
{
var p = new GearPiece { Id = id, Equipped = equipped, Location = location };
p.Name = host.TryGetObjectName(id, out string name) && name.Length > 0 ? name : $"Item 0x{id:X8}";
if (host.TryGetItemType(id, out uint type)) p.ItemType = type;
var buf = new uint[128];
int n = host.GetObjectSpellIds(id, buf, buf.Length);
// No cached list: never appraised, or appraised with no spells (the engine keeps no empty list).
p.Appraised = n >= 0 || (_askedAt.TryGetValue(id, out long at) && now - at >= SettleMs);
if (n > 0)
{
var inscribed = new List<uint>();
var onItem = new List<uint>();
for (int i = 0; i < Math.Min(n, buf.Length); i++)
{
uint raw = buf[i];
if (raw == 0) continue;
if ((raw & 0x8000_0000u) != 0) onItem.Add(raw & 0x7FFF_FFFFu);
else inscribed.Add(raw);
}
p.Inscribed = inscribed.ToArray();
p.OnItem = onItem.ToArray();
}
p.SetId = Int(host, id, 265);
p.MaxLevel = Int(host, id, 319);
p.XpStyle = Int(host, id, 320);
p.DamageType = Int(host, id, 45);
p.BaseXp = host.TryGetObjectQuadProperty(id, 5, out long b) ? b : 0;
p.TotalXp = host.TryGetObjectQuadProperty(id, 4, out long t) ? t : 0;
var ratings = new List<(int, int)>();
foreach (var (prop, _, _) in GearAnalysis.RatingProps)
{
int v = Int(host, id, (uint)prop);
if (v != 0) ratings.Add((prop, v));
}
p.Ratings = ratings.ToArray();
// T11 modifier lines: the appraisal's "Modifiers:" section, in the Use text (14) on armour
// and jewelry, in the long description (16) on weapons.
string use = host.TryGetObjectStringProperty(id, 14, out string u) ? u : "";
string longDesc = host.TryGetObjectStringProperty(id, 16, out string d) ? d : "";
(p.Modifiers, p.ZoneLocked) = T11Modifiers.Parse(use, longDesc);
// The Mag-style line's properties (only the ones the appraisal has).
foreach (int prop in MagFormat.IntProps)
if (host.TryGetObjectIntProperty(id, (uint)prop, out int iv)) p.Ints[prop] = iv;
foreach (int prop in MagFormat.FloatProps)
if (host.TryGetObjectDoubleProperty(id, (uint)prop, out double fv)) p.Floats[prop] = fv;
return p;
}
private static int Int(RynthCoreHost host, uint id, uint stype) =>
host.TryGetObjectIntProperty(id, stype, out int v) ? v : 0;
/// <summary>
/// What the character wears and wields: the engine's equipment record (API 87), else every
/// object the client knows whose wielder is the character.
/// </summary>
private static List<uint> WornItems(RynthCoreHost host, uint player)
{
var list = new List<uint>();
if (host.TryGetWieldedItems(out var items))
{
foreach (var (id, _) in items) if (id != 0 && !list.Contains(id)) list.Add(id);
if (list.Count > 0) return list;
}
foreach (uint id in host.GetLiveObjectIds())
if (host.TryGetObjectWielderInfo(id, out uint wielder, out uint loc) && wielder == player && loc != 0 && !list.Contains(id))
list.Add(id);
return list;
}
/// <summary>The wearables in the main pack and the packs inside it (one level, as AC nests them).</summary>
private static List<uint> PackItems(RynthCoreHost host, uint player)
{
var list = new List<uint>();
var buf = new uint[512];
var packs = new List<uint>();
int n = host.GetContainerContents(player, buf);
for (int i = 0; i < n; i++) Consider(host, buf[i], list, packs);
foreach (uint pack in packs)
{
int m = host.GetContainerContents(pack, buf);
for (int i = 0; i < m; i++) Consider(host, buf[i], list, null);
}
return list;
}
private static void Consider(RynthCoreHost host, uint id, List<uint> items, List<uint>? packs)
{
if (id == 0 || !host.TryGetItemType(id, out uint type)) return;
if ((type & GearAnalysis.ItemContainer) != 0) { packs?.Add(id); return; }
if ((type & GearAnalysis.ItemWearables) != 0 && !items.Contains(id)) items.Add(id);
}
/// <summary>The character's enchantments by spell id (life wards, buffs, worn items' cantrips).</summary>
private static uint[] PlayerBuffs(RynthCoreHost host)
{
var ids = new uint[256];
var exp = new double[256];
int n = host.ReadPlayerEnchantments(ids, exp, ids.Length);
if (n <= 0) return Array.Empty<uint>();
var list = new List<uint>(n);
for (int i = 0; i < Math.Min(n, ids.Length); i++) if (ids[i] != 0) list.Add(ids[i]);
return list.ToArray();
}
}

View file

@ -0,0 +1,72 @@
using System;
namespace RynthCore.Plugin.RynthOracle.Data;
// Where a guide quest stands, in four states (2026-11-22, Silentkelpie: "on all the quest, society, contracts tabs it
// should flag 4 states, quest fully done (no extra flags still needed), quest partially done (stamps to still get) redo
// timer not up, quest partially done (stamps to still get) timer up, or quest not done (no stamps done)"), and whether a
// kill task was done before ("the kill task tab should flag if the kill task has been done before or if it is the 1st
// time"). On every server, for every guide (the server's wiki, the AC Community Wiki, a server plugin's).
// A stamp counts as held when the character has it in /myquests (any run), the account's /qb list names it, or it was
// stamped this session. The timer is the redo timer of the stamps held: the longest wait left on any of them.
internal enum GuideProgressState
{
/// <summary>No stamp of the quest held.</summary>
NotDone,
/// <summary>Some stamps held, some still to get, and the held ones' redo timer is still running.</summary>
PartialWaiting,
/// <summary>Some stamps held, some still to get, and the held ones' redo timer is up (or there is none).</summary>
PartialReady,
/// <summary>Every stamp held: no flag still needed.</summary>
Done,
}
internal static class GuideProgress
{
/// <summary>The state from the stamps held of all and the held stamps' redo wait.</summary>
public static GuideProgressState Of(int held, int all, TimeSpan wait)
{
if (all <= 0 || held <= 0) return GuideProgressState.NotDone;
if (held >= all) return GuideProgressState.Done;
return wait > TimeSpan.Zero ? GuideProgressState.PartialWaiting : GuideProgressState.PartialReady;
}
/// <summary>
/// The list's short status (it has about 14 letters of room) and the tooltip's sentence. <paramref name="repeats"/>:
/// the quest can be done again (a timer on the wiki or the server).
/// </summary>
public static (string Status, string Tip) Text(GuideProgressState s, int held, int all, TimeSpan wait, bool repeats)
{
switch (s)
{
case GuideProgressState.Done:
if (wait > TimeSpan.Zero)
return ("Done " + Short(wait), $"Fully done: all {all} stamps held. It can be done again in {Short(wait)}.");
return repeats
? ("Done, redo", $"Fully done: all {all} stamps held. Its timer is up: it can be done again now.")
: ("Done", all > 0 ? $"Fully done: all {all} stamps held, nothing still needed." : "Fully done.");
case GuideProgressState.PartialWaiting:
return ($"{held}/{all} wait {Short(wait)}",
$"Partly done: {held} of {all} stamps held, {all - held} still to get. The redo timer isn't up: {Short(wait)} left.");
case GuideProgressState.PartialReady:
return ($"{held}/{all} ready",
$"Partly done: {held} of {all} stamps held, {all - held} still to get. The redo timer is up: go get them.");
default:
return ("Not done", all > 0 ? $"Not done: none of its {all} stamps held yet." : "Not done.");
}
}
/// <summary>"3d 4h", "5h", "9m" (short: the list's status column is narrow).</summary>
public static string Short(TimeSpan t)
{
if (t.TotalDays >= 1) return $"{(int)t.TotalDays}d{(t.Hours > 0 ? " " + t.Hours + "h" : "")}";
if (t.TotalHours >= 1) return $"{(int)t.TotalHours}h{(t.Minutes > 0 ? " " + t.Minutes + "m" : "")}";
return $"{Math.Max(1, (int)Math.Ceiling(t.TotalMinutes))}m";
}
/// <summary>The kill task tag: done before ("Again") or the first time ("1st").</summary>
public static (string Tag, string Tip) KillTag(bool doneBefore) => doneBefore
? ("Again", "Done before: a stamp or flag of this kill task is held (this character's /myquests, or the account's /qb list).")
: ("1st", "First time: no stamp or flag of this kill task held yet.");
}

View file

@ -0,0 +1,332 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.Json;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>One Leaftide feature from RynthILT's profile: its state on this server and where it lives.</summary>
internal sealed record IltFeature(string Key, string Label, string Group, int State, string Where);
/// <summary>One QB Deeds tier as RynthILT's last /deeds list gave it (its reward lines as the server printed them).</summary>
internal sealed record IltDeedTier(int Number, long Qb, bool Unlocked, IReadOnlyList<string> Rewards);
/// <summary>
/// ACECustom's QB Deeds as RynthILT last read them (the profile's "deeds" object, RynthILT 2026-11-21): the account QB,
/// Deeds on or off (null unknown), the tiers unlocked, the next tier's QB (0 at the top) and every tier's rewards.
/// </summary>
internal sealed record IltDeedsInfo(bool Loaded, bool Unsupported, bool Busy, long Qb, bool? On, int Unlocked, long NextAt,
string Status, DateTime LoadedUtc, IReadOnlyList<IltDeedTier> Tiers);
/// <summary>
/// The ACECustom quest bonus list ("/qb list") as RynthILT last read it (the profile's "questBonus"
/// object). <see cref="Generation"/> 0 = not loaded this session; <see cref="Count"/> -1 = unknown.
/// <see cref="CompletedCount"/> / <see cref="IncompleteCount"/> are the list sizes RynthILT reports
/// (-1 = an older RynthILT that sent the lists inline); from RynthILT 0.2.22 the lists themselves
/// arrive separately (<see cref="IltServerLink.QuestBonus"/>).
/// </summary>
internal sealed record IltQuestBonusList(bool Disabled, int Generation, long Count, string Status,
IReadOnlyList<string> Completed, IReadOnlyList<string> Incomplete,
int CompletedCount = -1, int IncompleteCount = -1)
{
/// <summary>The profile names flags whose lists it didn't carry: they come from GetQuestBonusJson.</summary>
public bool ListsElsewhere => Completed.Count == 0 && Incomplete.Count == 0 && CompletedCount + IncompleteCount > 0;
}
/// <summary>
/// What RynthILT reports about the Infinite Leaftide server (the "RynthILT.Server" profile JSON,
/// Plugins/Shared/RynthIltServerApi.cs): whether this is an ILT world, the Leaftide features with
/// their server state, and the fellowship rules. <see cref="None"/> without RynthILT; every field is
/// read leniently so an older or newer RynthILT still parses.
/// </summary>
internal sealed class IltServerProfile
{
/// <summary>No RynthILT (or nothing parsed): a retail fellowship and no features.</summary>
public static readonly IltServerProfile None = new();
/// <summary>RynthILT answered with a profile.</summary>
public bool Available { get; private init; }
public bool Ilt { get; private init; }
public string World { get; private init; } = "";
public bool Forced { get; private init; }
public string Source { get; private init; } = "";
/// <summary>Last server-options check (UTC); MinValue = never.</summary>
public DateTime CheckedUtc { get; private init; } = DateTime.MinValue;
public IReadOnlyList<IltFeature> Features { get; private init; } = Array.Empty<IltFeature>();
/// <summary>The server's fellowship size limit (retail 9 without RynthILT or off ILT).</summary>
public int FellowshipMax { get; private init; } = RynthIltServer.RetailFellowshipMax;
/// <summary>Fellowship feature states (RynthIltServer.State*): Zone Share, Fellowship Blackjack, luminance share.</summary>
public int ZoneShare { get; private init; } = RynthIltServer.StateUnknown;
public int Blackjack { get; private init; } = RynthIltServer.StateUnknown;
public int LuminanceShare { get; private init; } = RynthIltServer.StateUnknown;
/// <summary>The /qb list (ILT worlds with RynthILT 0.2.3 or later); null = none offered.</summary>
public IltQuestBonusList? QuestBonus { get; private init; }
/// <summary>QB Deeds (RynthILT from 2026-11-21, ILT worlds); null = none offered.</summary>
public IltDeedsInfo? Deeds { get; private init; }
/// <summary>The features in one group, in RynthILT's order.</summary>
public IEnumerable<IltFeature> InGroup(string group)
{
foreach (IltFeature f in Features)
if (string.Equals(f.Group, group, StringComparison.OrdinalIgnoreCase)) yield return f;
}
/// <summary>Parses the profile JSON; <see cref="None"/> when it is empty or not JSON.</summary>
public static IltServerProfile Parse(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return None;
try
{
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) return None;
var features = new List<IltFeature>();
if (root.TryGetProperty("features", out JsonElement fs) && fs.ValueKind == JsonValueKind.Array)
{
foreach (JsonElement f in fs.EnumerateArray())
{
if (f.ValueKind != JsonValueKind.Object) continue;
string key = Str(f, "key");
if (key.Length == 0) continue;
string label = Str(f, "label");
features.Add(new IltFeature(key, label.Length > 0 ? label : key, Str(f, "group"),
Int(f, "state", RynthIltServer.StateUnknown), Str(f, "where")));
}
}
bool ilt = Bool(root, "ilt");
int max = RynthIltServer.RetailFellowshipMax;
int zone = RynthIltServer.StateUnknown, bj = RynthIltServer.StateUnknown, lum = RynthIltServer.StateUnknown;
if (root.TryGetProperty("fellowship", out JsonElement fel) && fel.ValueKind == JsonValueKind.Object)
{
max = Int(fel, "maxMembers", max);
zone = Int(fel, "zoneShare", zone);
bj = Int(fel, "blackjack", bj);
lum = Int(fel, "luminanceShare", lum);
}
// A bogus size would let the tab claim room nobody has; stay within what the reader handles.
if (max < 1 || max > 64) max = RynthIltServer.RetailFellowshipMax;
DateTime checkedUtc = DateTime.MinValue;
string when = Str(root, "checked");
if (when.Length > 0
&& DateTime.TryParse(when, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t))
checkedUtc = t;
return new IltServerProfile
{
Available = true,
Ilt = ilt,
World = Str(root, "world"),
Forced = Bool(root, "forced"),
Source = Str(root, "source"),
CheckedUtc = checkedUtc,
Features = features,
FellowshipMax = max,
ZoneShare = zone,
Blackjack = bj,
LuminanceShare = lum,
QuestBonus = ParseQuestBonus(root),
Deeds = ParseDeeds(root),
};
}
catch (JsonException)
{
return None;
}
}
/// <summary>The "questBonus" object, or null when the profile has none.</summary>
private static IltQuestBonusList? ParseQuestBonus(JsonElement root)
{
if (!root.TryGetProperty("questBonus", out JsonElement q) || q.ValueKind != JsonValueKind.Object) return null;
long count = q.TryGetProperty("count", out JsonElement c) && c.ValueKind == JsonValueKind.Number && c.TryGetInt64(out long n) ? n : -1;
return new IltQuestBonusList(Bool(q, "disabled"), Int(q, "generation", 0), count, Str(q, "status"),
Strings(q, "completed"), Strings(q, "incomplete"),
Int(q, "completedCount", -1), Int(q, "incompleteCount", -1));
}
/// <summary>The "deeds" object, or null when the profile has none.</summary>
private static IltDeedsInfo? ParseDeeds(JsonElement root)
{
if (!root.TryGetProperty("deeds", out JsonElement d) || d.ValueKind != JsonValueKind.Object) return null;
var tiers = new List<IltDeedTier>();
if (d.TryGetProperty("tiers", out JsonElement a) && a.ValueKind == JsonValueKind.Array)
foreach (JsonElement t in a.EnumerateArray())
if (t.ValueKind == JsonValueKind.Object)
tiers.Add(new IltDeedTier(Int(t, "n", 0), Long(t, "qb", 0), Bool(t, "unlocked"), Strings(t, "rewards")));
bool? on = d.TryGetProperty("on", out JsonElement o) ? o.ValueKind == JsonValueKind.True ? true : o.ValueKind == JsonValueKind.False ? false : null : null;
DateTime at = DateTime.TryParse(Str(d, "loadedUtc"), System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AdjustToUniversal | System.Globalization.DateTimeStyles.AssumeUniversal, out DateTime p) ? p : DateTime.MinValue;
return new IltDeedsInfo(Bool(d, "loaded"), Bool(d, "unsupported"), Bool(d, "busy"), Long(d, "qb", -1), on,
Int(d, "unlocked", 0), Long(d, "nextAt", 0), Str(d, "status"), at, tiers);
}
private static long Long(JsonElement o, string name, long fallback) =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long l) ? l : fallback;
private static string[] Strings(JsonElement o, string name)
{
if (!o.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) return Array.Empty<string>();
var list = new List<string>(a.GetArrayLength());
foreach (JsonElement e in a.EnumerateArray())
if (e.ValueKind == JsonValueKind.String && e.GetString() is { Length: > 0 } s) list.Add(s);
return list.ToArray();
}
/// <summary>"on", "off" or "checking" for a feature state.</summary>
public static string StateText(int state) => state switch
{
RynthIltServer.StateOn => "on",
RynthIltServer.StateOff => "off",
_ => "checking",
};
private static string Str(JsonElement o, string name) =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
private static bool Bool(JsonElement o, string name) =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True;
private static int Int(JsonElement o, string name, int fallback) =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : fallback;
}
/// <summary>
/// Reads RynthILT's "RynthILT.Server" interface on the plugin pump (Infinite Leaftide only: the
/// caller polls it while ServerIdentity.IsIlt). Looks the table up through the host (re-checked
/// while RynthILT is missing or after it unloads, Version 0) and copies the JSON out every
/// <see cref="PollMs"/>; <see cref="Revision"/> goes up when the profile changes. The profile
/// carries the /qb lists inline ("questBonus"), which is where the Dynamic stamps /myquests
/// leaves out are found.
/// </summary>
internal sealed unsafe class IltServerLink
{
private const long PollMs = 2000;
private const long RequeryMs = 10_000;
// The profile with the /qb lists inline: 25,000 flags are about 1 MB; room for well past that.
private const int MaxBuffer = 8 * 1024 * 1024;
private RynthIltServerApiV1* _table;
private long _nextPollAt, _nextQueryAt;
private byte[] _buffer = new byte[8192];
private string _lastJson = "";
public IltServerProfile Profile { get; private set; } = IltServerProfile.None;
public int Revision { get; private set; }
/// <summary>The /qb summary and lists, or null (no RynthILT, or not an ILT world).</summary>
public IltQuestBonusList? QuestBonus => Profile.QuestBonus;
/// <summary>QB Deeds as RynthILT last read them, or null (no RynthILT, an older one, or not an ILT world).</summary>
public IltDeedsInfo? Deeds => Profile.Deeds;
private IReadOnlyList<string>? _qbSetSource;
private HashSet<string> _qbSet = new(StringComparer.OrdinalIgnoreCase);
/// <summary>The completed /qb flags (any case), empty until RynthILT has read the list this session.</summary>
public IReadOnlySet<string> QbCompletedSet
{
get
{
IReadOnlyList<string> done = QuestBonus?.Completed ?? Array.Empty<string>();
if (!ReferenceEquals(done, _qbSetSource))
{
_qbSetSource = done;
_qbSet = new HashSet<string>(done, StringComparer.OrdinalIgnoreCase);
}
return _qbSet;
}
}
private IReadOnlyList<string>? _stampDoneSource, _stampTodoSource;
private HashSet<string> _stampSet = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Every Dynamic stamp flag in the /qb list (any case), from both sections; empty until
/// RynthILT has read the list this session. ACECustom writes a stamp's account row with one
/// completion when the NPC stamps it, so a Dynamic flag in the list is a done stamp (the
/// incomplete section is read too: the server splits the same flags differently read to read).
/// </summary>
public IReadOnlySet<string> QbStampSet
{
get
{
IltQuestBonusList? qb = QuestBonus;
IReadOnlyList<string> done = qb?.Completed ?? Array.Empty<string>();
IReadOnlyList<string> todo = qb?.Incomplete ?? Array.Empty<string>();
if (!ReferenceEquals(done, _stampDoneSource) || !ReferenceEquals(todo, _stampTodoSource))
{
_stampDoneSource = done;
_stampTodoSource = todo;
_stampSet = new HashSet<string>(done.Concat(todo).Where(f => f.StartsWith(DynamicStampList.FlagPrefix, StringComparison.OrdinalIgnoreCase)),
StringComparer.OrdinalIgnoreCase);
}
return _stampSet;
}
}
/// <summary>Forget the profile (logout, or off Infinite Leaftide); the next poll reads it again.</summary>
public void Clear()
{
_nextPollAt = 0;
SetJson("");
}
/// <summary>Pump thread. Cheap when not due.</summary>
public void Poll(RynthCoreHost host, long now)
{
if (now < _nextPollAt) return;
_nextPollAt = now + PollMs;
RynthIltServerApiV1* t = Table(host, now);
SetJson(t == null ? "" : Read(t->GetProfileJson));
}
/// <summary>The table, re-queried when it is missing or RynthILT has shut down (Version 0).</summary>
private RynthIltServerApiV1* Table(RynthCoreHost host, long now)
{
if (_table != null && _table->Version >= 1) return _table;
_table = null;
if (now < _nextQueryAt || !host.HasGetPluginInterface) return null;
_nextQueryAt = now + RequeryMs;
// v1 is all the profile needs (v2 added the quest guide's calls after it: QuestGuideClient), so an
// older RynthILT's shorter table still serves.
var p = (RynthIltServerApiV1*)host.GetPluginInterface(RynthIltServer.PluginName, RynthIltServerApiV1.InterfaceName, 1);
if (p != null && p->Version >= 1 && p->StructSize >= (uint)(8 + sizeof(IntPtr)) && p->GetProfileJson != null)
_table = p;
return _table;
}
/// <summary>Copies the JSON out, growing the buffer when RynthILT says it didn't fit.</summary>
private string Read(delegate* unmanaged[Cdecl]<byte*, int, int> get)
{
if (get == null) return "";
for (int attempt = 0; attempt < 2; attempt++)
{
int len;
fixed (byte* b = _buffer) len = get(b, _buffer.Length);
if (len <= 0) return "";
if (len < _buffer.Length) return Encoding.UTF8.GetString(_buffer, 0, len);
if (len + 1 > MaxBuffer) return "";
_buffer = new byte[len + 1024];
}
return "";
}
/// <summary>Takes a profile JSON (internal: the tests feed one without RynthILT).</summary>
internal void SetJson(string json)
{
if (json == _lastJson) return;
_lastJson = json;
Profile = IltServerProfile.Parse(json);
Revision++;
}
}

View file

@ -0,0 +1,75 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Plugin.RynthOracle.Data;
// How to get the Leaftide wiki login the ILT quest guide needs, on the ILT Tracker tab (2026-11-21, Silentkelpie: "add in
// the itl wiki how to to this tab as well"). The same steps as RynthILT's WikiLoginGuide (RynthServers,
// IltWiki/WikiLoginGuide.cs, shown in /ilt settings > Quest guide and by "/ilt wiki help"): every page of
// leaftidewiki.com needs a login, so RynthILT reads it with a bot password, a read-only second password of the player's
// own wiki account. RynthOracle never sees or keeps the login: the last step hands over to RynthILT's settings. The pages
// open in the system browser (ShellExecuteW on its own short STA thread, never Process.Start inside acclient); only the
// fixed addresses below are ever opened.
internal static class IltWikiGuide
{
public const string CreateAccountUrl = "https://www.leaftidewiki.com/index.php?title=Special:CreateAccount";
public const string LoginUrl = "https://www.leaftidewiki.com/index.php?title=Special:UserLogin";
public const string BotPasswordsUrl = "https://www.leaftidewiki.com/index.php?title=Special:BotPasswords";
public const string SuggestedBotName = "rynth";
/// <summary>One step: a heading, what to do, and the page it happens on ("" none).</summary>
public readonly record struct Step(string Title, string Text, string Url);
public static readonly Step[] Steps =
{
new("Make a wiki account",
"Open the wiki's Create account page. Pick a user name and a password, and answer the Asheron's Call question it "
+ "asks (it keeps bots out). The account works at once; if the wiki turns it down, ask on the Infinite Leaftide "
+ "Discord (the wiki's home page links it). Already have one? Skip to step 2.",
CreateAccountUrl),
new("Log in on the wiki",
"Log in with that user name and password, in your browser. RynthILT and RynthOracle never see this password.",
LoginUrl),
new("Make a bot password",
"Open Special:BotPasswords. Type a bot name (for example \"" + SuggestedBotName + "\") and press Create. Tick only "
+ "\"Basic rights\" (reading is all RynthILT does), leave the rest, and press Create again.",
BotPasswordsUrl),
new("Copy the login it shows",
"The wiki shows the new login once: the login name, YourName@" + SuggestedBotName + ", and a long password. Copy "
+ "both now; the password can't be shown again (make a new one if you lose it).",
""),
new("Type it into RynthILT",
"Press RynthILT settings below. Under Quest guide, type the login name (YourName@" + SuggestedBotName + ") and the "
+ "bot password, then Save login and Read the wiki now. The password stays on this PC, sealed for your Windows "
+ "user; /ilt wiki logout forgets it.",
""),
new("Done",
"RynthILT reads the wiki's quest pages, Dynamic Stamps and Kill Tasks; RynthOracle's Wiki, Kill Tasks and Stamps "
+ "tabs show them. It reads them again at login once a day (/ilt wiki for the status).",
""),
};
[DllImport("shell32.dll", CharSet = CharSet.Unicode, EntryPoint = "ShellExecuteW")]
private static extern IntPtr ShellExecuteW(IntPtr hwnd, string? operation, string file, string? parameters, string? directory, int showCmd);
/// <summary>The guide's own pages only (nothing typed or read elsewhere is ever opened).</summary>
internal static bool IsGuidePage(string url) => url is CreateAccountUrl or LoginUrl or BotPasswordsUrl;
/// <summary>Opens one of the guide's pages in the system browser, off the render thread. False for any other address.</summary>
public static bool Open(string url)
{
if (!IsGuidePage(url)) return false;
try
{
var t = new Thread(() =>
{
try { ShellExecuteW(IntPtr.Zero, "open", url, null, null, 1); } catch { }
}) { IsBackground = true, Name = "RynthOracle wiki page" };
t.SetApartmentState(ApartmentState.STA);
t.Start();
return true;
}
catch { return false; }
}
}

View file

@ -0,0 +1,81 @@
// Kill task counts from chat (2026-11-21): the server says each kill of a kill task's creature as
// "You have killed 27 Empyrean Handlers! You must kill 250 to complete your task." (Silentkelpie's chat
// log), and some tasks only "You have killed some Coral Golem Viceroys". /myquests holds the same count on
// the task's counter flag, but may be read only once a minute; this keeps the last count each creature's
// line gave this session, so the Kill Tasks tab moves with every kill. Pump thread.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>One creature's last kill line: the count and the goal (0: the line gave none), and when.</summary>
internal readonly record struct KillCount(string Creature, int Kills, int Goal, DateTime AtUtc);
internal sealed class KillChat
{
private static readonly Regex CountRx = new(
@"^You have killed (?<n>\d{1,6}) (?<what>.+?)! You must kill (?<max>\d{1,6}) to complete your task",
RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
private static readonly Regex SomeRx = new(@"^You have killed (?:some|enough|all(?: the)?) (?<what>.+?)[.!]*$",
RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
private readonly Dictionary<string, KillCount> _byKey = new(StringComparer.Ordinal);
/// <summary>Goes up with every kill line taken (the view redraws).</summary>
public int Revision { get; private set; }
public IReadOnlyDictionary<string, KillCount> ByCreature => _byKey;
public void Clear()
{
if (_byKey.Count == 0) return;
_byKey.Clear();
Revision++;
}
/// <summary>
/// Takes a chat line; true when it was a kill task's kill line (the counter flags then need reading
/// again). A "some X" line keeps the count it had, so it only marks the creature as being killed.
/// </summary>
public bool OnChatLine(string? line, DateTime utcNow)
{
if (string.IsNullOrEmpty(line) || !line.StartsWith("You have killed ", StringComparison.OrdinalIgnoreCase)) return false;
string text = line.Trim();
Match m = CountRx.Match(text);
if (m.Success)
{
string what = m.Groups["what"].Value.Trim();
int n = int.Parse(m.Groups["n"].Value, NumberStyles.None, CultureInfo.InvariantCulture);
int max = int.Parse(m.Groups["max"].Value, NumberStyles.None, CultureInfo.InvariantCulture);
_byKey[GuideQuest.KillKey(what)] = new KillCount(what, n, max, utcNow);
Revision++;
return true;
}
m = SomeRx.Match(text);
if (!m.Success) return false;
string some = m.Groups["what"].Value.Trim();
string key = GuideQuest.KillKey(some);
_byKey[key] = _byKey.TryGetValue(key, out KillCount had) ? had with { AtUtc = utcNow } : new KillCount(some, 0, 0, utcNow);
Revision++;
return true;
}
/// <summary>
/// The last kill line for a task's creature: the same key, else one that holds the other
/// ("Rare Game" tasks name many creatures, so a key shorter than 5 letters never matches loosely).
/// </summary>
public KillCount? For(string creatureKey)
{
if (creatureKey.Length == 0) return null;
if (_byKey.TryGetValue(creatureKey, out KillCount k)) return k;
if (creatureKey.Length < 5) return null;
KillCount? best = null;
foreach (KeyValuePair<string, KillCount> kv in _byKey)
if (kv.Key.Length >= 5 && (kv.Key.Contains(creatureKey, StringComparison.Ordinal) || creatureKey.Contains(kv.Key, StringComparison.Ordinal))
&& (best == null || kv.Value.AtUtc > best.Value.AtUtc))
best = kv.Value;
return best;
}
}

View file

@ -0,0 +1,220 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>
/// An item as one Mag-Tools ItemInfo line (Mag-Plugins Mag-Tools/ItemInfo/ItemInfo.cs, the text
/// Mag-Tools prints when an item is identified), read from the appraisal:
/// "Gold Heavy Crossbow (Crossbow), Shimmering Shadows Set, AL 300, CS, Tinks 3, 35.25-47, +12,
/// +20%, +5%a, 10%md, Legendary Strength, Wield Lvl 180, Diff 300, Craft 9, Value 12,345, BU 50,
/// [D 3, CD 2]"
/// Same order, abbreviations and spell filter as Mag-Tools. Added for the Gear tab: the item's level
/// after its set ("Lvl 12/50"), the rating cluster with T11 modifier ratings included, and the
/// T11 modifier lines at the end. Mag's "buffed values" (its own weapon damage maths) are left out.
/// </summary>
internal static class MagFormat
{
// ACE PropertyInt ids (Decal's LongValueKey numbers where Decal has them).
public const int PropBurden = 5, PropValue = 19, PropArmorLevel = 28, PropResistMagic = 36, PropDamage = 44,
PropWorkmanship = 105, PropDifficulty = 109, PropActivationLevel = 115, PropMaterial = 131,
PropWieldRequirement = 158, PropWieldSkill = 159, PropWieldDifficulty = 160, PropTinks = 171,
PropActivationSkill = 176, PropImbued = 179, PropElementalBonus = 204, PropMastery = 353;
// ACE PropertyFloat ids.
public const int FloatSlashProt = 13, FloatPierceProt = 14, FloatBludgeonProt = 15, FloatColdProt = 16,
FloatFireProt = 17, FloatAcidProt = 18, FloatLightningProt = 19, FloatVariance = 22,
FloatMeleeDefense = 29, FloatOffense = 62, FloatDamageMod = 63, FloatManaConversion = 144,
FloatMissileDefense = 149, FloatMagicDefense = 150, FloatElementalVsMonsters = 152;
/// <summary>The int properties <see cref="GearScanner"/> reads for the line.</summary>
public static readonly int[] IntProps =
{
PropBurden, PropValue, PropArmorLevel, PropResistMagic, PropDamage, PropWorkmanship, PropDifficulty,
PropActivationLevel, PropMaterial, PropWieldRequirement, PropWieldSkill, PropWieldDifficulty, PropTinks,
PropActivationSkill, PropImbued, PropElementalBonus, PropMastery,
};
/// <summary>The float properties <see cref="GearScanner"/> reads for the line.</summary>
public static readonly int[] FloatProps =
{
FloatSlashProt, FloatPierceProt, FloatBludgeonProt, FloatColdProt, FloatFireProt, FloatAcidProt, FloatLightningProt,
FloatVariance, FloatMeleeDefense, FloatOffense, FloatDamageMod, FloatManaConversion, FloatMissileDefense,
FloatMagicDefense, FloatElementalVsMonsters,
};
/// <summary>Mag's imbue abbreviations by PropertyInt.ImbuedEffect bit.</summary>
private static readonly (int Bit, string Text)[] Imbues =
{
(1, "CS"), (2, "CB"), (4, "AR"), (8, "SlashRend"), (16, "PierceRend"), (32, "BludgeRend"), (64, "AcidRend"),
(128, "FrostRend"), (256, "LightRend"), (512, "FireRend"), (1024, "MeleeImbue"), (4096, "MagicImbue"),
(8192, "Hematited"), (536870912, "MagicAbsorb"),
};
/// <summary>The weapon-buff spell families Mag-Tools keeps only at level 7 and up.</summary>
private static bool IsWeaponBuffFamily(uint family) => family is >= 152 and <= 158 or 195 or 325;
private static readonly string[] LowLevels = { " I", " II", " III", " IV", " V", " VI" };
/// <summary>The whole Mag-style line for one piece.</summary>
public static string Describe(GearPiece p, Func<uint, SpellMeta>? lookup, (int Prop, int Value)[] ratings)
{
var sb = new StringBuilder();
CultureInfo inv = CultureInfo.InvariantCulture;
int material = p.Int(PropMaterial);
if (material > 0)
{
string m = GearNames.Material(material);
sb.Append(m.Length > 0 ? m : "unknown material " + material.ToString(inv)).Append(' ');
}
sb.Append(p.Name);
int mastery = p.Int(PropMastery);
if (mastery > 0)
{
string m = GearNames.Mastery(mastery);
sb.Append(" (").Append(m.Length > 0 ? m : "Unknown mastery " + mastery.ToString(inv)).Append(')');
}
if (p.SetId != 0) sb.Append(", ").Append(GearNames.SetName(p.SetId));
if (p.MaxLevel > 0 && p.Leveled) sb.Append(", Lvl ").Append(p.Level.ToString(inv)).Append('/').Append(p.MaxLevel.ToString(inv));
int al = p.Int(PropArmorLevel);
if (al > 0) sb.Append(", AL ").Append(al.ToString(inv));
int imbued = p.Int(PropImbued);
if (imbued > 0)
{
sb.Append(',');
foreach (var (bit, text) in Imbues)
if ((imbued & bit) == bit) sb.Append(' ').Append(text);
}
int tinks = p.Int(PropTinks);
if (tinks > 0) sb.Append(", Tinks ").Append(tinks.ToString(inv));
int maxDamage = p.Int(PropDamage);
double variance = p.Float(FloatVariance, 0);
if (maxDamage != 0 && variance != 0)
sb.Append(", ").Append((maxDamage - maxDamage * variance).ToString("N2", inv)).Append('-').Append(maxDamage.ToString(inv));
else if (maxDamage != 0)
sb.Append(", ").Append(maxDamage.ToString(inv));
int elemental = p.Int(PropElementalBonus);
if (elemental != 0) sb.Append(", +").Append(elemental.ToString(inv));
AppendPercent(sb, p.Float(FloatDamageMod, 1), "+", "%", 0);
AppendPercent(sb, p.Float(FloatElementalVsMonsters, 1), "+", "%vs. Monsters", 0);
AppendPercent(sb, p.Float(FloatOffense, 1), "+", "%a", 0);
AppendPercent(sb, p.Float(FloatMeleeDefense, 1), "", "%md", 0);
AppendPercent(sb, p.Float(FloatMagicDefense, 1), "", "%mgc.d", 1);
AppendPercent(sb, p.Float(FloatMissileDefense, 1), "", "%msl.d", 1);
double manaC = p.Float(FloatManaConversion, 0);
if (manaC != 0) sb.Append(", ").Append(Math.Round(manaC * 100).ToString(inv)).Append("%mc");
if (lookup != null)
foreach (string spell in ShownSpells(p, lookup)) sb.Append(", ").Append(spell);
int wieldDiff = p.Int(PropWieldDifficulty);
if (wieldDiff > 0)
{
int req = p.Int(PropWieldRequirement), skill = p.Int(PropWieldSkill);
if (req == 7 && skill == 1) sb.Append(", Wield Lvl ").Append(wieldDiff.ToString(inv));
else
{
string s = GearNames.Skill(skill);
sb.Append(", ").Append(s.Length > 0 ? s : "Unknown skill: " + skill.ToString(inv)).Append(' ').Append(wieldDiff.ToString(inv));
}
}
// "Melee Defense 300 to Activate", unless the wield requirement already says as much.
int actLevel = p.Int(PropActivationLevel), actSkill = p.Int(PropActivationSkill);
if (actLevel > 0 && (p.Int(PropWieldSkill) != actSkill || wieldDiff < actLevel))
{
string s = GearNames.Skill(actSkill);
sb.Append(", ").Append(s.Length > 0 ? s : "Unknown skill: " + actSkill.ToString(inv))
.Append(' ').Append(actLevel.ToString(inv)).Append(" to Activate");
}
int diff = p.Int(PropDifficulty);
if (diff > 0) sb.Append(", Diff ").Append(diff.ToString(inv));
int work = p.Int(PropWorkmanship);
if (work > 0 && tinks != 10) sb.Append(", Craft ").Append(work.ToString(inv)); // Mag hides it on a 10-tink item
// Unenchantable armour: its fixed protections, Slash/Pierce/Bludge/Cold/Fire/Acid/Lightning.
if ((p.ItemType & GearAnalysis.ItemArmor) != 0 && Unenchantable(p))
{
sb.Append(", [");
int[] prots = { FloatSlashProt, FloatPierceProt, FloatBludgeonProt, FloatColdProt, FloatFireProt, FloatAcidProt, FloatLightningProt };
for (int i = 0; i < prots.Length; i++)
{
if (i > 0) sb.Append('/');
sb.Append(p.Float(prots[i], 0).ToString("N1", inv));
}
sb.Append(']');
}
int value = p.Int(PropValue);
if (value > 0) sb.Append(", Value ").Append(value.ToString("N0", inv));
int burden = p.Int(PropBurden);
if (burden > 0) sb.Append(", BU ").Append(burden.ToString(inv));
var shown = ratings.Where(r => r.Value > 0).ToList();
if (shown.Count > 0)
sb.Append(", [").Append(string.Join(", ", shown.Select(r => GearAnalysis.RatingShort(r.Prop) + " " + r.Value.ToString(inv)))).Append(']');
if (p.Modifiers.Length > 0)
{
sb.Append(", T11 [").Append(string.Join(", ", p.Modifiers.Select(m => m.Text))).Append(']');
if (p.ZoneLocked) sb.Append(" (zone locked)");
}
return sb.ToString();
}
/// <summary>Mag's "+20%" style: a multiplier shown as the percent it adds (only when it isn't 1).</summary>
private static void AppendPercent(StringBuilder sb, double mod, string sign, string suffix, int digits)
{
if (mod == 1) return;
sb.Append(", ").Append(sign).Append(Math.Round((mod - 1) * 100, digits).ToString(CultureInfo.InvariantCulture)).Append(suffix);
}
/// <summary>ResistMagic 9999: the item can't be enchanted (Mag's "Unenchantable").</summary>
private static bool Unenchantable(GearPiece p) => p.Int(PropResistMagic) >= 9999;
/// <summary>
/// Mag-Tools' spell filter, highest id first: everything on an item that isn't loot (no
/// material); on loot the cantrips and the notable spells, without the level 1-7 noise.
/// Banes and Impenetrability show only on unenchantable gear (on the rest they get recast).
/// </summary>
internal static List<string> ShownSpells(GearPiece p, Func<uint, SpellMeta> lookup)
{
var shown = new List<string>();
bool loot = p.Int(PropMaterial) > 0;
bool unenchantable = Unenchantable(p);
foreach (uint id in p.Inscribed.Distinct().OrderByDescending(i => i))
{
SpellMeta s = lookup(id);
string n = s.Name;
if (!loot || Keep(n, s, unenchantable)) shown.Add(n);
}
return shown;
}
private static bool Keep(string n, SpellMeta s, bool unenchantable)
{
if (n.Contains("Minor Impenetrability") || n.Contains("Major Impenetrability") || n.Contains("Epic Impenetrability")
|| n.Contains("Legendary Impenetrability") || n.Contains("Augmented"))
return true;
bool baneOrImpen = n.Contains(" Bane") || n.Contains("Impen") || n.StartsWith("Brogard", StringComparison.Ordinal);
if (baneOrImpen) return unenchantable;
if (IsWeaponBuffFamily(s.Category)) return s.Power == 300 || s.Power >= 400;
foreach (string level in LowLevels) if (n.EndsWith(level, StringComparison.Ordinal)) return false;
if (s.Power == 300) return false;
if (n.Contains("Incantation")) return false;
return true;
}
}

View file

@ -0,0 +1,132 @@
// MediaWikiJson.cs - The MediaWiki API's answers, for RynthOracle's own wiki reader (FandomFeed.cs, 2026-11-21).
// A copy of RynthILT's IltWiki/WikiApi.cs (Silentkelpie: "under oracle duplicate ilt functions for pulling in
// overall quests"), without the login: the AC Community Wiki (asheron.fandom.com) reads without one.
// list=categorymembers a category's pages and sub-categories
// list=embeddedin eititle=Template:Quest_Summary (every page with the quest box)
// prop=info the pages' last revision ids (an unchanged page isn't fetched again)
// prop=revisions the changed pages' wikitext (50 a request)
// Pure JSON reading here (the offline tests feed it answers); FandomFeed.cs does the HTTP.
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
namespace RynthCore.Plugin.RynthOracle.Data;
internal static class MediaWikiJson
{
/// <summary>Titles per prop=info / prop=revisions request (the API's limit for an anonymous reader).</summary>
public const int TitlesPerRequest = 50;
/// <summary>The URL for a GET with these parameters (format=json, formatversion=2 added).</summary>
public static string Url(string api, params (string Key, string Value)[] args)
{
var sb = new StringBuilder(api);
sb.Append(api.Contains('?') ? '&' : '?').Append("format=json&formatversion=2");
foreach (var (k, v) in args) sb.Append('&').Append(Uri.EscapeDataString(k)).Append('=').Append(Uri.EscapeDataString(v));
return sb.ToString();
}
/// <summary>
/// A list=categorymembers or list=embeddedin page: the members' titles (pages, namespace 0), the
/// sub-categories, and the "continue" parameters for the next page (empty = done).
/// </summary>
public static (List<string> Pages, List<string> SubCats, List<(string Key, string Value)> Continue) Members(string json, string listName)
{
var pages = new List<string>();
var cats = new List<string>();
var cont = new List<(string, string)>();
try
{
using JsonDocument d = JsonDocument.Parse(json);
JsonElement root = d.RootElement;
if (root.TryGetProperty("query", out JsonElement q) && q.TryGetProperty(listName, out JsonElement list) && list.ValueKind == JsonValueKind.Array)
foreach (JsonElement m in list.EnumerateArray())
{
string title = Str(m, "title");
if (title.Length == 0) continue;
int ns = m.TryGetProperty("ns", out JsonElement n) && n.TryGetInt32(out int v) ? v : 0;
if (ns == 14) cats.Add(title);
else if (ns == 0) pages.Add(title);
}
if (root.TryGetProperty("continue", out JsonElement c) && c.ValueKind == JsonValueKind.Object)
foreach (JsonProperty p in c.EnumerateObject())
cont.Add((p.Name, p.Value.ValueKind == JsonValueKind.String ? p.Value.GetString() ?? "" : p.Value.GetRawText()));
}
catch (JsonException) { }
return (pages, cats, cont);
}
/// <summary>prop=info: each page's title and last revision id (missing pages left out).</summary>
public static Dictionary<string, long> LastRevisions(string json)
{
var map = new Dictionary<string, long>(StringComparer.Ordinal);
foreach (JsonElement p in Pages(json))
{
if (p.TryGetProperty("missing", out _)) continue;
string title = Str(p, "title");
long rev = p.TryGetProperty("lastrevid", out JsonElement r) && r.TryGetInt64(out long v) ? v : 0;
if (title.Length > 0) map[title] = rev;
}
return map;
}
/// <summary>prop=revisions (rvprop=content|ids, rvslots=main): each page's title, revision id and wikitext.</summary>
public static List<(string Title, long Rev, string Text)> Contents(string json)
{
var list = new List<(string, long, string)>();
foreach (JsonElement p in Pages(json))
{
string title = Str(p, "title");
if (title.Length == 0 || !p.TryGetProperty("revisions", out JsonElement revs) || revs.ValueKind != JsonValueKind.Array) continue;
foreach (JsonElement r in revs.EnumerateArray())
{
long id = r.TryGetProperty("revid", out JsonElement i) && i.TryGetInt64(out long v) ? v : 0;
string text = "";
if (r.TryGetProperty("slots", out JsonElement slots) && slots.TryGetProperty("main", out JsonElement main))
text = Str(main, "content");
else
text = Str(r, "content");
list.Add((title, id, text));
break;
}
}
return list;
}
/// <summary>query.pages (formatversion=2: an array), copied out so the document can go.</summary>
private static List<JsonElement> Pages(string json)
{
var list = new List<JsonElement>();
try
{
using JsonDocument d = JsonDocument.Parse(json);
if (d.RootElement.TryGetProperty("query", out JsonElement q) && q.TryGetProperty("pages", out JsonElement pages))
{
if (pages.ValueKind == JsonValueKind.Array)
foreach (JsonElement p in pages.EnumerateArray()) list.Add(p.Clone());
else if (pages.ValueKind == JsonValueKind.Object) // formatversion=1: keyed by page id
foreach (JsonProperty p in pages.EnumerateObject()) list.Add(p.Value.Clone());
}
}
catch (JsonException) { }
return list;
}
/// <summary>Titles split into requests of at most <see cref="TitlesPerRequest"/>, joined with '|'.</summary>
public static List<string> Batches(IReadOnlyList<string> titles)
{
var list = new List<string>();
for (int i = 0; i < titles.Count; i += TitlesPerRequest)
{
int n = Math.Min(TitlesPerRequest, titles.Count - i);
var part = new string[n];
for (int k = 0; k < n; k++) part[k] = titles[i + k];
list.Add(string.Join("|", part));
}
return list;
}
private static string Str(JsonElement o, string name) =>
o.ValueKind == JsonValueKind.Object && o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
}

View file

@ -80,6 +80,19 @@ internal static class NavTargets
return label.Length > 60 ? label.Substring(0, 60).TrimEnd() : label;
}
/// <summary>Every coordinate pair in <paramref name="text"/>, in order, written "8.8S, 53.1E" (the same pair once).</summary>
public static List<string> AllCoords(string? text)
{
var list = new List<string>();
if (string.IsNullOrEmpty(text)) return list;
foreach (Match m in CoordsRx.Matches(text))
{
string c = Format(m);
if (!list.Contains(c)) list.Add(c);
}
return list;
}
private static string Format(Match m) =>
string.Create(CultureInfo.InvariantCulture,
$"{m.Groups["ns"].Value}{char.ToUpperInvariant(m.Groups["nsc"].Value[0])}, {m.Groups["ew"].Value}{char.ToUpperInvariant(m.Groups["ewc"].Value[0])}");

View file

@ -0,0 +1,284 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using RynthCore.Plugin.RynthAi.Raycasting;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>
/// One spell of the client's spell table (portal.dat 0x0E00000E, ACE.DatLoader SpellBase): what
/// the Gear tab needs to tell which spells compete. <see cref="Category"/> is the stacking family
/// (ACE SpellCategory): enchantments of one family don't stack, the highest <see cref="Power"/> wins.
/// </summary>
internal readonly record struct PortalSpell(uint Id, string Name, uint School, uint Category, uint Bitfield,
uint Power, uint MetaType, uint TargetType)
{
/// <summary>SpellType Enchantment (1) or FellowEnchantment (12): the kinds that sit in an enchantment registry.</summary>
public bool IsEnchantment => MetaType == 1 || MetaType == 12;
/// <summary>
/// Cast on an item (a bane on armour, Blood Drinker on a weapon), not on a creature: its
/// NonComponentTargetType names item types and not Creature (ItemType 0x10).
/// </summary>
public bool IsItemTarget => TargetType != 0 && (TargetType & 0x10) == 0;
}
/// <summary>
/// An equipment set's bonus spells by tier (portal.dat SpellTable.SpellSet). The tier key is the
/// set's level: the number of pieces worn, or for leveled sets the sum of the pieces' item levels.
/// </summary>
internal sealed class SpellSetDef
{
public readonly SortedDictionary<uint, uint[]> Tiers = new();
public uint HighestTier => Tiers.Count == 0 ? 0 : LastKey();
private uint LastKey()
{
uint last = 0;
foreach (uint k in Tiers.Keys) last = k;
return last;
}
/// <summary>
/// The spells active at <paramref name="level"/>, as ACE's GetSpellSet: the level is capped at
/// the highest tier and a level between two tiers takes the lower one (SpellSetTiersNoGaps).
/// Level 0 (or below the first tier) has none.
/// </summary>
public uint[] SpellsAt(uint level)
{
uint tier = Math.Min(level, HighestTier);
if (tier == 0) return Array.Empty<uint>();
uint[]? best = null;
foreach (var kv in Tiers)
{
if (kv.Key > tier) break;
best = kv.Value;
}
return best ?? Array.Empty<uint>();
}
/// <summary>The tier key <see cref="SpellsAt"/> resolves to (for the label), or 0.</summary>
public uint TierAt(uint level)
{
uint tier = Math.Min(level, HighestTier);
uint found = 0;
foreach (uint k in Tiers.Keys)
{
if (k > tier) break;
found = k;
}
return tier == 0 ? 0 : found;
}
}
/// <summary>
/// The client's own spell table and equipment-set spells, read once from portal.dat in the
/// background. Every server's client carries the spells it can show (custom ones included), so
/// this works on any server; SpellData.txt (retail) only fills in when the dat can't be read.
/// </summary>
internal sealed class PortalSpellBook
{
public const uint SpellTableFileId = 0x0E00000E;
/// <summary>The one book the plugin shares (the dat is read once per process).</summary>
public static PortalSpellBook Shared { get; } = new();
private volatile Dictionary<uint, PortalSpell>? _spells;
private volatile Dictionary<uint, SpellSetDef>? _sets;
private int _started;
/// <summary>"" until the load ends; then what it found, or why it couldn't (for the tab and the log).</summary>
public volatile string Status = "";
/// <summary>True once the load has finished, whether or not the dat was read.</summary>
public volatile bool Done;
public bool HasDat => _spells != null;
public int SpellCount => _spells?.Count ?? 0;
public int SetCount => _sets?.Count ?? 0;
/// <summary>Starts the one background read (any later call does nothing).</summary>
public void EnsureLoading(Action<string>? log = null)
{
if (Interlocked.Exchange(ref _started, 1) == 1) return;
_ = Task.Run(() => Load(log));
}
/// <summary>Tests: a book from a hand-built table, already loaded.</summary>
internal static PortalSpellBook FromParsed(Dictionary<uint, PortalSpell> spells, Dictionary<uint, SpellSetDef> sets)
{
var b = new PortalSpellBook { _spells = spells, _sets = sets, Done = true, _started = 1, Status = "test" };
return b;
}
public bool TryGet(uint id, out PortalSpell spell)
{
var t = _spells;
if (t != null && t.TryGetValue(id, out spell)) return true;
spell = default;
return false;
}
public bool TryGetSet(uint setId, out SpellSetDef set)
{
var t = _sets;
if (t != null && t.TryGetValue(setId, out SpellSetDef? s)) { set = s; return true; }
set = null!;
return false;
}
private void Load(Action<string>? log)
{
try
{
string? path = FindPortalDat();
if (path == null) { Status = "portal.dat not found next to the game client"; return; }
using var dat = new DatDatabase();
if (!dat.Open(path)) { Status = "portal.dat could not be opened"; return; }
byte[]? raw = dat.GetFileData(SpellTableFileId);
if (raw == null || raw.Length < 8) { Status = "the spell table isn't in portal.dat"; return; }
var (spells, sets) = Parse(raw);
_sets = sets;
_spells = spells;
Status = $"{spells.Count:N0} spells and {sets.Count:N0} equipment sets from {Path.GetFileName(path)}";
}
catch (Exception ex)
{
Status = $"spell table read failed: {ex.GetType().Name}: {ex.Message}";
}
finally
{
Done = true;
log?.Invoke("[RynthOracle] Gear: " + Status);
}
}
/// <summary>
/// The SpellTable file: id, a PackedHashTable of SpellBase, then a PackedHashTable of SpellSet
/// (ACE.DatLoader FileTypes/SpellTable.cs). Every SpellBase field is read so the table stays
/// aligned; a cut-short table keeps what was read before the overrun.
/// </summary>
internal static (Dictionary<uint, PortalSpell> Spells, Dictionary<uint, SpellSetDef> Sets) Parse(byte[] raw)
{
var spells = new Dictionary<uint, PortalSpell>();
var sets = new Dictionary<uint, SpellSetDef>();
var r = new Reader(raw);
r.U32(); // file id
int total = r.U16();
r.U16(); // bucket size
for (int i = 0; i < total && r.Ok; i++)
{
uint id = r.U32();
string name = r.ObfuscatedString();
r.ObfuscatedString(); // description
uint school = r.U32();
r.U32(); // icon
uint category = r.U32();
uint bitfield = r.U32();
r.U32(); // base mana
r.Skip(8); // base range constant, range mod
uint power = r.U32();
r.Skip(12); // economy mod, formula version, component loss
uint meta = r.U32();
r.U32(); // meta spell id
if (meta == 1 || meta == 12) r.Skip(16); // duration (f64), degrade modifier, degrade limit
else if (meta == 7) r.Skip(8); // portal lifetime (f64)
r.Skip(8 * 4); // the component formula
r.Skip(12); // caster, target and fizzle effects
r.Skip(8 + 4 + 4); // recovery interval (f64), recovery amount, display order
uint target = r.U32(); // NonComponentTargetType (ItemType)
r.U32(); // mana mod
if (!r.Ok) break;
spells[id] = new PortalSpell(id, name, school, category, bitfield, power, meta, target);
}
// SpellSet: setId -> PackedHashTable<tier, List<uint> spells>.
if (r.Ok)
{
int setCount = r.U16();
r.U16();
for (int i = 0; i < setCount && r.Ok; i++)
{
uint setId = r.U32();
var def = new SpellSetDef();
int tiers = r.U16();
r.U16();
for (int t = 0; t < tiers && r.Ok; t++)
{
uint tier = r.U32();
int n = (int)r.U32();
if (n < 0 || n > 4096) { r.Fail(); break; }
var list = new uint[n];
for (int k = 0; k < n; k++) list[k] = r.U32();
if (r.Ok) def.Tiers[tier] = list;
}
if (r.Ok) sets[setId] = def;
}
}
return (spells, sets);
}
/// <summary>The client's portal.dat: beside acclient.exe (we run inside it), else the usual install folders.</summary>
private static string? FindPortalDat()
{
var dirs = new List<string>();
try
{
string? exe = Environment.ProcessPath;
if (!string.IsNullOrEmpty(exe) && Path.GetDirectoryName(exe) is string d) dirs.Add(d);
}
catch { /* no process path: the fixed folders below */ }
dirs.Add(@"C:\Turbine\Asheron's Call");
dirs.Add(@"C:\Program Files (x86)\Turbine\Asheron's Call");
dirs.Add(@"C:\Program Files\Turbine\Asheron's Call");
foreach (string dir in dirs)
foreach (string name in new[] { "client_portal.dat", "portal.dat" })
{
string full = Path.Combine(dir, name);
if (File.Exists(full)) return full;
}
return null;
}
/// <summary>Bounds-checked little-endian reader; <see cref="Ok"/> turns false on an overrun.</summary>
private sealed class Reader
{
private readonly byte[] _b;
private int _p;
public bool Ok = true;
public Reader(byte[] b) => _b = b;
private bool Has(int n)
{
if (Ok && n >= 0 && _p + n <= _b.Length) return true;
Ok = false;
return false;
}
public void Fail() => Ok = false;
public uint U32() { if (!Has(4)) return 0; uint v = BitConverter.ToUInt32(_b, _p); _p += 4; return v; }
public ushort U16() { if (!Has(2)) return 0; ushort v = BitConverter.ToUInt16(_b, _p); _p += 2; return v; }
public void Skip(int n) { if (Has(n)) _p += n; }
/// <summary>u16 length, bytes with their nibbles swapped, then aligned to 4 from the file start (as ACE reads it).</summary>
public string ObfuscatedString()
{
int n = U16();
if (!Has(n)) return "";
var chars = new char[n];
for (int i = 0; i < n; i++)
{
byte x = _b[_p + i];
chars[i] = (char)(byte)((x >> 4) | (x << 4)); // Latin-1: byte == code point
}
_p += n;
_p = (_p + 3) & ~3;
if (_p > _b.Length) Ok = false;
return new string(chars);
}
}
}

View file

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthOracle.Data;
// ACECustom's QB Deeds for the ILT Tracker tab (2026-11-21, Silentkelpie: "look at acecustom ... should be called deeds based
// on total qb"). ACECustom (origin/master 8d2460ff2, Source/ACE.Server/Entity/DeedsTiers.cs, upstream #564 2026-10-24 and the
// damage steps of 2026-11-10): 15 cumulative tiers, tier N at N x 1,000 account QB, always on while Deeds are ON (/deeds on |
// off). The server caps the tiers with deeds_max_tier, and the damage step (deeds_damage_step, 2% by default), the Breath of
// Renewal chance and the Cheat Death timings are live settings, so the tier lines below are the defaults; RynthILT's /deeds
// list read (IltDeedsInfo) is the server's own text and wins when it is in.
/// <summary>One Deeds tier as ACECustom's DeedsTiers table has it: its QB and a short line of what it gives.</summary>
internal readonly record struct QbDeedTier(int Number, long Qb, string Summary);
internal static class QbDeeds
{
public const int QbPerTier = 1000;
public const int MaxTier = 15;
/// <summary>The tier that unlocks /rebuff and the Deedkeeper's Writ (/deeds item).</summary>
public const int RebuffTier = 10;
/// <summary>The tiers that each add the damage step (2% at the server's default).</summary>
public static readonly int[] DamageStepTiers = { 3, 6, 9, 12, 15 };
public const double DefaultDamageStep = 0.02;
public static readonly QbDeedTier[] Tiers =
{
new(1, 1000, "Legendary attributes, Legendary skills, Legendary Health / Stamina / Mana Gain, Augmented Understanding III, "
+ "Asheron's Lesser Benediction and Blackmoor's Favor"),
new(2, 2000, "Legendary Armor and the seven Legendary wards (bludgeoning, piercing, slashing, acid, flame, frost, storm)"),
new(3, 3000, "Prodigal Dirty Fighting, Life, Deception, Recklessness, Shield, Sneak Attack, Magic Resistance, "
+ "Invulnerability, Impregnability, Void, War and Healing"),
new(4, 4000, "Dispersion, Uncanny Dodge, Foresight, Master Negator's / Guardian's / Wayfarer's, Master Voidlock's, "
+ "Paragon's Void V, Master Warlock's and Paragon's War V"),
new(5, 5000, "The health, stamina and mana buffs (31 spells, Sigil of Vigor XV among them)"),
new(6, 6000, "Surge of Destruction, Protection and Regeneration always on, with your life augs (your Aetheria no longer "
+ "procs these three)"),
new(7, 7000, "Prodigal Strength to Willpower, and Prodigal Regeneration, Rejuvenation and Mana Renewal"),
new(8, 8000, "Rating and armor buffs: Master Brute's, Hero's, Duelist's, Rover's, Sage's and Adherent's, Sigil of Fury X, "
+ "damage and damage reduction ratings, Ruschk Skin, Timaru's Shelter, Society Master's Blessing and more"),
new(9, 9000, "The Legendary banes and Legendary Impenetrability as a floor on every armor piece you wear"),
new(10, 10000, "/rebuff casts all your known level 8 buffs at once; /deeds item gives a Deedkeeper's Writ that does the same"),
new(11, 11000, "Prodigal Armor, the Prodigal protections and the Masterwork resistances"),
new(12, 12000, "Breath of Renewal: a chance on every attack"),
new(13, 13000, "Cheat Death: a monster's killing blow leaves you at 1 health and immune for a moment (shared cooldown with "
+ "Cheat Death boots)"),
new(14, 14000, "+100% of your base critical chance (10% becomes 20%)"),
new(15, 15000, "Loot luck: every item's quality roll on your kills is rolled twice and the better kept"),
};
/// <summary>The tier a QB reaches: 0 below 1,000, at most 15 (ACECustom's TierFor).</summary>
public static int TierFor(long qb) => (int)Math.Clamp(Math.Max(0, qb) / QbPerTier, 0, MaxTier);
/// <summary>The Deeds damage bonus at a tier at the default step: 0 below tier 3, then +2% at 3, 6, 9, 12 and 15.</summary>
public static double DamageBonus(int tier, double step = DefaultDamageStep)
{
int steps = 0;
foreach (int t in DamageStepTiers) if (tier >= t) steps++;
return steps * step;
}
/// <summary>The tier's line, with the damage step on the step tiers (at the default).</summary>
public static string Line(QbDeedTier t)
{
if (Array.IndexOf(DamageStepTiers, t.Number) < 0) return t.Summary;
return t.Summary + $"; +{DefaultDamageStep * 100:0}% damage ({DamageBonus(t.Number) * 100:0}% in all)";
}
/// <summary>How far the QB is to the next tier: the next tier (0 at the top), its fraction done, the QB still needed.</summary>
public static (int Next, float Fraction, long ToNext) Progress(long qb)
{
qb = Math.Max(0, qb);
int tier = TierFor(qb);
if (tier >= MaxTier) return (0, 1f, 0);
long into = qb - (long)tier * QbPerTier;
return (tier + 1, (float)into / QbPerTier, QbPerTier - into);
}
}

View file

@ -0,0 +1,115 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthOracle.Data;
// The ILT Tracker tab's quest bonus (Infinite Leaftide, ACECustom read 2026-11-21, Silentkelpie: "look at acecustom add in
// itl qb bonus levels and bonus tracker"). In ACECustom (Source/ACE.Server):
// * the quest bonus (QB) is the account's: one per quest row (AccountQuest, written when any character of the account first
// stamps the quest) and one more once it has a completion (Account.CachedQuestBonusCount, what Deeds and the QB bounty
// read); the character carries it as PropertyInt64 9006 QuestCount;
// * each QB is +0.5% kill XP: GetQuestCountXPBonus() = 1 + QB x 0.005 (Player_Xp.questToBonusRation);
// * "/bonus" prints the four XP multipliers: Quests, Equipment (1 + the XP enchantments + 5% a Bonus XP aug),
// Enlightenment (1 + ENL x 0.1) and the Total, their product ("[BONUS] Your XP multiplier from Quests is: x2.35");
// * "/qb" prints "Your current quest bonus count: 270"; "/qb list" the completed and the incomplete quest bonus list
// (RynthILT reads that one and hands it over: IltQuestBonusList); portals can ask for a QB amount
// (PortalRequirement.QuestBonus) or a total multiplier (XPMultiplier).
// The QB levels are ACECustom's QB Deeds: a tier every 1,000 QB, up to 15 (Data/QbDeeds.cs).
/// <summary>The four "/bonus" multipliers as the server last printed them (0 = not seen).</summary>
internal sealed record BonusReading(double Quests, double Equipment, double Enlightenment, double Total, DateTime AtUtc)
{
public static readonly BonusReading None = new(0, 0, 0, 0, DateTime.MinValue);
public bool Seen => AtUtc != DateTime.MinValue;
}
internal sealed class QuestBonus
{
/// <summary>ACECustom's Player_Xp.questToBonusRation: kill XP per QB.</summary>
public const double PerQb = 0.005;
/// <summary>ACECustom's Player_Xp.enlightenmentToBonusRatio: kill XP per enlightenment.</summary>
public const double PerEnlightenment = 0.1;
private static readonly Regex BonusLine = new(
@"^\[BONUS\] Your (?:(Total) XP multiplier|XP multiplier from (Quests|Equipment|Enlightenment)) is: x([0-9][0-9,]*(?:\.[0-9]+)?)",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
private static readonly Regex CountLine = new(@"^Your current quest bonus count: ([0-9][0-9,]*)",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
private double _q, _e, _n, _t;
/// <summary>The last "/bonus" reply (its four lines).</summary>
public BonusReading Bonus { get; private set; } = BonusReading.None;
/// <summary>The last "/qb" count seen in chat (-1 none).</summary>
public long ChatCount { get; private set; } = -1;
/// <summary>Goes up when anything here changes (the view redraws).</summary>
public int Revision { get; private set; }
/// <summary>Goes up at each logout (the view asks for /bonus and the /qb list again once a session).</summary>
public int Session { get; private set; }
public void Clear()
{
Bonus = BonusReading.None;
ChatCount = -1;
_q = _e = _n = _t = 0;
Revision++;
Session++;
}
/// <summary>A chat line: true when it is a "/bonus" or "/qb" count line (read, not eaten).</summary>
public bool OnChatLine(string line, DateTime utcNow)
{
string t = line.Trim();
Match m = CountLine.Match(t);
if (m.Success)
{
if (long.TryParse(m.Groups[1].Value.Replace(",", ""), NumberStyles.Integer, CultureInfo.InvariantCulture, out long n))
{
ChatCount = n;
Revision++;
}
return true;
}
m = BonusLine.Match(t);
if (!m.Success) return false;
if (!double.TryParse(m.Groups[3].Value.Replace(",", ""), NumberStyles.Float, CultureInfo.InvariantCulture, out double v)) return true;
string which = m.Groups[1].Success ? "total" : m.Groups[2].Value.ToLowerInvariant();
switch (which)
{
case "quests": _q = v; break;
case "equipment": _e = v; break;
case "enlightenment": _n = v; break;
default: _t = v; break;
}
// The server prints Quests, Equipment, Enlightenment, then Total: the reading is whole at Total.
if (which == "total") Bonus = new BonusReading(_q, _e, _n, _t, utcNow);
Revision++;
return true;
}
/// <summary>The quest multiplier a QB gives: 1 + QB x 0.005.</summary>
public static double Multiplier(long qb) => 1 + Math.Max(0, qb) * PerQb;
/// <summary>The QB a "/bonus" Quests multiplier stands for (it prints two decimals: about +/- 1 QB).</summary>
public static long QbFromMultiplier(double m) => m <= 1 ? 0 : (long)Math.Round((m - 1) / PerQb);
/// <summary>
/// The best QB known: RynthILT's /deeds or /qb read, else a "/qb" count in chat, else the "/bonus" Quests multiplier
/// (-1 when none). <paramref name="source"/> says which.
/// </summary>
public long BestCount(IltQuestBonusList? ilt, out string source, IltDeedsInfo? deeds = null)
{
if (deeds != null && deeds.Loaded && deeds.Qb >= 0) { source = "RynthILT's /deeds read"; return deeds.Qb; }
if (ilt != null && ilt.Count >= 0) { source = "RynthILT's /qb read"; return ilt.Count; }
if (ilt != null && ilt.Generation > 0 && ilt.Completed.Count > 0) { source = "the /qb list's completed quests"; return ilt.Completed.Count; }
if (ChatCount >= 0) { source = "/qb"; return ChatCount; }
if (Bonus.Seen && Bonus.Quests > 0) { source = "/bonus (to about 1 QB)"; return QbFromMultiplier(Bonus.Quests); }
source = "";
return -1;
}
/// <summary>A quest bonus flag that is a Dynamic stamp (they count towards QB as any quest does).</summary>
public static bool IsStamp(string flag) => flag.StartsWith(DynamicStampList.FlagPrefix, StringComparison.OrdinalIgnoreCase);
}

View file

@ -325,6 +325,16 @@ internal sealed class QuestFlagStore
public bool TryGet(string flag, out QuestFlag q) => Flags.TryGetValue(flag, out q!);
/// <summary>
/// Whether RynthOracle should read /myquests again by itself: auto refresh is on, nothing
/// happened for <paramref name="minutes"/> since <paramref name="sinceUtc"/> (the later of the
/// last reply, the login and RynthOracle's own last try), no reply is on its way, the server
/// has /myquests on and its once-a-minute limit is up. Pure: the tests drive it.
/// </summary>
internal static bool AutoRefreshDue(int minutes, DateTime sinceUtc, DateTime utcNow, bool loading, bool serverDisabled, int throttleSecondsLeft)
=> minutes > 0 && !loading && !serverDisabled && throttleSecondsLeft == 0
&& utcNow - sinceUtc >= TimeSpan.FromMinutes(minutes);
internal static QuestFlag? Parse(string line)
{
Match m = LineRegex.Match(line);

View file

@ -0,0 +1,511 @@
// The quest guide (2026-11-01): Infinite Leaftide's wiki quests (leaftidewiki.com, Category:Quest_Index)
// as RynthILT reads them (WikiQuestParser.cs) and saves them, and as RynthOracle's Quests tab shows
// them: each quest's summary, its walkthrough as steps (coordinates, the QB stamps each step gives,
// the items it names) and its rewards. One JSON file, written by RynthILT and read by RynthOracle
// (this file is linked into RynthILT so both use one reader and writer). No reflection serializer:
// both plugins are NativeAOT.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>One walkthrough step: what to do, where ("28.5S, 90.9W"), the stamps it gives and the items it names.</summary>
internal sealed class GuideStep
{
public string Text = "";
/// <summary>The step's sub-lines (tips), cleaned of markup; stamps and empty lines left out.</summary>
public List<string> Notes = new();
public List<string> Coords = new();
/// <summary>The QB stamps (quest flags) this step gives, as the wiki writes them ("Shiny_Red_Stone_Found").</summary>
public List<string> Stamps = new();
/// <summary>The {{Itemlink}} items the step names.</summary>
public List<string> Items = new();
}
/// <summary>One wiki quest.</summary>
internal sealed class GuideQuest
{
public string Title = "";
public string Url = "";
/// <summary>The page's revision id (an unchanged page isn't fetched again).</summary>
public long Rev;
public string Level = "";
public string RecommendedLevel = "";
public string Type = "";
public string KillTask = "";
public string StartsWith = "";
public string StartsAt = "";
public string Route = "";
/// <summary>The repeat timer as the wiki writes it ("20 Hours"); "" = none given.</summary>
public string Repeat = "";
/// <summary>The repeat timer in seconds: 0 = one-time (or none given), -1 = given but not understood.</summary>
public long RepeatSec;
public string TimeToComplete = "";
public string Contracts = "";
public int Qb;
/// <summary>The society rank the quest is for ("Initiate", "Adept", ...), from the box's "Society Rank"; "" none.</summary>
public string SocietyRank = "";
public List<string> Categories = new();
public string Overview = "";
public List<GuideStep> Steps = new();
/// <summary>QB stamps the page lists that no step could be tied to.</summary>
public List<string> ExtraStamps = new();
/// <summary>The items to pick up on the way (named in a step that kills, loots or finds something).</summary>
public List<string> Loot = new();
public List<string> Rewards = new();
/// <summary>Every stamp of the quest, steps first, in order, each once.</summary>
public IEnumerable<string> AllStamps()
{
var seen = new HashSet<string>(StringComparer.Ordinal);
foreach (GuideStep s in Steps)
foreach (string st in s.Stamps)
if (seen.Add(GuideStamp.Key(st))) yield return st;
foreach (string st in ExtraStamps)
if (seen.Add(GuideStamp.Key(st))) yield return st;
}
/// <summary>A daily: repeats within a day (and more than an hour, so a timer typo isn't a daily).</summary>
public bool IsDaily => RepeatSec > 0 && RepeatSec <= 26 * 3600;
/// <summary>A weekly: repeats in more than a day, up to about a month.</summary>
public bool IsWeekly => RepeatSec > 26 * 3600 && RepeatSec <= 31L * 86400;
/// <summary>A one-time (story) quest: no repeat timer given.</summary>
public bool IsOneTime => RepeatSec == 0;
/// <summary>
/// A kill task (2026-11-21): the Quest Summary box says "Kill Task = Yes" (150 pages), or, when the box
/// doesn't say, the title does ("... Kill Task", "... Killtask", "Kill: ..."). "Kill Task = False" is not one.
/// </summary>
public bool IsKillTask
{
get
{
string k = KillTask.Trim();
if (k.Length > 0)
return k.StartsWith("y", StringComparison.OrdinalIgnoreCase) || k.StartsWith("t", StringComparison.OrdinalIgnoreCase);
return Title.Contains("Kill Task", StringComparison.OrdinalIgnoreCase)
|| Title.Contains("Killtask", StringComparison.OrdinalIgnoreCase)
|| Title.StartsWith("Kill:", StringComparison.OrdinalIgnoreCase);
}
}
private static readonly System.Text.RegularExpressions.Regex KillCountRx = new(
@"\b(?:kill|slay|hunt(?:\s+down)?|defeat|destroy)\s+(?:a\s+total\s+of\s+)?(?<n>\d{1,5})\b",
System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.CultureInvariant);
/// <summary>How many kills the walkthrough asks for ("Kill 100 Drudge Lurkers."), from its first step that says; 0 when none does.</summary>
public int KillTarget
{
get
{
foreach (GuideStep s in Steps)
{
System.Text.RegularExpressions.Match m = KillCountRx.Match(s.Text);
if (m.Success && int.TryParse(m.Groups["n"].Value, System.Globalization.NumberStyles.None,
System.Globalization.CultureInfo.InvariantCulture, out int n) && n > 0) return n;
}
return 0;
}
}
/// <summary>
/// The creature a kill task names, as a GuideStamp key ("Drudge Lurker Kill Task" -> "drudgelurker",
/// "Kill: Rynthid Minions" -> "rynthidminion"): matches the server's kill chat and counter flags.
/// </summary>
public string KillCreatureKey
{
get
{
string t = Title;
foreach (string cut in new[] { "Kill Task", "Killtask", "Kill:" })
t = t.Replace(cut, " ", StringComparison.OrdinalIgnoreCase);
return KillKey(t);
}
}
/// <summary>A creature name as a key, without a plural "s" ("Rynthid Minions" -> "rynthidminion").</summary>
public static string KillKey(string name)
{
string k = GuideStamp.Key(name);
return k.Length > 4 && k.EndsWith('s') ? k[..^1] : k;
}
}
/// <summary>Stamp names as the server and the wiki write them, compared alike.</summary>
internal static class GuideStamp
{
/// <summary>Lower case letters and digits only: "Shiny_Red_Stone_Found", "shinyredstonefound" and "Shiny Red Stone Found" are one stamp.</summary>
public static string Key(string? stamp)
{
if (string.IsNullOrEmpty(stamp)) return "";
var sb = new StringBuilder(stamp.Length);
foreach (char ch in stamp)
if (char.IsLetterOrDigit(ch)) sb.Append(char.ToLowerInvariant(ch));
return sb.ToString();
}
private static readonly System.Text.RegularExpressions.Regex Qualifier = new(
@"^(?<stamp>\S+)\s+(?:(?:on|after|when|at|for|per|if|once|each|every|until|then|from)\b|\().*$",
System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.CultureInvariant);
/// <summary>
/// A stamp as the wiki writes it inside {{stamped|...}}, cut to the flag itself (2026-11-21). 125 pages
/// write "KillTaskDrudgeLurkers_0507 on first completion" and three "You've stamped GleeqeoStart!"; the
/// words after the flag made the stamp never match /myquests, so every kill task's counter step stayed
/// unticked. A stamp of plain words with spaces ("Shiny Red Stone Found") is left alone.
/// </summary>
public static string Clean(string? stamp)
{
if (string.IsNullOrWhiteSpace(stamp)) return "";
string s = stamp.Trim();
if (FromChat(s) is string chat) s = chat;
else if (s.StartsWith("stamped ", StringComparison.OrdinalIgnoreCase)) s = s.Substring(8).Trim();
System.Text.RegularExpressions.Match m = Qualifier.Match(s);
if (m.Success) s = m.Groups["stamp"].Value;
return s.TrimEnd('!', '.', ',', ';', ':', ' ');
}
/// <summary>The stamp in the server's "You've stamped X!" line, or null.</summary>
public static string? FromChat(string? line)
{
if (string.IsNullOrEmpty(line)) return null;
const string Lead = "You've stamped ";
int i = line.IndexOf(Lead, StringComparison.OrdinalIgnoreCase);
if (i < 0) return null;
string rest = line.Substring(i + Lead.Length).Trim();
rest = rest.TrimEnd('!', '.', ' ');
return rest.Length is > 0 and <= 120 ? rest : null;
}
}
/// <summary>
/// One row of the wiki's Dynamic Stamps page (2026-11-21): the NPC who takes a sheet of parchment, where, the
/// stamp it gives and the item back. Area is the page's town or camp heading ("Arwic"), or "Miscellaneous".
/// </summary>
internal sealed class GuideDynStamp
{
public string Area = "";
public string Place = "";
public string Npc = "";
public string Coords = "";
public string Stamp = "";
public string Reward = "";
public string Note = "";
}
/// <summary>
/// A contract (2026-11-21, the AC Community Wiki's Category:Contracts): the item you buy or are given that starts
/// or repeats a quest, where it comes from, and the quests it is for.
/// </summary>
internal sealed class GuideContract
{
public string Title = "";
public string Name = "";
public string Url = "";
public long Rev;
public string Description = "";
public string Level = "";
/// <summary>Where it comes from, as the page's notes say ("Purchased from Hanadi the Barkeeper in the Sho hall ...").</summary>
public string Where = "";
/// <summary>The person it comes from (the first link in <see cref="Where"/>), for RynthNav.</summary>
public string Npc = "";
/// <summary>The quests it is for (the Intro box's "Related Quests").</summary>
public List<string> Quests = new();
}
/// <summary>The whole guide: the quests, where they came from and when.</summary>
internal sealed class QuestGuide
{
public const int Schema = 1;
public static readonly QuestGuide Empty = new();
/// <summary>
/// The page reader that made the guide (WikiQuestParser.Version; 1 for a guide saved before 2026-11-21).
/// A guide from an older reader is read from the wiki again whole, not just the pages that changed.
/// </summary>
public int Parser = 1;
/// <summary>"api" (the wiki's API with the player's bot password) or "export" (a Special:Export file).</summary>
public string Source = "";
public DateTime UpdatedUtc = DateTime.MinValue;
public List<GuideQuest> Quests = new();
/// <summary>The wiki's Dynamic Stamps page (2026-11-21); empty when it wasn't read. RynthOracle's Stamps tab uses it over its own sheet.</summary>
public List<GuideDynStamp> DynStamps = new();
/// <summary>The Dynamic Stamps page's revision id (0 unknown).</summary>
public long DynStampsRev;
/// <summary>The pages in the wiki's Category:Kill Tasks (2026-11-21), its list of kill tasks.</summary>
public List<string> KillTasks = new();
/// <summary>Society quests by the rank they are for (title -> "Initiate", ...; the wiki's society categories, 2026-11-21).</summary>
public Dictionary<string, string> Society = new(StringComparer.OrdinalIgnoreCase);
/// <summary>The wiki's contracts (2026-11-21).</summary>
public List<GuideContract> Contracts = new();
/// <summary>The society rank a quest is for: its box's, else the society category it is in; "" none.</summary>
public string SocietyRankOf(GuideQuest q) =>
q.SocietyRank.Length > 0 ? q.SocietyRank : Society.TryGetValue(q.Title, out string? r) ? r : "";
/// <summary>A kill task: the wiki's Kill Tasks category lists it, or its own page says so (GuideQuest.IsKillTask).</summary>
public bool IsKillTask(GuideQuest q)
{
if (q.IsKillTask) return true;
if (KillTasks.Count == 0) return false;
if (!ReferenceEquals(_killSetOf, KillTasks))
{
_killSet = new HashSet<string>(KillTasks, StringComparer.OrdinalIgnoreCase);
_killSetOf = KillTasks;
}
return _killSet!.Contains(q.Title);
}
private HashSet<string>? _killSet;
private List<string>? _killSetOf;
public GuideQuest? Find(string title)
{
foreach (GuideQuest q in Quests)
if (string.Equals(q.Title, title, StringComparison.OrdinalIgnoreCase)) return q;
return null;
}
// ── JSON ────────────────────────────────────────────────────────────────
public string ToJson()
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms))
{
w.WriteStartObject();
w.WriteNumber("schema", Schema);
w.WriteNumber("parser", Parser);
w.WriteString("source", Source);
w.WriteString("updated", UpdatedUtc == DateTime.MinValue ? "" : UpdatedUtc.ToString("o"));
w.WriteStartArray("quests");
foreach (GuideQuest q in Quests)
{
w.WriteStartObject();
w.WriteString("title", q.Title);
w.WriteString("url", q.Url);
w.WriteNumber("rev", q.Rev);
Opt(w, "level", q.Level);
Opt(w, "recLevel", q.RecommendedLevel);
Opt(w, "type", q.Type);
Opt(w, "killTask", q.KillTask);
Opt(w, "startsWith", q.StartsWith);
Opt(w, "startsAt", q.StartsAt);
Opt(w, "route", q.Route);
Opt(w, "repeat", q.Repeat);
w.WriteNumber("repeatSec", q.RepeatSec);
Opt(w, "time", q.TimeToComplete);
Opt(w, "contracts", q.Contracts);
Opt(w, "societyRank", q.SocietyRank);
w.WriteNumber("qb", q.Qb);
Arr(w, "categories", q.Categories);
Opt(w, "overview", q.Overview);
w.WriteStartArray("steps");
foreach (GuideStep s in q.Steps)
{
w.WriteStartObject();
w.WriteString("text", s.Text);
Arr(w, "notes", s.Notes);
Arr(w, "coords", s.Coords);
Arr(w, "stamps", s.Stamps);
Arr(w, "items", s.Items);
w.WriteEndObject();
}
w.WriteEndArray();
Arr(w, "extraStamps", q.ExtraStamps);
Arr(w, "loot", q.Loot);
Arr(w, "rewards", q.Rewards);
w.WriteEndObject();
}
w.WriteEndArray();
Arr(w, "killTasks", KillTasks);
if (Society.Count > 0)
{
w.WriteStartObject("society");
foreach (var kv in Society) w.WriteString(kv.Key, kv.Value);
w.WriteEndObject();
}
if (Contracts.Count > 0)
{
w.WriteStartArray("contracts");
foreach (GuideContract c in Contracts)
{
w.WriteStartObject();
w.WriteString("title", c.Title);
Opt(w, "name", c.Name == c.Title ? "" : c.Name);
Opt(w, "url", c.Url);
if (c.Rev != 0) w.WriteNumber("rev", c.Rev);
Opt(w, "description", c.Description);
Opt(w, "level", c.Level);
Opt(w, "where", c.Where);
Opt(w, "npc", c.Npc);
Arr(w, "quests", c.Quests);
w.WriteEndObject();
}
w.WriteEndArray();
}
if (DynStamps.Count > 0)
{
w.WriteNumber("dynRev", DynStampsRev);
w.WriteStartArray("dynStamps");
foreach (GuideDynStamp d in DynStamps)
{
w.WriteStartObject();
Opt(w, "area", d.Area);
Opt(w, "place", d.Place);
Opt(w, "npc", d.Npc);
Opt(w, "coords", d.Coords);
w.WriteString("stamp", d.Stamp);
Opt(w, "reward", d.Reward);
Opt(w, "note", d.Note);
w.WriteEndObject();
}
w.WriteEndArray();
}
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray());
}
private static void Opt(Utf8JsonWriter w, string name, string value)
{
if (!string.IsNullOrEmpty(value)) w.WriteString(name, value);
}
private static void Arr(Utf8JsonWriter w, string name, List<string> items)
{
if (items.Count == 0) return;
w.WriteStartArray(name);
foreach (string s in items) w.WriteStringValue(s);
w.WriteEndArray();
}
/// <summary>Reads a guide; <see cref="Empty"/> when the text isn't one (read leniently: missing fields are empty).</summary>
public static QuestGuide Parse(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return Empty;
try
{
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) return Empty;
var g = new QuestGuide { Source = Str(root, "source"), Parser = (int)Math.Max(1, Long(root, "parser")) };
if (DateTime.TryParse(Str(root, "updated"), System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.RoundtripKind, out DateTime t))
g.UpdatedUtc = t.ToUniversalTime();
if (root.TryGetProperty("quests", out JsonElement qs) && qs.ValueKind == JsonValueKind.Array)
foreach (JsonElement e in qs.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.Object) continue;
var q = new GuideQuest
{
Title = Str(e, "title"),
Url = Str(e, "url"),
Rev = Long(e, "rev"),
Level = Str(e, "level"),
RecommendedLevel = Str(e, "recLevel"),
Type = Str(e, "type"),
KillTask = Str(e, "killTask"),
StartsWith = Str(e, "startsWith"),
StartsAt = Str(e, "startsAt"),
Route = Str(e, "route"),
Repeat = Str(e, "repeat"),
RepeatSec = Long(e, "repeatSec"),
TimeToComplete = Str(e, "time"),
Contracts = Str(e, "contracts"),
SocietyRank = Str(e, "societyRank"),
Qb = (int)Long(e, "qb"),
Categories = Strs(e, "categories"),
Overview = Str(e, "overview"),
ExtraStamps = Stamps(Strs(e, "extraStamps")),
Loot = Strs(e, "loot"),
Rewards = Strs(e, "rewards"),
};
if (q.Title.Length == 0) continue;
if (e.TryGetProperty("steps", out JsonElement ss) && ss.ValueKind == JsonValueKind.Array)
foreach (JsonElement s in ss.EnumerateArray())
{
if (s.ValueKind != JsonValueKind.Object) continue;
q.Steps.Add(new GuideStep
{
Text = Str(s, "text"),
Notes = Strs(s, "notes"),
Coords = Strs(s, "coords"),
Stamps = Stamps(Strs(s, "stamps")),
Items = Strs(s, "items"),
});
}
g.Quests.Add(q);
}
g.KillTasks = Strs(root, "killTasks");
if (root.TryGetProperty("society", out JsonElement so) && so.ValueKind == JsonValueKind.Object)
foreach (JsonProperty p in so.EnumerateObject())
if (p.Value.ValueKind == JsonValueKind.String) g.Society[p.Name] = p.Value.GetString() ?? "";
if (root.TryGetProperty("contracts", out JsonElement cs) && cs.ValueKind == JsonValueKind.Array)
foreach (JsonElement e in cs.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.Object) continue;
var c = new GuideContract
{
Title = Str(e, "title"), Url = Str(e, "url"), Rev = Long(e, "rev"), Description = Str(e, "description"),
Level = Str(e, "level"), Where = Str(e, "where"), Npc = Str(e, "npc"), Quests = Strs(e, "quests"),
};
string n = Str(e, "name");
c.Name = n.Length > 0 ? n : c.Title;
if (c.Title.Length > 0) g.Contracts.Add(c);
}
g.DynStampsRev = Long(root, "dynRev");
if (root.TryGetProperty("dynStamps", out JsonElement ds) && ds.ValueKind == JsonValueKind.Array)
foreach (JsonElement d in ds.EnumerateArray())
{
if (d.ValueKind != JsonValueKind.Object) continue;
var row = new GuideDynStamp
{
Area = Str(d, "area"), Place = Str(d, "place"), Npc = Str(d, "npc"), Coords = Str(d, "coords"),
Stamp = Str(d, "stamp"), Reward = Str(d, "reward"), Note = Str(d, "note"),
};
if (row.Stamp.Length > 0) g.DynStamps.Add(row);
}
return g;
}
catch (JsonException)
{
return Empty;
}
}
/// <summary>Stamps cleaned (GuideStamp.Clean) and each once: a guide saved by an older reader reads right at once.</summary>
private static List<string> Stamps(List<string> raw)
{
var list = new List<string>(raw.Count);
foreach (string r in raw)
{
string s = GuideStamp.Clean(r);
if (s.Length > 0 && !list.Exists(x => GuideStamp.Key(x) == GuideStamp.Key(s))) list.Add(s);
}
return list;
}
private static string Str(JsonElement o, string name) =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
private static long Long(JsonElement o, string name) =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long n) ? n : 0;
private static List<string> Strs(JsonElement o, string name)
{
var list = new List<string>();
if (!o.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) return list;
foreach (JsonElement e in a.EnumerateArray())
if (e.ValueKind == JsonValueKind.String && e.GetString() is { Length: > 0 } s) list.Add(s);
return list;
}
}

View file

@ -0,0 +1,131 @@
// The Leaftide wiki quest guide as RynthILT keeps it (2026-11-01): "RynthILT.Server" v2's GetQuestGuideInfoJson
// says where the guide file is and when it changed; the file is read again only then. Infinite Leaftide only
// (RynthOracle polls it while its server is ILT). Pump thread.
using System;
using System.IO;
using System.Text;
using System.Text.Json;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthOracle.Data;
internal sealed unsafe class QuestGuideClient
{
private const long PollMs = 2000;
private const long RequeryMs = 10_000;
private RynthIltServerApiV1* _table;
private long _nextPollAt, _nextQueryAt;
private readonly byte[] _buffer = new byte[4096];
private long _seenRevision = -1;
private string _seenPath = "";
private DateTime _fileTime = DateTime.MinValue;
public QuestGuide Guide { get; private set; } = QuestGuide.Empty;
/// <summary>Goes up when the guide or its status changes (the view redraws).</summary>
public int Revision { get; private set; }
/// <summary>RynthILT serves the guide (v2).</summary>
public bool Available { get; private set; }
public bool Running { get; private set; }
public bool LoginSaved { get; private set; }
public string Status { get; private set; } = "";
/// <summary>The server's name from the info ("tag", the server guide's; "" for RynthILT's).</summary>
public string Tag { get; private set; } = "";
/// <summary>The Stamps tab follows this guide's Dynamic Stamps (RynthILT's); a server guide's has none.</summary>
public bool FeedsDynamicStamps = true;
public void Clear()
{
_nextPollAt = 0;
_seenRevision = -1;
_seenPath = "";
if (Guide.Quests.Count > 0 || Available) Revision++;
Guide = QuestGuide.Empty;
Available = false;
Tag = "";
if (FeedsDynamicStamps) DynamicStampList.UseWiki(null);
Status = "";
}
public void Poll(RynthCoreHost host, long now)
{
if (now < _nextPollAt) return;
_nextPollAt = now + PollMs;
RynthIltServerApiV1* t = Table(host, now);
if (t == null)
{
if (Available) { Available = false; Revision++; }
return;
}
string json;
fixed (byte* b = _buffer)
{
int len = t->GetQuestGuideInfoJson(b, _buffer.Length);
json = len > 0 && len < _buffer.Length ? Encoding.UTF8.GetString(_buffer, 0, len) : "";
}
Take(json);
}
/// <summary>Takes RynthILT's info JSON and reads the guide file when it changed (internal: the tests feed one).</summary>
internal void Take(string infoJson)
{
if (infoJson.Length == 0) return;
try
{
using JsonDocument d = JsonDocument.Parse(infoJson);
JsonElement r = d.RootElement;
string path = r.TryGetProperty("path", out JsonElement p) && p.ValueKind == JsonValueKind.String ? p.GetString() ?? "" : "";
long rev = r.TryGetProperty("revision", out JsonElement v) && v.TryGetInt64(out long n) ? n : 0;
bool running = r.TryGetProperty("running", out JsonElement ru) && ru.ValueKind == JsonValueKind.True;
bool login = r.TryGetProperty("login", out JsonElement lo) && lo.ValueKind == JsonValueKind.True;
string status = r.TryGetProperty("status", out JsonElement st) && st.ValueKind == JsonValueKind.String ? st.GetString() ?? "" : "";
Tag = r.TryGetProperty("tag", out JsonElement tg) && tg.ValueKind == JsonValueKind.String ? tg.GetString() ?? "" : "";
bool changed = !Available || running != Running || login != LoginSaved || status != Status;
Available = true;
Running = running;
LoginSaved = login;
Status = status;
if (rev != _seenRevision || path != _seenPath)
{
bool pathChanged = path != _seenPath;
_seenRevision = rev;
_seenPath = path;
DateTime t = path.Length > 0 && File.Exists(path) ? File.GetLastWriteTimeUtc(path) : DateTime.MinValue;
if (t != _fileTime || pathChanged)
{
_fileTime = t;
Guide = t == DateTime.MinValue ? QuestGuide.Empty : QuestGuide.Parse(File.ReadAllText(path));
if (FeedsDynamicStamps) DynamicStampList.UseWiki(Guide.DynStamps); // the Stamps tab follows the wiki (2026-11-21)
}
changed = true;
}
if (changed) Revision++;
}
catch (Exception)
{
// A guide being written (or a bad one): the next poll tries again.
_seenRevision = -1;
}
}
/// <summary>Asks RynthILT to "refresh", "import" or open its "settings". False without RynthILT v2.</summary>
public bool Command(string line)
{
if (_table == null || _table->Version < 2) return false;
byte[] bytes = Encoding.UTF8.GetBytes(line + "\0");
fixed (byte* b = bytes) return _table->QuestGuideCommand(b) != 0;
}
private RynthIltServerApiV1* Table(RynthCoreHost host, long now)
{
if (_table != null && _table->Version >= 2) return _table;
_table = null;
if (now < _nextQueryAt || !host.HasGetPluginInterface) return null;
_nextQueryAt = now + RequeryMs;
var p = (RynthIltServerApiV1*)host.GetPluginInterface(RynthIltServer.PluginName, RynthIltServerApiV1.InterfaceName, 2);
if (p != null && p->Version >= 2 && p->StructSize >= (uint)sizeof(RynthIltServerApiV1) && p->GetQuestGuideInfoJson != null && p->QuestGuideCommand != null)
_table = p;
return _table;
}
}

View file

@ -0,0 +1,286 @@
// Who and where a wiki quest step names (2026-11-07). Most steps have no coordinates (5,739 of the
// guide's 7,091): "Talk to Xsao Lann in Fort Tethana.", "Return the collar to Xsao for your rewards.",
// "Take the note to Ahyara and she will sign it and hand you Congratulations (Nasun ibn Tifar & Ahyara)."
// Run this quest goes to the names instead ("/rnav go Xsao Lann || Fort Tethana": RynthNav takes the
// first one on its Atlas as a whole word or more) and, there, has RynthAi talk to the person or hand
// them the quest's items ("questloot talk|handin ..."). Host-free: the tests drive it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthOracle.Data;
internal static class QuestNames
{
/// <summary>Names one step offers at most.</summary>
public const int MaxNames = 6;
// A name: capitalised words, joined by a space, by "ibn", "of", "the"..., or by "al-"/"el-" ("Mara al-Luq").
private const string Tok = @"[A-Z][\p{L}'’]*(?:-[A-Z][\p{L}'’]*)*";
private static readonly Regex NameRx = new(
Tok + @"(?:(?:\s+(?:ibn|bin|of|the|de|du|da|la|le|von|van)\s+|\s+(?:al|el)-|\s+)" + Tok + @")*",
RegexOptions.CultureInvariant);
// A step's first word, when it starts a name ("Talk to ...", "Return ..."): not part of it.
private static readonly HashSet<string> Lead = new(StringComparer.OrdinalIgnoreCase)
{
"a", "an", "the", "this", "that", "these", "those", "then", "once", "after", "before", "when", "while", "if",
"you", "your", "he", "she", "they", "it", "his", "her", "their", "there", "here", "now", "next", "also",
"talk", "speak", "ask", "tell", "take", "bring", "return", "give", "hand", "deliver", "show", "turn", "go",
"run", "head", "walk", "travel", "enter", "exit", "leave", "use", "kill", "slay", "defeat", "loot", "find",
"collect", "gather", "get", "open", "read", "visit", "see", "meet", "wait", "repeat", "continue", "follow",
"search", "look", "inside", "outside", "at", "on", "in", "to", "from", "into", "with", "by", "near", "for",
"note", "notes", "route", "step", "tip", "warning", "optional", "quest", "item", "items", "reward", "rewards",
"portal", "recall", "and", "or", "but", "not", "all", "each", "every", "any", "some", "both", "either", "i",
"qb", "xp", "level", "lvl", "stamp", "stamps", "flag", "up", "down", "left", "right", "keep", "complete",
"close", "escape", "opposite", "npc", "npcs", "dereth", "please", "beware", "remember", "however", "otherwise",
"first", "second", "third", "finally", "last", "again", "back", "around", "through", "across", "inner", "outer",
"spotted", "seen", "weak", "strong", "immune", "resistant", "you'll", "you’ll", "you're", "you’re", "it's", "it’s",
"don't", "don’t", "do", "does", "be", "is", "are", "was", "will", "can", "may", "must", "should",
};
// Words that are never a place or a person on their own (damage types in "(Weak to Acid)").
private static readonly HashSet<string> NotNames = new(StringComparer.OrdinalIgnoreCase)
{
"acid", "fire", "frost", "cold", "lightning", "electric", "pierce", "piercing", "bludgeon", "bludgeoning",
"slash", "slashing", "nether", "void", "health", "stamina", "mana", "loot", "boss", "bosses", "key", "keys",
"hour", "hours", "minute", "minutes", "day", "days", "week", "weeks", "team", "group", "fellow", "fellowship",
};
// A direction starts a place's name ("North Yaraq Outpost"), so it isn't trimmed off; alone it is no name.
private static readonly HashSet<string> Directions = new(StringComparer.OrdinalIgnoreCase)
{
"north", "south", "east", "west", "northeast", "northwest", "southeast", "southwest", "n", "s", "e", "w",
};
// A hand-in: return/bring/deliver/show, give or hand (not "hand you"/"give you"), turn in, take ... to.
private static readonly Regex HandInRx = new(
@"\b(?:return|returns|returned|bring|deliver|show)\b"
+ @"|\b(?:hand|give)\b(?!\s+(?:you|it\s+to\s+you|them\s+to\s+you)\b)"
+ @"|\bturn(?:s|ed)?\s+(?:\w+\s+){0,3}?in\b"
+ @"|\btake\b[^.;]*?\bto\b",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
/// <summary>
/// The names <paramref name="s"/> gives, best first: the quest's own people ("starts with") the step
/// mentions, then the step's names in order, a place it comes "from" last. Item names, the quest's
/// title and its stamps are left out. For the first step the quest's start place comes last.
/// </summary>
public static List<string> Candidates(GuideQuest q, GuideStep s, bool firstStep = false)
{
var names = new List<string>();
var later = new List<string>();
string text = Strip(q, s.Text);
foreach (string person in Split(q.StartsWith))
{
foreach (string w in person.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
if (w.Length < 3 || Lead.Contains(w)) continue;
if (!WholeWord(text, w.Trim('"', '“', '”'))) continue;
Add(names, person);
// '"Pistol" Pete': the Atlas may write it without the quotes.
string plain = person.Replace("\"", "").Replace("“", "").Replace("”", "").Trim();
if (plain != person) Add(names, plain);
break;
}
}
foreach (Match m in NameRx.Matches(text))
{
string name = TrimLead(m.Value);
if (name.Length < 3 || Lead.Contains(name) || Directions.Contains(name) || NotNames.Contains(name) || IsExcluded(q, s, name)) continue;
// One word starting a sentence ("Unlock the door", "Jump down", "Just beyond..."): a name only when
// the quest knows it (its people, start, title) or the step writes it with a capital elsewhere too.
int nameAt = m.Index + Math.Max(0, m.Value.IndexOf(name, StringComparison.Ordinal)); // after "Kill ", "Talk to "...
if (!name.Contains(' ') && SentenceStart(text, nameAt) && !KnownToQuest(q, name) && !CapitalElsewhere(text, name, nameAt))
continue;
// "From Yaraq follow the paths...": where it starts from, not where it goes.
bool from = Regex.IsMatch(text.Substring(0, m.Index), @"\bfrom\s+(?:the\s+)?$", RegexOptions.IgnoreCase);
// A person already named in full ("Xsao" after "Xsao Lann"): once.
bool part = names.Exists(n => n.StartsWith(name + " ", StringComparison.OrdinalIgnoreCase) || n.Equals(name, StringComparison.OrdinalIgnoreCase));
if (part) continue;
Add(from ? later : names, name);
}
foreach (string n in later) Add(names, n);
if (firstStep)
foreach (string at in Split(q.StartsAt, people: false)) Add(names, at);
// A name that is only part of another ("Xsao" of Xsao Lann, "Candeth" of Candeth Keep): the longer one.
// (Not inside coordinates written with a place: "1.5N, 71.6W in Fort Tethana" keeps Fort Tethana.)
names.RemoveAll(n => names.Exists(o => !ReferenceEquals(o, n) && !o.Any(char.IsDigit) && WordsOf(o).IsProperSupersetOf(WordsOf(n))));
if (names.Count > MaxNames) names.RemoveRange(MaxNames, names.Count - MaxNames);
return names;
}
/// <summary>
/// The names for step <paramref name="i"/>: its own, or, when it names nobody ("Hand her each note"),
/// the step before's (where the run already is).
/// </summary>
public static List<string> TargetsAt(GuideQuest q, int i)
{
if (i < 0 || i >= q.Steps.Count) return new List<string>();
List<string> c = Candidates(q, q.Steps[i], i == 0);
if (c.Count == 0 && i > 0) c = Candidates(q, q.Steps[i - 1], i - 1 == 0);
return c;
}
// Talking: talk, speak, ask, tell, visit, meet, see, find, greet, report, listen.
private static readonly Regex TalkRx = new(@"\b(?:talk|talks|speak|speaks|ask|asks|tell|visit|meet|see|find|greet|report|listen|chat)\b",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
/// <summary>The step talks to someone: it says so ("Talk to", "find"), or names one of the quest's own people.</summary>
public static bool IsTalk(GuideQuest q, GuideStep s)
{
// A note in brackets ("(see map)") isn't what the step does.
string text = Regex.Replace(Strip(q, s.Text), @"\([^)]*\)", " ");
// "dropped by Female Tuskers", "kill the Captain": monsters, nobody to talk to (2026-11-07).
if (KillRx.IsMatch(text) && !TalkRx.IsMatch(text)) return false;
if (TalkRx.IsMatch(text)) return true;
foreach (string person in Split(q.StartsWith))
if (person.Length >= 3 && WholeWord(text, person.Split(' ')[0])) return true;
return false;
}
internal static readonly Regex KillRx = new(@"\b(?:dropped\s+by|drops?\s+from|kill|kills|slay|slays|defeat|defeats|loot|loots|hunt)\b",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
/// <summary>
/// The items the rewards say the quest hands in ("For Hand in Female Tusker Tusk:", "For Vial of The
/// Architect's Blood:"): the run loots them (2026-11-07, the wiki lists no loot for such quests).
/// </summary>
public static List<string> RewardItems(GuideQuest q)
{
var list = new List<string>();
foreach (string r in q.Rewards)
{
Match m = RewardForRx.Match(r ?? "");
if (!m.Success) continue;
string item = m.Groups["item"].Value.Trim();
if (item.Length < 3 || Regex.IsMatch(item, @"^(?:completing|completion|finishing|each|the\s+quest|turning)", RegexOptions.IgnoreCase)) continue;
if (!list.Exists(x => x.Equals(item, StringComparison.OrdinalIgnoreCase))) list.Add(item);
}
return list;
}
private static readonly Regex RewardForRx = new(@"^For\s+(?:(?:Hand(?:ing)?\s+in|turning\s+in|giving|returning)\s+)?(?:the\s+|a\s+|an\s+)?(?<item>[^:]+?)\s*:\s*$",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
/// <summary>The step hands something over ("Return the collar to Xsao", "Take the note to Ahyara").</summary>
public static bool IsHandIn(GuideStep s) => HandInRx.IsMatch(Strip(null, s.Text));
/// <summary>
/// What to hand over at step <paramref name="step"/>: the quest's items got before it (its loot and the
/// items earlier steps name), not the ones this step gives. Those the step's words name ("the collar":
/// Darling's Collar) when there are any, else all of them.
/// </summary>
public static List<string> HandInItems(GuideQuest q, int step)
{
// Only what is in hand by now: the items of the steps before this one, and loot no step names.
var got = new List<string>();
for (int i = 0; i < step && i < q.Steps.Count; i++)
foreach (string it in q.Steps[i].Items) Add(got, it);
foreach (string it in q.Loot)
if (!q.Steps.Exists(st => st.Items.Exists(x => x.Equals(it, StringComparison.OrdinalIgnoreCase)))) Add(got, it);
if (step >= 0 && step < q.Steps.Count)
got.RemoveAll(it => q.Steps[step].Items.Exists(x => x.Equals(it, StringComparison.OrdinalIgnoreCase)));
if (step < 0 || step >= q.Steps.Count) return got;
string text = q.Steps[step].Text;
var named = got.FindAll(it =>
{
foreach (string w in Bare(it).Split(new[] { ' ', '\'', '’' }, StringSplitOptions.RemoveEmptyEntries))
if (w.Length >= 4 && !Lead.Contains(w) && WholeWord(text, w)) return true;
return false;
});
return named.Count > 0 ? named : got;
}
private static bool IsExcluded(GuideQuest q, GuideStep s, string name)
{
if (name.Equals(q.Title, StringComparison.OrdinalIgnoreCase)) return true;
foreach (string it in s.Items) if (Bare(it).Equals(name, StringComparison.OrdinalIgnoreCase)) return true;
foreach (string it in q.Loot) if (Bare(it).Equals(name, StringComparison.OrdinalIgnoreCase)) return true;
foreach (string st in s.Stamps) if (st.Equals(name, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
/// <summary>The text without the item names in it (a person named only inside an item's name isn't the step's).</summary>
private static string Strip(GuideQuest? q, string text)
{
text ??= "";
if (q == null) return text;
var items = new List<string>(q.Loot);
foreach (GuideStep st in q.Steps) items.AddRange(st.Items);
items.Sort((a, b) => b.Length.CompareTo(a.Length));
foreach (string it in items)
if (it.Length > 0) text = text.Replace(it, " ", StringComparison.OrdinalIgnoreCase);
return text;
}
private static string TrimLead(string name)
{
string[] w = name.Split(' ', StringSplitOptions.RemoveEmptyEntries);
int i = 0;
// "Using the map", "Killing Burnja", "Eventually you...": a sentence's first word, not a name.
while (i < w.Length && (Lead.Contains(w[i]) || (i == 0 && IsAdverbOrVerb(w[i])))) i++;
if (i >= w.Length) return "";
int j = w.Length - 1;
while (j > i && Lead.Contains(w[j])) j--;
string n = string.Join(" ", w, i, j - i + 1).Trim('\'', '’', '-');
if (n.EndsWith("'s", StringComparison.OrdinalIgnoreCase) || n.EndsWith("’s", StringComparison.OrdinalIgnoreCase)) n = n.Substring(0, n.Length - 2);
return n;
}
private static bool IsAdverbOrVerb(string w) =>
w.Length > 4 && (w.EndsWith("ing", StringComparison.OrdinalIgnoreCase) || w.EndsWith("ly", StringComparison.OrdinalIgnoreCase));
/// <summary>
/// "Nasun ibn Tifar / Ahyara", "Jarvis Hammerstone (Optional)": the separate names, notes in brackets
/// left off. A place ("1.5N, 71.6W in Fort Tethana") is not split at its comma.
/// </summary>
internal static IEnumerable<string> Split(string s, bool people = true)
{
string pattern = people ? @"\s*(?:/|;|,|\bor\b|\band\b)\s*" : @"\s*(?:\s/\s|;|\bor\b)\s*";
foreach (string part in Regex.Split(s ?? "", pattern, RegexOptions.IgnoreCase))
{
string p = Regex.Replace(part, @"\s*\([^)]*\)", "").Trim();
if (p.Length >= 2) yield return p;
}
}
private static bool SentenceStart(string text, int at)
{
string before = text.Substring(0, at).TrimEnd();
return before.Length == 0 || ".!?:;-–(\"".IndexOf(before[^1]) >= 0;
}
private static bool KnownToQuest(GuideQuest q, string name) =>
WholeWord(q.StartsWith, name) || WholeWord(q.StartsAt, name) || WholeWord(q.Title, name);
private static bool CapitalElsewhere(string text, string name, int at)
{
foreach (Match m in Regex.Matches(text, @"(?<![\p{L}\d])" + Regex.Escape(name) + @"(?![\p{L}\d])", RegexOptions.CultureInvariant))
if (m.Index != at && !SentenceStart(text, m.Index)) return true;
return false;
}
private static HashSet<string> WordsOf(string name) =>
new(Regex.Split(name, @"[^\p{L}\d'’-]+").Where(w => w.Length > 0), StringComparer.OrdinalIgnoreCase);
private static string Bare(string item)
{
item = (item ?? "").Trim();
int open = item.LastIndexOf(" (", StringComparison.Ordinal);
return open > 0 && item.EndsWith(")", StringComparison.Ordinal) ? item.Substring(0, open) : item;
}
private static bool WholeWord(string text, string word) =>
Regex.IsMatch(text, @"(?<![\p{L}\d])" + Regex.Escape(word) + @"(?![\p{L}\d])", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static void Add(List<string> list, string s)
{
s = s.Trim();
if (s.Length > 0 && !list.Exists(x => x.Equals(s, StringComparison.OrdinalIgnoreCase))) list.Add(s);
}
}

View file

@ -0,0 +1,74 @@
// Quests an NPC gives (2026-11-08, Silentkelpie: "when one clicks on a npc and they talk back check to see if
// their text is the start of a quest and ask if you want to do that quest"). An NPC talking to the character
// ("Xsao Lann tells you, \"...\"", "Warden says, \"...\"") is matched against the wiki guide's quests by who
// they start with (GuideQuest.StartsWith); the quests it starts are offered (the RynthOracle quest offer
// window), the ones whose words the NPC's text shares first. Host-free: the tests drive it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthOracle.Data;
internal static class QuestOffers
{
/// <summary>Quests one offer lists at most.</summary>
public const int MaxQuests = 4;
// "Xsao Lann tells you, "..."", "Warden says, "..."" (an NPC's Tell and Say emotes).
private static readonly Regex NpcLineRx = new(
@"^(?<name>[A-Z\""][^,\""]{1,60}?)\s+(?:tells\s+you|says),\s*\""(?<text>.*)\""\s*$",
RegexOptions.CultureInvariant);
/// <summary>An NPC talking to the character: who and what. False for anything else (and for "You say").</summary>
public static bool TryNpcLine(string? line, out string name, out string text)
{
name = text = "";
Match m = NpcLineRx.Match((line ?? "").Trim());
if (!m.Success) return false;
name = m.Groups["name"].Value.Trim();
text = m.Groups["text"].Value.Trim();
if (name.Equals("You", StringComparison.OrdinalIgnoreCase)) return false;
return name.Length >= 2;
}
/// <summary>
/// The guide's quests <paramref name="npc"/> starts (one of the people its "starts with" names, as the game
/// writes them: quotes and a note in brackets left off), the ones the NPC's <paramref name="text"/> shares
/// most words with first (its title, overview and first step).
/// </summary>
public static List<GuideQuest> StartedBy(IEnumerable<GuideQuest> quests, string npc, string text)
{
string who = Norm(npc);
var found = new List<(GuideQuest Q, int Score, int Order)>();
int order = 0;
if (who.Length < 2) return new List<GuideQuest>();
foreach (GuideQuest q in quests)
{
order++;
bool starts = false;
foreach (string person in QuestNames.Split(q.StartsWith))
if (Norm(person) == who) { starts = true; break; }
if (!starts) continue;
found.Add((q, Overlap(text, q), order));
}
return found.OrderByDescending(f => f.Score).ThenBy(f => f.Order).Select(f => f.Q).ToList();
}
/// <summary>How many of the quest's words (4 letters or more) the NPC's text has.</summary>
internal static int Overlap(string text, GuideQuest q)
{
var said = Words(text);
if (said.Count == 0) return 0;
string about = q.Title + " " + q.Overview + " " + (q.Steps.Count > 0 ? q.Steps[0].Text : "");
int n = 0;
foreach (string w in Words(about)) if (said.Contains(w)) n++;
return n;
}
private static HashSet<string> Words(string s) =>
new(Regex.Split(s ?? "", @"[^\p{L}']+").Where(w => w.Length >= 4 && w != "quest"), StringComparer.OrdinalIgnoreCase);
private static string Norm(string s) =>
Regex.Replace(Regex.Replace(s ?? "", @"[\""“”]", ""), @"\s+", " ").Trim().ToLowerInvariant();
}

View file

@ -0,0 +1,854 @@
using System.Linq;
// "Run this quest" (2026-11-01): walks a wiki quest's steps (QuestGuide.cs) with RynthNav. Each step that
// isn't done yet (its stamps not all held) is visited in order: RynthNav goes to its coordinates ("/rnav go
// 28.5S, 90.9W"; a step with several places goes to each in turn), and when RynthNav says it arrived the
// step's instructions go to chat. The step is done when the server stamps it ("You've stamped X!") or its
// flags show up, or with Next. A step without coordinates is shown and waits for its stamp or Next. The
// quest's loot (the items its steps kill or loot for) goes on RynthAi's quest loot list while it runs
// ("questloot" broker action, "add <name>") and comes off again when it ends. Since 2026-11-05 the run also makes the
// quest's own loot profile the one in use: RynthAi builds it from LootProfiles\base-quest-dynamic.utl and the
// quest's items ("questloot profile <quest>|<item>..."), and goes back to the profile before when the run ends
// ("questloot profile off"). Since 2026-11-07 a step without coordinates goes to the people and places it
// names (QuestNames: "Talk to Xsao Lann in Fort Tethana" is "/rnav go Xsao Lann || Fort Tethana"), and at
// a step's place RynthAi talks to the person it names ("questloot talk ...") or, on a hand-in ("Return the
// collar to Xsao"), gives them the quest's items got so far ("questloot handin ..."). Inside a dungeon
// (2026-11-07) RynthAi walks the dungeon's map instead of RynthNav: to a step's coordinates ("questloot
// dungeon goto"), or all over it for a step that names none ("dungeon patrol"), fighting, looting the quest's
// items and opening doors (the quest's keys first on a locked one); a step that only takes you in ("Enter
// the Keep") is done once you are in, and "dungeon stop" ends the walk when you come out or the run ends.
// A step's place reached outdoors whose text enters something has RynthAi use the portal there ("dungeon
// enter"). Since 2026-11-08 (the Acid Axe Quest, 09:01: it went to Suntik Village and stopped there): a step
// that only travels ("Travel to Suntik Village at ...") is done on arrival; a step goes to the coordinates its
// own words give, not the ones its notes name for another route ("Route 2: ... to 16.9N 3.5E"); a step that
// gets items ("grab the Acid Axe on the ground") asks RynthAi which are carried ("questloot have ...": RynthAi
// picks the rest up off corpses and the ground) and is done when RynthAi says it got them all ("Quest: got X"),
// where the run already is when the step names no place; and entering a building isn't taking a portal.
// Pump thread; no host calls here (the tests drive it with fake senders).
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthOracle.Data;
internal sealed class QuestRunner
{
/// <summary>RynthNav's "goto: arrived" line (RynthNavPlugin FinishGoto).</summary>
internal const string ArrivedText = "goto: arrived";
private readonly Func<string, bool> _nav;
private readonly Func<string, bool> _ai;
private readonly Action<string> _print;
private readonly List<string> _lootAdded = new();
private bool _profileOn; // RynthAi switched to this quest's loot profile
private List<string> _targets = new(); // the step's people and places (QuestNames)
private bool _inDungeon; // the character is in a dungeon (OnWhere)
private string _fallback = ""; // coordinates to go to when RynthNav knows none of the step's names
private uint _dungeon; // the dungeon's landblock (OnWhere), 0 outdoors
private string _wentTo = ""; // the coordinates RynthNav last went to outdoors
/// <summary>The Town Network's landblock: a portal hub on RynthNav's routes, not a quest dungeon.</summary>
internal const uint TownNetworkLandblock = 0x0007;
private bool _dungeonWalk; // RynthAi walks the dungeon for the run
private int _askedAt = -1; // the step RynthAi was asked about its items ("have")
private bool _portalTried; // a travel step's place: its portal looked for once
private readonly HashSet<string> _got = new(StringComparer.OrdinalIgnoreCase); // quest items RynthAi got this run (bare names)
private bool _insideAsk; // in a dungeon: RynthNav was asked which of the step's people is in it ("inside")
private uint _insideCell; // RynthNav's arrival named the cell the step's person is in; walked to once inside
/// <summary>RynthAi walks a dungeon for the run (its map: a goto or the patrol).</summary>
public bool DungeonWalk => _dungeonWalk;
public bool InDungeon => _inDungeon;
/// <summary>What the last arrival had RynthAi do: "talk", "handin" or "" (for the view and the tests).</summary>
public string LastNpc { get; private set; } = "";
/// <summary>The current step's people and places.</summary>
public IReadOnlyList<string> Targets => _targets;
private Func<string, bool> _stampDone = _ => false;
/// <summary>Player society when the run started (filters CH/EW/RB wiki alternatives).</summary>
private SocietyStanding _society;
public GuideQuest? Quest { get; private set; }
/// <summary>The step being done (index into Quest.Steps), -1 before the first.</summary>
public int Step { get; private set; } = -1;
/// <summary>Which of the step's places RynthNav is going to (0-based).</summary>
public int Place { get; private set; }
public bool Active => Quest != null;
public bool Travelling { get; private set; }
/// <summary>What the runner is doing, for the view.</summary>
public string Note { get; private set; } = "";
public int Revision { get; private set; }
public IReadOnlyList<string> LootAdded => _lootAdded;
/// <param name="nav">Sends a RynthNav command ("go 28.5S, 90.9W", "stop"); false when RynthNav isn't there.</param>
/// <param name="ai">Sends a RynthAi command ("questloot add X"); false when RynthAi isn't there.</param>
/// <param name="print">A line to chat.</param>
public QuestRunner(Func<string, bool> nav, Func<string, bool> ai, Action<string> print)
{
_nav = nav;
_ai = ai;
_print = print;
}
/// <summary>A step is done when it has stamps and every one is held.</summary>
public bool StepDone(GuideStep s)
{
if (s.Stamps.Count == 0) return false;
foreach (string st in s.Stamps)
if (!_stampDone(st)) return false;
return true;
}
/// <summary>
/// Starts <paramref name="q"/> at its first step not done (from <paramref name="fromStep"/> when given).
/// <paramref name="stampDone"/> says whether the character holds a stamp. With <paramref name="loot"/>, the
/// quest's loot goes on RynthAi's quest loot list.
/// <paramref name="society"/> picks Celestial Hand / Eldrytch Web / Radiant Blood NPCs, forts and
/// stronghold portals when the wiki lists all three (otherwise the run loops on the wrong faction).
/// </summary>
public void Start(GuideQuest q, Func<string, bool> stampDone, bool loot, int fromStep = -1,
SocietyStanding society = default)
{
if (Active) Stop("switched quests");
_society = society;
if (society.IsMember && SocietyQuestResolve.NeedsFilter(q))
{
q = SocietyQuestResolve.ForPlayer(q, society);
_print($"Society run: using {society.SocietyName} ({SocietyQuestResolve.Code(society)}) portals and NPCs.");
}
else if (!society.IsMember && SocietyQuestResolve.NeedsFilter(q))
_print("Society run: you are not in a society — wiki lists all three factions; join one (or pick the right portal yourself).");
Quest = q;
_got.Clear();
_askedAt = -1;
_portalTried = false;
// A run starts at the quest's first part (2026-11-07): stamps already held (an earlier run of a
// repeatable quest) don't finish its steps; only the ones this run gets do.
var heldAtStart = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (GuideStep st in q.Steps)
foreach (string stamp in st.Stamps)
if (stampDone(stamp)) heldAtStart.Add(GuideStamp.Key(stamp));
_stampDone = stamp => stampDone(stamp) && !heldAtStart.Contains(GuideStamp.Key(stamp));
if (loot)
{
// The quest's items (its loot, and what the rewards say it hands in), then its loot profile, always:
// with no items it is base-quest-dynamic alone (2026-11-07: the Female Tusker Tusk run built none).
foreach (string it in QuestNames.RewardItems(q))
if (!q.Loot.Exists(x => x.Equals(it, StringComparison.OrdinalIgnoreCase))) q.Loot.Add(it);
AddLoot(q);
_profileOn = _ai("profile " + ProfileLine(q));
}
Step = -1;
if (fromStep >= 0 && fromStep < q.Steps.Count) { Step = fromStep; Place = 0; GoStep(); }
else Advance(first: true);
Changed();
}
/// <summary>The quest's loot onto RynthAi's quest loot list (what was added comes off at the end).</summary>
public int AddLoot(GuideQuest q)
{
int n = 0;
foreach (string item in q.Loot)
{
if (_lootAdded.Contains(item)) continue;
if (_ai("add " + item)) { _lootAdded.Add(item); n++; }
}
return n;
}
private void RemoveLoot()
{
if (_dungeonWalk) _ai("dungeon stop");
_dungeonWalk = false;
foreach (string item in _lootAdded) _ai("remove " + item);
_lootAdded.Clear();
if (_profileOn) _ai("profile off");
_profileOn = false;
}
/// <summary>
/// "&lt;quest&gt;|&lt;item&gt;|&lt;item&gt;...": the quest and its loot for RynthAi's quest loot profile
/// ("questloot build ..." / "questloot profile ..."). A '|' in a name becomes '/'.
/// </summary>
public static string ProfileLine(GuideQuest q)
{
var parts = new List<string> { q.Title.Replace('|', '/') };
foreach (string item in q.Loot) parts.Add(item.Replace('|', '/'));
return string.Join("|", parts);
}
/// <summary>Has RynthAi write the quest's loot profile (LootProfiles\Quests); false without RynthAi or loot.</summary>
public bool BuildProfile(GuideQuest q) => _ai("build " + ProfileLine(q)); // no items: base-quest-dynamic alone
/// <summary>Next: the next place of this step, else the next step not done.</summary>
public void Next()
{
if (Quest == null) return;
if (Step >= 0 && Step < Quest.Steps.Count && Place + 1 < Places(Quest.Steps[Step]).Count)
{
Place++;
GoPlace();
}
else Advance(first: false);
Changed();
}
/// <summary>
/// The step the player picked (2026-11-08: "click on the step you want to do vs using just next or back"):
/// done or not, at its first place; RynthNav's trip to the old step stops.
/// </summary>
public void GoTo(int step)
{
if (Quest == null || step < 0 || step >= Quest.Steps.Count) return;
if (Travelling) _nav("stop");
Travelling = false;
Step = step;
Place = 0;
_askedAt = -1;
_print($"Quest run: step {step + 1}/{Quest.Steps.Count}.");
GoStep();
Changed();
}
/// <summary>Back one step (done or not), at its first place.</summary>
public void Back()
{
if (Quest == null || Step <= 0) return;
Step--;
Place = 0;
GoStep();
Changed();
}
/// <summary>Goes to the current step's current place again (RynthNav stopped, the player wandered off).</summary>
public void Again()
{
if (Quest == null) return;
GoStep(keepPlace: true);
Changed();
}
public void Stop(string why = "stopped")
{
if (Quest == null) return;
if (Travelling) _nav("stop");
_print($"Quest run {why}: {Quest.Title}.");
Travelling = false;
RemoveLoot();
Quest = null;
Step = -1;
Place = 0;
Note = "";
Changed();
}
/// <summary>A chat line: a stamp (the step may be done) or RynthNav's arrival.</summary>
public void OnChat(string line)
{
if (Quest == null) return;
string? stamp = GuideStamp.FromChat(line);
if (stamp != null)
{
CheckStep(GuideStamp.Key(stamp));
return;
}
if (line.Contains(GotPrefix, StringComparison.Ordinal))
{
OnGot(line);
return;
}
// No portal at a travel step's place after all: being there is the step.
if (_portalTried && line.Contains("[RynthAi] Quest: no portal right here", StringComparison.Ordinal)
&& Quest != null && Step >= 0 && Step < Quest.Steps.Count && !_inDungeon && TravelOnly(Quest, Step))
{
_portalTried = false;
_print($"Step {Step + 1} done: you're there.");
Advance(first: false);
Changed();
return;
}
if (_insideAsk && Travelling && line.Contains("[RynthNav] inside:", StringComparison.Ordinal))
{
// None of the step's people is in this dungeon (by the Atlas): walk it as before.
_insideAsk = false;
Travelling = false;
GuideStep si = Quest.Steps[Step];
if (!GoDungeon(Quest, si)) Note = $"Step {Step + 1}: {si.Text} (Next when done)";
DoNpc();
Changed();
return;
}
if (Travelling && line.Contains("[RynthNav]", StringComparison.Ordinal) && line.Contains(ArrivedText, StringComparison.OrdinalIgnoreCase))
{
Travelling = false;
_insideAsk = false;
GuideStep s = Quest.Steps[Step];
// The step's person is inside a dungeon (RynthNav names the cell): RynthAi walks its map there, and the talk
// or hand-in waits for them on the way (2026-11-11).
uint cellIn = InsideCell(line);
if (cellIn != 0)
{
_insideCell = cellIn;
Note = $"Step {Step + 1}: {s.Text}";
_print($"Step {Step + 1}/{Quest.Steps.Count}: {s.Text}");
foreach (string n in s.Notes) _print(" " + n);
if (_inDungeon) WalkToCell(Quest, s);
else Note = $"Step {Step + 1}: in; walking to {string.Join(" or ", _targets)} once the dungeon loads";
AskItems(s);
Changed();
return;
}
Note = $"Step {Step + 1}: here. {s.Text}";
_print($"Step {Step + 1}/{Quest.Steps.Count}: {s.Text}");
foreach (string n in s.Notes) _print(" " + n);
DoNpc();
if (_inDungeon)
{
// RynthNav's route ended inside (the step's place is in the dungeon): walk it as the step says.
if (EntersOnly(s)) { _print($"Step {Step + 1} done: you're in."); Advance(first: false); }
else GoDungeon(Quest, s);
}
// "Enter the Hidden Keep at ...", "Take the portal to ...": the portal at the step's place takes you in.
else if (GoesIn(Quest, Step)) _ai("dungeon enter" + PortalHint(s, _society));
// The step's place is a dungeon's portal and the next step is inside it (2026-11-10, "the route isn't
// going in the portal"): a portal right there is taken; the step ends in the dungeon (OnWhere).
else if (TravelOnly(Quest, Step) && NextInside(Quest, Step) && !_portalTried)
{
_portalTried = true;
_ai("dungeon enter near" + PortalHint(s, _society));
Changed();
return;
}
// "Travel to Suntik Village at ...": being there is the step (2026-11-08: the run stopped there).
else if (TravelOnly(Quest, Step))
{
if (Place + 1 < Places(s).Count) { Place++; GoPlace(); }
else { _print($"Step {Step + 1} done: you're there."); Advance(first: false); }
Changed();
return;
}
if (Quest != null && Step >= 0 && Step < Quest.Steps.Count && Quest.Steps[Step] == s) AskItems(s);
Changed();
}
else if (Travelling && line.Contains("[RynthNav]", StringComparison.Ordinal)
&& (line.Contains("none of these is a place on the map", StringComparison.OrdinalIgnoreCase)
|| line.Contains("on the map", StringComparison.OrdinalIgnoreCase) && line.Contains("no place called", StringComparison.OrdinalIgnoreCase)))
{
// RynthNav doesn't know where the step's names are: coordinates the quest gives elsewhere, else say so.
Travelling = false;
if (_fallback.Length > 0)
{
string at = _fallback;
_fallback = "";
if (Go(at, $"Step {Step + 1}: RynthNav doesn't know the name; going to {at}")) { Changed(); return; }
}
string who = _targets.Count > 0 ? string.Join(" or ", _targets) : "it";
Note = $"Step {Step + 1}: RynthNav doesn't know where {who} is - go there yourself, then Again (to talk) or Next.";
_print($"Step {Step + 1}/{Quest.Steps.Count}: {Quest.Steps[Step].Text}");
DoNpc();
Changed();
}
else if (Travelling && line.Contains("[RynthNav] goto:", StringComparison.OrdinalIgnoreCase))
{
// RynthNav gave up or was stopped: say so; Again tries once more.
Travelling = false;
Note = $"Step {Step + 1}: RynthNav {line.Substring(line.IndexOf("goto:", StringComparison.OrdinalIgnoreCase))} (Again tries once more).";
Changed();
}
}
/// <summary>The flags changed (a /myquests read): the current step may be done.</summary>
public void OnFlagsChanged() => CheckStep(null);
private void CheckStep(string? stampKey)
{
if (Quest == null || Step < 0 || Step >= Quest.Steps.Count) return;
GuideStep s = Quest.Steps[Step];
if (s.Stamps.Count == 0) return;
bool mine = stampKey == null || s.Stamps.Exists(x => GuideStamp.Key(x) == stampKey);
if (!mine) return;
// The chat line comes before the flag list knows it: the stamp just seen counts.
bool done = true;
foreach (string st in s.Stamps)
if (GuideStamp.Key(st) != stampKey && !_stampDone(st)) { done = false; break; }
if (!done) return;
_print($"Step {Step + 1} done.");
Advance(first: false);
Changed();
}
private void Advance(bool first)
{
GuideQuest q = Quest!;
int i = Step + 1;
while (i < q.Steps.Count && StepDone(q.Steps[i])) i++;
if (i >= q.Steps.Count)
{
if (first && q.Steps.Count > 0) _print($"Every step of {q.Title} is stamped already.");
Finish();
return;
}
Step = i;
Place = 0;
GoStep();
}
private void Finish()
{
GuideQuest q = Quest!;
_print($"Quest run done: {q.Title}." + (q.ExtraStamps.Count > 0 ? " (The wiki lists more stamps: " + string.Join(", ", q.ExtraStamps) + ".)" : ""));
Travelling = false;
RemoveLoot();
Quest = null;
Step = -1;
Note = "";
}
private void GoStep(bool keepPlace = false)
{
GuideQuest q = Quest!;
GuideStep s = q.Steps[Step];
if (!keepPlace) Place = 0;
_portalTried = false;
_insideAsk = false;
_insideCell = 0;
_targets = QuestNames.TargetsAt(q, Step);
_fallback = "";
// In a dungeon, a step that happens outside it (a hand-in, "Return to ...") leaves it: the dungeon walk
// stops and RynthNav takes the run there (2026-11-10: it kept fighting there after the last item).
if (_inDungeon && HappensOutside(q, Step))
{
if (_dungeonWalk) { _ai("dungeon stop"); _dungeonWalk = false; }
_print($"Step {Step + 1}: leaving the dungeon for it.");
}
else if (_inDungeon && _targets.Count > 0 && Places(s).Count == 0 && (QuestNames.IsHandIn(s) || QuestNames.IsTalk(q, s))
&& _nav("inside " + string.Join(" || ", _targets)))
{
// The step's person may be in this dungeon (the Bur, a dungeon's quest giver, 2026-11-11): RynthNav says
// which cell, and RynthAi walks there; not here, the dungeon is walked as before (OnChat).
_insideAsk = true;
Travelling = true;
Note = $"Step {Step + 1}: looking for {string.Join(" or ", _targets)} in this dungeon";
AskItems(s);
return;
}
else if (_inDungeon && GoDungeon(q, s)) { AskItems(s); return; }
// Items carried already (picked up by hand, an earlier run) finish the step before the trip.
if (Places(s).Count > 0) { GoPlace(); AskItems(s); return; }
// Coordinates in the step's own words ("Ollar at 71.4N, 28.6W"): there, before any name.
// The same in the names it gives (the start place "A Renegade Stronghold at 71.4N, 28.6W").
string? own0 = CoordsIn(s.Text) ?? s.Notes.Select(CoordsIn).FirstOrDefault(c => c != null)
?? QuestNames.Candidates(q, s, Step == 0).Select(CoordsIn).FirstOrDefault(c => c != null);
if (own0 != null && Go(own0, $"Step {Step + 1}: going to {own0}")) { AskItems(s); return; }
// "Enter the blacksmith building and grab the Acid Axe on the ground": no place of its own, so it is
// where the run already is (the step before's place); the items are picked up there.
if (Step > 0 && IsPickup(s) && !QuestNames.IsHandIn(s))
{
Travelling = false;
Note = $"Step {Step + 1}: picking up {string.Join(", ", s.Items)} here (RynthAi's quest loot) - Next when done";
_print($"Step {Step + 1}/{q.Steps.Count}: {s.Text}");
foreach (string n in s.Notes) _print(" " + n);
AskItems(s);
return;
}
_fallback = FallbackCoords(q, Step) ?? "";
// No coordinates: the people and places the step names, in order (RynthNav takes the first on its
// Atlas; the first step adds the quest's start place).
List<string> own = QuestNames.Candidates(q, s, Step == 0);
if (own.Count > 0 && Go(string.Join(" || ", own), $"Step {Step + 1}: going to {string.Join(" or ", own)}"))
{
AskItems(s);
return;
}
Travelling = false;
Note = $"Step {Step + 1}: {s.Text} (Next when done)";
_print($"Step {Step + 1}/{q.Steps.Count}: {s.Text}");
foreach (string n in s.Notes) _print(" " + n);
// Naming nobody ("Hand her each note"): the person of the step before, where the run already is.
if (own.Count == 0) DoNpc();
AskItems(s);
}
/// <summary>RynthAi's line for a quest item got (RynthAiPlugin.QuestNpc.cs QuestGotPrefix).</summary>
internal const string GotPrefix = "[RynthAi] Quest: got ";
/// <summary>
/// A step that gets items and has no stamp to say it's done: RynthAi says which are carried already
/// ("questloot have ..."); the rest come off corpses and the ground (the quest loot list).
/// </summary>
private void AskItems(GuideStep s)
{
if (s.Items.Count == 0 || QuestNames.IsHandIn(s) || _askedAt == Step) return;
_askedAt = Step; // once a step: RynthAi's quest loot list does the rest
_ai("have " + string.Join(" | ", s.Items.ConvertAll(i => i.Replace('|', '/'))));
}
private bool Got(string item) => _got.Contains(BareItem(item));
/// <summary>"[RynthAi] Quest: got Acid Axe." / "... (already in your pack).": the step that wanted it may be done.</summary>
private void OnGot(string line)
{
string name = line.Substring(line.IndexOf(GotPrefix, StringComparison.Ordinal) + GotPrefix.Length).Trim();
if (name.EndsWith("(already in your pack).", StringComparison.OrdinalIgnoreCase))
name = name.Substring(0, name.Length - "(already in your pack).".Length).Trim();
name = name.TrimEnd('.').Trim();
if (name.Length == 0) return;
_got.Add(BareItem(name));
if (Quest == null || Step < 0 || Step >= Quest.Steps.Count) return;
GuideStep s = Quest.Steps[Step];
// Every item of the step is in the pack: on to the next step, its stamp or not (2026-11-10: "when a quest
// pickups the last loot item it should move to the next step vs keep fighting").
if (s.Items.Count == 0 || QuestNames.IsHandIn(s) || !s.Items.TrueForAll(Got)) return;
if (Travelling) { _nav("stop"); Travelling = false; }
_print($"Step {Step + 1} done: you have {string.Join(", ", s.Items)}.");
Advance(first: false);
Changed();
}
/// <summary>An item's name without a note in brackets at the end ("Darling's Collar (Quest Item)").</summary>
internal static string BareItem(string name)
{
name = (name ?? "").Trim();
int open = name.LastIndexOf(" (", StringComparison.Ordinal);
return open > 0 && name.EndsWith(")", StringComparison.Ordinal) ? name.Substring(0, open).Trim() : name;
}
// "Return to ...", "Bring ... to", a hand-in: done out of the dungeon.
private static readonly System.Text.RegularExpressions.Regex OutsideRx = new(
@"\b(?:return|returns|go\s+back|head\s+back|bring|deliver|turn\s+(?:it\s+|them\s+)?in|hand\s+(?:it\s+|them\s+)?in|give)\b",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
/// <summary>
/// The step happens out of the dungeon the run is in: nothing to loot or kill there, nothing to go into, and
/// it hands in or goes back somewhere ("Return to Xsao", "Bring the jaw to ..."), or only travels.
/// </summary>
internal static bool HappensOutside(GuideQuest q, int i)
{
if (i < 0 || i >= q.Steps.Count) return false;
GuideStep s = q.Steps[i];
if (GoesIn(s) || (s.Items.Count > 0 && !QuestNames.IsHandIn(s)) || QuestNames.KillRx.IsMatch(s.Text)) return false;
return QuestNames.IsHandIn(s) || OutsideRx.IsMatch(s.Text) || TravelOnly(q, i);
}
/// <summary>The step after <paramref name="i"/> is done inside a dungeon (its loot, its kills, further in).</summary>
internal static bool NextInside(GuideQuest q, int i)
{
if (i + 1 >= q.Steps.Count) return false;
GuideStep n = q.Steps[i + 1];
// Not into a building ("Enter the blacksmith building and grab ...", the Acid Axe Quest): no portal there.
return !HappensOutside(q, i + 1) && !IntoBuilding(n.Text)
&& (QuestNames.KillRx.IsMatch(n.Text) || GoesIn(n) || (n.Items.Count > 0 && !QuestNames.IsHandIn(n)));
}
/// <summary>A step that picks items up ("grab the Acid Axe on the ground", "pick up the note").</summary>
internal static bool IsPickup(GuideStep s) =>
s.Items.Count > 0 && System.Text.RegularExpressions.Regex.IsMatch(s.Text,
@"\b(?:grab|grabs|pick(?:s|ed)?\s+(?:it\s+|them\s+)?up|pick|collect|gather|on\s+the\s+(?:ground|floor|table|shelf)|lying)\b",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
/// <summary>
/// A step whose job is getting somewhere ("Travel to Suntik Village at 16.2N 4.3E."): no stamp, no item,
/// nobody to talk to, nothing to go into. Done on arrival.
/// </summary>
internal static bool TravelOnly(GuideQuest q, int i)
{
if (i < 0 || i >= q.Steps.Count) return false;
GuideStep s = q.Steps[i];
return s.Stamps.Count == 0 && s.Items.Count == 0
&& System.Text.RegularExpressions.Regex.IsMatch(s.Text, @"^\s*(?:travel|go|head|run|walk|journey|proceed|make\s+your\s+way)\b",
System.Text.RegularExpressions.RegexOptions.IgnoreCase)
&& !GoesIn(q, i) && !QuestNames.IsTalk(q, s) && !QuestNames.IsHandIn(s);
}
/// <summary>
/// The places a step goes to: the coordinates its own words give ("Travel to Suntik Village at 16.2N 4.3E"),
/// not the ones only its notes give for another way there ("Route 2: ... to 16.9N 3.5E"); all of them when
/// its words give none.
/// </summary>
internal static List<string> Places(GuideStep s)
{
var inText = new List<string>();
foreach (System.Text.RegularExpressions.Match m in CoordsRx.Matches(s.Text ?? ""))
foreach (string c in s.Coords)
if (SameCoords(c, m.Value) && !inText.Contains(c)) inText.Add(c);
return inText.Count > 0 ? inText : s.Coords;
}
private static readonly System.Text.RegularExpressions.Regex CoordsRx = new(@"(\d+(?:\.\d+)?)\s*([NnSs])[\s,]+(\d+(?:\.\d+)?)\s*([EeWw])");
/// <summary>
/// The character is in a dungeon (<paramref name="inDungeon"/>) or not: the plugin's tick says so. Going in
/// during the run: a step that only takes you in is done, and the step is walked with the dungeon's map.
/// Coming out: the dungeon walk ends.
/// </summary>
public void OnWhere(bool inDungeon) => OnWhere(inDungeon, inDungeon ? 1u : 0u);
/// <summary>
/// As above, with the dungeon's landblock: a portal from one dungeon into another (17:29 on 11-07, into
/// Abayar's Laboratory) walks the step again in the new one, not on the old one's route.
/// </summary>
public void OnWhere(bool inDungeon, uint landblock)
{
uint was = _dungeon;
_dungeon = inDungeon ? landblock : 0;
if (inDungeon == _inDungeon)
{
if (inDungeon && was != 0 && was != landblock && Quest != null && !Travelling && Step >= 0 && Step < Quest.Steps.Count)
{
if (_dungeonWalk) { _ai("dungeon stop"); _dungeonWalk = false; }
GoStep(keepPlace: true);
Changed();
}
return;
}
_inDungeon = inDungeon;
if (Quest == null) return;
// RynthNav is still on its way (its route may pass through a dungeon): its arrival decides.
if (Travelling) { Changed(); return; }
if (!inDungeon)
{
if (_dungeonWalk) { _ai("dungeon stop"); _dungeonWalk = false; }
Changed();
return;
}
Travelling = false;
GuideQuest q = Quest;
if (_insideCell != 0 && Step >= 0 && Step < q.Steps.Count && _insideCell >> 16 == landblock)
{
WalkToCell(q, q.Steps[Step]);
Changed();
return;
}
if (Step >= 0 && Step < q.Steps.Count && (EntersOnly(q.Steps[Step]) || (TravelOnly(q, Step) && NextInside(q, Step))))
{
_print($"Step {Step + 1} done: you're in.");
Advance(first: false);
}
else if (Step >= 0 && Step < q.Steps.Count) GoStep(keepPlace: true);
Changed();
}
/// <summary>A step whose job is going in ("Enter the Keep", "Take the portal to ..."): no stamp, no item.</summary>
internal static bool EntersOnly(GuideStep s) =>
s.Stamps.Count == 0 && s.Items.Count == 0 && !IntoBuilding(s.Text)
&& System.Text.RegularExpressions.Regex.IsMatch(s.Text, @"\b(?:enter|enters|portal|dungeon|go\s+(?:in|inside|down)|head\s+(?:in|inside|down)|teleport)\b",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
/// <summary>
/// A step that goes in by a portal, whether or not it also wants a stamp or an item ("Take the portal to
/// the Hidden Keep and kill ...", "Enter the dungeon at ..."): at its place the nearest portal is used.
/// </summary>
internal static bool GoesIn(GuideStep s) =>
System.Text.RegularExpressions.Regex.IsMatch(s.Text, @"\b(?:enter|enters|portal|dungeon|go\s+(?:in|inside|down)|head\s+(?:in|inside|down)|teleport)\b",
System.Text.RegularExpressions.RegexOptions.IgnoreCase)
&& !IntoBuilding(s.Text);
/// <summary>
/// "Enter the blacksmith building and ...": walking into a building (its door), not a portal; unless the
/// step also says portal or dungeon.
/// </summary>
internal static bool IntoBuilding(string text) =>
System.Text.RegularExpressions.Regex.IsMatch(text ?? "",
@"\benters?\s+(?:the\s+|a\s+|an\s+)?(?:[\p{L}'’\-]+\s+){0,3}?(?:building|house|shop|hut|inn|tavern|cottage|cabin|store|smithy|forge|home|tent|room|bank|temple|chapel|church|mansion|manor)\b",
System.Text.RegularExpressions.RegexOptions.IgnoreCase)
&& !System.Text.RegularExpressions.Regex.IsMatch(text ?? "", @"\b(?:portal|dungeon|teleport)\b",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
/// <summary>
/// Step <paramref name="i"/> goes in by a portal: it says so, its place is a dungeon by name ("Head to the
/// Tusker Burrow at ..."), or the next step happens in a dungeon ("... at the end of the dungeon").
/// </summary>
internal static bool GoesIn(GuideQuest q, int i)
{
if (i < 0 || i >= q.Steps.Count) return false;
GuideStep s = q.Steps[i];
if (GoesIn(s) || DungeonPlaceRx.IsMatch(s.Text)) return true;
return i + 1 < q.Steps.Count && System.Text.RegularExpressions.Regex.IsMatch(q.Steps[i + 1].Text,
@"\b(?:dungeon|inside|in\s+the\s+(?:burrow|cave|caverns?|crypt|mines?|catacombs?|lair|tomb|sewers?|warren|vault|grotto|barrow|labyrinth))\b",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
}
private static readonly System.Text.RegularExpressions.Regex DungeonPlaceRx = new(
@"\b(?:Burrow|Cave|Caverns?|Crypt|Mines?|Catacombs?|Lair|Tomb|Sewers?|Warren|Vault|Grotto|Barrow|Labyrinth|Dungeon|Hive|Den|Pit|Halls?)\b",
System.Text.RegularExpressions.RegexOptions.CultureInvariant);
/// <summary>
/// " &lt;words&gt;" naming the portal the step means (its capitalised words), for RynthAi to prefer; "" when none.
/// With a society membership, faction/society stronghold steps prefer that society's stronghold name words
/// so Town Network's three "Stronghold" portals don't loop on the wrong one.
/// </summary>
internal static string PortalHint(GuideStep s, SocietyStanding society = default)
{
string societyHint = SocietyQuestResolve.PortalHintExtra(s, society);
if (societyHint.Length > 0) return societyHint;
var words = new List<string>();
foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(s.Text, @"\b[A-Z][a-z'\-]{2,}\b"))
{
string w = m.Value;
if (w is "Enter" or "Take" or "The" or "Use" or "Go" or "Head" or "Portal" or "Dungeon" or "Then" or "Kill" or "Talk" or "Find" or "Return"
or "Faction" or "Society" or "Your" or "Speak" or "Once" or "Several") continue;
if (!words.Contains(w)) words.Add(w);
}
return words.Count == 0 ? "" : " " + string.Join(" || ", words);
}
/// <summary>"71.4N, 28.6W" from text that has coordinates, else null.</summary>
internal static string? CoordsIn(string? text)
{
var m = System.Text.RegularExpressions.Regex.Match(text ?? "", @"(\d+(?:\.\d+)?)\s*([NnSs])[\s,]+(\d+(?:\.\d+)?)\s*([EeWw])");
return m.Success ? $"{m.Groups[1].Value}{char.ToUpperInvariant(m.Groups[2].Value[0])}, {m.Groups[3].Value}{char.ToUpperInvariant(m.Groups[4].Value[0])}" : null;
}
/// <summary>
/// Where to go when RynthNav knows none of a step's names: the quest's start place for the first step,
/// else the last place of the nearest step before it, else the start place (null: none known).
/// </summary>
internal static string? FallbackCoords(GuideQuest q, int step)
{
string? start = CoordsIn(q.StartsAt);
if (step == 0 && start != null) return start;
for (int i = step - 1; i >= 0; i--)
{
GuideStep p = q.Steps[i];
List<string> pl = Places(p);
if (pl.Count > 0) return CoordsIn(pl[^1]) ?? pl[^1];
string? inText = CoordsIn(p.Text);
if (inText != null) return inText;
}
return start;
}
/// <summary>
/// The step inside a dungeon: RynthAi walks its map, to the step's coordinates, else all over it
/// (fighting, looting, doors). False when RynthAi isn't there.
/// </summary>
/// <summary>"... (Drogur is in cell 009C0270)" at the end of RynthNav's arrival line: that cell, else 0.</summary>
internal static uint InsideCell(string line)
{
var m = System.Text.RegularExpressions.Regex.Match(line ?? "", @" is in cell ([0-9A-Fa-f]{8})\)");
return m.Success ? uint.Parse(m.Groups[1].Value, System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture) : 0;
}
/// <summary>
/// Inside, to the cell RynthNav named: RynthAi walks the dungeon's map there (fighting, doors, the quest's keys),
/// and the step's talk or hand-in is sent at once; RynthAi keeps looking for the person while it walks.
/// </summary>
private void WalkToCell(GuideQuest q, GuideStep s)
{
uint cell = _insideCell;
_insideCell = 0;
string keys = string.Join("", QuestKeys(q).ConvertAll(k => " | " + k));
if (_ai($"dungeon to {cell:X8}{keys}"))
{
_dungeonWalk = true;
Note = $"Step {Step + 1}: walking the dungeon to {string.Join(" or ", _targets)} (cell {cell:X8})";
}
DoNpc();
}
private bool GoDungeon(GuideQuest q, GuideStep s)
{
string keys = string.Join("", QuestKeys(q).ConvertAll(k => " | " + k));
string cmd;
string note;
// The step's own coordinates that RynthNav took it to outdoors are the way in, not a place inside.
List<string> places = Places(s);
string here = places.Count > 0 ? places[Math.Clamp(Place, 0, places.Count - 1)] : "";
bool entrance = here.Length > 0 && SameCoords(here, _wentTo);
if (!entrance && here.Length > 0 && TrySignedCoords(here, out double ns, out double ew))
{
cmd = $"dungeon goto {ns.ToString("0.###", System.Globalization.CultureInfo.InvariantCulture)} {ew.ToString("0.###", System.Globalization.CultureInfo.InvariantCulture)}{keys}";
note = $"Step {Step + 1}: walking the dungeon to {here} (fighting, looting, doors)";
}
else
{
cmd = "dungeon patrol" + keys;
note = $"Step {Step + 1}: patrolling the dungeon (fighting, looting the quest's items, doors) - the stamp or Next moves on";
}
if (!_ai(cmd)) return false;
_dungeonWalk = true;
Travelling = false;
Note = note;
_print($"Step {Step + 1}/{q.Steps.Count}: {s.Text}");
foreach (string n in s.Notes) _print(" " + n);
return true;
}
/// <summary>The quest's keys (its items named key or keyring), for locked doors.</summary>
internal static List<string> QuestKeys(GuideQuest q)
{
var keys = new List<string>();
void Add(string it)
{
if (System.Text.RegularExpressions.Regex.IsMatch(it, @"(?<![\p{L}])(?:key|keys|keyring)(?![\p{L}])", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
&& !keys.Exists(k => k.Equals(it, StringComparison.OrdinalIgnoreCase))) keys.Add(it.Replace('|', '/'));
}
foreach (string it in q.Loot) Add(it);
foreach (GuideStep st in q.Steps) foreach (string it in st.Items) Add(it);
return keys;
}
/// <summary>"28.5S, 90.9W" as signed numbers: north and east positive.</summary>
internal static bool TrySignedCoords(string text, out double ns, out double ew)
{
ns = ew = 0;
var m = System.Text.RegularExpressions.Regex.Match(text ?? "",
@"(\d+(?:\.\d+)?)\s*([NnSs])[\s,]+(\d+(?:\.\d+)?)\s*([EeWw])");
if (!m.Success) return false;
var inv = System.Globalization.CultureInfo.InvariantCulture;
ns = double.Parse(m.Groups[1].Value, inv) * (char.ToUpperInvariant(m.Groups[2].Value[0]) == 'S' ? -1 : 1);
ew = double.Parse(m.Groups[3].Value, inv) * (char.ToUpperInvariant(m.Groups[4].Value[0]) == 'W' ? -1 : 1);
return true;
}
/// <summary>
/// At the step's place: a hand-in step gives the quest's items got so far to the person it names, a step
/// that talks ("Talk to", "find", the quest's own people) talks to them (RynthAi, "questloot talk|handin").
/// </summary>
private void DoNpc()
{
GuideQuest q = Quest!;
if (Step < 0 || Step >= q.Steps.Count || _targets.Count == 0) return;
GuideStep s = q.Steps[Step];
string names = string.Join(" || ", _targets);
if (QuestNames.IsHandIn(s))
{
List<string> items = QuestNames.HandInItems(q, Step);
_ai("handin " + names + (items.Count > 0 ? " | " + string.Join(" | ", items) : ""));
LastNpc = "handin";
}
else if (QuestNames.IsTalk(q, s))
{
_ai("talk " + names);
LastNpc = "talk";
}
else LastNpc = "";
}
private void GoPlace()
{
List<string> places = Places(Quest!.Steps[Step]);
string c = places[Math.Clamp(Place, 0, places.Count - 1)];
string more = places.Count > 1 ? $" (place {Place + 1} of {places.Count})" : "";
Go(c, $"Step {Step + 1}: going to {c}{more}");
}
/// <summary>Two coordinate texts within 0.5 of each other on both axes.</summary>
internal static bool SameCoords(string a, string b) =>
TrySignedCoords(a, out double an, out double ae) && TrySignedCoords(b, out double bn, out double be)
&& Math.Abs(an - bn) <= 0.5 && Math.Abs(ae - be) <= 0.5;
private bool Go(string target, string note)
{
if (!_inDungeon && TrySignedCoords(target, out _, out _)) _wentTo = target;
if (_nav("go " + target))
{
Travelling = true;
Note = note;
return true;
}
Travelling = false;
Note = note + " - RynthNav isn't loaded: walk there yourself, then Next.";
return false;
}
private void Changed() => Revision++;
}

View file

@ -0,0 +1,68 @@
// ServerGuideClient.cs - The active server's own wiki quest guide (2026-11-21): "RynthServer.QuestGuide"
// (Plugins/Shared/RynthServerQuestGuideApi.cs) from the plugin RynthCore names as the server's owner, e.g.
// RynthConquest's Conquest wiki quests. Its info JSON has RynthILT's guide info's shape, so a QuestGuideClient
// takes it (Take) and reads the guide file when it changed. RynthOracle names no server: whatever guide the
// active server's plugin offers is used (OracleContext.Wiki merges it over the AC Community Wiki's).
// Pump thread.
using System.Text;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthOracle.Data;
internal sealed unsafe class ServerGuideClient
{
private const long PollMs = 2000;
private const long RequeryMs = 10_000;
private RynthServerQuestGuideApiV1* _table;
private string _owner = "";
private long _nextPollAt, _nextQueryAt;
private readonly byte[] _buffer = new byte[4096];
/// <summary>The guide as read (its Guide, Status, Tag, Revision).</summary>
public readonly QuestGuideClient Client = new() { FeedsDynamicStamps = false };
public void Clear()
{
_table = null;
_owner = "";
_nextPollAt = _nextQueryAt = 0;
Client.Clear();
}
public void Poll(RynthCoreHost host, string owner, long now)
{
if (now < _nextPollAt) return;
_nextPollAt = now + PollMs;
if (owner != _owner)
{
_owner = owner;
_table = null;
_nextQueryAt = 0;
Client.Clear();
}
if (owner.Length == 0) return;
if (_table != null && _table->Version == 0) { _table = null; _nextQueryAt = 0; }
if (_table == null)
{
if (now < _nextQueryAt || !host.HasGetPluginInterface) return;
_nextQueryAt = now + RequeryMs;
var p = (RynthServerQuestGuideApiV1*)host.GetPluginInterface(owner, RynthServerQuestGuideApiV1.InterfaceName, RynthServerQuestGuideApiV1.InterfaceVersion);
if (p == null || p->Version < 1 || p->StructSize < (uint)sizeof(RynthServerQuestGuideApiV1) || p->GetGuideInfoJson == null) return;
_table = p;
}
string json;
fixed (byte* b = _buffer)
{
int len = _table->GetGuideInfoJson(b, _buffer.Length);
json = len > 0 && len < _buffer.Length ? Encoding.UTF8.GetString(_buffer, 0, len) : "";
}
if (json.Length == 0)
{
if (Client.Guide.Quests.Count > 0 || Client.Available) Client.Clear();
return;
}
Client.Take(json);
}
}

View file

@ -28,6 +28,13 @@ internal sealed class ServerIdentity
public bool Known => WorldName.Length > 0 || ServerId.Length > 0;
public int Revision { get; private set; }
/// <summary>
/// RynthCore's active server is Infinite Leaftide (EngineServerState.IltId). Gates the rows and
/// reads that only that server has: the Dynamic Stamps and Temple guardian rows of the Quests
/// tab, RynthILT's /qb list and guardian data, and the Dynamic stamp source log line.
/// </summary>
public bool IsIlt => string.Equals(ServerId, EngineServerState.IltId, StringComparison.OrdinalIgnoreCase);
/// <summary>The active server's name for the player: its name, its id, or "no server".</summary>
public string DisplayName => ServerName.Length > 0 ? ServerName : ServerId.Length > 0 ? ServerId : "no server";

View file

@ -0,0 +1,212 @@
// Society quest wiki pages list all three factions (CH / EW / RB NPCs, forts, strongholds).
// Running one without picking the player's society sends RynthNav / portal-enter at the wrong
// faction forever (Town Network's three "Stronghold" portals, Palm Fort's three coords, …).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthOracle.Data;
/// <summary>
/// Filters a society wiki quest down to the player's Celestial Hand / Eldrytch Web / Radiant Blood
/// alternatives before QuestRunner walks it.
/// </summary>
internal static class SocietyQuestResolve
{
// "Aldrion of the Celestial Hand (CH)", "92.1S, 50.3W (CH)", "… (Eldrytch Web)".
private static readonly Regex TaggedRx = new(
@"(?<body>(?:\d+(?:\.\d+)?\s*[NnSs][\s,]+\d+(?:\.\d+)?\s*[EeWw]|[^()]+?))\s*\((?<tag>CH|EW|RB|Celestial\s+Hand|Eldrytch\s+Web|Radiant\s+Blood)\)",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static readonly Regex CoordsRx = new(
@"(\d+(?:\.\d+)?)\s*([NnSs])[\s,]+(\d+(?:\.\d+)?)\s*([EeWw])",
RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static readonly Regex StrongholdPlaceRx = new(
@"\b(?:your\s+)?(?:faction|society)\s+stronghold\b|\bsociety\s+chapterhouse\b|\bfaction\s+stronghold\b",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
/// <summary>"CH", "EW", "RB", or "" when not in a society.</summary>
public static string Code(SocietyStanding s) => s.SocietyName switch
{
"Celestial Hand" => "CH",
"Eldrytch Web" => "EW",
"Radiant Blood" => "RB",
_ => "",
};
/// <summary>"Celestial Hand Stronghold" (empty when not a member).</summary>
public static string StrongholdName(SocietyStanding s) =>
s.IsMember ? s.SocietyName + " Stronghold" : "";
/// <summary>True when the wiki page is a society quest or its start lists CH/EW/RB alternatives.</summary>
public static bool NeedsFilter(GuideQuest q) =>
q.SocietyRank.Length > 0
|| TaggedRx.IsMatch(q.StartsWith ?? "")
|| TaggedRx.IsMatch(q.StartsAt ?? "")
|| StrongholdPlaceRx.IsMatch(q.StartsAt ?? "")
|| q.Steps.Exists(st => StrongholdPlaceRx.IsMatch(st.Text ?? "") || TaggedRx.IsMatch(st.Text ?? ""));
/// <summary>
/// A copy of <paramref name="q"/> with only this player's society NPCs / coords / stronghold name.
/// Unchanged when not a member or the quest has no faction alternatives.
/// </summary>
public static GuideQuest ForPlayer(GuideQuest q, SocietyStanding s)
{
if (!s.IsMember || !NeedsFilter(q)) return q;
string code = Code(s);
string stronghold = StrongholdName(s);
var copy = new GuideQuest
{
Title = q.Title,
Url = q.Url,
Rev = q.Rev,
Level = q.Level,
RecommendedLevel = q.RecommendedLevel,
Type = q.Type,
KillTask = q.KillTask,
StartsWith = FilterTaggedParts(q.StartsWith, code, s.SocietyName),
StartsAt = FilterStartsAt(q.StartsAt, code, s.SocietyName, stronghold),
Route = q.Route,
Repeat = q.Repeat,
RepeatSec = q.RepeatSec,
TimeToComplete = q.TimeToComplete,
Contracts = q.Contracts,
Qb = q.Qb,
SocietyRank = q.SocietyRank,
Categories = new List<string>(q.Categories),
Overview = q.Overview,
ExtraStamps = new List<string>(q.ExtraStamps),
Loot = new List<string>(q.Loot),
Rewards = new List<string>(q.Rewards),
};
// Coords tagged in StartsAt map which of a step's untagged list belongs to this society.
var societyCoords = TaggedCoords(q.StartsAt, code, s.SocietyName);
foreach (GuideStep st in q.Steps)
{
copy.Steps.Add(new GuideStep
{
Text = RewriteStrongholdText(st.Text, stronghold),
Notes = st.Notes.ConvertAll(n => RewriteStrongholdText(n, stronghold)),
Coords = FilterStepCoords(st.Coords, societyCoords, st.Text, code, s.SocietyName),
Stamps = new List<string>(st.Stamps),
Items = new List<string>(st.Items),
});
}
return copy;
}
/// <summary>
/// Extra portal-name words for RynthAi's "dungeon enter": the player's stronghold when the step
/// says faction/society stronghold (Town Network has three portals all named "Stronghold").
/// </summary>
public static string PortalHintExtra(GuideStep s, SocietyStanding standing)
{
if (!standing.IsMember) return "";
if (!StrongholdPlaceRx.IsMatch(s.Text ?? "")
&& !StrongholdPlaceRx.IsMatch(string.Join(" ", s.Notes)))
return "";
// Full society name words + Stronghold so scoring prefers "Celestial Hand Stronghold" over the others.
return " " + string.Join(" || ", standing.SocietyName.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Concat(new[] { "Stronghold" }));
}
private static string FilterStartsAt(string startsAt, string code, string societyName, string stronghold)
{
string raw = startsAt ?? "";
if (raw.Length == 0) return raw;
if (StrongholdPlaceRx.IsMatch(raw) && !TaggedRx.IsMatch(raw))
{
// "Faction Stronghold (east wing)" → "Celestial Hand Stronghold (east wing)".
string wing = "";
var m = Regex.Match(raw, @"\(([^)]+)\)");
if (m.Success) wing = " (" + m.Groups[1].Value.Trim() + ")";
return stronghold + wing;
}
string filtered = FilterTaggedParts(raw, code, societyName);
return filtered.Length > 0 ? filtered : raw;
}
/// <summary>Keep only "(CH)" / "(EW)" / "(RB)" (or full society-name) segments for this player.</summary>
private static string FilterTaggedParts(string text, string code, string societyName)
{
if (string.IsNullOrWhiteSpace(text) || code.Length == 0) return text ?? "";
var kept = new List<string>();
foreach (Match m in TaggedRx.Matches(text))
{
if (!TagMatches(m.Groups["tag"].Value, code, societyName)) continue;
string body = m.Groups["body"].Value.Trim().TrimStart(':', '-', ' ');
if (body.Length > 0) kept.Add(body);
}
if (kept.Count == 0) return text; // no tags → leave alone (single-society page)
return string.Join(" / ", kept);
}
private static List<string> TaggedCoords(string startsAt, string code, string societyName)
{
var list = new List<string>();
if (string.IsNullOrWhiteSpace(startsAt) || code.Length == 0) return list;
foreach (Match m in TaggedRx.Matches(startsAt))
{
if (!TagMatches(m.Groups["tag"].Value, code, societyName)) continue;
Match c = CoordsRx.Match(m.Groups["body"].Value);
if (c.Success) list.Add(NormalizeCoords(c));
}
return list;
}
private static List<string> FilterStepCoords(List<string> coords, List<string> societyCoords,
string stepText, string code, string societyName)
{
if (coords == null || coords.Count == 0) return new List<string>();
// Coords written with a tag in the step text itself.
var fromText = new List<string>();
foreach (Match m in TaggedRx.Matches(stepText ?? ""))
{
if (!TagMatches(m.Groups["tag"].Value, code, societyName)) continue;
Match c = CoordsRx.Match(m.Groups["body"].Value);
if (c.Success)
{
string n = NormalizeCoords(c);
if (coords.Exists(x => SameCoords(x, n))) fromText.Add(coords.First(x => SameCoords(x, n)));
}
}
if (fromText.Count > 0) return fromText;
// Palm Fort: step lists all three forts; StartsAt tags say which is ours.
if (societyCoords.Count > 0)
{
var matched = coords.Where(c => societyCoords.Exists(sc => SameCoords(c, sc))).ToList();
if (matched.Count > 0) return matched;
}
return new List<string>(coords);
}
private static string RewriteStrongholdText(string text, string stronghold)
{
if (string.IsNullOrEmpty(text) || stronghold.Length == 0) return text ?? "";
return StrongholdPlaceRx.Replace(text, stronghold);
}
private static bool TagMatches(string tag, string code, string societyName)
{
tag = (tag ?? "").Trim();
if (tag.Equals(code, StringComparison.OrdinalIgnoreCase)) return true;
return tag.Equals(societyName, StringComparison.OrdinalIgnoreCase);
}
private static string NormalizeCoords(Match m) =>
$"{m.Groups[1].Value}{char.ToUpperInvariant(m.Groups[2].Value[0])}, {m.Groups[3].Value}{char.ToUpperInvariant(m.Groups[4].Value[0])}";
private static bool SameCoords(string a, string b)
{
Match ma = CoordsRx.Match(a ?? ""), mb = CoordsRx.Match(b ?? "");
if (!ma.Success || !mb.Success) return false;
return string.Equals(NormalizeCoords(ma), NormalizeCoords(mb), StringComparison.OrdinalIgnoreCase);
}
}

View file

@ -6,12 +6,14 @@ using System.Reflection;
namespace RynthCore.Plugin.RynthOracle.Data;
internal readonly record struct SpellInfo(string Name, double Duration, bool IsDebuff);
/// <summary>A spell from SpellData.txt. <see cref="Category"/> is ACE's SpellCategory (the stacking family), <see cref="Power"/> its difficulty.</summary>
internal readonly record struct SpellInfo(string Name, double Duration, bool IsDebuff, int Category = 0, int Power = 0);
/// <summary>
/// Spell names and base durations from RynthAi's embedded spell table (SpellData.txt, linked
/// into this plugin): tab separated, id, name, category, family, words, duration (s, -1 none),
/// difficulty, then three flags, the second of which marks a debuff. Loaded on first use.
/// difficulty, then three flags, the second of which marks a debuff. Loaded on first use. The
/// Gear tab falls back to it (category, power) when the client's portal.dat can't be read.
/// </summary>
internal static class SpellTable
{
@ -46,7 +48,9 @@ internal static class SpellTable
if (c.Length < 2 || !uint.TryParse(c[0].Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out uint id)) continue;
double duration = c.Length > 5 && double.TryParse(c[5].Trim(), NumberStyles.Float | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out double d) ? d : -1;
bool debuff = c.Length > 8 && c[8].Trim().Equals("True", StringComparison.OrdinalIgnoreCase);
map[id] = new SpellInfo(c[1].Trim(), duration, debuff);
int category = c.Length > 2 && int.TryParse(c[2].Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out int cat) ? cat : 0;
int power = c.Length > 6 && int.TryParse(c[6].Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out int pw) ? pw : 0;
map[id] = new SpellInfo(c[1].Trim(), duration, debuff, category, power);
}
}
}

View file

@ -0,0 +1,272 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthOracle.Data;
// The T11 Tracking tab's data (Infinite Leaftide, ACECustom upstream to 8d2460ff2, read 2026-11-11):
// * item bounties: the character's slots R1 R2 B1 B2 from PropertyString 57702 ItemBountyDisplay, which the server keeps
// current on the client ("v2|R1,R2,B1,B2;R1|tier|kind|progress|kills|target|rewardWcid|amount|icon|overlay|underlay|
// bountyName|rewardName|rewardUse|placeShort|placeName;B2|empty"), and bounty items carried, not yet applied (their
// description: "... Use it on a ring or bracelet you have to start it");
// * the levelled charms (1-100, T11+): their level and the Prestige Coins put in, from the charm's appraisal ("Charm [Level
// 41 (95% to 42)]", "Prestige Coins put in: 14,210 - next level in 46"), and the Charm Infusion Gems carried (one gem
// puts its number of coins in: Charm Infusion Gem (1) ... (5,000));
// * the school gems (T15-T25, +1 to a school past the cap): Battlemage's Wrath (war), Nether Veil (void), Crashing Steel
// (melee), True Shot (missile), with the tier each was earned at (PropertyInt 50651 EarnedGemTier) when the client has it;
// * the lum tokens the bank takes from the pack: the ten Bounty Reward Tokens and the Event Lum Tokens (1B / 3B / 5B).
/// <summary>One item bounty slot (R1, R2, B1, B2) as ItemBountyDisplay gives it.</summary>
internal sealed record ItemBountySlot(string Key, bool Empty, int Tier, int Kind, double Progress, int Kills, string Target,
uint RewardWcid, int RewardAmount, string Name, string RewardName, string RewardUse, string PlaceShort, string PlaceName)
{
/// <summary>Kind 1: any kill in the place counts. Kind 2 (Species): only <see cref="Target"/>.</summary>
public bool Species => Kind == 2;
/// <summary>Kills still needed (0 when the count is hidden or done).</summary>
public double Left => Kills > 0 ? Math.Max(0, Kills - Progress) : 0;
/// <summary>How far along, 0-1 (0 when the kill count is a mystery until the bounty is applied).</summary>
public float Fraction => Kills > 0 ? (float)Math.Clamp(Progress / Kills, 0, 1) : 0f;
/// <summary>"Kill 250 Banderlings in Tier 15", "Kill 400 creatures in Valley of Death".</summary>
public string Task => $"Kill {(Kills > 0 ? Kills.ToString("N0", CultureInfo.InvariantCulture) : "?")} {(Species && Target.Length > 0 ? Target : "creatures")} in {(PlaceName.Length > 0 ? PlaceName : "Tier " + Tier)}";
/// <summary>"5 x Bounty Reward Token" (or the reward's name alone for one).</summary>
public string Reward => RewardName.Length == 0 ? "" : RewardAmount > 1 ? $"{RewardAmount:N0} x {RewardName}" : RewardName;
}
/// <summary>A carried item the tab counts: what it is, how many, and what its appraisal says.</summary>
internal sealed record T11Item(uint Id, uint Wcid, string Name, int Stack, string Use, string Desc, int GemTier);
/// <summary>A levelled charm carried, with its level from the appraisal.</summary>
internal sealed record LevelledCharmRow(uint Id, string Name, int Level, int PercentToNext, long CoinsIn, long CoinsToNext, bool Active, bool Known);
internal static class T11Tracking
{
/// <summary>PropertyString ItemBountyDisplay on the player.</summary>
public const uint StrItemBountyDisplay = 57702;
/// <summary>PropertyInt EarnedGemTier on a school gem.</summary>
public const uint IntEarnedGemTier = 50651;
/// <summary>The slot keys, in the order /bounty lists them.</summary>
public static readonly string[] SlotKeys = { "R1", "R2", "B1", "B2" };
/// <summary>Charm Infusion Gems (777700089-097): the coins one gem puts into a levelled charm.</summary>
public static readonly IReadOnlyDictionary<uint, int> InfusionGems = new Dictionary<uint, int>
{
[777700089] = 1, [777700090] = 5, [777700091] = 10, [777700092] = 25, [777700093] = 50,
[777700094] = 100, [777700095] = 500, [777700096] = 1_000, [777700097] = 5_000,
};
/// <summary>The school gems (SchoolGems.cs): one per school, reused at every tier.</summary>
public static readonly (uint Wcid, string School, string Kind)[] SchoolGems =
{
(777700052, "Battlemage's Wrath", "War"),
(777700057, "Nether Veil", "Void"),
(777700062, "Crashing Steel", "Melee"),
(777700067, "True Shot", "Missile"),
};
/// <summary>The levelled charms (777700035-040): level 1-100, T11+ only.</summary>
public static readonly IReadOnlyDictionary<uint, string> LevelledCharms = new Dictionary<uint, string>
{
[777700035] = "Split Arrow", [777700036] = "Chain", [777700037] = "Pandemic",
[777700038] = "Improved Cleave", [777700039] = "Armor Breaker", [777700040] = "Shield Arc",
};
/// <summary>The lum tokens the bank takes from the pack (a double click banks one): Bounty Reward Tokens and Event Lum Tokens.</summary>
public static bool IsLumToken(uint wcid) => wcid is >= 777708001 and <= 777708010 or 99980076 or 99980078 or 99980079;
/// <summary>An unapplied bounty item: its description ends with how to start it.</summary>
public static bool IsBountyItem(string desc) =>
desc.Contains("Use it on a ring or bracelet", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// ItemBountyDisplay ("v2|R1,R2,B1,B2;R1|...;B2|empty") as slots; empty for no text, another format version, or junk.
/// Fields past the ones known are ignored, missing trailing ones are blank.
/// </summary>
public static List<ItemBountySlot> ParseDisplay(string? text)
{
var list = new List<ItemBountySlot>();
if (string.IsNullOrWhiteSpace(text)) return list;
string[] parts = text.Split(';');
string[] head = parts[0].Split('|');
if (head.Length < 1 || !head[0].StartsWith("v", StringComparison.Ordinal)) return list;
for (int i = 1; i < parts.Length; i++)
{
string[] f = parts[i].Split('|');
if (f.Length < 2 || f[0].Length == 0) continue;
string key = f[0].Trim();
if (f[1] == "empty") { list.Add(new ItemBountySlot(key, true, 0, 0, 0, 0, "", 0, 0, "", "", "", "", "")); continue; }
string F(int n) => n < f.Length ? f[n] : "";
int I(int n) => int.TryParse(F(n), NumberStyles.Integer, CultureInfo.InvariantCulture, out int v) ? v : 0;
double progress = double.TryParse(F(3), NumberStyles.Float, CultureInfo.InvariantCulture, out double p) ? p : 0;
uint reward = uint.TryParse(F(6), NumberStyles.Integer, CultureInfo.InvariantCulture, out uint r) ? r : 0;
list.Add(new ItemBountySlot(key, false, I(1), I(2), progress, I(4), F(5), reward, I(7), F(11), F(12), F(13), F(14), F(15)));
}
return list;
}
private static readonly Regex LevelText = new(@"Charm \[Level (\d+)(?: \((\d+)% to \d+\)| \(max\))?", RegexOptions.CultureInvariant);
private static readonly Regex CoinsText = new(@"Prestige Coins put in: ([\d,]+)(?: - next level in ([\d,]+))?", RegexOptions.CultureInvariant);
/// <summary>A levelled charm's appraisal: level, share to the next, coins put in, coins to the next; Known false without the text.</summary>
public static (int Level, int Pct, long Coins, long ToNext, bool Known) ParseCharm(string text)
{
var m = LevelText.Match(text ?? "");
if (!m.Success) return (0, 0, 0, 0, false);
int level = int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
int pct = m.Groups[2].Success ? int.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture) : 0;
var c = CoinsText.Match(text ?? "");
long coins = c.Success ? long.Parse(c.Groups[1].Value.Replace(",", ""), CultureInfo.InvariantCulture) : 0;
long next = c.Success && c.Groups[2].Success ? long.Parse(c.Groups[2].Value.Replace(",", ""), CultureInfo.InvariantCulture) : 0;
return (level, pct, coins, next, true);
}
}
/// <summary>
/// Reads what the T11 Tracking tab shows from the client: the packs (two levels deep, as AC nests them) and the player's
/// bounty slots. Items whose appraisal the tab needs (charms, school gems, bounty items) and the client doesn't have yet are
/// asked about, a few at a time and not again for a while. Pump thread.
/// </summary>
internal sealed class T11Scanner
{
private const long IdSpacingMs = 400, ReaskMs = 60_000;
private readonly Dictionary<uint, long> _askedAt = new();
private readonly Queue<uint> _idQueue = new();
private long _nextIdAt;
public List<ItemBountySlot> Slots { get; private set; } = new();
public List<T11Item> Infusion { get; private set; } = new();
public List<T11Item> SchoolGems { get; private set; } = new();
public List<T11Item> Bounties { get; private set; } = new();
public List<T11Item> LumTokens { get; private set; } = new();
public List<LevelledCharmRow> Charms { get; private set; } = new();
/// <summary>The player's raw ItemBountyDisplay ("" when the server never sent it).</summary>
public string BountyText { get; private set; } = "";
public long ScannedAt { get; private set; } = -1;
/// <summary>Goes up when anything the tab shows changed.</summary>
public int Revision { get; private set; }
private string _lastKey = "";
public long InfusionCoins => Infusion.Sum(g => (long)g.Stack * (T11Tracking.InfusionGems.TryGetValue(g.Wcid, out int c) ? c : 0));
public void Clear()
{
Slots = new(); Infusion = new(); SchoolGems = new(); Bounties = new(); LumTokens = new(); Charms = new();
BountyText = ""; ScannedAt = -1; _lastKey = ""; _askedAt.Clear(); _idQueue.Clear();
Revision++;
}
/// <summary>Reads everything again; true when something changed.</summary>
public bool Scan(RynthCoreHost host, long now, Func<uint, bool>? charmActive = null)
{
uint player = host.GetPlayerId();
if (player == 0) return false;
ScannedAt = now;
string bounty = host.HasGetObjectStringProperty && host.TryGetObjectStringProperty(player, T11Tracking.StrItemBountyDisplay, out string b) ? b ?? "" : "";
var infusion = new List<T11Item>();
var gems = new List<T11Item>();
var items = new List<T11Item>();
var tokens = new List<T11Item>();
var charms = new List<LevelledCharmRow>();
foreach (uint id in Carried(host, player))
{
if (!host.HasGetObjectWcid || !host.TryGetObjectWcid(id, out uint wcid)) continue;
bool infusionGem = T11Tracking.InfusionGems.ContainsKey(wcid);
bool schoolGem = Array.Exists(T11Tracking.SchoolGems, g => g.Wcid == wcid);
bool charm = T11Tracking.LevelledCharms.ContainsKey(wcid);
bool token = T11Tracking.IsLumToken(wcid);
string desc = Str(host, id, 16);
bool bountyItem = !infusionGem && !schoolGem && !charm && !token && T11Tracking.IsBountyItem(desc);
if (!infusionGem && !schoolGem && !charm && !token && !bountyItem)
{
// a bounty item the client hasn't been told about yet: a name with "Bounty" in it is asked about
if (desc.Length == 0 && Name(host, id).Contains("Bounty", StringComparison.OrdinalIgnoreCase) && !Name(host, id).Contains("Token", StringComparison.OrdinalIgnoreCase))
Ask(id, now);
continue;
}
string use = Str(host, id, 14);
int stack = host.TryGetObjectIntProperty(id, 12, out int st) && st > 0 ? st : 1;
int tier = host.TryGetObjectIntProperty(id, T11Tracking.IntEarnedGemTier, out int t) ? t : 0;
var item = new T11Item(id, wcid, Name(host, id), stack, use, desc, tier);
if (infusionGem) infusion.Add(item);
else if (schoolGem) { gems.Add(item); if (use.Length == 0 && desc.Length == 0) Ask(id, now); }
else if (token) tokens.Add(item);
else if (bountyItem) items.Add(item);
else
{
var (level, pct, coins, next, known) = T11Tracking.ParseCharm(use.Length > 0 ? use : desc);
if (!known) Ask(id, now);
bool active = (use + desc).Contains("Status: ON", StringComparison.OrdinalIgnoreCase) || charmActive?.Invoke(id) == true;
charms.Add(new LevelledCharmRow(id, T11Tracking.LevelledCharms[wcid], level, pct, coins, next, active, known));
}
}
infusion.Sort((a, x) => a.Wcid.CompareTo(x.Wcid));
gems.Sort((a, x) => a.Wcid != x.Wcid ? a.Wcid.CompareTo(x.Wcid) : a.GemTier.CompareTo(x.GemTier));
charms.Sort((a, x) => string.CompareOrdinal(a.Name, x.Name));
string key = string.Join("#", bounty,
string.Join(",", infusion.Select(i => i.Wcid + "x" + i.Stack)),
string.Join(",", gems.Select(i => i.Id + "x" + i.Stack + "t" + i.GemTier)),
string.Join(",", items.Select(i => i.Id + i.Desc)),
string.Join(",", tokens.Select(i => i.Wcid + "x" + i.Stack)),
string.Join(",", charms.Select(c => c.Id + ":" + c.Level + ":" + c.PercentToNext + ":" + c.CoinsIn + ":" + c.Active)));
if (key == _lastKey) return false;
_lastKey = key;
BountyText = bounty;
Slots = T11Tracking.ParseDisplay(bounty);
Infusion = infusion; SchoolGems = gems; Bounties = items; LumTokens = tokens; Charms = charms;
Revision++;
return true;
}
/// <summary>One queued appraisal request, spaced out (pump thread, each tick).</summary>
public void Tick(RynthCoreHost host, long now)
{
if (_idQueue.Count == 0 || now < _nextIdAt || !host.HasRequestId) return;
host.RequestId(_idQueue.Dequeue());
_nextIdAt = now + IdSpacingMs;
}
/// <summary>Forgets when the items were asked about, so Refresh asks again at once.</summary>
public void ForgetAsked() => _askedAt.Clear();
private void Ask(uint id, long now)
{
if (_askedAt.TryGetValue(id, out long at) && now - at < ReaskMs) return;
_askedAt[id] = now;
_idQueue.Enqueue(id);
}
private static string Str(RynthCoreHost host, uint id, uint key) =>
host.HasGetObjectStringProperty && host.TryGetObjectStringProperty(id, key, out string s) ? s ?? "" : "";
private static string Name(RynthCoreHost host, uint id) => host.TryGetObjectName(id, out string n) ? n ?? "" : "";
/// <summary>Every item in the main pack and the packs inside it.</summary>
private static List<uint> Carried(RynthCoreHost host, uint player)
{
var list = new List<uint>();
var buf = new uint[512];
var packs = new List<uint>();
int n = host.GetContainerContents(player, buf);
for (int i = 0; i < n; i++)
{
uint id = buf[i];
if (id == 0) continue;
if (host.TryGetItemType(id, out uint type) && (type & GearAnalysis.ItemContainer) != 0) packs.Add(id);
else list.Add(id);
}
foreach (uint pack in packs)
{
int m = host.GetContainerContents(pack, buf);
for (int i = 0; i < m; i++) if (buf[i] != 0) list.Add(buf[i]);
}
return list;
}
}

View file

@ -0,0 +1,665 @@
// Reads an Infinite Leaftide wiki quest page (MediaWiki wikitext, leaftidewiki.com) into a GuideQuest
// (QuestGuide.cs), 2026-11-01. Pure text work: RynthILT fetches the pages (its WikiFeed) and the offline
// tests feed it the sample pages. Linked into RynthILT.
//
// The pages look like this (the two samples the player sent, "Pistol" Pete Trophy Hunts and
// Mistreated Virindi):
// {{Leaftide Content}}
// {{Quest Summary | Level = 180+ | Recommended Level = 275+ | Quest Type = Solo/Fellowship
// | Starts With = [[Mistreated Virindi]] | Starts At = [[Zaikhal]] | Repeat Timer = 20 Hours | QB = ... }}
// == Overview == (also "== Discord Description ==")
// == Walkthrough & Notes == either numbered steps: # Talk to ... with #* {{stamped|Sneaky_Virindi}}
// or plain paragraphs, one per task, with the stamps listed apart:
// == QB Stamps == {{stamped|NephriteTooth}} ...
// == Rewards == {{Rewards Table | Quest Task = {{Itemlink|X}} | Item Reward = * {{Icon Link|Y}} (x80) }}
// == Images == / == Dialog == / == Update History ==
// [[Category:Enlightened Coin Quests]]
// Coordinates are written every which way ("28.5S, 90.9W", "62.7s 66.6W", "85.8s,78.8w"): NavTargets reads them.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthOracle.Data;
internal static class WikiQuestParser
{
public const string WikiBase = "https://www.leaftidewiki.com/";
/// <summary>
/// This reader's version, saved in the guide (QuestGuide.Parser). Raise it when the reader changes what
/// it takes from a page: RynthILT then reads every page again, not only the ones edited since.
/// 2: stamps cut to the flag ("X on first completion"), kill tasks, the Kill Tasks category and the
/// Dynamic Stamps page (2026-11-21).
/// </summary>
public const int Version = 2;
/// <summary>The wiki's page of Dynamic Stamps (2026-11-21).</summary>
public const string DynamicStampsPage = "Dynamic Stamps";
/// <summary>The wiki's list of kill tasks (2026-11-21; the page "Kill Tasks" redirects here).</summary>
public const string KillTasksCategory = "Category:Kill Tasks";
private static readonly Regex DynStampRx = new(@"\{\{\s*stamped\s*\|\s*(Dynamic_[^}|]+?)\s*\}\}", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex Heading3Rx = new(@"^\s*===\s*([^=].*?)\s*===\s*$", RegexOptions.CultureInvariant);
/// <summary>
/// The Dynamic Stamps page (2026-11-21): "== Network ==" headings, "=== [[Town]] ===" under them, each with
/// a table "Name | Coordinates | Stamp | Item Reward | Notes" (cells one per line, or on one line split by
/// "||"). "==Miscellaneous stamps==" has one table whose Notes say where. Rows without a Dynamic_ stamp
/// ("NO STAMP", "?") are left out, and so is "==Original Unsorted List==" (stamps without an NPC). Each
/// stamp once, first row wins. Area is the town (the heading's shown text), or "Miscellaneous".
/// </summary>
public static List<GuideDynStamp> ParseDynamicStamps(string? wikitext)
{
var list = new List<GuideDynStamp>();
if (string.IsNullOrEmpty(wikitext)) return list;
string text = CommentRx.Replace(wikitext, "").Replace("\r\n", "\n").Replace('\r', '\n');
var seen = new HashSet<string>(StringComparer.Ordinal);
string network = "", town = "";
bool inTable = false, unsorted = false;
var cells = new List<string>();
void Row()
{
if (cells.Count == 0 || unsorted) { cells.Clear(); return; }
string stampCell = cells.Count > 2 ? cells[2] : string.Join(" ", cells);
Match m = DynStampRx.Match(stampCell);
if (!m.Success) m = DynStampRx.Match(string.Join(" ", cells));
if (m.Success)
{
string stamp = m.Groups[1].Value.Trim();
if (seen.Add(stamp.ToLowerInvariant()))
{
bool misc = network.StartsWith("Misc", StringComparison.OrdinalIgnoreCase);
string notes = cells.Count > 4 ? Clean(cells[4]) : "";
string area = misc ? "Miscellaneous" : town.Length > 0 ? town : network;
list.Add(new GuideDynStamp
{
Area = area,
Place = misc ? notes : area,
Npc = cells.Count > 0 ? Clean(cells[0]) : "",
Coords = cells.Count > 1 ? NavTargets.FirstCoords(Clean(cells[1])) ?? Clean(cells[1]) : "",
Stamp = stamp,
Reward = cells.Count > 3 ? Clean(cells[3]) : "",
Note = misc ? "" : notes,
});
}
}
cells.Clear();
}
foreach (string raw in text.Split('\n'))
{
string line = raw.TrimEnd();
Match h3 = Heading3Rx.Match(line);
if (h3.Success) { Row(); town = Clean(h3.Groups[1].Value); continue; }
Match h2 = HeadingRx.Match(line);
if (h2.Success)
{
Row();
network = Clean(h2.Groups[1].Value);
town = "";
unsorted = network.Contains("Unsorted", StringComparison.OrdinalIgnoreCase);
continue;
}
string t = line.TrimStart();
if (t.StartsWith("{|", StringComparison.Ordinal)) { inTable = true; cells.Clear(); continue; }
if (!inTable) continue;
if (t.StartsWith("|}", StringComparison.Ordinal)) { Row(); inTable = false; continue; }
if (t.StartsWith("|-", StringComparison.Ordinal)) { Row(); continue; }
if (t.StartsWith('!')) continue;
if (t.StartsWith('|'))
foreach (string c in t.Substring(1).Split("||")) cells.Add(c.Trim());
else if (cells.Count > 0)
cells[^1] += " " + t;
}
Row();
return list;
}
/// <summary>A contract's item page (2026-11-21, the AC Community Wiki): the {{Item}} box and a contract's name or category.</summary>
public static bool IsContractPage(string title, string? wikitext) =>
!string.IsNullOrEmpty(wikitext) && wikitext.IndexOf("{{Item", StringComparison.OrdinalIgnoreCase) >= 0
&& (title.StartsWith("Contract for ", StringComparison.OrdinalIgnoreCase)
|| wikitext.IndexOf("[[Category:Contracts", StringComparison.OrdinalIgnoreCase) >= 0);
private static readonly Regex FirstLinkRx = new(@"\[\[([^\[\]|#]+)(?:\|[^\[\]]*)?\]\]", RegexOptions.CultureInvariant);
/// <summary>
/// A contract's item page (2026-11-21): {{Intro | Related Quests = [[Aerbax's Citadel]]}}, {{Item | Name, Description,
/// Recommended Level}}, and the notes' "Purchased from [[Hanadi the Barkeeper]] in the Sho hall ...".
/// </summary>
public static GuideContract ParseContract(string title, string wikitext, long rev = 0, string? wikiBase = null)
{
string text = RefRx.Replace(CommentRx.Replace(wikitext ?? "", ""), "").Replace("\r\n", "\n").Replace('\r', '\n');
var c = new GuideContract { Title = title.Trim(), Url = UrlOf(title.Trim(), wikiBase), Rev = rev };
Dictionary<string, string> item = TemplateParams(text, "Item");
Dictionary<string, string> intro = TemplateParams(text, "Intro");
string name = Clean(Param(item, "Name"));
c.Name = name.Length > 0 ? name : c.Title;
c.Description = Clean(Param(item, "Description"));
c.Level = Clean(Param(item, "Recommended Level", "Level"));
foreach (Match m in FirstLinkRx.Matches(Param(intro, "Related Quests", "Related Quest", "Quest")))
{
string t = m.Groups[1].Value.Trim().TrimStart(':');
if (t.Length > 0 && !c.Quests.Contains(t)) c.Quests.Add(t);
}
foreach (var (heading, lines) in Sections(text))
{
if (!heading.StartsWith("note", StringComparison.OrdinalIgnoreCase)) continue;
foreach (string l in lines)
{
if (l.IndexOf("purchase", StringComparison.OrdinalIgnoreCase) < 0 && l.IndexOf("sold by", StringComparison.OrdinalIgnoreCase) < 0
&& l.IndexOf("given by", StringComparison.OrdinalIgnoreCase) < 0 && l.IndexOf("from [[", StringComparison.OrdinalIgnoreCase) < 0) continue;
c.Where = Clean(l.TrimStart('*', '#', ':', ' '));
Match m = FirstLinkRx.Match(l);
if (m.Success) c.Npc = Clean("[[" + m.Groups[1].Value + "]]");
break;
}
if (c.Where.Length > 0) break;
}
return c;
}
/// <summary>The page is a quest page (it has the Quest Summary box).</summary>
public static bool IsQuestPage(string? wikitext) =>
!string.IsNullOrEmpty(wikitext) && wikitext.IndexOf("{{Quest Summary", StringComparison.OrdinalIgnoreCase) >= 0;
/// <summary>The page's address on the wiki.</summary>
public static string UrlOf(string title, string? wikiBase = null) =>
(wikiBase ?? WikiBase) + Uri.EscapeDataString(title.Replace(' ', '_')).Replace("%2F", "/");
private static readonly Regex CommentRx = new(@"<!--.*?-->", RegexOptions.Singleline | RegexOptions.CultureInvariant);
private static readonly Regex RefRx = new(@"<ref[^>/]*/>|<ref[^>]*>.*?</ref>", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex HeadingRx = new(@"^\s*==\s*([^=].*?)\s*==\s*$", RegexOptions.CultureInvariant);
private static readonly Regex StampRx = new(@"\{\{\s*stamped\s*\|\s*([^}|]+?)\s*\}\}", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex ItemRx = new(@"\{\{\s*Item\s*link\s*\|\s*([^}|]+?)\s*(?:\|[^}]*)?\}\}", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex CategoryRx = new(@"\[\[\s*Category\s*:\s*([^\]|]+?)\s*(?:\|[^\]]*)?\]\]", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
/// <summary>Reads a quest page. <paramref name="title"/> is the page's title; <paramref name="rev"/> its revision id (0 unknown).</summary>
public static GuideQuest Parse(string title, string wikitext, long rev = 0, string? wikiBase = null)
{
var q = new GuideQuest { Title = title.Trim(), Url = UrlOf(title.Trim(), wikiBase), Rev = rev };
string text = RefRx.Replace(CommentRx.Replace(wikitext ?? "", ""), "").Replace("\r\n", "\n").Replace('\r', '\n');
foreach (Match m in CategoryRx.Matches(text))
{
string c = m.Groups[1].Value.Trim();
if (c.Length > 0 && !q.Categories.Contains(c)) q.Categories.Add(c);
}
Dictionary<string, string> box = TemplateParams(text, "Quest Summary");
q.Level = Clean(Param(box, "Level"));
q.RecommendedLevel = Clean(Param(box, "Recommended Level", "Recommended Aug Level", "Recommended"));
q.Type = Clean(Param(box, "Quest Type", "Type"));
q.KillTask = Clean(Param(box, "Kill Task"));
q.StartsWith = Clean(Param(box, "Starts With", "NPC"));
q.StartsAt = Clean(Param(box, "Starts At", "Location"));
q.Route = Clean(Param(box, "Route"));
q.Repeat = Clean(Param(box, "Repeat Timer", "Timer", "Repeat"));
q.RepeatSec = RepeatSeconds(q.Repeat);
q.TimeToComplete = Clean(Param(box, "Time to Complete"));
q.Contracts = Clean(Param(box, "Contracts"));
q.Qb = FirstInt(Clean(Param(box, "QB", "Quest Bonus")));
q.SocietyRank = Clean(Param(box, "Society Rank"));
List<(string Heading, List<string> Lines)> sections = Sections(text);
string overview = "";
List<string>? walk = null;
var looseStamps = new List<string>();
foreach (var (heading, lines) in sections)
{
string h = heading.ToLowerInvariant();
if (h.StartsWith("overview") || h.Contains("description"))
{
// The Overview wins over the Discord Description when a page has both.
string o = Clean(string.Join(" ", lines));
if (o.Length > 0 && (h.StartsWith("overview") || overview.Length == 0)) overview = o;
}
else if (h.StartsWith("walkthrough") || h == "steps" || h.StartsWith("quest steps") || h == "notes" && walk == null)
walk = lines;
else if (h.Contains("stamp"))
{
foreach (string l in lines)
foreach (Match m in StampRx.Matches(l))
if (GuideStamp.Clean(m.Groups[1].Value) is { Length: > 0 } ls) looseStamps.Add(ls);
}
else if (h.StartsWith("reward"))
q.Rewards = Rewards(string.Join("\n", lines));
}
q.Overview = overview.Length > 700 ? overview.Substring(0, 700).TrimEnd() + "..." : overview;
if (walk != null) q.Steps = Steps(walk);
// Stamps listed outside the steps: tied to a step by name, else (as many as there are stampless
// steps) in order, else kept apart.
var have = new HashSet<string>(StringComparer.Ordinal);
foreach (GuideStep s in q.Steps) foreach (string st in s.Stamps) have.Add(GuideStamp.Key(st));
var left = new List<string>();
foreach (string st in looseStamps)
{
if (!have.Add(GuideStamp.Key(st))) continue;
GuideStep? byName = StepNamed(q.Steps, st);
if (byName != null) byName.Stamps.Add(st);
else left.Add(st);
}
var bare = q.Steps.FindAll(s => s.Stamps.Count == 0);
if (left.Count > 0 && left.Count == bare.Count)
{
for (int i = 0; i < left.Count; i++) bare[i].Stamps.Add(left[i]);
left.Clear();
}
q.ExtraStamps = left;
q.Loot = LootItems(q.Steps);
return q;
}
// ── Sections and steps ──────────────────────────────────────────────────
/// <summary>The page's "== X ==" sections with their lines (the text before the first heading is "").</summary>
internal static List<(string Heading, List<string> Lines)> Sections(string text)
{
var list = new List<(string, List<string>)>();
string heading = "";
var lines = new List<string>();
foreach (string raw in text.Split('\n'))
{
Match m = HeadingRx.Match(raw);
if (m.Success)
{
list.Add((heading, lines));
heading = m.Groups[1].Value.Trim();
lines = new List<string>();
continue;
}
lines.Add(raw);
}
list.Add((heading, lines));
return list;
}
/// <summary>
/// The walkthrough's steps: its numbered "# " lines with their "#*" / "#:" / "##" lines under them;
/// or, with no numbered lines, its top-level bullets or its paragraphs (one step each). Sub-sections
/// ("=== Part 2 ===") only break paragraphs.
/// </summary>
internal static List<GuideStep> Steps(List<string> lines)
{
var steps = new List<GuideStep>();
bool numbered = lines.Exists(l => IsTopLevel(l, '#'));
bool bullets = !numbered && lines.Exists(l => IsTopLevel(l, '*'));
char lead = numbered ? '#' : '*';
if (numbered || bullets)
{
GuideStep? cur = null;
foreach (string raw in lines)
{
string l = raw.TrimEnd();
if (l.Length == 0) continue;
if (IsTopLevel(l, lead))
{
cur = NewStep(l.Substring(1));
steps.Add(cur);
}
else if (cur != null && l[0] == lead)
AddSub(cur, l.TrimStart('#', '*', ':', ';'));
else if (cur != null && (l[0] == '*' || l[0] == ':'))
AddSub(cur, l.TrimStart('#', '*', ':', ';'));
// Anything else between steps (a paragraph, a table) is left out.
}
}
else
{
var para = new StringBuilder();
void Flush()
{
string p = para.ToString().Trim();
para.Clear();
if (p.Length == 0) return;
GuideStep s = NewStep(p);
if (s.Text.Length > 0 || s.Stamps.Count > 0) steps.Add(s);
}
foreach (string raw in lines)
{
string l = raw.Trim();
if (l.Length == 0 || l.StartsWith("===") || l.StartsWith("{|") || l.StartsWith("|}") || l.StartsWith("[[File:", StringComparison.OrdinalIgnoreCase))
{
Flush();
continue;
}
if (para.Length > 0) para.Append(' ');
para.Append(l);
}
Flush();
}
steps.RemoveAll(s => s.Text.Length == 0 && s.Stamps.Count == 0 && s.Coords.Count == 0);
return steps;
}
private static bool IsTopLevel(string l, char lead) =>
l.Length > 1 && l[0] == lead && l[1] != '*' && l[1] != '#' && l[1] != ':' && l[1] != ';';
private static GuideStep NewStep(string raw)
{
var s = new GuideStep();
Collect(s, raw);
s.Text = Clean(raw);
return s;
}
private static void AddSub(GuideStep s, string raw)
{
Collect(s, raw);
string note = Clean(raw);
if (note.Length > 0) s.Notes.Add(note);
}
/// <summary>The stamps, items and coordinates in a line of the step.</summary>
private static void Collect(GuideStep s, string raw)
{
foreach (Match m in StampRx.Matches(raw))
{
string st = GuideStamp.Clean(m.Groups[1].Value);
if (st.Length > 0 && !s.Stamps.Exists(x => GuideStamp.Key(x) == GuideStamp.Key(st))) s.Stamps.Add(st);
}
foreach (Match m in ItemRx.Matches(raw))
{
string it = m.Groups[1].Value.Trim();
if (it.Length > 0 && !s.Items.Contains(it, StringComparer.OrdinalIgnoreCase)) s.Items.Add(it);
}
foreach (string c in NavTargets.AllCoords(Clean(raw)))
if (!s.Coords.Contains(c)) s.Coords.Add(c);
}
private static readonly Regex LootVerbRx = new(
@"\b(kill|kills|killing|loot|loots|looted|drop|drops|dropped|collect|collects|gather|find|finds|obtain|obtains|pick\s+up|grab|hunt|hunts|for\s+(a|an|the|their|its|his|her))\b",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
/// <summary>
/// The items worth picking up: those named in a step that kills, loots, drops or finds something
/// (not one only handed in or upgraded), each once, in order.
/// </summary>
internal static List<string> LootItems(List<GuideStep> steps)
{
var loot = new List<string>();
foreach (GuideStep s in steps)
{
if (s.Items.Count == 0) continue;
string all = s.Text + " " + string.Join(" ", s.Notes);
if (!LootVerbRx.IsMatch(all)) continue;
if (Regex.IsMatch(s.Text, @"^\s*(instead|return|turn\s+in|hand\s+in|give|bring|upgrade)\b", RegexOptions.IgnoreCase)) continue;
foreach (string it in s.Items)
if (!loot.Contains(it, StringComparer.OrdinalIgnoreCase)) loot.Add(it);
}
return loot;
}
/// <summary>
/// The step a stamp listed apart belongs to, by its name: "NephriteTooth" goes with the step that
/// talks about the Nephrite, "WinstonsLeg" with Winston's. The single best step, or null.
/// </summary>
internal static GuideStep? StepNamed(List<GuideStep> steps, string stamp)
{
List<string> tokens = StampTokens(stamp);
if (tokens.Count == 0) return null;
GuideStep? best = null;
int bestScore = 0;
bool tie = false;
foreach (GuideStep s in steps)
{
var words = new HashSet<string>(Words(s.Text + " " + string.Join(" ", s.Notes) + " " + string.Join(" ", s.Items)), StringComparer.Ordinal);
int score = 0;
foreach (string t in tokens)
foreach (string w in words)
if (w.Length >= 4 && (w == t || w.StartsWith(t, StringComparison.Ordinal) || t.StartsWith(w, StringComparison.Ordinal))) { score++; break; }
if (score > bestScore) { best = s; bestScore = score; tie = false; }
else if (score == bestScore && score > 0) tie = true;
}
return tie ? null : best;
}
private static readonly HashSet<string> StampNoise = new(StringComparer.Ordinal)
{ "quest", "stamp", "found", "turnin", "turned", "done", "complete", "completed", "kill", "killed", "the", "obtained", "timer", "flag", "started", "start" };
/// <summary>"Shiny_Red_Stone_Found" → shiny, red, stone; "WinstonsLeg" → winston, leg (words of 3+ letters, an 's dropped).</summary>
internal static List<string> StampTokens(string stamp)
{
string spaced = Regex.Replace(stamp, @"(?<=[a-z0-9])(?=[A-Z])", " ");
var list = new List<string>();
foreach (string w in Words(spaced))
{
string t = w.Length > 4 && w.EndsWith("s", StringComparison.Ordinal) ? w.Substring(0, w.Length - 1) : w;
if (t.Length >= 3 && !StampNoise.Contains(t) && !list.Contains(t)) list.Add(t);
}
return list;
}
private static IEnumerable<string> Words(string text)
{
foreach (Match m in Regex.Matches(text.ToLowerInvariant(), @"[a-z0-9]+"))
{
string w = m.Value;
// "Winston's" reads as "winston" + "s".
yield return w;
}
}
// ── Rewards ─────────────────────────────────────────────────────────────
/// <summary>The rewards section as short lines: "For Vial of The Architect's Blood:", then "Enlightened Coin (x80)" ...</summary>
internal static List<string> Rewards(string section)
{
var lines = new List<string>();
int at = 0;
bool anyTable = false;
while (true)
{
int i = section.IndexOf("{{Rewards Table", at, StringComparison.OrdinalIgnoreCase);
if (i < 0) break;
int end = TemplateEnd(section, i);
if (end < 0) break;
anyTable = true;
Dictionary<string, string> p = SplitParams(section.Substring(i + 2, end - i - 4));
string task = Clean(Param(p, "Quest Task", "Task"));
if (task.Length > 0) lines.Add("For " + task + ":");
foreach (string key in new[] { "Item Reward", "Items", "XP Reward", "Experience", "Luminance Reward", "Luminance", "Other Reward", "Other" })
{
string v = Param(p, key);
if (v.Length == 0) continue;
foreach (string part in v.Split('\n'))
{
string c = Clean(part.TrimStart('*', ' ', '#'));
if (c.Length == 0) continue;
lines.Add(key.StartsWith("XP") || key.StartsWith("Exp") ? "XP: " + c : key.StartsWith("Lum") ? "Luminance: " + c : c);
}
}
at = end;
}
if (!anyTable)
foreach (string l in section.Split('\n'))
{
string c = Clean(l.TrimStart('*', '#', ':', ' '));
if (c.Length > 0) lines.Add(c);
}
if (lines.Count > 30) lines.RemoveRange(30, lines.Count - 30);
return lines;
}
// ── Templates ───────────────────────────────────────────────────────────
/// <summary>The first {{<paramref name="name"/> ...}} template's named parameters (keys trimmed, any case).</summary>
internal static Dictionary<string, string> TemplateParams(string text, string name)
{
int i = text.IndexOf("{{" + name, StringComparison.OrdinalIgnoreCase);
if (i < 0) return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
int end = TemplateEnd(text, i);
if (end < 0) end = text.Length;
int bodyEnd = Math.Max(i + 2, end - 2);
return SplitParams(text.Substring(i + 2, bodyEnd - (i + 2)));
}
/// <summary>Where the template starting at <paramref name="start"/> ("{{") ends (just past its "}}"), or -1.</summary>
private static int TemplateEnd(string text, int start)
{
int depth = 0;
for (int i = start; i < text.Length - 1; i++)
{
if (text[i] == '{' && text[i + 1] == '{') { depth++; i++; }
else if (text[i] == '}' && text[i + 1] == '}') { depth--; i++; if (depth == 0) return i + 1; }
}
return -1;
}
/// <summary>A template body's "| key = value" parameters, split at the top level only (links and inner templates kept whole).</summary>
private static Dictionary<string, string> SplitParams(string body)
{
var parts = new List<string>();
int depthT = 0, depthL = 0, from = 0;
for (int i = 0; i < body.Length; i++)
{
char c = body[i];
char n = i + 1 < body.Length ? body[i + 1] : '\0';
if (c == '{' && n == '{') { depthT++; i++; }
else if (c == '}' && n == '}') { depthT--; i++; }
else if (c == '[' && n == '[') { depthL++; i++; }
else if (c == ']' && n == ']') { depthL--; i++; }
else if (c == '|' && depthT == 0 && depthL == 0)
{
parts.Add(body.Substring(from, i - from));
from = i + 1;
}
}
parts.Add(body.Substring(from));
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
for (int k = 1; k < parts.Count; k++)
{
string p = parts[k];
int eq = p.IndexOf('=');
if (eq <= 0) continue;
string key = Regex.Replace(p.Substring(0, eq), @"\s+", " ").Trim();
if (key.Length == 0 || map.ContainsKey(key)) continue;
map[key] = p.Substring(eq + 1).Trim();
}
return map;
}
internal static string Param(Dictionary<string, string> p, params string[] names)
{
foreach (string n in names)
if (p.TryGetValue(n, out string? v) && v.Trim().Length > 0) return v.Trim();
return "";
}
// ── Text ────────────────────────────────────────────────────────────────
private static readonly Regex FileRx = new(@"\[\[\s*(File|Image)\s*:[^\[\]]*(\[\[[^\]]*\]\][^\[\]]*)*\]\]", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex LinkRx = new(@"\[\[([^\[\]|]*)\|([^\[\]]*)\]\]", RegexOptions.CultureInvariant);
private static readonly Regex PlainLinkRx = new(@"\[\[([^\[\]|]*)\]\]", RegexOptions.CultureInvariant);
private static readonly Regex ExtLinkRx = new(@"\[(https?://[^\s\]]+)(?:\s+([^\]]*))?\]", RegexOptions.CultureInvariant);
private static readonly Regex NamedTemplateRx = new(@"\{\{\s*(?:Item\s*link|Icon\s*Link|Creature\s*link|NPC\s*link|Link)\s*\|\s*([^}|]+?)\s*(?:\|[^{}]*)?\}\}", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex AnyTemplateRx = new(@"\{\{[^{}]*\}\}", RegexOptions.CultureInvariant);
private static readonly Regex TagRx = new(@"<[^>]+>", RegexOptions.CultureInvariant);
private static readonly Regex SpaceRx = new(@"\s+", RegexOptions.CultureInvariant);
/// <summary>Wikitext as plain text: links as their words, item templates as the item, other templates, files, bold and tags dropped.</summary>
public static string Clean(string? wikitext)
{
if (string.IsNullOrEmpty(wikitext)) return "";
string s = wikitext;
s = StampRx.Replace(s, "");
s = FileRx.Replace(s, "");
s = CategoryRx.Replace(s, "");
s = LinkRx.Replace(s, "$2");
s = PlainLinkRx.Replace(s, m => m.Groups[1].Value.TrimStart(':'));
s = ExtLinkRx.Replace(s, m => m.Groups[2].Success && m.Groups[2].Value.Length > 0 ? m.Groups[2].Value : m.Groups[1].Value);
s = NamedTemplateRx.Replace(s, "$1");
for (int pass = 0; pass < 4 && s.Contains("{{"); pass++) s = AnyTemplateRx.Replace(s, "");
s = Regex.Replace(s, @"<br\s*/?>", " ", RegexOptions.IgnoreCase);
s = TagRx.Replace(s, "");
s = s.Replace("'''", "").Replace("''", "");
s = s.Replace("&nbsp;", " ").Replace("&amp;", "&").Replace("&lt;", "<").Replace("&gt;", ">").Replace("&quot;", "\"");
s = SpaceRx.Replace(s, " ").Trim();
// A "[[A]]s" plural leaves "Tortured Raveners" whole; a list leftover "* " at the start goes.
return s.TrimStart('*', '#', ':', ' ').Trim();
}
private static int FirstInt(string s)
{
Match m = Regex.Match(s, @"\d+");
return m.Success && int.TryParse(m.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n) ? n : 0;
}
/// <summary>
/// "20 Hours", "7 days", "1 Week", "20h", "3d 12h", "Daily" → seconds; "", "None", "N/A", "Once",
/// "One time" → 0; anything else -1.
/// </summary>
public static long RepeatSeconds(string? repeat)
{
if (string.IsNullOrWhiteSpace(repeat)) return 0;
string r = repeat.Trim().ToLowerInvariant();
if (r is "none" or "n/a" or "na" or "-" or "once" or "no" or "never" || r.StartsWith("one time") || r.StartsWith("one-time") || r.StartsWith("not repeatable")
|| r.StartsWith("non repeatable") || r.StartsWith("non-repeatable") || r.StartsWith("nonrepeatable") || r.StartsWith("unrepeatable")) return 0;
if (r.StartsWith("daily")) return 86400;
if (r.StartsWith("weekly")) return 7 * 86400;
long total = 0;
bool any = false;
foreach (Match m in Regex.Matches(r, @"(\d+(?:\.\d+)?)\s*(weeks?|w|days?|d|hours?|hrs?|h|minutes?|mins?|m|seconds?|secs?|s)\b"))
{
double n = double.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
string u = m.Groups[2].Value;
double mult = u[0] switch { 'w' => 7 * 86400, 'd' => 86400, 'h' => 3600, 'm' => 60, _ => 1 };
total += (long)Math.Round(n * mult);
any = true;
}
return any && total > 0 ? total : -1;
}
// ── Special:Export ──────────────────────────────────────────────────────
/// <summary>
/// The pages in a Special:Export XML file: (title, revision id, wikitext), main namespace only.
/// </summary>
public static List<(string Title, long Rev, string Text)> ReadExport(System.IO.TextReader xml)
{
var pages = new List<(string, long, string)>();
var settings = new System.Xml.XmlReaderSettings { DtdProcessing = System.Xml.DtdProcessing.Ignore, XmlResolver = null, IgnoreWhitespace = true };
using var r = System.Xml.XmlReader.Create(xml, settings);
string title = "", text = "";
long rev = 0;
int ns = 0;
bool inRevision = false;
bool advance = true;
while (true)
{
// ReadElementContentAsString leaves the reader on the next node already: no Read then.
if (advance && !r.Read()) break;
advance = true;
if (r.EOF) break;
if (r.NodeType == System.Xml.XmlNodeType.Element)
{
switch (r.LocalName)
{
case "page": title = ""; text = ""; rev = 0; ns = 0; inRevision = false; break;
case "title": title = r.ReadElementContentAsString(); advance = false; break;
case "ns":
int.TryParse(r.ReadElementContentAsString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out ns);
advance = false;
break;
case "revision": inRevision = true; break;
case "id" when inRevision && rev == 0:
long.TryParse(r.ReadElementContentAsString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out rev);
advance = false;
break;
case "text" when inRevision: text = r.ReadElementContentAsString(); advance = false; break;
}
}
else if (r.NodeType == System.Xml.XmlNodeType.EndElement && r.LocalName == "page")
{
if (ns == 0 && title.Length > 0) pages.Add((title, rev, text));
}
}
return pages;
}
}