diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/AbilitiesPage.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/AbilitiesPage.cs new file mode 100644 index 0000000..b517bdd --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/AbilitiesPage.cs @@ -0,0 +1,420 @@ +// AbilitiesPage.cs - RynthDreamWeave's Abilities page (2026-11-17): what class ability points cost on DreamWeave, in +// luminance and in experience, where you stand, and buying them. A tab of the DreamWeave window on RynthCore's bar +// (and of the /rserver window). +// +// top your points (available, earned), read from "/abilities points" when the page is first opened in a +// login (its reply kept out of chat; Read now asks again), and what the last purchase came to; +// each lane how many you have bought with it and about what they cost, the next point's price and how the price +// grows from there, what you have (banked luminance from the bank check, DreamWeaveBank.cs; unassigned +// experience from the character) against it, how many that buys, and how long the next one takes at +// what you are earning this login; +// buying experience: Buy the next point, or the number planned below ("/abilities buyxp N"; the page asks +// Yes or No first, the server doesn't). Luminance: only at the Reckoning-Stone of Radiance in the +// Drift Network (the command is the developers'); near it, Use the stone (AC then asks Yes or No with +// the price); elsewhere, Recall to the Drift Network (/dn); +// plan ahead "Bought so far" (filled in from the reading; change it to plan), "Points to price", their total, +// and the next points' prices with a running total and what each still needs; +// footer the curves the prices come from (AbilityPointPrices.cs), and a warning when the server's quoted +// price for your next point isn't the published curve's (the prices are then scaled to it). +// Plain ImGui like the Bank page: it is a form, and the retail canvas (RetailCanvas.cs) has no number boxes. +// Render thread: draws holding the reader's lock (the bank's value is taken first, never inside it), and queues +// what it sends for the tick. +using System; +using System.Globalization; +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.ServerPack; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthDreamWeave; + +internal sealed class AbilitiesPage +{ + private const int MaxRows = 50, MaxCount = 1000; + private const long ConfirmMs = 15_000; + private const long LumRateSpanMs = 10 * 60_000, XpRateSpanMs = 5 * 60_000; + private static readonly CultureInfo Inv = CultureInfo.InvariantCulture; + private static readonly Vector4 Good = new(0.55f, 0.85f, 0.55f, 1f); + private static readonly Vector4 Warn = new(1f, 0.75f, 0.3f, 1f); + private static readonly Vector4 Bad = new(1f, 0.45f, 0.4f, 1f); + + private sealed class Lane + { + public readonly string Id, Title, Unit; + public int Bought, Count = 1; + public bool Edited; // the player changed "Bought so far": a new reading doesn't overwrite it + public Lane(string id, string title, string unit) { Id = id; Title = title; Unit = unit; } + } + + /// What one lane stands at, for the drawing. + private readonly record struct LaneState(AbilityCurve Published, AbilityCurve Curve, bool Matches, int? ReadBought, long? Quoted, + long? Have, string HaveName, double? PerHour, string? Locked); + + private readonly DreamWeaveAbilityPoints _p; + private readonly Func _active; + private readonly Func _bankLuminance; + private readonly Action _runOnTick; + private readonly Action _readNow; + private readonly Action _checkBank; + private readonly Action _drawn; + private readonly Action _buyXp; + private readonly Action _useStone; + private readonly Action _recall; + private readonly Lane _lum = new("lum", "Luminance", "luminance"); + private readonly Lane _xp = new("xp", "Experience", "experience"); + private int _seen = -1; + // The experience purchase waiting for the page's own Yes: how many, their price, until when, and from which count. + private (int Count, long Price, long UntilMs, int From)? _confirm; + + /// The bank check's reading (takes the bank's lock; null before one). + /// Asks for /abilities points at the next quiet moment (pump thread, queued with runOnTick). + /// The Bank page's Check now (pump thread). + /// Render thread, every frame the page draws: the host keeps the character's numbers fresh. + /// Sends "/abilities buyxp N" (pump thread). + /// Uses the remembered Reckoning-Stone (pump thread). + /// Sends /dn (pump thread). + public AbilitiesPage(DreamWeaveAbilityPoints points, Func active, Func bankLuminance, Action runOnTick, + Action readNow, Action checkBank, Action drawn, Action buyXp, Action useStone, Action recall) + { + _p = points; + _active = active; + _bankLuminance = bankLuminance; + _runOnTick = runOnTick; + _readNow = readNow; + _checkBank = checkBank; + _drawn = drawn; + _buyXp = buyXp; + _useStone = useStone; + _recall = recall; + } + + public ServerPage Page() => new("abilities", "Abilities", + "Class ability points: what you've bought, what the next ones cost in luminance and experience, and buying them (RynthDreamWeave).", Draw); + + private void Draw() + { + if (!_active()) + { + SafeImGui.TextWrapped("This page is for DreamWeave. RynthCore doesn't see this world as DreamWeave " + + "(check RynthCore Options > Diagnostics, or /rserver info)."); + return; + } + _drawn(); + long? bank = _bankLuminance(); + long now = Environment.TickCount64; + lock (_p.Gate) + { + _p.PageOpened(); + if (_p.Revision != _seen) + { + _seen = _p.Revision; + if (!_lum.Edited && _p.LumBought is int lb) _lum.Bought = lb; + if (!_xp.Edited && _p.XpBought is int xb) _xp.Bought = xb; + } + Header(now); + + // The luminance the stone spends: on you first, then the bank. The client sees the bank only (the bank + // check); the stone's own count, when it has given one, is newer than nothing. + long? lumHave = bank is long b ? b + (_p.StoneOnYou ?? 0) : _p.StoneSpendable; + ImGui.SeparatorText("Luminance"); + var lum = new LaneState(AbilityCurve.Luminance, _p.LumCurve, _p.LumMatches, _p.LumBought, _p.LumNext, + lumHave, "banked luminance", _p.LumRate.PerHour(LumRateSpanMs), null); + Standing(_lum, lum); + if (bank == null) + { + SafeImGui.TextDisabled("Your banked luminance isn't read yet."); + ImGui.SameLine(); + if (ImGui.SmallButton("Check the bank##dw_ab_bank")) _runOnTick(_checkBank); + Tooltip("Sends /b now (the Bank page's Check now). With the Bank page's every-minute check on, this fills in by itself."); + } + BuyLum(lum, now); + Plan(_lum, lum); + + ImGui.Spacing(); + ImGui.SeparatorText("Experience"); + string? locked = null; + if (_p.XpUnlockLevel is int lv) + locked = $"Opens at level {lv.ToString("N0", Inv)}" + (_p.Level > 0 ? $" (you are {_p.Level.ToString("N0", Inv)})." : "."); + else if (!_p.HasReading && _p.Level > 0 && _p.Level < AbilityCurve.ExperienceMinLevel) + locked = $"Opens at level {AbilityCurve.ExperienceMinLevel} (you are {_p.Level.ToString("N0", Inv)})."; + var xp = new LaneState(AbilityCurve.Experience, _p.XpCurve, _p.XpMatches, _p.XpBought, _p.XpNext, + _p.UnassignedXp, "unassigned experience", _p.XpRate.PerHour(XpRateSpanMs), locked); + Standing(_xp, xp); + if (_p.UnassignedXp == null) SafeImGui.TextDisabled("Your unassigned experience isn't known yet."); + BuyXp(xp, now); + Plan(_xp, xp); + + ImGui.Spacing(); + ImGui.Separator(); + SafeImGui.TextWrapped("Prices are DreamWeave's own curves (its published server code). Luminance: 1,000,000 for the " + + "first point, then each one x1.25 the last to the 10th, x1.5 to the 20th and x1.75 after. " + + "Experience (from level 275, unassigned experience only, never a level): 200,000,000,000 for " + + "the first, then each one x1.4. Each lane counts its own points, and neither has a cap."); + } + } + + private void Header(long now) + { + if (_p.HasReading && !_p.Off) + { + SafeImGui.Text($"Class ability points: {_p.Available?.ToString("N0", Inv) ?? "?"} available, " + + $"{_p.Earned?.ToString("N0", Inv) ?? "?"} earned in all"); + ImGui.SameLine(); + SafeImGui.TextDisabled($"(read at {_p.ReadUtc.ToLocalTime():HH:mm})"); + } + else if (_p.Waiting(now)) SafeImGui.TextDisabled("Asking DreamWeave (/abilities points)..."); + else SafeImGui.TextDisabled("Your points aren't read yet."); + ImGui.SameLine(); + if (ImGui.SmallButton("Read now##dw_ab_read")) _runOnTick(_readNow); + Tooltip("Sends /abilities points at the next quiet moment and keeps its reply out of chat. It goes by itself the " + + "first time this page opens in a login, and after each purchase."); + if (_p.LastMiss.Length > 0) SafeImGui.TextColored(Warn, _p.LastMiss); + if (_p.Off) SafeImGui.TextColored(Warn, "DreamWeave says class abilities are off on this server right now."); + if (_p.BuyMessage.Length > 0) SafeImGui.TextColored(_p.BuyFailed ? Bad : Good, _p.BuyMessage); + ImGui.Spacing(); + } + + // ── Where you stand in a lane ──────────────────────────────────────── + + private void Standing(Lane l, LaneState s) + { + if (s.Locked != null) SafeImGui.TextDisabled(s.Locked); + int bought = s.ReadBought ?? l.Bought; + long next = s.Curve.Cost(bought + 1); + if (!ImGui.BeginTable($"##dw_ab_s_{l.Id}", 2, ImGuiTableFlags.SizingStretchProp)) return; + ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthFixed, ImGui.GetFontSize() * 11f); + ImGui.TableSetupColumn(""); + + Row($"Bought with {l.Unit}", s.ReadBought is int rb ? Count(rb) : "not read yet"); + if (s.ReadBought is int r2 && r2 > 0) + { + Row("Spent on them", "about " + AbilityText.Num(s.Curve.CostOfRange(0, r2))); + Tooltip("The curve's prices for those points, as the server charges them today."); + } + Row($"The {AbilityText.Ordinal(bought + 1)} point costs", AbilityText.Num(next)); + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + SafeImGui.TextDisabled("Then " + AbilityText.Stage(s.Curve, bought + 2) + "."); + + if (s.Have is long have) + { + int k = s.Curve.Affordable(bought, have, out long spent, out _, out long need); + Row($"You have ({s.HaveName})", AbilityText.Num(have)); + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + if (k == 0) + { + float frac = next > 0 ? (float)Math.Clamp((double)have / next, 0, 1) : 0f; + ImGui.ProgressBar(frac, new Vector2(-1f, 0f), $"{frac * 100:0.#}% of the {AbilityText.Ordinal(bought + 1)}"); + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + SafeImGui.Text("Still needed"); + ImGui.TableNextColumn(); + SafeImGui.Text(AbilityText.Num(need)); + } + else + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + SafeImGui.Text("Enough for"); + ImGui.TableNextColumn(); + SafeImGui.TextColored(Good, $"{Count(k)} more (to the {AbilityText.Ordinal(bought + k)}), {AbilityText.Num(spent)} in all"); + Row($"Then the {AbilityText.Ordinal(bought + k + 1)} needs", AbilityText.Num(need) + " more"); + } + if (s.PerHour is double rate) + { + string when = rate > 0 ? EarnRate.Time(need, rate) : ""; + Row("Earning this login", (rate > 0 ? $"about {AbilityText.Num((long)rate)} an hour" : "nothing yet") + + (when.Length > 0 ? $": the {AbilityText.Ordinal(bought + k + 1)} in {when}" : "")); + Tooltip($"What your {s.HaveName} grew by since this login's first reading (purchases added back)."); + } + } + ImGui.EndTable(); + } + + private static void Row(string label, string value) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + SafeImGui.TextDisabled(label); + ImGui.TableNextColumn(); + SafeImGui.Text(value); + } + + private static string Count(int n) => n == 1 ? "1 point" : n.ToString("N0", Inv) + " points"; + + // ── Buying ─────────────────────────────────────────────────────────── + + private void BuyLum(LaneState s, long now) + { + int bought = s.ReadBought ?? _lum.Bought; + long next = s.Curve.Cost(bought + 1); + if (_p.StoneNear) + { + bool shortKnown = s.Have is long have && have < next; + ImGui.BeginDisabled(_p.Buying(now) || _p.Off || shortKnown); + if (ImGui.Button($"Use the Reckoning-Stone (the {AbilityText.Ordinal(bought + 1)} point, {AbilityText.Num(next)})##dw_ab_stone")) + _runOnTick(_useStone); + ImGui.EndDisabled(); + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + SafeImGui.SetTooltip(shortKnown + ? "Not enough luminance for the next point yet." + : "Walks to the stone and uses it. AC then asks Yes or No with the price: nothing is spent until you say Yes. " + + "The stone takes the luminance on you first, then the bank."); + return; + } + SafeImGui.TextWrapped(_p.StoneKnown + ? "Luminance points are bought at the Reckoning-Stone of Radiance, by the Skillmaster in the Drift Network. " + + "When you're near it, a button here uses it." + : "Luminance points are bought at the Reckoning-Stone of Radiance, by the Skillmaster in the Drift Network " + + "(DreamWeave has no command for it). Select the stone once and this page remembers it: when you're near it, " + + "a button here uses it."); + ImGui.BeginDisabled(_p.Buying(now)); + if (ImGui.SmallButton("Recall to the Drift Network (/dn)##dw_ab_dn")) _runOnTick(_recall); + ImGui.EndDisabled(); + Tooltip("Sends /dn, DreamWeave's recall to the Drift Network."); + } + + private void BuyXp(LaneState s, long now) + { + if (_confirm is { } c && (now >= c.UntilMs || _p.XpBought != c.From)) _confirm = null; + if (_confirm is { } ask) + { + SafeImGui.TextColored(Warn, $"Spend {(s.Matches ? "" : "about ")}{AbilityText.Num(ask.Price)} unassigned experience on " + + (ask.Count == 1 ? $"the {AbilityText.Ordinal(ask.From + 1)} point" : $"{Count(ask.Count)} (the " + + $"{AbilityText.Ordinal(ask.From + 1)} to the {AbilityText.Ordinal(ask.From + ask.Count)})") + + "? It can't be undone; your level and total experience stay as they are."); + if (ImGui.Button("Yes, buy##dw_ab_yes")) + { + int count = ask.Count; + _confirm = null; + _runOnTick(() => _buyXp(count)); + } + ImGui.SameLine(); + if (ImGui.Button("No##dw_ab_no")) _confirm = null; + return; + } + + bool open = s.Locked == null && _p.XpUnlockLevel == null; + int? from = s.ReadBought; + string why = !open ? "The experience lane isn't open yet." + : from == null ? "Read your points first (Read now): the price depends on how many you have bought." + : _p.Off ? "Class abilities are off on this server right now." + : _p.Buying(now) ? "Waiting for the last purchase's answer." + : s.Have == null ? "Your unassigned experience isn't known yet." + : ""; + int bought = from ?? _xp.Bought; + long one = s.Curve.Cost(bought + 1); + bool canOne = why.Length == 0 && s.Have >= one; + ImGui.BeginDisabled(!canOne); + if (ImGui.Button($"Buy the {AbilityText.Ordinal(bought + 1)} point ({AbilityText.Num(one)} experience)##dw_ab_buy1")) + _confirm = (1, one, now + ConfirmMs, bought); + ImGui.EndDisabled(); + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + SafeImGui.SetTooltip(why.Length > 0 ? why + : canOne ? "Sends /abilities buyxp 1 after you say Yes. Unassigned experience only: never a level." + : "Not enough unassigned experience for the next point yet."); + int n = _xp.Count; + if (n > 1 && from is int f && _xp.Bought == f) + { + long all = s.Curve.CostOfRange(f, n); + bool canAll = why.Length == 0 && s.Have >= all; + ImGui.SameLine(); + ImGui.BeginDisabled(!canAll); + if (ImGui.Button($"Buy {Count(n)} ({AbilityText.Num(all)})##dw_ab_buyn")) + _confirm = (n, all, now + ConfirmMs, f); + ImGui.EndDisabled(); + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + SafeImGui.SetTooltip(why.Length > 0 ? why + : canAll ? $"Sends /abilities buyxp {n} after you say Yes: all of them or none." + : $"Not enough unassigned experience for {n} yet."); + } + } + + // ── Plan ahead: other counts, and the next points' prices ─────────── + + private void Plan(Lane l, LaneState s) + { + if (!ImGui.TreeNodeEx($"Plan ahead and the next prices##dw_ab_plan_{l.Id}", ImGuiTreeNodeFlags.DefaultOpen)) return; + float box = ImGui.GetFontSize() * 7f; + ImGui.SetNextItemWidth(box); + int b = l.Bought; + if (ImGui.InputInt($"Bought so far##dw_ab_b_{l.Id}", ref b)) + { + l.Bought = Math.Clamp(b, 0, AbilityCurve.MaxPoints); + l.Edited = s.ReadBought != l.Bought; + } + Tooltip($"How many points have been bought with {l.Unit}: where its price stands. Filled in from /abilities points; " + + "change it to plan ahead."); + if (s.ReadBought is int mine && mine != l.Bought) + { + ImGui.SameLine(); + if (ImGui.SmallButton($"Mine ({mine.ToString("N0", Inv)})##dw_ab_m_{l.Id}")) { l.Bought = mine; l.Edited = false; } + } + ImGui.SetNextItemWidth(box); + int c = l.Count; + if (ImGui.InputInt($"Points to price##dw_ab_c_{l.Id}", ref c)) l.Count = Math.Clamp(c, 1, MaxCount); + + long total = s.Curve.CostOfRange(l.Bought, l.Count); + SafeImGui.Text(l.Count == 1 + ? $"The {AbilityText.Ordinal(l.Bought + 1)} point: {AbilityText.Num(total)} {l.Unit}" + : $"{Count(l.Count)} (the {AbilityText.Ordinal(l.Bought + 1)} to the {AbilityText.Ordinal(l.Bought + l.Count)}): " + + $"{AbilityText.Num(total)} {l.Unit} in all"); + if (s.Have is long have && total > have && total < long.MaxValue) + SafeImGui.TextDisabled($"That is {AbilityText.Num(total - have)} more than you have."); + + if (!s.Matches && s.ReadBought is int rb && s.Quoted is long q) + SafeImGui.TextColored(Warn, $"DreamWeave quoted {q.ToString("N0", Inv)} for your {AbilityText.Ordinal(rb + 1)} point, not the " + + $"published curve's {s.Published.Cost(rb + 1).ToString("N0", Inv)}: prices here are " + + "scaled to the server's, and past that point they're estimates."); + + Table(l, s); + ImGui.TreePop(); + } + + private static void Table(Lane l, LaneState s) + { + int rows = Math.Clamp(Math.Max(10, l.Count), 1, MaxRows); + if (!ImGui.BeginTable($"##dw_ab_t_{l.Id}", 4, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp)) return; + ImGui.TableSetupColumn("Point", ImGuiTableColumnFlags.WidthFixed, ImGui.GetFontSize() * 4f); + ImGui.TableSetupColumn("Price"); + ImGui.TableSetupColumn("Total from now"); + ImGui.TableSetupColumn(s.Have != null ? "Still needed" : ""); + ImGui.TableHeadersRow(); + for (int i = 1; i <= rows; i++) + { + int n = l.Bought + i; + long price = s.Curve.Cost(n); + long running = s.Curve.CostOfRange(l.Bought, i); + bool can = s.Have is long have && running <= have; + bool asked = i <= l.Count; + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + Cell(AbilityText.Ordinal(n), can, asked); + ImGui.TableNextColumn(); + Cell(AbilityText.Num(price), can, asked); + ImGui.TableNextColumn(); + Cell(AbilityText.Num(running), can, asked); + ImGui.TableNextColumn(); + if (s.Have is long h) Cell(can ? "you have it" : running < long.MaxValue ? AbilityText.Num(running - h) : "", can, asked); + if (price >= long.MaxValue) break; + } + ImGui.EndTable(); + if (s.Have != null) SafeImGui.TextDisabled("Green: within what you have now."); + } + + // Green when it's within what you have; dim past the points asked about. + private static void Cell(string text, bool affordable, bool asked) + { + if (affordable) SafeImGui.TextColored(Good, text); + else if (asked) SafeImGui.Text(text); + else SafeImGui.TextDisabled(text); + } + + private static void Tooltip(string text) + { + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(text); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/AbilityPointPrices.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/AbilityPointPrices.cs new file mode 100644 index 0000000..16d5026 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/AbilityPointPrices.cs @@ -0,0 +1,249 @@ +// AbilityPointPrices.cs - what DreamWeave charges for a class ability point (2026-11-17), for the Abilities +// page's calculator (AbilitiesPage.cs). Two lanes, each with its own count of points bought and its own price: +// Luminance (the reckoning-stone by the Skillmaster in the Drift Network): 1,000,000 for the first point, +// each next one x1.25 up to the 10th, x1.5 up to the 20th and x1.75 after that, with no cap. +// Experience (the exchange stone, or /abilities buyxp, from level 275): 200,000,000,000 for the first point, +// each next one x1.4, with no cap. It spends unassigned experience only (never a level). +// The math is the server's own (ACE-DreamWeave Source/ACE.Server/ClassAbilities/ClassAbilityLumCurve.cs, which both +// lanes use, with the defaults of class_ability_lum_* and class_ability_xp_* in PropertyManager.cs): +// cost(n) = base * r1^(min(n, bp1) - 1) * r2^(clamp(n - bp1, 0, bp2 - bp1)) * r3^(max(n - bp2, 0)) +// with n the 1-indexed point (the lane's 1st, 2nd... point bought). A range is the sum of the unrounded prices, +// rounded once, and a price past long.MaxValue stays there (as the server's CostForRange). +// The server's tunables can change without a new client; "/abilities points" quotes the next point's price in +// each lane, so the page checks the curve against it (Fit) and scales the curve to it when they differ. +// Pure: RynthServerPack.Tests covers it. +using System; + +namespace RynthCore.Plugin.RynthDreamWeave; + +/// One lane's price curve (DreamWeave's ClassAbilityLumCurve). +internal readonly record struct AbilityCurve(double BaseCost, double Ratio1, double Ratio2, double Ratio3, int Breakpoint1, int Breakpoint2) +{ + /// DreamWeave's luminance lane (class_ability_lum_*: 1M, x1.25 to the 10th, x1.5 to the 20th, x1.75 after). + public static readonly AbilityCurve Luminance = new(1_000_000, 1.25, 1.5, 1.75, 10, 20); + + /// DreamWeave's experience lane (class_ability_xp_*: 200B, x1.4 each; its breakpoints are inert). + public static readonly AbilityCurve Experience = new(200_000_000_000, 1.4, 1.4, 1.4, 1, 1); + + /// The level the experience lane opens at (class_ability_xp_min_level). + public const int ExperienceMinLevel = 275; + + /// The unrounded price of the th point (1-indexed; 0 below 1). + public double Raw(int n) + { + if (n < 1) return 0; + int width = Math.Max(0, Breakpoint2 - Breakpoint1); + int e1 = Math.Min(n, Breakpoint1) - 1; + int e2 = Math.Clamp(n - Breakpoint1, 0, width); + int e3 = Math.Max(n - Breakpoint2, 0); + return BaseCost * Math.Pow(Ratio1, e1) * Math.Pow(Ratio2, e2) * Math.Pow(Ratio3, e3); + } + + /// The price of the th point, as the server rounds it. + public long Cost(int n) => ToLong(Raw(n)); + + /// + /// The price of more points when have been bought (points + /// bought+1 .. bought+count): the server's CostForRange, long.MaxValue when it gets there. + /// + public long CostOfRange(int bought, int count) + { + if (count < 1) return 0; + double total = 0; + for (int i = 1; i <= count; i++) + { + total += Raw(bought + i); + if (total >= long.MaxValue) return long.MaxValue; + } + return ToLong(total); + } + + /// + /// How many more points buys after , bought one at a time + /// (each price rounded, as the stone charges them), what they cost in all, and how much more the next one + /// needs ( its price). + /// + public int Affordable(int bought, long budget, out long spent, out long next, out long needMore) + { + int count = 0; + spent = 0; + next = Cost(bought + 1); + while (count < MaxPoints && next <= budget - spent && next < long.MaxValue) + { + spent += next; + count++; + next = Cost(bought + count + 1); + } + needMore = next >= long.MaxValue ? long.MaxValue : next - (budget - spent); + return count; + } + + /// The most points the calculator walks over (a price past long.MaxValue stops it well before this). + public const int MaxPoints = 10_000; + + /// + /// The curve that gives for point +1 (the price the server just + /// quoted for the next one): this one when it already does, else this one with its base scaled to it. Its + /// later prices are then estimates (a changed ratio can't be seen from one price). + /// + public AbilityCurve Fit(int bought, long quoted, out bool matches) + { + long mine = Cost(bought + 1); + // The server rounds to the nearest whole point price; a price this curve can't reach stays as it is. + matches = quoted <= 0 || mine == quoted || mine >= long.MaxValue || quoted >= long.MaxValue; + if (matches) return this; + double shape = Raw(bought + 1) / BaseCost; + if (shape <= 0 || double.IsInfinity(shape) || double.IsNaN(shape)) { matches = true; return this; } + return this with { BaseCost = quoted / shape }; + } + + private static long ToLong(double cost) + { + if (double.IsNaN(cost) || cost < 0) return 0; + if (cost >= long.MaxValue) return long.MaxValue; + return (long)Math.Round(cost); + } +} + +/// How the calculator says its numbers (the page and "/rserver abilities"). +internal static class AbilityText +{ + private static readonly System.Globalization.CultureInfo Inv = System.Globalization.CultureInfo.InvariantCulture; + + /// A price or an amount: "2,441,406", with words from a billion up ("392,000,000,000 (392 billion)"). + public static string Num(long v) + { + if (v >= long.MaxValue) return "more than 9.2 quintillion"; + string exact = v.ToString("N0", Inv); + string words = Words(v); + return words.Length == 0 ? exact : exact + " (" + words + ")"; + } + + /// A short form from a billion up ("1.23 trillion"), else "". + public static string Words(long v) + { + double a = Math.Abs((double)v); + (double div, string name) = a >= 1e18 ? (1e18, "quintillion") : a >= 1e15 ? (1e15, "quadrillion") + : a >= 1e12 ? (1e12, "trillion") : a >= 1e9 ? (1e9, "billion") : (0, ""); + if (div == 0) return ""; + double x = v / div; + string f = Math.Abs(x) >= 100 ? x.ToString("0", Inv) : Math.Abs(x) >= 10 ? x.ToString("0.#", Inv) : x.ToString("0.##", Inv); + return f + " " + name; + } + + /// + /// How the price grows from point on: "each point costs x1.5 the last up to the 20th, then + /// x1.75", or "each point costs x1.4 the last, with no end". + /// + public static string Stage(AbilityCurve c, int n) + { + string R(double r) => "x" + r.ToString("0.###", Inv); + if (c.Ratio1 == c.Ratio2 && c.Ratio2 == c.Ratio3) return $"each point costs {R(c.Ratio1)} the last, with no end"; + if (n <= c.Breakpoint1) + return $"each point costs {R(c.Ratio1)} the last up to the {Ordinal(c.Breakpoint1)}, then {R(c.Ratio2)} up to the " + + $"{Ordinal(c.Breakpoint2)}, then {R(c.Ratio3)}"; + if (n <= c.Breakpoint2) + return $"each point costs {R(c.Ratio2)} the last up to the {Ordinal(c.Breakpoint2)}, then {R(c.Ratio3)}"; + return $"each point costs {R(c.Ratio3)} the last, with no end"; + } + + /// 1st, 2nd, 3rd, 4th, 11th, 12th, 13th, 21st... + public static string Ordinal(int n) + { + int h = n % 100; + string s = h is 11 or 12 or 13 ? "th" : (n % 10) switch { 1 => "st", 2 => "nd", 3 => "rd", _ => "th" }; + return n.ToString("N0", Inv) + s; + } + + /// + /// One lane in a sentence: where it stands, the next point's price, and what buys + /// ("Luminance: 5 bought; the 6th costs 3,051,758; your 8,904,758 banked buys 2 more (6,866,455), the 8th + /// needs 2,730,069 more"). + /// + public static string Lane(string title, AbilityCurve curve, int bought, long? budget, string budgetWord) + { + long next = curve.Cost(bought + 1); + string s = $"{title}: {bought.ToString("N0", Inv)} bought; the {Ordinal(bought + 1)} costs {Num(next)}"; + if (budget is not long have) return s; + int k = curve.Affordable(bought, have, out long spent, out _, out long need); + if (k == 0) return s + $"; your {Num(have)} {budgetWord} is {Num(need)} short of it"; + return s + $"; your {Num(have)} {budgetWord} buys {k.ToString("N0", Inv)} more ({Num(spent)}), " + + $"the {Ordinal(bought + k + 1)} needs {Num(need)} more"; + } + + /// + /// more points in one lane: "Luminance: points 6 to 10 cost 25,045,872 in all (3,051,758, + /// 3,814,697, ...)", at most ten prices listed. + /// + public static string Range(string title, AbilityCurve curve, int bought, int count) + { + count = Math.Clamp(count, 1, AbilityCurve.MaxPoints); + long total = curve.CostOfRange(bought, count); + if (count == 1) return $"{title}: the {Ordinal(bought + 1)} point costs {Num(total)}"; + string s = $"{title}: points {(bought + 1).ToString("N0", Inv)} to {(bought + count).ToString("N0", Inv)} cost {Num(total)} in all"; + var each = new System.Collections.Generic.List(); + for (int i = 1; i <= Math.Min(count, 10); i++) each.Add(curve.Cost(bought + i).ToString("N0", Inv)); + return s + " (" + string.Join(", ", each) + (count > 10 ? ", ..." : "") + ")"; + } +} + +/// +/// How fast a number grows this login (the banked luminance, the total experience), for "the next point in about +/// N h". Readings come as they come; a purchase's price is added back (Spent), so buying a point doesn't read as +/// a loss. A drop nothing explains (luminance spent on something else) starts the count again from there. +/// +internal sealed class EarnRate +{ + private bool _has; + private long _firstMs, _lastMs, _first, _last, _spent; + + public void Clear() + { + _has = false; + _spent = 0; + } + + /// A reading of the number at (Environment.TickCount64). + public void Add(long nowMs, long value) + { + long counted = value + _spent; + if (!_has || counted < _last) + { + _has = true; + _spent = 0; + _firstMs = _lastMs = nowMs; + _first = _last = value; + return; + } + _lastMs = nowMs; + _last = counted; + } + + /// Some of the number went on a point (it comes back into the count). + public void Spent(long amount) + { + if (_has && amount > 0) _spent += amount; + } + + /// Per hour, once the readings span ; else null. + public double? PerHour(long minSpanMs) + { + if (!_has || _lastMs - _firstMs < Math.Max(1, minSpanMs)) return null; + return (_last - _first) / ((_lastMs - _firstMs) / 3_600_000.0); + } + + /// How long more takes at : "about 25 min", "about 3.5 h", + /// "about 6 days"; "" when it never comes at that rate. + public static string Time(long need, double perHour) + { + if (need <= 0) return "now"; + if (perHour <= 0 || double.IsNaN(perHour)) return ""; + double h = need / perHour; + var inv = System.Globalization.CultureInfo.InvariantCulture; + if (h < 1) return $"about {Math.Max(1, Math.Round(h * 60)).ToString("0", inv)} min"; + if (h < 10) return $"about {h.ToString("0.#", inv)} h"; + if (h < 72) return $"about {Math.Round(h).ToString("0", inv)} h"; + double d = h / 24; + return d < 1000 ? $"about {Math.Round(d).ToString("0", inv)} days" : "more than 1,000 days"; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveAbilityPoints.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveAbilityPoints.cs new file mode 100644 index 0000000..44dfd88 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveAbilityPoints.cs @@ -0,0 +1,511 @@ +// DreamWeaveAbilityPoints.cs - your class ability points on DreamWeave (2026-11-17), for the Abilities page +// (AbilitiesPage.cs): how many you have, how many you have bought in each lane (where each lane's price curve stands, +// AbilityPointPrices.cs), what you are earning, and the purchases made from the page. The client is never sent the +// counts; "/abilities points" (ACE-DreamWeave Source/ACE.Server/Command/Handlers/ClassAbilityCommands.cs, +// HandlePoints) answers with Broadcast lines: +// Points: 12 available, 30 lifetime earned. +// Luminance purchases: 5 bought so far; the next point costs 3,051,758 Luminance. Exchange it at the ... +// Experience purchases: 2 bought so far; the next point costs 392,000,000,000 experience and you have +// 1,234 unassigned. Prices rise with each point and there is no cap. +// or Experience purchases: unlocked at level 275 (you are 200). +// or (the feature off) Class abilities are not currently enabled on this server. +// RynthDreamWeave sends it when the Abilities page is first opened in a login (and on Read now), at a quiet moment +// (none of its other commands within GapMs), and keeps that reply out of chat. One the player types shows as usual +// and is read the same way. The "Points:" line also ends other /abilities replies, and every grant says +// You gain 1 class ability point from spending 3,051,758 Luminance. Available: 13. Use /abilities to spend them. +// so a purchase moves its lane's count on at once (and a read follows to confirm the next price). +// +// Buying (2026-11-17: a button raises a lane where a command can buy it): +// experience "/abilities buyxp N" is a player command (no server prompt: the page asks first). Its refusals: +// Buying 1 point costs X experience; you have Y unassigned. +// You must be level 275 to exchange experience for class ability points. You are level 200. +// luminance only at the Reckoning-Stone of Radiance (the Drift Network): "/abilities buy" is developer-only. +// Using the stone says ": this weighs your Luminance ..." and then either AC's Yes/No prompt with +// the price (nothing is spent until the player says Yes) or +// Your next point would cost X Luminance; you have Y (A available + B banked). +// A Yes the server can't honour answers "Buying 1 point costs X Luminance; you have Y (...)". +// Those answers, and the grant, are said on the page (BuyMessage); none is hidden. +// +// Every regex is anchored at the start of the line (after an optional chat timestamp), so a pasted copy in a tell +// or a channel can't set anything; player-authored chat is never read. +// Threads: everything here runs under Gate (pump; the page draws holding it), except NoteChatBar, which the chat +// bar calls on AC's thread (interlocked fields only). Pure: RynthServerPack.Tests covers it. +using System; +using System.Globalization; +using System.Text.RegularExpressions; +using System.Threading; +using RynthCore.Plugin.ServerPack; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthDreamWeave; + +internal sealed class DreamWeaveAbilityPoints +{ + public const string Command = "/abilities points"; + /// None of RynthDreamWeave's other server commands this close before the read (as the offline bonus read). + public const long GapMs = DreamWeaveXpBonus.GapMs; + /// An experience purchase's answer comes within this. + public const long BuyWindowMs = 6_000; + /// A stone's use: the walk there and AC's Yes/No take longer. + public const long StoneWindowMs = 45_000; + /// The luminance stone's name (DreamWeave's Drift Network). + public const string LumStoneName = "Reckoning-Stone of Radiance"; + + private const string Ts = @"^\s*(?:\[[^\]]*\][\s:]*)?"; + private const string N = @"([\d,]+)"; + private static readonly Regex PointsLine = new(Ts + @"Points:\s*" + N + @" available,\s*" + N + @" lifetime earned\.\s*$"); + // Learning or unlearning an ability ends its line with the same summary. + private static readonly Regex LearnLine = new(Ts + @"You have (?:learned|unlearned) .*\bPoints:\s*" + N + @" available,\s*" + N + @" lifetime earned\.\s*$"); + private static readonly Regex LumLine = new(Ts + @"Luminance purchases:\s*" + N + @" bought so far; the next point costs " + N + @" Luminance\."); + private static readonly Regex XpLine = new(Ts + @"Experience purchases:\s*" + N + @" bought so far; the next point costs " + N + + @" experience and you have " + N + @" unassigned\."); + private static readonly Regex XpLockedLine = new(Ts + @"Experience purchases:\s*unlocked at level " + N + @" \(you are " + N + @"\)\."); + private static readonly Regex OffLine = new(Ts + @"Class abilities are not currently enabled on this server\.\s*$"); + private static readonly Regex GainLine = new(Ts + @"You gain " + N + @" class ability points? from (.+?)\. Available: " + N + @"\."); + private static readonly Regex SpentLum = new(@"^spending ([\d,]+) Luminance$", RegexOptions.IgnoreCase); + private static readonly Regex SpentXp = new(@"^spending ([\d,]+) experience$", RegexOptions.IgnoreCase); + private static readonly Regex XpShortLine = new(Ts + @"(?:Buying " + N + @" points? costs|Your next point would cost) " + N + + @" experience; you have " + N + @" unassigned\.\s*$"); + private static readonly Regex XpLevelLine = new(Ts + @"You must be level " + N + @" to exchange experience for class ability points\. You are level " + N + @"\.\s*$"); + private static readonly Regex LumShortLine = new(Ts + @"(?:Buying " + N + @" points? costs|Your next point would cost) " + N + + @" Luminance; you have " + N + @"(?: \(" + N + @" available \+ " + N + @" banked\))?\.\s*$"); + + /// Held for everything below (pump and render thread). + public readonly object Gate = new(); + + // ── The reading (null before one this login) ───────────────────────── + + public int? Available { get; private set; } + public int? Earned { get; private set; } + /// Points bought with luminance: where the luminance curve stands. + public int? LumBought { get; private set; } + /// The server's price for the next luminance point (null when a purchase since made it stale). + public long? LumNext { get; private set; } + /// Points bought with experience (0 while the lane is locked: it can't have been used). + public int? XpBought { get; private set; } + public long? XpNext { get; private set; } + /// The experience lane's level, when the server said it is still locked (else null). + public int? XpUnlockLevel { get; private set; } + /// Class abilities are off on this server (the server said so). + public bool Off { get; private set; } + public DateTime ReadUtc { get; private set; } = DateTime.MinValue; + public bool HasReading => ReadUtc != DateTime.MinValue; + /// Why the last read gave nothing ("" when it didn't fail). + public string LastMiss { get; private set; } = ""; + /// Moves on whenever the reading changes (the page refills its boxes from it). + public int Revision { get; private set; } + /// The luminance the stone last counted for you (on you + banked), and the part on you; null before one. + public long? StoneSpendable { get; private set; } + public long? StoneOnYou { get; private set; } + + // ── Live from the character (the host's tick) ──────────────────────── + + public int Level { get; private set; } + /// Unassigned experience (AvailableExperience), null when the client doesn't know it. + public long? UnassignedXp { get; private set; } + /// The banked luminance (deposits taken out) and the total experience, as they rise this login. + public EarnRate LumRate { get; } = new(); + public EarnRate XpRate { get; } = new(); + + public void SetCharacter(int level, long? unassignedXp) + { + if (level > 0) Level = level; + if (unassignedXp != null) UnassignedXp = unassignedXp; + } + + /// The luminance stone: remembered (selected once), and in sight now (the page's Use button). + public bool StoneKnown { get; private set; } + public bool StoneNear { get; private set; } + + public void SetStone(bool known, bool near) + { + StoneKnown = known; + StoneNear = known && near; + } + + // ── The price curves, fitted to the server's quotes ────────────────── + + /// The luminance curve: the published one, or scaled to the server's last quote (LumMatches false). + public AbilityCurve LumCurve { get; private set; } = AbilityCurve.Luminance; + public bool LumMatches { get; private set; } = true; + public AbilityCurve XpCurve { get; private set; } = AbilityCurve.Experience; + public bool XpMatches { get; private set; } = true; + + /// Everything in a few sentences ("/rserver abilities"); the bank check's reading. + public string Summary(long? bankLum) + { + if (Off) return "Class abilities are off on DreamWeave right now"; + if (!HasReading) return "Your class ability points aren't read yet"; + var inv = CultureInfo.InvariantCulture; + string head = $"Class ability points: {Available?.ToString("N0", inv) ?? "?"} available, {Earned?.ToString("N0", inv) ?? "?"} earned"; + string lum = AbilityText.Lane("Luminance", LumCurve, LumBought ?? 0, bankLum, "banked"); + string xp = XpUnlockLevel is int lv + ? $"Experience: opens at level {lv.ToString("N0", inv)}" + (Level > 0 ? $" (you are {Level.ToString("N0", inv)})" : "") + : AbilityText.Lane("Experience", XpCurve, XpBought ?? 0, UnassignedXp, "unassigned"); + return head + ". " + lum + ". " + xp; + } + + // ── Requests ────────────────────────────────────────────────────────── + + private readonly ServerChatRequest _request = new(); + private bool _asked; // an own request went out and hasn't been answered or given up + private bool _wanted; // a read waits for a quiet moment + private bool _openedThisLogin; // the page asked for its first read already + private int _selfSends; // our /abilities points not yet seen by the chat bar (0 or 1) + private int _typed; // the player typed /abilities points (AC's thread sets it) + + public void Login() => Clear(); + + public void Logout() => Clear(); + + private void Clear() + { + Available = Earned = null; + LumBought = XpBought = XpUnlockLevel = null; + LumNext = XpNext = null; + StoneSpendable = StoneOnYou = null; + Off = false; + ReadUtc = DateTime.MinValue; + LastMiss = ""; + Level = 0; + UnassignedXp = null; + LumCurve = AbilityCurve.Luminance; + XpCurve = AbilityCurve.Experience; + LumMatches = XpMatches = true; + LumRate.Clear(); + XpRate.Clear(); + _buy = BuyKind.None; + _buyUntilMs = 0; + BuyMessage = ""; + BuyFailed = false; + _request.Clear(); + _asked = _wanted = _openedThisLogin = false; + Interlocked.Exchange(ref _selfSends, 0); + Interlocked.Exchange(ref _typed, 0); + Revision++; + } + + /// The page is being drawn: the first time in a login with nothing read, a read is wanted. + public void PageOpened() + { + if (_openedThisLogin) return; + _openedThisLogin = true; + if (!HasReading) _wanted = true; + } + + /// Read now (the page's button, "/rserver abilities check"): at the next quiet moment. + public void CheckSoon() + { + _wanted = true; + LastMiss = ""; + Revision++; + } + + /// An own request waits for its reply, or a read waits to go. + public bool Waiting(long nowMs) => _wanted || (_asked && _request.Awaiting(nowMs)); + + /// A read wants to go (the host then looks whether it is a quiet moment). + public bool Wanted => _wanted; + + /// + /// The pump's tick: the command when a read is wanted and may go now, else null. is + /// false outside the world and in portal space; false while another of + /// RynthDreamWeave's commands is within , or a purchase waits for its answer. + /// + public string? Due(long nowMs, bool canSend, bool quiet) + { + if (!_wanted || !canSend || !quiet || Buying(nowMs) || (_asked && _request.Awaiting(nowMs))) return null; + _wanted = false; + return Request(nowMs); + } + + /// Marks a request as RynthDreamWeave's own (its reply is hidden) and returns the command to send. + public string Request(long nowMs) + { + _request.Sent(nowMs); + _asked = true; + LastMiss = ""; + // One at a time: if the engine's chat bar never sees our sends, the count still can't grow. + Interlocked.Exchange(ref _selfSends, 1); + return Command; + } + + /// The request didn't go out (not in the world, no chat parser). + public void NotSent() + { + _request.Clear(); + _asked = false; + Interlocked.Exchange(ref _selfSends, 0); + } + + /// True for "/abilities points" (any case, any spacing). + public static bool IsCommand(string? text) + { + string[] words = (text ?? "").Trim().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + return words.Length == 2 && words[0].Equals("/abilities", StringComparison.OrdinalIgnoreCase) + && words[1].Equals("points", StringComparison.OrdinalIgnoreCase); + } + + /// AC's thread (chat bar): a /abilities points went through it. Ours, or typed by the player? + public void NoteChatBar() + { + if (Interlocked.Decrement(ref _selfSends) >= 0) return; + Interlocked.Exchange(ref _selfSends, 0); + Interlocked.Exchange(ref _typed, 1); + } + + /// + /// The pump's tick: a typed /abilities points makes the reply the player's; an own request with no reply in time + /// is given up, and so is a purchase. True when the read was given up just now. + /// + public bool Tick(long nowMs) + { + TakeTyped(); + if (_buy != BuyKind.None && nowMs >= _buyUntilMs) + { + if (_buy == BuyKind.Xp) Said("No answer to the experience purchase; Read now shows whether it went through.", failed: true); + _buy = BuyKind.None; + } + if (!_request.Awaiting(nowMs)) Interlocked.Exchange(ref _selfSends, 0); + if (!_asked || _request.Awaiting(nowMs)) return false; + _asked = false; + LastMiss = "No reply to " + Command + "."; + Revision++; + return true; + } + + private void TakeTyped() + { + if (Interlocked.Exchange(ref _typed, 0) == 0) return; + _request.Clear(); + _asked = false; + } + + // ── Buying ──────────────────────────────────────────────────────────── + + private enum BuyKind { None, Xp, Stone } + private BuyKind _buy; + private long _buyUntilMs; + + /// What the last purchase came to ("" when none this login); BuyFailed when it was a refusal. + public string BuyMessage { get; private set; } = ""; + public bool BuyFailed { get; private set; } + + /// A purchase (or a stone's use) waits for its answer. + public bool Buying(long nowMs) => _buy != BuyKind.None && nowMs < _buyUntilMs; + + /// + /// The command that buys points with experience ("/abilities buyxp N"), now marked as + /// waiting for its answer; null while another purchase waits or the count is out of range. + /// + public string? BuyXp(int count, long nowMs) + { + if (count < 1 || count > AbilityCurve.MaxPoints || Buying(nowMs)) return null; + _buy = BuyKind.Xp; + _buyUntilMs = nowMs + BuyWindowMs; + Said($"Buying {Points(count)} with experience...", failed: false); + return "/abilities buyxp " + count.ToString(CultureInfo.InvariantCulture); + } + + /// The luminance stone was used from the page: the walk there and AC's Yes/No follow. + public void StoneUsed(long nowMs) + { + _buy = BuyKind.Stone; + _buyUntilMs = nowMs + StoneWindowMs; + Said("Using the Reckoning-Stone: AC asks Yes or No with the price; nothing is spent until you say Yes.", failed: false); + } + + /// The purchase didn't go out. + public void BuyNotSent(string why) + { + _buy = BuyKind.None; + _buyUntilMs = 0; + Said(why, failed: true); + } + + private void Said(string message, bool failed) + { + BuyMessage = message; + BuyFailed = failed; + Revision++; + } + + private static string Points(int n) => n == 1 ? "1 point" : n.ToString("N0", CultureInfo.InvariantCulture) + " points"; + + // ── Reading the server's lines ──────────────────────────────────────── + + /// + /// An incoming chat message on DreamWeave. True when it should be kept out of the chat window: the reply to + /// RynthDreamWeave's own /abilities points. + /// + public bool OnChatText(string? text, int chatType, long nowMs, DateTime utcNow) + { + if (string.IsNullOrEmpty(text) || ChatSource.IsPlayerAuthored(chatType)) return false; + TakeTyped(); + bool hide = false; + foreach (string raw in text.Split('\n')) + { + string line = raw.TrimEnd('\r', ' ', '\t'); + if (line.Length == 0) continue; + Kind kind = ReadLine(line, nowMs, utcNow); + if (kind == Kind.None || kind == Kind.Aside) continue; + bool ours = _asked && _request.Awaiting(nowMs); + if (!ours) continue; + hide = true; + _request.Extend(nowMs); + if (kind == Kind.Last) + { + _asked = false; + _request.Clear(); + } + } + return hide; + } + + private enum Kind { None, Part, Last, Aside } + + private Kind ReadLine(string line, long nowMs, DateTime utcNow) + { + Match m; + if ((m = PointsLine.Match(line)).Success) + { + if (TryInt(m.Groups[1].Value, out int a) && TryInt(m.Groups[2].Value, out int e)) { Available = a; Earned = e; Revision++; } + return Kind.Part; + } + if ((m = LumLine.Match(line)).Success) + { + if (TryInt(m.Groups[1].Value, out int b) && TryLong(m.Groups[2].Value, out long next)) + { + LumBought = b; + LumNext = next; + LumCurve = AbilityCurve.Luminance.Fit(b, next, out bool same); + LumMatches = same; + Off = false; + ReadUtc = utcNow; + Revision++; + } + return Kind.Part; + } + if ((m = XpLine.Match(line)).Success) + { + if (TryInt(m.Groups[1].Value, out int b) && TryLong(m.Groups[2].Value, out long next)) + { + XpBought = b; + XpNext = next; + XpCurve = AbilityCurve.Experience.Fit(b, next, out bool same); + XpMatches = same; + XpUnlockLevel = null; + if (TryLong(m.Groups[3].Value, out long un)) UnassignedXp = un; + Revision++; + } + return Kind.Last; + } + if ((m = XpLockedLine.Match(line)).Success) + { + if (TryInt(m.Groups[1].Value, out int lv)) + { + XpUnlockLevel = lv; + if (TryInt(m.Groups[2].Value, out int now) && now > 0) Level = now; + // The lane can't be used below its level, so none were bought with it; its next price is the first. + XpBought = 0; + XpNext = null; + Revision++; + } + return Kind.Last; + } + if (OffLine.IsMatch(line)) + { + Off = true; + ReadUtc = utcNow; + if (Buying(nowMs)) EndBuy("DreamWeave says class abilities are off right now.", failed: true); + Revision++; + return Kind.Last; + } + if ((m = LearnLine.Match(line)).Success) + { + if (TryInt(m.Groups[1].Value, out int a) && TryInt(m.Groups[2].Value, out int e)) { Available = a; Earned = e; Revision++; } + return Kind.Aside; // not part of a /abilities points reply + } + if ((m = GainLine.Match(line)).Success) + { + if (!TryInt(m.Groups[1].Value, out int got)) return Kind.Aside; + string from = m.Groups[2].Value.Trim(); + if (TryInt(m.Groups[3].Value, out int avail)) Available = avail; + if (Earned is int e) Earned = e + got; + Match spent; + if ((spent = SpentLum.Match(from)).Success) + { + if (TryLong(spent.Groups[1].Value, out long lum)) LumRate.Spent(lum); + if (LumBought is int lb) + { + LumBought = lb + got; + LumNext = null; // the curve's price until the read below confirms the server's + _wanted = true; + } + if (_buy == BuyKind.Stone) EndBuy($"Bought {Points(got)} with luminance ({spent.Groups[1].Value}). Available now: {avail}.", failed: false); + } + else if ((spent = SpentXp.Match(from)).Success) + { + if (XpBought is int xb) + { + XpBought = xb + got; + XpNext = null; + _wanted = true; + } + if (_buy == BuyKind.Xp) EndBuy($"Bought {Points(got)} with experience ({spent.Groups[1].Value}). Available now: {avail}.", failed: false); + } + Revision++; + return Kind.Aside; + } + if ((m = XpShortLine.Match(line)).Success) + { + // "Buying N points costs X experience; you have Y unassigned." (the command) or the XP stone's "Your next + // point would cost X experience; you have Y unassigned." + if (TryLong(m.Groups[3].Value, out long un)) UnassignedXp = un; + if (Buying(nowMs)) EndBuy("Not enough unassigned experience: " + Clean(line), failed: true); + Revision++; + return Kind.Aside; + } + if ((m = XpLevelLine.Match(line)).Success) + { + if (TryInt(m.Groups[1].Value, out int lv)) XpUnlockLevel = lv; + if (TryInt(m.Groups[2].Value, out int now) && now > 0) Level = now; + if (Buying(nowMs)) EndBuy(Clean(line), failed: true); + Revision++; + return Kind.Aside; + } + if ((m = LumShortLine.Match(line)).Success) + { + // The stone (or a Yes it couldn't honour): what it counted, the luminance on you included. + bool single = m.Groups[1].Value.Length == 0 || m.Groups[1].Value == "1"; + if (single && TryLong(m.Groups[2].Value, out long cost) && LumBought is int lb) + { + LumNext = cost; + LumCurve = AbilityCurve.Luminance.Fit(lb, cost, out bool same); + LumMatches = same; + } + if (TryLong(m.Groups[3].Value, out long have)) StoneSpendable = have; + if (m.Groups[4].Success && TryLong(m.Groups[4].Value, out long onYou)) StoneOnYou = onYou; + if (Buying(nowMs)) EndBuy("Not enough luminance: " + Clean(line), failed: true); + Revision++; + return Kind.Aside; + } + return Kind.None; + } + + private void EndBuy(string message, bool failed) + { + _buy = BuyKind.None; + _buyUntilMs = 0; + Said(message, failed); + } + + // A server line for the page: without a chat timestamp. + private static string Clean(string line) => Regex.Replace(line, Ts, "").Trim(); + + private static bool TryInt(string text, out int value) + => int.TryParse(text.Replace(",", ""), NumberStyles.None, CultureInfo.InvariantCulture, out value); + + private static bool TryLong(string text, out long value) + => long.TryParse(text.Replace(",", ""), NumberStyles.None, CultureInfo.InvariantCulture, out value); +} diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveBank.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveBank.cs index 18c2aba..2e77776 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveBank.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveBank.cs @@ -183,12 +183,12 @@ internal sealed class DreamWeaveBank } if ((m = DepositAllLine.Match(line)).Success) { - // Deposit all: only the new balance. What the bank gained since the last reading moved in. - if (TryNumber(m.Groups[1].Value, out long balance)) - { - if (Luminance is long before && balance > before) MovedIn += balance - before; - Read(balance, nowMs); - } + // Deposit all: only the new balance, a reading. Its luminance move isn't counted: earned + // luminance goes straight into the bank on DreamWeave, so taking all the bank gained since + // the last reading as "moved in" threw away what was earned meanwhile. R-20261125-230220-95f8: + // a meta's "/b d" left Lum/hr at 6.6m against 71m banked. The trade: luminance that was on + // the character and goes in with it counts as earned once. + if (TryNumber(m.Groups[1].Value, out long balance)) Read(balance, nowMs); return false; } return ReplyLine.IsMatch(line) && Ours(nowMs); diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveAbilitiesHost.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveAbilitiesHost.cs new file mode 100644 index 0000000..53c20a1 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveAbilitiesHost.cs @@ -0,0 +1,329 @@ +// DreamWeaveAbilitiesHost.cs - RynthDreamWeave's class ability point calculator (2026-11-17), through the shared +// server plugin's hooks (Plugins/Shared/ServerPack/ServerPackPlugin.cs): the Abilities page of the DreamWeave window +// (DreamWeave/AbilitiesPage.cs) and "/rserver abilities", priced with DreamWeave's own curves +// (DreamWeave/AbilityPointPrices.cs) from where you stand in each lane (DreamWeave/DreamWeaveAbilityPoints.cs reads +// "/abilities points"). +// +// "/abilities points" goes only when asked: the first time the page opens in a login, Read now, "/rserver abilities +// check", and after a purchase at a stone (to confirm the next price). It waits for a quiet moment, as the offline +// bonus read does (none of RynthDreamWeave's /b, /top or /offlinebonus within 5 s), and its reply is kept out of +// chat; one the player types shows as usual and is read the same way. The budgets are the bank check's banked +// luminance (DreamWeaveBank.cs) and the character's unassigned experience, read on the tick (twice a second while the +// page is drawn, every 30 s otherwise), with what each grows by this login (the bank's readings, the total experience). +// +// Buying from the page: experience with "/abilities buyxp N" (after the page's own Yes); luminance only at the +// Reckoning-Stone of Radiance. The stone is remembered once the player selects it (AC's selection, its name checked; +// a world object's id stays the same, so it is kept in the settings), and while the client has it in the same +// landblock within StoneNearM the page's Use button uses it (the server walks there; AC asks Yes or No with the price). +// +// The hooks it shares with the bank, the leaderboards, the offline bonus, the Skills panel and the web tools are +// implemented once (DreamWeavePlugin.cs, DreamWeaveSkills.cs) and call the Abilities* methods here. +// Threads: the chat bar note runs on AC's thread (interlocked fields only); the page draws on the render thread +// holding _abilities.Gate; everything else on the pump, taking one gate at a time (never around Send or Reply). +using System; +using System.Collections.Generic; +using System.Threading; +using RynthCore.Plugin.RynthDreamWeave; + +namespace RynthCore.Plugin.ServerPack; + +public sealed partial class ServerPackPlugin +{ + private const uint AbilitiesIntLevel = 25, AbilitiesQuadAvailableExperience = 2; + private const long AbilitiesCharacterEveryMs = 500, AbilitiesCharacterIdleMs = 30_000; + private const uint AbilitiesQuadTotalExperience = 1; + private const string AbilitiesStoneSetting = "abilitiesLumStone"; + private const float StoneNearM = 60f; + private uint _abilitiesStone; // the Reckoning-Stone's id (0 unknown); pump thread + private bool _abilitiesStoneLoaded; + private uint _abilitiesLastSelection; + private DateTime _abilitiesBankRead = DateTime.MinValue; + private readonly DreamWeaveAbilityPoints _abilities = new(); + private long _abilitiesDrawnMs = long.MinValue / 2; // render thread writes (Interlocked) + private long _abilitiesCharacterDueMs; + // A typed "/rserver abilities check": its answer (or that none came) is said in chat. + private bool _abilitiesAnnounce; + + private void AddAbilitiesPage(List pages) + { + var page = new AbilitiesPage(_abilities, () => Active, AbilitiesBankLuminance, RunOnTick, + () => AbilitiesCheck(typed: false), CheckBankNow, + () => Interlocked.Exchange(ref _abilitiesDrawnMs, Environment.TickCount64), + AbilitiesBuyXp, AbilitiesUseStone, AbilitiesRecall); + pages.Add(page.Page()); + } + + /// The bank check's banked luminance (its own lock, taken alone). + private long? AbilitiesBankLuminance() + { + lock (_bank.Gate) return _bank.Luminance; + } + + private void AbilitiesLogin() + { + _abilitiesAnnounce = false; + lock (_abilities.Gate) _abilities.Login(); + } + + private void AbilitiesLogout() + { + _abilitiesAnnounce = false; + lock (_abilities.Gate) _abilities.Logout(); + } + + /// AC's thread: a line through the chat bar. Our own /abilities points, or one the player typed? + private void AbilitiesChatBar(string text) + { + if (DreamWeaveAbilityPoints.IsCommand(text)) _abilities.NoteChatBar(); + } + + /// An incoming chat line on DreamWeave: true when it answers RynthDreamWeave's own /abilities points. + private bool AbilitiesChatText(string text, int chatType) + { + bool ours, done; + lock (_abilities.Gate) + { + ours = _abilities.OnChatText(text, chatType, Environment.TickCount64, DateTime.UtcNow); + done = ours && !_abilities.Waiting(Environment.TickCount64); + } + if (done && _abilitiesAnnounce) + { + _abilitiesAnnounce = false; + long? bank = AbilitiesBankLuminance(); + string summary; + lock (_abilities.Gate) summary = _abilities.Summary(bank); + Reply.Ok(summary + "."); + } + return ours; + } + + /// + /// The pump's tick: the character's level and unassigned experience while the page is open, and the read when one + /// is wanted and it is a quiet moment. + /// + private void AbilitiesTick() + { + long now = Environment.TickCount64; + uint player = Host.HasGetPlayerId ? Host.GetPlayerId() : 0; + bool drawn = now - Interlocked.Read(ref _abilitiesDrawnMs) < 3000; + if (player != 0) AbilitiesNoteSelection(player); + if (player != 0 && now >= _abilitiesCharacterDueMs) + { + _abilitiesCharacterDueMs = now + (drawn || _abilitiesAnnounce ? AbilitiesCharacterEveryMs : AbilitiesCharacterIdleMs); + int level = Host.HasGetObjectIntProperty && Host.TryGetObjectIntProperty(player, AbilitiesIntLevel, out int lv) ? lv : 0; + long? unassigned = Host.HasGetObjectQuadProperty && Host.TryGetObjectQuadProperty(player, AbilitiesQuadAvailableExperience, out long xp) + ? xp : null; + long? total = Host.HasGetObjectQuadProperty && Host.TryGetObjectQuadProperty(player, AbilitiesQuadTotalExperience, out long tx) && tx > 0 + ? tx : null; + bool known = false, near = false; + if (drawn) (known, near) = AbilitiesStone(player); + lock (_abilities.Gate) + { + _abilities.SetCharacter(level, unassigned); + if (total is long t) _abilities.XpRate.Add(now, t); + if (drawn) _abilities.SetStone(known, near); + } + } + // The bank's readings, as they come, for what the bank grows by (deposits taken out: DreamWeaveBank.Published). + long? published = null; + lock (_bank.Gate) + { + if (_bank.ReadUtc != _abilitiesBankRead) + { + _abilitiesBankRead = _bank.ReadUtc; + published = _bank.Published; + } + } + if (published is long pub) lock (_abilities.Gate) _abilities.LumRate.Add(now, pub); + bool canSend = player != 0 && Host.HasInvokeChatParser && !(Host.HasIsPortaling && Host.IsPortaling()); + bool wanted; + lock (_abilities.Gate) wanted = _abilities.Wanted; + bool quiet = wanted && AbilitiesQuiet(now); // the other gates are taken one at a time, never nested + string? command; + bool missed; + lock (_abilities.Gate) + { + missed = _abilities.Tick(now); + command = _abilities.Due(now, canSend, quiet); + } + if (missed && _abilitiesAnnounce) + { + _abilitiesAnnounce = false; + Reply.Fail($"No reply to {DreamWeaveAbilityPoints.Command}."); + } + if (command != null) + { + if (Send(command)) NoteServerSend(); // the offline bonus read keeps clear of it too + else lock (_abilities.Gate) _abilities.NotSent(); + } + } + + /// + /// The Reckoning-Stone (pump thread, while the page is drawn): remembered when the player has it selected, and + /// whether the client has it near now (same landblock, within StoneNearM). + /// + private (bool Known, bool Near) AbilitiesStone(uint player) + { + if (!_abilitiesStoneLoaded) + { + _abilitiesStoneLoaded = true; + string saved = Settings.GetString(AbilitiesStoneSetting, ""); + if (uint.TryParse(saved, System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture, out uint id)) + _abilitiesStone = id; + } + uint stone = _abilitiesStone; + if (stone == 0) return (false, false); + if (!Host.HasGetObjectPosition || !Host.TryGetObjectPosition(stone, out uint cell, out float x, out float y, out float z)) return (true, false); + if (!Host.TryGetObjectName(stone, out string seen) || !seen.Trim().Equals(DreamWeaveAbilityPoints.LumStoneName, StringComparison.OrdinalIgnoreCase)) + return (true, false); + if (!Host.TryGetPlayerPose(out uint pcell, out float px, out float py, out float pz, out _, out _, out _, out _)) return (true, false); + if (cell >> 16 != pcell >> 16) return (true, false); + float dx = x - px, dy = y - py, dz = z - pz; + return (true, dx * dx + dy * dy + dz * dz <= StoneNearM * StoneNearM); + } + + /// + /// Every tick (pump thread): a newly selected object named as the Reckoning-Stone is remembered (its id kept in + /// the settings). Only a change of selection costs a name lookup. + /// + private void AbilitiesNoteSelection(uint player) + { + if (!Host.HasGetSelectedItemId || !Host.HasGetObjectName) return; + uint sel = Host.GetSelectedItemId(); + if (sel == _abilitiesLastSelection) return; + _abilitiesLastSelection = sel; + if (sel == 0 || sel == player || sel == _abilitiesStone) return; + if (!Host.TryGetObjectName(sel, out string name) + || !name.Trim().Equals(DreamWeaveAbilityPoints.LumStoneName, StringComparison.OrdinalIgnoreCase)) return; + _abilitiesStone = sel; + _abilitiesStoneLoaded = true; // newer than anything saved + if (Settings.SetString(AbilitiesStoneSetting, sel.ToString("X8", System.Globalization.CultureInfo.InvariantCulture))) Settings.Save(); + LogTagged($"Abilities: the Reckoning-Stone is 0x{sel:X8}."); + } + + /// The page's Yes on an experience purchase (pump thread): "/abilities buyxp N". + private void AbilitiesBuyXp(int count) + { + if (!Active) return; + string? command; + lock (_abilities.Gate) command = _abilities.BuyXp(count, Environment.TickCount64); + if (command == null) return; + if (Send(command)) NoteServerSend(); + else lock (_abilities.Gate) _abilities.BuyNotSent($"Couldn't send {command}."); + } + + /// The page's Use the Reckoning-Stone (pump thread): the server walks there, and AC asks Yes or No. + private void AbilitiesUseStone() + { + if (!Active) return; + uint stone = _abilitiesStone; + bool used = stone != 0 && Host.HasUseObject && Host.UseObject(stone); + lock (_abilities.Gate) + { + if (used) _abilities.StoneUsed(Environment.TickCount64); + else _abilities.BuyNotSent("Couldn't use the Reckoning-Stone (is it still in sight?)."); + } + } + + /// The page's Recall to the Drift Network (pump thread): DreamWeave's /dn. + private void AbilitiesRecall() + { + if (!Active) return; + if (Send("/dn")) NoteServerSend(); + else lock (_abilities.Gate) _abilities.BuyNotSent("Couldn't send /dn."); + } + + /// The offline bonus read's quiet moment (no /b, /top or /offlinebonus near), and no /offlinebonus on its way. + private bool AbilitiesQuiet(long now) + { + if (!XpBonusQuiet(now)) return false; + lock (_xpBonus.Gate) return !_xpBonus.Waiting(now); + } + + // ── What Read now and "/rserver abilities" do (pump thread) ── + + private const string AbilitiesNotDreamWeave = "Class ability points are DreamWeave's; RynthCore doesn't see this world as DreamWeave."; + + private void AbilitiesCheck(bool typed) + { + if (!Active) { Reply.Fail(AbilitiesNotDreamWeave); return; } + if (!Host.HasInvokeChatParser) { Reply.Fail($"This RynthCore can't send {DreamWeaveAbilityPoints.Command} for a plugin."); return; } + lock (_abilities.Gate) + { + if (_abilities.Waiting(Environment.TickCount64) && !_abilities.Wanted) + { + if (typed) Reply.Fail("Still waiting for the last /abilities points reply; try again in a few seconds."); + return; + } + _abilities.CheckSoon(); + } + if (!typed) return; + _abilitiesAnnounce = true; + Reply.Ok($"Asking DreamWeave ({DreamWeaveAbilityPoints.Command}, at the next quiet moment); the answer follows here."); + } + + private void AbilitiesCommandVerbs(List verbs) => verbs.Add("abilities"); + + private const string AbilitiesUsage = "/rserver abilities [check | lum [count] | xp [count]]: what class ability points cost " + + "in luminance and experience (also the DreamWeave window's Abilities tab)"; + + private void AbilitiesChatCommand(string[] parts, ref bool handled) + { + if (parts.Length < 2 || !parts[1].Equals("abilities", StringComparison.OrdinalIgnoreCase)) return; + handled = true; + if (!Active) { Reply.Fail(AbilitiesNotDreamWeave); return; } + string verb = parts.Length > 2 ? parts[2].ToLowerInvariant() : ""; + switch (verb) + { + case "": + case "status": + { + long? bank = AbilitiesBankLuminance(); + string summary; + bool have; + lock (_abilities.Gate) + { + summary = _abilities.Summary(bank); + have = _abilities.HasReading; + } + if (have) Reply.Ok(summary + "."); + else Reply.Fail(summary + ": /rserver abilities check asks DreamWeave."); + return; + } + case "check": + case "refresh": + AbilitiesCheck(typed: true); + return; + case "lum": + case "luminance": + case "xp": + case "experience": + { + int count = 1; + if (parts.Length > 3 && (!int.TryParse(parts[3], out count) || count < 1 || count > AbilityCurve.MaxPoints)) + { + Reply.Fail("Usage: " + AbilitiesUsage); + return; + } + bool lum = verb.StartsWith("l", StringComparison.Ordinal); + string line; + lock (_abilities.Gate) + { + int? bought = lum ? _abilities.LumBought : _abilities.XpBought; + AbilityCurve curve = lum ? _abilities.LumCurve : _abilities.XpCurve; + line = AbilityText.Range(lum ? "Luminance" : "Experience", curve, bought ?? 0, count) + + (bought == null ? " (from 0 bought: your count isn't read yet, /rserver abilities check)" : ""); + } + Reply.Ok(line + "."); + return; + } + } + Reply.Fail("Usage: " + AbilitiesUsage); + } + + private void AbilitiesInfoLines(Action line) + { + long? bank = AbilitiesBankLuminance(); + lock (_abilities.Gate) line(_abilities.Summary(bank) + " (/rserver abilities)."); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeavePlugin.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeavePlugin.cs index deffb76..0acfc1c 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeavePlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeavePlugin.cs @@ -5,6 +5,8 @@ // The leaderboards (DreamWeaveBoardsHost.cs, 2026-11-15) share these hooks too: each calls its Boards* method; // so does the offline bonus tracker (DreamWeaveXpBonusHost.cs, 2026-11-15, its XpBonus* methods), which reads the // bank check's [BANK] lines as well and keeps its own /offlinebonus clear of the bank's /b and the boards' /top. +// The class ability point calculator (DreamWeaveAbilitiesHost.cs, 2026-11-17, its Abilities* methods) too: its page +// prices points with the bank's banked luminance, and its /abilities points keeps clear of the others as well. // The website buttons and verbs (DreamWeaveWebTools.cs) share these hooks: each one below hands off to // its Web* method first, so a launch-code line is read whatever the world is and the bank's own gates // stay as they were. @@ -22,6 +24,7 @@ public sealed partial class ServerPackPlugin var bankPages = new DreamWeavePages(_bank, () => Active, RunOnTick, CheckBankNow, SaveDreamWeaveSettings); pages.AddRange(bankPages.Pages()); AddBoardsPage(pages); // DreamWeaveBoardsHost.cs: the Leaderboards page + AddAbilitiesPage(pages); // DreamWeaveAbilitiesHost.cs: the class ability point calculator AddCharacterPage(pages); // DreamWeaveSkills.cs: the Character panel's page } @@ -43,6 +46,7 @@ public sealed partial class ServerPackPlugin lock (_bank.Gate) _bank.Login(Environment.TickCount64); BoardsLogin(); XpBonusLogin(); + AbilitiesLogin(); } partial void ServerLogout() @@ -52,6 +56,7 @@ public sealed partial class ServerPackPlugin SkillsLogout(); BoardsLogout(); XpBonusLogout(); + AbilitiesLogout(); } partial void ServerShutdown() @@ -69,6 +74,7 @@ public sealed partial class ServerPackPlugin if (BoardsChatText(text, chatType)) eat = true; // Before the bank: it reads the [BANK] Offline Bonus Time line too (the bank may hide it; it is read anyway). if (XpBonusChatText(text, chatType)) eat = true; + if (AbilitiesChatText(text, chatType)) eat = true; bool ours; long? value; lock (_bank.Gate) @@ -86,6 +92,7 @@ public sealed partial class ServerPackPlugin if (DreamWeaveBank.IsBalanceCommand(text)) _bank.NoteTypedCommand(); BoardsChatBar(text); XpBonusChatBar(text); + AbilitiesChatBar(text); } partial void ServerTick(bool active) @@ -105,6 +112,7 @@ public sealed partial class ServerPackPlugin else lock (_bank.Gate) _bank.NotSent(); } XpBonusTick(); // after the bank and the boards: it goes only when neither just went or is about to + AbilitiesTick(); // last: its read keeps clear of all three } /// The page's Check now (on the tick). @@ -130,6 +138,7 @@ public sealed partial class ServerPackPlugin } BoardsInfoLines(line); XpBonusInfoLines(line); + AbilitiesInfoLines(line); WebInfoLines(line); } } diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveSkills.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveSkills.cs index ceae407..5da812a 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveSkills.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveSkills.cs @@ -250,6 +250,7 @@ public sealed partial class ServerPackPlugin WebCommandVerbs(verbs); // DreamWeaveWebTools.cs: the website verbs BoardsCommandVerbs(verbs); // DreamWeaveBoardsHost.cs: /rserver boards XpBonusCommandVerbs(verbs); // DreamWeaveXpBonusHost.cs: /rserver xpbonus + AbilitiesCommandVerbs(verbs); // DreamWeaveAbilitiesHost.cs: /rserver abilities } partial void ServerChatCommand(string[] parts, ref bool handled) @@ -260,6 +261,8 @@ public sealed partial class ServerPackPlugin if (handled) return; XpBonusChatCommand(parts, ref handled); // DreamWeaveXpBonusHost.cs: /rserver xpbonus if (handled) return; + AbilitiesChatCommand(parts, ref handled); // DreamWeaveAbilitiesHost.cs: /rserver abilities + if (handled) return; if (parts.Length < 2 || !parts[1].Equals("skills", StringComparison.OrdinalIgnoreCase)) return; handled = true; // "press character|titles": what AC's own Character button or Titles window does now (the engine runs it diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs index f6e7538..504b081 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs @@ -54,6 +54,7 @@ public sealed partial class ServerPackPlugin add(DreamWeaveWeb.UsageLine()); add(BoardsUsage); // DreamWeaveBoardsHost.cs add(XpBonusUsage); // DreamWeaveXpBonusHost.cs + add(AbilitiesUsage); // DreamWeaveAbilitiesHost.cs } catch (Exception) { diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs index 187cc48..50d4d87 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/IltSettingsView/IltSettingsUi.cs @@ -3,7 +3,8 @@ // Drawn in its own window ("/ilt settings"). Shows RynthCore's verdict and reason, this character's // Auto / On / Off override, the ILT world names (edited through RynthCore), this character's ILT // options (the settings that moved here from RynthAi on 2026-10-20: the Empyrean Handler ring -// evade, ...; saved in the Hub's state), and every ILT feature with the state RynthILT's Hub read +// evade, ...; saved in the Hub's state), the Leaftide wiki quest guide's sign-in (IltWiki/IltWikiUi.cs, +// 2026-11-27), and every ILT feature with the state RynthILT's Hub read // from the server (IltSettingsModel has where each comes from). // Edits are RynthCore commands, queued for the plugin tick; the next server-list poll shows the // result. Render thread only. @@ -28,6 +29,7 @@ internal sealed class IltSettingsUi private readonly Action _runCommand; private readonly Func _refreshFeatures; private readonly Func _hub; + private readonly Action? _renderWiki; private string _newName = string.Empty; private string _status = string.Empty; @@ -37,12 +39,15 @@ internal sealed class IltSettingsUi /// Queues a RynthCore command (run on the plugin tick). /// Asks the Hub to read the server's features again; false before it exists. /// This character's Hub (its options live in the Hub's state); null before login. - public IltSettingsUi(IltSettingsModel model, Action runCommand, Func refreshFeatures, Func? hub = null) + /// The Leaftide wiki quest guide's part (IltWiki/IltWikiUi.cs); null leaves it out. + public IltSettingsUi(IltSettingsModel model, Action runCommand, Func refreshFeatures, Func? hub = null, + Action? renderWiki = null) { _model = model; _runCommand = runCommand; _refreshFeatures = refreshFeatures; _hub = hub ?? (() => null); + _renderWiki = renderWiki; } /// The standalone window, while open. @@ -63,6 +68,11 @@ internal sealed class IltSettingsUi ImGui.Separator(); RenderCharacterOptions(); ImGui.Separator(); + if (_renderWiki != null) + { + _renderWiki(); + ImGui.Separator(); + } RenderFeatures(); if (_status.Length > 0) { diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltWiki/IltWikiGuide.cs b/Plugins/RynthCore.Plugin.RynthILT/IltWiki/IltWikiGuide.cs new file mode 100644 index 0000000..9a225f1 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltWiki/IltWikiGuide.cs @@ -0,0 +1,538 @@ +// IltWikiGuide.cs - RynthILT's quest guide from the Leaftide wiki, opt-in (2026-11-27). +// +// The server's wiki shows no page without a login. A player who has a wiki login (and is willing to +// use it) can let RynthILT read the wiki's quest pages with it, for RynthOracle's Guide tab, which gets +// the guide through "RynthServer.QuestGuide" (Plugins/Shared/ServerQuestGuideHost.cs). OFF by default: +// nothing is fetched and nothing is saved until the player signs in, in /ilt settings > Leaftide wiki +// quest guide (or RynthOracle's Guide tab > "Its settings", which opens it). +// - Sign in: the wiki's address (a setting with no default: RynthILT ships no wiki address), a login +// name and a bot password. The sign-in is tried first; only a sign-in that works is saved +// (WikiLoginStore: this PC only, DPAPI for this Windows user). Then the guide is read. +// - The guide is saved per wiki (Wiki\wiki-guide-.json) and read again at login on ILT when it is +// a day old (a switch), or on Refresh guide (at most every 5 minutes). Reads are spaced out +// (WikiClient: the site's Crawl-delay, else 10 s between requests) and fetch only edited pages. +// - Sign out stops a read and deletes the saved sign-in and the saved guide. +// - "/ilt wiki [status|signin|signout|refresh|address |auto on|off|help]" answers in chat. The +// password is never taken in chat. +// Threads: Tick, the commands and the UI requests run on the plugin tick (the UI queues them from the +// render thread); a sign-in or read runs on a pool thread and hands its result back through fields the +// tick takes. The UI reads the volatile fields only. +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.IltWiki; + +internal sealed class IltWikiGuide +{ + /// What RynthOracle calls the guide ("Leaftide Wiki"). + public const string Tag = "Leaftide"; + public const string PluginName = "RynthILT"; + public const string SettingsFile = "wiki-settings.json"; + public static readonly TimeSpan RefreshAfter = TimeSpan.FromHours(24); + public static readonly TimeSpan RefreshCooldown = TimeSpan.FromMinutes(5); + public const int MaxUserLength = 120; + public const int MaxPasswordLength = 200; + + private readonly Func _handler; + private readonly Func? _delay; + private readonly Func _utcNow; + private readonly Action _say; + private readonly Action _log; + private readonly ConcurrentQueue _requests = new(); + private readonly ConcurrentQueue<(string Text, bool Ok)> _messages = new(); + + private CancellationTokenSource? _cts; + private Task? _task; + private volatile QuestGuide? _ready; + private DateTime _lastStartUtc = DateTime.MinValue; + private bool _loginReadDone; + private string _published = string.Empty; + private int _guideRevision; + + // Read by the UI (render thread). + private volatile string _status = "off: not signed in"; + private volatile string _user = string.Empty; + private volatile bool _signedIn; + private volatile string _address = string.Empty; + private volatile bool _daily = true; + + /// The guide in use (tick thread): the saved one until a read replaces it. + public QuestGuide Guide { get; private set; } = new(); + + /// One line for the UI and RynthOracle ("312 quests ... (read 2026-11-27 10:00)", "signing in..."). + public string Status => _status; + /// Signed in: a sign-in is saved on this PC. + public bool SignedIn => _signedIn; + /// The saved login's name ("" when signed out). + public string User => _user; + /// The wiki's API address (a setting; "" until the player types one). + public string Address => _address; + /// Read the guide again at login once it is a day old. + public bool Daily => _daily; + public bool Running => _task is { IsCompleted: false }; + + /// Opens RynthILT's settings window (RynthOracle's "settings" command, "/ilt wiki signin" without a saved login). + public Action? OpenSettings; + + /// A chat line: (text, worked). + /// A new HTTP handler per sign-in or read (WikiClient.NewHandler; the tests' fake wiki). + /// The wait between requests (Task.Delay; the tests note the waits). + public IltWikiGuide(Action say, Action? log = null, Func? handler = null, + Func? delay = null, Func? utcNow = null) + { + _say = say; + _log = log ?? (_ => { }); + _handler = handler ?? WikiClient.NewHandler; + _delay = delay; + _utcNow = utcNow ?? (() => DateTime.UtcNow); + } + + // ── Files ─────────────────────────────────────────────────────────────── + + public static string Folder => WikiLoginStore.Folder; + public static string SettingsPath => Path.Combine(Folder, SettingsFile); + public static string GuidePath(string api) => Path.Combine(Folder, "wiki-guide-" + WikiAddress.FileKey(api) + ".json"); + + /// Plugin start (tick thread): the address and switch, whether a sign-in is saved, and its saved guide. + public void Load() + { + try + { + if (File.Exists(SettingsPath)) + { + using JsonDocument d = JsonDocument.Parse(File.ReadAllText(SettingsPath)); + JsonElement r = d.RootElement; + if (r.TryGetProperty("api", out JsonElement a) && a.ValueKind == JsonValueKind.String + && WikiAddress.TryNormalize(a.GetString(), out string api, out _)) _address = api; + if (r.TryGetProperty("daily", out JsonElement dy) && dy.ValueKind is JsonValueKind.True or JsonValueKind.False) + _daily = dy.ValueKind == JsonValueKind.True; + } + } + catch (Exception ex) { _log("wiki settings unreadable: " + ex.GetType().Name); } + + WikiLogin? login = WikiLoginStore.Load(out string error); + if (login != null && WikiAddress.Same(login.Api, _address)) + { + _signedIn = true; + _user = login.User; + Guide = LoadGuide(_address); + _guideRevision++; + _status = Guide.IsEmpty ? "signed in as " + login.User + "; the guide isn't read yet" : Summary(Guide); + } + else if (login != null) + { + // A sign-in made for another address is never sent to this one. + _status = "off: the saved sign-in was for another wiki address; sign in again"; + } + else if (error.Length > 0) _status = "off: " + error; + else _status = "off: not signed in"; + } + + private static QuestGuide LoadGuide(string api) + { + try + { + string path = GuidePath(api); + if (File.Exists(path)) return QuestGuide.Parse(File.ReadAllText(path)); + } + catch { } + return new QuestGuide(); + } + + private void SaveSettings() + { + try + { + Directory.CreateDirectory(Folder); + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms)) + { + w.WriteStartObject(); + w.WriteString("api", _address); + w.WriteBoolean("daily", _daily); + w.WriteEndObject(); + } + File.WriteAllBytes(SettingsPath + ".tmp", ms.ToArray()); + File.Move(SettingsPath + ".tmp", SettingsPath, overwrite: true); + } + catch (Exception ex) { _log("wiki settings not saved: " + ex.GetType().Name); } + } + + public static string Summary(QuestGuide g) => + $"{g.Quests.Count} quests, {g.KillTasks.Count} kill tasks, {g.Society.Count} society quests, {g.Contracts.Count} contracts" + + (g.UpdatedUtc == DateTime.MinValue ? "" : $" (read {g.UpdatedUtc.ToLocalTime():yyyy-MM-dd HH:mm})"); + + /// The saved guide wants reading: none yet, a day old, or made by an older page reader. + internal static bool Due(QuestGuide g, DateTime utcNow) => + g.IsEmpty || g.Reader < QuestWikiText.ReaderVersion || utcNow - g.UpdatedUtc >= RefreshAfter; + + // ── The tick ──────────────────────────────────────────────────────────── + + /// Plugin tick: the UI's requests, a finished read, RynthOracle's commands, the chat lines, the published guide. + public void Tick() + { + while (_requests.TryDequeue(out Action? a)) + { + try { a(); } + catch (Exception ex) { _log("wiki request failed: " + ex.GetType().Name); } + } + if (_ready is QuestGuide g) + { + _ready = null; + // A read that ended after a sign-out is dropped. + if (_signedIn) + { + Guide = g; + _guideRevision++; + } + } + while (ServerQuestGuideHost.TryTakeCommand(out string word)) + { + if (word == RynthServerQuestGuide.CommandRefresh) Refresh(fromChat: false); + else if (word == RynthServerQuestGuide.CommandSettings) OpenSettings?.Invoke(); + } + while (_messages.TryDequeue(out var m)) _say("[RynthILT] Leaftide wiki: " + m.Text, m.Ok); + Publish(); + } + + /// Hands RynthOracle the guide and status when either changed (tick thread). + private void Publish() + { + bool running = Running; + string key = $"{_guideRevision}|{_signedIn}|{running}|{_status}"; + if (key == _published) return; + _published = key; + string[] words = _signedIn + ? new[] { RynthServerQuestGuide.CommandRefresh, RynthServerQuestGuide.CommandSettings } + : new[] { RynthServerQuestGuide.CommandSettings }; + string status = _signedIn ? _status : "Off. Sign in to the Leaftide wiki in /ilt settings to read its quests (your own wiki login)."; + ServerQuestGuideHost.Publish(Tag, PluginName, _signedIn ? Guide : null, status, running, words); + } + + /// + /// After login (tick thread, until it has run once on an ILT world): one read a session when signed in, the switch + /// on, and the saved guide due. True when it started one. + /// + public bool OnLogin(bool iltActive) + { + if (!iltActive || !_signedIn || !_daily || _loginReadDone || Running) return false; + _loginReadDone = true; + if (!Due(Guide, _utcNow())) return false; + return StartSaved(announce: false); + } + + public void Shutdown() + { + try { _cts?.Cancel(); _task?.Wait(2000); } catch { } + ServerQuestGuideHost.Withdraw(); + } + + // ── What the UI asks (render thread: queued for the tick) ─────────────── + + public void RequestSignIn(string address, string user, string password) => _requests.Enqueue(() => SignIn(address, user, password, fromChat: false)); + public void RequestSignOut() => _requests.Enqueue(() => SignOut(fromChat: false)); + public void RequestRefresh() => _requests.Enqueue(() => Refresh(fromChat: false)); + public void RequestDaily(bool on) => _requests.Enqueue(() => SetDaily(on)); + + // ── The actions (tick thread) ─────────────────────────────────────────── + + /// Tries the sign-in; when it works it is saved and the guide is read. False (with the reason said) when it can't start. + public bool SignIn(string address, string user, string password, bool fromChat) + { + user = (user ?? string.Empty).Trim(); + password ??= string.Empty; + if (Running) return Refuse("busy: " + _status + " (wait for it, or Sign out to stop it)", fromChat); + if (!WikiAddress.TryNormalize(address, out string api, out string error)) return Refuse(error, fromChat); + if (user.Length == 0) return Refuse("type the login name (a bot password's: YourName@botname)", fromChat); + if (password.Length == 0) return Refuse("type the bot password", fromChat); + if (user.Length > MaxUserLength || password.Length > MaxPasswordLength) return Refuse("that login is too long", fromChat); + if (_signedIn && !WikiAddress.Same(api, _address)) return Refuse("sign out first to change the wiki's address", fromChat); + if (!WikiAddress.Same(api, _address)) + { + _address = api; + Guide = LoadGuide(api); + _guideRevision++; + SaveSettings(); + } + _status = "signing in to " + WikiAddress.HostOf(api) + " as " + user + "..."; + Start(new WikiLogin(api, user, password), save: true, announce: true); + return true; + } + + /// Signs in again with the saved login and reads ("/ilt wiki signin" when signed in). + private bool StartSaved(bool announce) + { + WikiLogin? login = WikiLoginStore.Load(out string error); + if (login == null) + { + SetSignedOut(error.Length > 0 ? error : "the saved sign-in is gone; sign in again"); + if (announce) _messages.Enqueue((_status, false)); + return false; + } + if (!WikiAddress.Same(login.Api, _address)) + { + SetSignedOut("the saved sign-in was for another wiki address; sign in again"); + if (announce) _messages.Enqueue((_status, false)); + return false; + } + Start(login, save: false, announce: announce); + return true; + } + + /// Stops a read, deletes the saved sign-in and the saved guide. True when nothing of the wiki is left on this PC. + public bool SignOut(bool fromChat) + { + // The read stops first (it would save the guide again); a request under way ends at once when cancelled. + try { _cts?.Cancel(); _task?.Wait(2000); } catch { } + bool was = _signedIn || WikiLoginStore.Exists; + bool ok = WikiLoginStore.Delete(out string error); + string guideError = string.Empty; + try + { + if (Directory.Exists(Folder)) + foreach (string f in Directory.GetFiles(Folder, "wiki-guide-*.json*")) File.Delete(f); + } + catch (Exception ex) { guideError = "couldn't delete the saved guide: " + ex.GetType().Name; ok = false; } + _ready = null; + Guide = new QuestGuide(); + _guideRevision++; + SetSignedOut(ok ? "off: signed out" : "off: " + (error.Length > 0 ? error : guideError)); + string line = !ok ? "sign out didn't finish: " + (error.Length > 0 ? error : guideError) + : was ? "signed out; the saved sign-in and the saved guide are deleted from this PC." + : "not signed in; nothing was saved."; + if (fromChat) _say("[RynthILT] Leaftide wiki: " + line, ok); + else if (ok) _status = was ? "off: signed out; the saved sign-in and guide are deleted" : "off: not signed in"; + return ok; + } + + /// Reads the wiki again now (signed in, not reading, not read in the last 5 minutes). + public bool Refresh(bool fromChat) + { + if (!_signedIn) return Refuse("not signed in. Sign in in /ilt settings > Leaftide wiki quest guide first.", fromChat); + if (Running) return Refuse("already reading: " + _status, fromChat); + TimeSpan since = _utcNow() - _lastStartUtc; + if (since < RefreshCooldown) + return Refuse($"read {Math.Max(1, (int)since.TotalMinutes)} min ago; again in {(int)Math.Ceiling((RefreshCooldown - since).TotalSeconds)} s (the wiki is read gently)", fromChat); + bool started = StartSaved(announce: true); + if (started && fromChat) _say("[RynthILT] Leaftide wiki: reading the quest pages again (a request every few seconds; the status says how far).", true); + return started; + } + + public bool SetAddress(string typed, bool fromChat) + { + if (_signedIn) return Refuse("sign out first to change the wiki's address", fromChat); + if (!WikiAddress.TryNormalize(typed, out string api, out string error)) return Refuse(error, fromChat); + _address = api; + Guide = LoadGuide(api); + _guideRevision++; + SaveSettings(); + if (fromChat) _say("[RynthILT] Leaftide wiki: address set to " + api + ". Sign in in /ilt settings.", true); + return true; + } + + public void SetDaily(bool on) + { + _daily = on; + SaveSettings(); + } + + private bool Refuse(string why, bool fromChat) + { + if (fromChat) _say("[RynthILT] Leaftide wiki: " + why, false); + else _status = _signedIn ? why : "off: " + why; + return false; + } + + private void SetSignedOut(string status) + { + _signedIn = false; + _user = string.Empty; + _status = status; + } + + // ── The background part ───────────────────────────────────────────────── + + private void Start(WikiLogin login, bool save, bool announce) + { + _cts?.Dispose(); + _cts = new CancellationTokenSource(); + CancellationToken token = _cts.Token; + QuestGuide old = Guide; + _lastStartUtc = _utcNow(); + _task = Task.Run(async () => + { + try { await RunAsync(login, save, announce, old, token).ConfigureAwait(false); } + catch (OperationCanceledException) { _status = _signedIn ? "stopped" : _status; } + catch (Exception ex) + { + // Never the exception's whole text: it could carry a request. Its kind is enough. + _status = "couldn't read the wiki (" + ex.GetType().Name + ")"; + _messages.Enqueue((_status, false)); + } + }, token); + } + + private async Task RunAsync(WikiLogin login, bool save, bool announce, QuestGuide old, CancellationToken token) + { + using var client = new WikiClient(login.Api, _handler(), _delay); + _status = "signing in to " + WikiAddress.HostOf(login.Api) + " as " + login.User + "..."; + WikiSignIn s = await client.SignInAsync(login.User, login.Password, token).ConfigureAwait(false); + token.ThrowIfCancellationRequested(); + if (!s.Ok) + { + // A saved sign-in the wiki turns down stays saved (the wiki may be down); the player can sign in again or out. + _status = (save ? "not signed in: " : "the saved sign-in didn't work: ") + s.Message + + (save ? string.Empty : ". Sign in again in /ilt settings, or Sign out."); + _messages.Enqueue((_status, false)); + return; + } + if (save) + { + if (!WikiLoginStore.Save(login, out string error)) + { + _status = "signed in, but " + error; + _messages.Enqueue((_status, false)); + return; + } + _signedIn = true; + _user = login.User; + if (announce) _messages.Enqueue(("signed in as " + s.UserName + "; reading the quest pages (a request every " + + client.Gap.TotalSeconds.ToString("0") + " s; the status says how far).", true)); + } + + string source = WikiAddress.HostOf(login.Api); + QuestGuide guide; + int fetched; + try + { + (guide, fetched) = await IltWikiReader.ReadAsync(client, old, source, s.ArticleBase, + async t => + { + WikiSignIn again = await client.SignInAsync(login.User, login.Password, t).ConfigureAwait(false); + return (again.Ok, again.Message); + }, + st => _status = st, _utcNow(), token).ConfigureAwait(false); + } + catch (WikiException ex) + { + // The saved guide stays as it was; a failure always gets its line (a login read too). + _status = "couldn't read the wiki: " + ex.Message + (Guide.IsEmpty ? string.Empty : " (the guide read before stays)"); + _messages.Enqueue((_status, false)); + return; + } + token.ThrowIfCancellationRequested(); + + string saved = string.Empty; + try + { + Directory.CreateDirectory(Folder); + string path = GuidePath(login.Api); + File.WriteAllText(path + ".tmp", guide.ToJson()); + File.Move(path + ".tmp", path, overwrite: true); + } + catch (Exception ex) { saved = "; couldn't save it: " + ex.GetType().Name; } + token.ThrowIfCancellationRequested(); + _ready = guide; + _status = Summary(guide) + saved; + if (announce) _messages.Enqueue(($"{Summary(guide)}; {fetched} pages read now{saved}.", saved.Length == 0)); + } + + /// The tests: waits for a sign-in or read to end. + internal bool WaitForTests(int ms = 10_000) + { + try { return _task?.Wait(ms) ?? true; } + catch { return true; } + } + + // ── "/ilt wiki ..." (tick thread) ─────────────────────────────────────── + + /// "/ilt wiki [status|signin|signout|refresh|address <url>|auto on|off|help]". Every form answers. + public void HandleCommand(string[] args) + { + string sub = args.Length > 0 ? args[0].ToLowerInvariant() : "status"; + switch (sub) + { + case "status": + case "": + foreach (string line in StatusLines()) _say("[RynthILT] Leaftide wiki: " + line, true); + return; + case "signin": + case "login": + case "sign-in": + if (args.Length > 1) + { + // Never in chat: the line could be seen, logged or sent. Nothing of it was kept. + _say("[RynthILT] Leaftide wiki: logins aren't taken in chat; nothing was sent or saved. Type it in /ilt settings > Leaftide wiki quest guide.", false); + OpenSettings?.Invoke(); + return; + } + if (_signedIn) + { + if (Running) { _say("[RynthILT] Leaftide wiki: already working: " + _status, false); return; } + if (StartSaved(announce: true)) _say("[RynthILT] Leaftide wiki: signing in again as " + _user + "...", true); + return; + } + OpenSettings?.Invoke(); + _say(OpenSettings != null + ? "[RynthILT] Leaftide wiki: not signed in. The ILT settings window is open: type the wiki's address, the login name and the bot password under Leaftide wiki quest guide, then Sign in." + : "[RynthILT] Leaftide wiki: not signed in. Sign in in /ilt settings > Leaftide wiki quest guide.", OpenSettings != null); + return; + case "signout": + case "logout": + case "sign-out": + SignOut(fromChat: true); + return; + case "refresh": + case "read": + Refresh(fromChat: true); + return; + case "address": + case "url": + if (args.Length < 2) + { + _say("[RynthILT] Leaftide wiki: address " + (_address.Length > 0 ? _address : "not set") + ". /ilt wiki address ", _address.Length > 0); + return; + } + SetAddress(args[1], fromChat: true); + return; + case "auto": + case "daily": + { + string v = args.Length > 1 ? args[1].ToLowerInvariant() : "toggle"; + bool on = v is "on" or "true" or "1" ? true : v is "off" or "false" or "0" ? false : !_daily; + SetDaily(on); + _say($"[RynthILT] Leaftide wiki: read again at login once a day is {(on ? "on" : "off")}.", true); + return; + } + case "help": + _say("[RynthILT] /ilt wiki [status] - the Leaftide wiki quest guide (off until you sign in, in /ilt settings), /ilt wiki signin - sign in again with the saved login (or open the settings),", true); + _say("[RynthILT] /ilt wiki signout - delete the saved login and guide, /ilt wiki refresh - read the wiki again, /ilt wiki address , /ilt wiki auto on|off - read again at login once a day.", true); + return; + default: + _say("[RynthILT] Leaftide wiki: unknown '" + WikiClient.Short(sub) + "'. /ilt wiki help", false); + return; + } + } + + /// The status in a few lines (no secret in any of them). + public List StatusLines() + { + var lines = new List(); + if (!_signedIn) lines.Add(_status + ". Off until you sign in (/ilt settings > Leaftide wiki quest guide)."); + else + { + lines.Add("signed in as " + _user + " on " + WikiAddress.HostOf(_address) + (Running ? "; reading now" : string.Empty) + "."); + lines.Add(_status + "."); + lines.Add("read again at login once a day: " + (_daily ? "on" : "off") + "."); + } + lines.Add("address: " + (_address.Length > 0 ? _address : "not set") + "."); + return lines; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltWiki/IltWikiReader.cs b/Plugins/RynthCore.Plugin.RynthILT/IltWiki/IltWikiReader.cs new file mode 100644 index 0000000..cf29fce --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltWiki/IltWikiReader.cs @@ -0,0 +1,262 @@ +// IltWikiReader.cs - Reading the Leaftide wiki's quest pages into a quest guide (2026-11-27). +// +// The wiki is a fork of the AC Community Wiki and writes its quests the same way (the {{Quest Summary}} +// box, "== Overview ==" or "== Discord Description ==", "== Walkthrough & Notes ==" with {{stamped|X}} +// and {{Itemlink|X}}, "== QB Stamps ==", "== Rewards ==" with {{Rewards Table}}), so the page reader is +// RynthSuite's shared one (Plugins/Shared/QuestWikiText.cs, linked). This file is the listing and the +// fetching, over WikiClient (signed in, requests spaced out): +// - the quests: every page with the Quest Summary box (generator=embeddedin, with each page's last +// revision in the same answer, so no separate revision checks); +// - the kill tasks: Category:Kill_Tasks and its sub-categories; +// - the society quests by rank: Category:Society_Quests' sub-categories; +// - the contracts: Category:Contracts' pages. +// Only pages new or edited since the saved guide are fetched (50 a request). A category tree is followed +// at most MaxCategories deep (each one is a request, and the wiki asks for seconds between requests). +// When the wiki drops the session mid-read the reader signs in once more (the relogin it is given) and +// goes on; a second loss ends the read with a plain message. +// The listing follows SilentKelpie's reader (Forgejo rynth PR #12); re-implemented. Pool thread only. +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.IltWiki; + +internal static class IltWikiReader +{ + public const string QuestTemplate = "Template:Quest_Summary"; + public const string KillTasksCategory = "Category:Kill_Tasks"; + public const string SocietyCategory = "Category:Society_Quests"; + public const string ContractsCategory = "Category:Contracts"; + + /// Categories followed per tree, at most (a request each). + internal const int MaxCategories = 25; + /// Pages listed per read, at most (a wiki that grew wildly, or a loop). + internal const int MaxPages = 4000; + /// Continuation pages per list, at most. + private const int MaxContinues = 40; + + /// One read: lists the pages, fetches the changed ones, and returns the new guide (old pages kept where unchanged). + /// Signs in again after a lost session; false (with a message) when that didn't work. + public static async Task<(QuestGuide Guide, int Fetched)> ReadAsync(WikiClient client, QuestGuide old, string source, string articleBase, + Func> relogin, Action status, DateTime utcNow, CancellationToken token) + { + var q = new Query(client, relogin); + var listed = new Dictionary(StringComparer.Ordinal); + var killTasks = new SortedSet(StringComparer.Ordinal); + var contracts = new HashSet(StringComparer.Ordinal); + var society = new Dictionary(StringComparer.OrdinalIgnoreCase); + void Add(string title, long rev) + { + if (listed.Count < MaxPages || listed.ContainsKey(title)) listed[title] = rev; + } + + status("listing the quest pages..."); + await ListAsync(q, new[] { ("generator", "embeddedin"), ("geititle", QuestTemplate), ("geinamespace", "0"), ("geilimit", "max") }, + (t, r) => Add(t, r), _ => { }, token).ConfigureAwait(false); + status("listing the kill tasks..."); + await WalkAsync(q, KillTasksCategory, (t, r, _) => { killTasks.Add(t); Add(t, r); }, token).ConfigureAwait(false); + status("listing the society quests..."); + await WalkAsync(q, SocietyCategory, (t, r, cat) => + { + Add(t, r); + string rank = RankOf(cat); + if (rank.Length > 0) society.TryAdd(t, rank); + }, token).ConfigureAwait(false); + status("listing the contracts..."); + await ListAsync(q, new[] { ("generator", "categorymembers"), ("gcmtitle", ContractsCategory), ("gcmtype", "page"), ("gcmlimit", "max") }, + (t, r) => { contracts.Add(t); Add(t, r); }, _ => { }, token).ConfigureAwait(false); + if (listed.Count == 0) throw new WikiException("the wiki listed no quest pages (no page has the Quest Summary box)"); + + List changed = PagesToRead(old, listed); + var fresh = new Dictionary(StringComparer.Ordinal); + var freshContracts = new Dictionary(StringComparer.Ordinal); + int read = 0; + foreach (string batch in QuestWikiText.Batches(changed)) + { + status($"reading pages ({read}/{changed.Count})..."); + string json = await q.GetAsync(token, ("prop", "revisions"), ("rvprop", "content|ids"), ("rvslots", "main"), ("titles", batch)).ConfigureAwait(false); + foreach (var (title, rev, text) in QuestWikiText.Contents(json)) + { + if (QuestWikiText.IsQuestPage(text)) fresh[title] = QuestWikiText.ParseQuest(title, text, rev, articleBase); + else if (contracts.Contains(title) && QuestWikiText.IsContractPage(title, text)) + freshContracts[title] = QuestWikiText.ParseContract(title, text, rev, articleBase); + } + read = Math.Min(changed.Count, read + QuestWikiText.TitlesPerRequest); + } + token.ThrowIfCancellationRequested(); + QuestGuide g = Merge(old, listed, fresh, freshContracts, source, utcNow); + g.KillTasks = new List(killTasks); + g.Society = society; + return (g, fresh.Count + freshContracts.Count); + } + + /// A query that signs in once more after a lost session. + private sealed class Query + { + private readonly WikiClient _client; + private readonly Func> _relogin; + private bool _relogged; + + public Query(WikiClient client, Func> relogin) + { + _client = client; + _relogin = relogin; + } + + public async Task GetAsync(CancellationToken token, params (string Key, string Value)[] args) + { + try + { + return await _client.QueryAsync(token, args).ConfigureAwait(false); + } + catch (WikiException ex) when (ex.SessionLost && !_relogged) + { + _relogged = true; + var (ok, message) = await _relogin(token).ConfigureAwait(false); + if (!ok) throw new WikiException("the wiki's session ended and signing in again didn't work: " + message); + try { return await _client.QueryAsync(token, args).ConfigureAwait(false); } + catch (WikiException again) when (again.SessionLost) + { + throw new WikiException("the wiki keeps ending the session; sign in again in /ilt settings"); + } + } + catch (WikiException ex) when (ex.SessionLost) + { + throw new WikiException("the wiki keeps ending the session; sign in again in /ilt settings"); + } + } + } + + /// A generator listing with its continuations: each page (ns 0) with its last revision, each sub-category (ns 14). + private static async Task ListAsync(Query q, (string, string)[] args, Action page, Action sub, CancellationToken token) + { + var cont = new List<(string, string)>(); + for (int i = 0; i < MaxContinues; i++) + { + var all = new List<(string, string)> { ("prop", "info") }; + all.AddRange(args); + all.AddRange(cont); + string json = await q.GetAsync(token, all.ToArray()).ConfigureAwait(false); + var (pages, next) = Generated(json); + foreach (var (title, ns, rev) in pages) + { + if (ns == 0) page(title, rev); + else if (ns == 14) sub(title); + } + if (next.Count == 0) return; + cont = next; + } + } + + /// A category's pages and, breadth first, its sub-categories' (each page with the category it was in). + private static async Task WalkAsync(Query q, string root, Action page, CancellationToken token) + { + var queue = new Queue(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase) { root, root.Replace('_', ' ') }; + queue.Enqueue(root); + int walked = 0; + while (queue.Count > 0 && walked < MaxCategories) + { + string cat = queue.Dequeue(); + walked++; + await ListAsync(q, new[] { ("generator", "categorymembers"), ("gcmtitle", cat), ("gcmtype", "page|subcat"), ("gcmlimit", "max") }, + (t, r) => page(t, r, cat), s => { if (!SkipCategory(s) && seen.Add(s)) queue.Enqueue(s); }, token).ConfigureAwait(false); + } + } + + // ── Pure parts (the tests feed them) ──────────────────────────────────── + + /// A generator answer (prop=info): each page's title, namespace and last revision; and the "continue" parameters (empty = done). + internal static (List<(string Title, int Ns, long Rev)> Pages, List<(string Key, string Value)> Continue) Generated(string json) + { + var pages = new List<(string, int, long)>(); + 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("pages", out JsonElement ps)) + { + IEnumerable list = ps.ValueKind == JsonValueKind.Array ? ps.EnumerateArray() : Values(ps); + foreach (JsonElement p in list) + { + if (p.ValueKind != JsonValueKind.Object || p.TryGetProperty("missing", out _)) continue; + string title = p.TryGetProperty("title", out JsonElement t) && t.ValueKind == JsonValueKind.String ? t.GetString() ?? "" : ""; + if (title.Length == 0) continue; + int ns = p.TryGetProperty("ns", out JsonElement n) && n.TryGetInt32(out int nv) ? nv : 0; + long rev = p.TryGetProperty("lastrevid", out JsonElement r) && r.TryGetInt64(out long rv) ? rv : 0; + pages.Add((title, ns, rev)); + } + } + 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, cont); + } + + private static IEnumerable Values(JsonElement obj) + { + var list = new List(); + if (obj.ValueKind == JsonValueKind.Object) + foreach (JsonProperty p in obj.EnumerateObject()) list.Add(p.Value); + return list; + } + + private static readonly Regex RankRx = new(@"(?:^|:\s*)(\w+)\s+Rank\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + /// The society rank a society sub-category stands for ("Society Quests: Knight Rank" is Knight), or "". + 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" : ""; + } + + /// A sub-category not followed: item, NPC, image and map lists, not quests. + internal static bool SkipCategory(string category) => + category.Contains("Items", StringComparison.OrdinalIgnoreCase) + || category.Contains("NPC", StringComparison.OrdinalIgnoreCase) + || category.Contains("Images", StringComparison.OrdinalIgnoreCase) + || category.Contains("Maps", StringComparison.OrdinalIgnoreCase); + + /// The pages to fetch: new or edited since the saved guide; all of them when it came from an older page reader. + internal static List PagesToRead(QuestGuide old, IReadOnlyDictionary listed) + { + var known = new Dictionary(StringComparer.Ordinal); + foreach (GuideQuest x in old.Quests) known[x.Title] = x.Rev; + foreach (GuideContract x in old.Contracts) known[x.Title] = x.Rev; + bool whole = old.Reader < QuestWikiText.ReaderVersion; + var changed = new List(); + foreach (KeyValuePair kv in listed) + if (whole || kv.Value == 0 || !known.TryGetValue(kv.Key, out long rev) || rev != kv.Value) changed.Add(kv.Key); + changed.Sort(StringComparer.Ordinal); + return changed; + } + + /// The new guide: the pages listed now, each the fresh read when there is one, else the saved one; a page no longer listed goes. + internal static QuestGuide Merge(QuestGuide old, IReadOnlyDictionary listed, IReadOnlyDictionary fresh, + IReadOnlyDictionary freshContracts, string source, DateTime utcNow) + { + var oldQuests = new Dictionary(StringComparer.Ordinal); + foreach (GuideQuest x in old.Quests) oldQuests[x.Title] = x; + var oldContracts = new Dictionary(StringComparer.Ordinal); + foreach (GuideContract x in old.Contracts) oldContracts[x.Title] = x; + var g = new QuestGuide { Source = source, UpdatedUtc = utcNow, Reader = QuestWikiText.ReaderVersion }; + 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; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltWiki/IltWikiUi.cs b/Plugins/RynthCore.Plugin.RynthILT/IltWiki/IltWikiUi.cs new file mode 100644 index 0000000..495ac95 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltWiki/IltWikiUi.cs @@ -0,0 +1,95 @@ +// IltWikiUi.cs - The "Leaftide wiki quest guide" part of the ILT settings (2026-11-27). +// +// In /ilt settings (and the settings section RynthCore's Mini Remote shows): what the guide does, the +// wiki's address, the login name and the bot password (masked), Sign in / Sign out, the status line, +// Refresh guide and the once-a-day switch. Buttons only queue requests (IltWikiGuide runs them on the +// tick). The password box is emptied as soon as Sign in is pressed. Render thread only. +using System.Numerics; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.IltWiki; + +internal sealed class IltWikiUi +{ + private static readonly Vector4 Teal = new(0.30f, 0.85f, 0.80f, 1f); + private static readonly Vector4 Mute = new(0.60f, 0.62f, 0.66f, 1f); + + private readonly IltWikiGuide _guide; + private string _address = string.Empty; + private string _user = string.Empty; + private string _password = string.Empty; + private bool _addressTaken; + + public IltWikiUi(IltWikiGuide guide) => _guide = guide; + + public void Render() + { + if (!_addressTaken) + { + _address = _guide.Address; + _addressTaken = true; + } + // Open at first: the opt-in is what RynthOracle's "Its settings" brings the player here for. + if (!ImGui.CollapsingHeader("Leaftide wiki quest guide##iltwiki", ImGuiTreeNodeFlags.DefaultOpen)) return; + + ImGui.PushStyleColor(ImGuiCol.Text, Mute); + ImGui.TextWrapped("Off until you sign in. With your own Leaftide wiki login, RynthILT reads the wiki's quest pages for " + + "RynthOracle's Guide tab. Every wiki page needs a login, so use a bot password: on the wiki, open " + + "Special:BotPasswords, make one with only \"Basic rights\", and type the login name it shows " + + "(YourName@botname) and its password here. The login stays on this PC, encrypted for your Windows " + + "user; Sign out deletes it and the saved guide. The wiki is read gently (seconds between requests, " + + "only pages edited since the last read)."); + ImGui.PopStyleColor(); + + bool signedIn = _guide.SignedIn; + bool running = _guide.Running; + if (signedIn) _address = _guide.Address; + + ImGui.BeginDisabled(signedIn); + ImGui.SetNextItemWidth(320); + ImGui.InputTextWithHint("Wiki address##iltwikiaddr", "https://... (the wiki's address)", ref _address, (uint)WikiAddress.MaxLength); + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + ImGui.SetTooltip(signedIn ? "Sign out to change the address." : "The wiki's address (its home page, index.php or api.php). RynthILT has none built in."); + if (!signedIn) + { + ImGui.SetNextItemWidth(220); + ImGui.InputTextWithHint("Login name##iltwikiuser", "YourName@botname", ref _user, (uint)IltWikiGuide.MaxUserLength); + ImGui.SetNextItemWidth(220); + ImGui.InputTextWithHint("Bot password##iltwikipw", "the bot password", ref _password, (uint)IltWikiGuide.MaxPasswordLength, + ImGuiInputTextFlags.Password); + } + ImGui.EndDisabled(); + + if (!signedIn) + { + ImGui.BeginDisabled(running); + if (ImGui.Button("Sign in##iltwikisignin")) + { + _guide.RequestSignIn(_address, _user, _password); + _password = string.Empty; + } + ImGui.EndDisabled(); + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + ImGui.SetTooltip("Tries the login on the wiki first; only a login that works is saved, then the guide is read."); + } + else + { + SafeImGui.TextColored(Teal, "Signed in as " + _guide.User); + ImGui.SameLine(); + if (ImGui.Button("Sign out##iltwikisignout")) _guide.RequestSignOut(); + if (ImGui.IsItemHovered()) ImGui.SetTooltip("Stops a read and deletes the saved login and the saved guide from this PC."); + } + + SafeImGui.TextWrapped("Status: " + _guide.Status); + + ImGui.BeginDisabled(!signedIn || running); + if (ImGui.Button("Refresh guide##iltwikirefresh")) _guide.RequestRefresh(); + ImGui.EndDisabled(); + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + ImGui.SetTooltip("Reads the wiki again now (only pages edited since the last read; at most every 5 minutes)."); + ImGui.SameLine(); + bool daily = _guide.Daily; + if (ImGui.Checkbox("Read again at login once a day##iltwikidaily", ref daily)) _guide.RequestDaily(daily); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltWiki/WikiAddress.cs b/Plugins/RynthCore.Plugin.RynthILT/IltWiki/WikiAddress.cs new file mode 100644 index 0000000..ca36380 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltWiki/WikiAddress.cs @@ -0,0 +1,73 @@ +// WikiAddress.cs - The wiki's address, as the player types it (2026-11-27). +// +// The quest guide's wiki address is a setting with no default: RynthILT ships no wiki address. The +// player types the wiki's address (the site, its index.php or its api.php) and this turns it into the +// MediaWiki API address the guide talks to. Only https: the sign-in goes to it. +using System; + +namespace RynthCore.Plugin.RynthILT.IltWiki; + +internal static class WikiAddress +{ + public const int MaxLength = 300; + + /// + /// The API address for what the player typed: "https://wiki.example/" and "https://wiki.example/index.php" + /// become "https://wiki.example/api.php"; an api.php address stays. Query and fragment dropped. False with + /// for an empty, non-https or malformed address. + /// + public static bool TryNormalize(string? typed, out string api, out string error) + { + api = string.Empty; + error = string.Empty; + string t = (typed ?? string.Empty).Trim(); + if (t.Length == 0) { error = "type the wiki's address first"; return false; } + if (t.Length > MaxLength) { error = "that address is too long"; return false; } + if (!t.Contains("://", StringComparison.Ordinal)) t = "https://" + t; + if (!Uri.TryCreate(t, UriKind.Absolute, out Uri? uri) || uri.Host.Length == 0) + { + error = "that isn't a web address"; + return false; + } + if (uri.Scheme != Uri.UriSchemeHttps) + { + error = "the wiki's address must start with https:// (the sign-in is sent to it)"; + return false; + } + if (uri.UserInfo.Length > 0) + { + error = "leave the login out of the address; type it in the login boxes"; + return false; + } + string path = uri.AbsolutePath; + if (path.EndsWith("/api.php", StringComparison.OrdinalIgnoreCase)) { } + else if (path.EndsWith("/index.php", StringComparison.OrdinalIgnoreCase)) path = path.Substring(0, path.Length - "index.php".Length) + "api.php"; + else path = (path.EndsWith('/') ? path : path + "/") + "api.php"; + api = uri.GetLeftPart(UriPartial.Authority) + path; + return true; + } + + /// The address's host ("wiki.example"), or "" for junk. + public static string HostOf(string? address) => + Uri.TryCreate(address ?? string.Empty, UriKind.Absolute, out Uri? u) ? u.Host.ToLowerInvariant() : string.Empty; + + /// Two API addresses are the same wiki (scheme, host, port and path, any case). + public static bool Same(string? a, string? b) => + Uri.TryCreate(a ?? string.Empty, UriKind.Absolute, out Uri? ua) && Uri.TryCreate(b ?? string.Empty, UriKind.Absolute, out Uri? ub) + && Uri.Compare(ua, ub, UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) == 0; + + /// The site's robots.txt next to the API ("https://wiki.example/robots.txt"). + public static string RobotsOf(string api) => + Uri.TryCreate(api, UriKind.Absolute, out Uri? u) ? u.GetLeftPart(UriPartial.Authority) + "/robots.txt" : string.Empty; + + /// The folder-safe form of a host, for the guide's cache file ("wiki.example" -> "wiki.example"). + public static string FileKey(string api) + { + string host = HostOf(api); + var chars = host.ToCharArray(); + for (int i = 0; i < chars.Length; i++) + if (!(char.IsAsciiLetterOrDigit(chars[i]) || chars[i] is '.' or '-')) chars[i] = '_'; + string s = new string(chars).Trim('.'); + return s.Length == 0 ? "wiki" : s; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltWiki/WikiClient.cs b/Plugins/RynthCore.Plugin.RynthILT/IltWiki/WikiClient.cs new file mode 100644 index 0000000..7029b2f --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltWiki/WikiClient.cs @@ -0,0 +1,353 @@ +// WikiClient.cs - Talking to a MediaWiki API with the player's own sign-in (2026-11-27). +// +// The Leaftide wiki is MediaWiki (1.39) and shows no page without a login, so the quest guide signs in +// with the player's bot password (Special:BotPasswords on the wiki: a login name "YourName@botname" and +// a generated password, "Basic rights" only, which the player can revoke there at any time): +// 1. GET api.php?action=query&meta=tokens&type=login -> query.tokens.logintoken (+ a session cookie) +// 2. POST api.php action=login lgname, lgpassword, lgtoken -> login.result "Success" (or "Failed" + reason) +// 3. GET api.php?action=query&meta=userinfo|siteinfo&assert=user -> the user id (> 0 = signed in) and the +// site's article path (the quests' page addresses) +// Every read after that carries assert=user: when the wiki has dropped the session the answer is the +// error "assertuserfailed" (or "readapidenied"), which this reports as a lost session so the reader can +// sign in once more. The session cookies live in memory only, for one read; nothing of them is saved. +// +// Politeness: one request at a time, at least Gap apart. Gap is the site's robots.txt Crawl-delay +// (read once per client) kept between 5 and 60 seconds, else 10 seconds. The User-Agent names the plugin +// only. Redirects are not followed (the sign-in is never sent anywhere but the typed address). +// The password goes only into the login POST's body: never into an address, a message or a log line. +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthILT.IltWiki; + +/// A wiki request that didn't work, said plainly; when the wiki no longer knows the sign-in. +internal sealed class WikiException : Exception +{ + public WikiException(string message, bool sessionLost = false) : base(message) => SessionLost = sessionLost; + + public bool SessionLost { get; } +} + +/// What a sign-in came to: whether it worked, a plain message, the wiki's name for the user, and the article address base. +internal readonly record struct WikiSignIn(bool Ok, string Message, string UserName, string ArticleBase); + +internal sealed class WikiClient : IDisposable +{ + /// The User-Agent: the plugin only (nothing about the player, the PC or the character). + public const string UserAgent = "RynthILT/1.0 (quest guide)"; + + public static readonly TimeSpan DefaultGap = TimeSpan.FromSeconds(10); + public static readonly TimeSpan MinGap = TimeSpan.FromSeconds(5); + public static readonly TimeSpan MaxGap = TimeSpan.FromSeconds(60); + public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + public const int MaxAnswerBytes = 16 * 1024 * 1024; + + private readonly string _api; + private readonly Uri _apiUri; + private readonly HttpClient _http; + private readonly CookieContainer _cookies = new(); + private readonly Func _delay; + private bool _robotsRead; + private bool _anySent; + + /// The gap kept between requests (robots.txt's Crawl-delay once read). + public TimeSpan Gap { get; private set; } = DefaultGap; + + /// Requests sent (the tests count them). + public int Requests { get; private set; } + + /// The API address (WikiAddress.TryNormalize). + /// The HTTP handler (the plugin's: no cookies of its own, no redirects; the tests' fake wiki). + /// Waits between requests (Task.Delay; the tests note the waits instead). + public WikiClient(string api, HttpMessageHandler handler, Func? delay = null) + { + _api = api; + _apiUri = new Uri(api); + _http = new HttpClient(handler, disposeHandler: true) { Timeout = Timeout, MaxResponseContentBufferSize = MaxAnswerBytes }; + _http.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent); + _delay = delay ?? Task.Delay; + } + + /// The plugin's handler: cookies kept by this client (in memory), redirects not followed. + public static HttpMessageHandler NewHandler() => new SocketsHttpHandler + { + UseCookies = false, + AllowAutoRedirect = false, + AutomaticDecompression = DecompressionMethods.All, + ConnectTimeout = TimeSpan.FromSeconds(15), + PooledConnectionLifetime = TimeSpan.FromMinutes(5), + }; + + public void Dispose() => _http.Dispose(); + + // ── Sign in ───────────────────────────────────────────────────────────── + + /// Signs in with a bot password (steps 1-3 above). Never throws for the wiki's answers; cancellation still throws. + public async Task SignInAsync(string user, string password, CancellationToken token) + { + try + { + string result = string.Empty, reason = string.Empty; + for (int attempt = 0; attempt < 2; attempt++) + { + string tokenJson = await SendAsync(HttpMethod.Get, QuestWikiText.ApiUrl(_api, ("action", "query"), ("meta", "tokens"), ("type", "login")), null, token).ConfigureAwait(false); + string loginToken = LoginToken(tokenJson); + if (loginToken.Length == 0) return Fail("the wiki gave no sign-in token (is the address the wiki's api.php?)"); + var form = new FormUrlEncodedContent(new[] + { + new KeyValuePair("action", "login"), + new KeyValuePair("lgname", user), + new KeyValuePair("lgpassword", password), + new KeyValuePair("lgtoken", loginToken), + new KeyValuePair("format", "json"), + new KeyValuePair("formatversion", "2"), + }); + string loginJson = await SendAsync(HttpMethod.Post, _api, form, token).ConfigureAwait(false); + (result, reason) = LoginResult(loginJson); + // A token the wiki didn't take (its session went between the two requests): once more with a fresh one. + if (!result.Equals("WrongToken", StringComparison.OrdinalIgnoreCase) && !result.Equals("NeedToken", StringComparison.OrdinalIgnoreCase)) break; + } + if (!result.Equals("Success", StringComparison.OrdinalIgnoreCase)) return Fail(Refusal(result, reason, user)); + + string info = await QueryAsync(token, ("meta", "userinfo|siteinfo"), ("siprop", "general")).ConfigureAwait(false); + var (id, name, articleBase) = UserAndSite(info, _api); + if (id <= 0) return Fail("the wiki took the sign-in but didn't keep it; try again"); + return new WikiSignIn(true, "signed in as " + name, name, articleBase); + } + catch (WikiException ex) + { + return Fail(ex.Message); + } + + static WikiSignIn Fail(string message) => new(false, message, string.Empty, string.Empty); + } + + /// The wiki's "no" in plain words (its own reason when it gives one; never the password). + internal static string Refusal(string result, string reason, string user) + { + string why = Short(reason); + string hint = user.Contains('@') ? string.Empty + : " A bot password's login name looks like YourName@botname (the wiki shows it when the bot password is made)."; + return result.ToLowerInvariant() switch + { + "failed" => "the wiki turned the sign-in down" + (why.Length > 0 ? ": " + why : " (wrong login name or password)") + hint, + "aborted" => "the wiki won't take this kind of sign-in" + (why.Length > 0 ? ": " + why : string.Empty) + + " Use a bot password (on the wiki: Special:BotPasswords).", + "throttled" => "too many sign-in tries; the wiki asks to wait" + (why.Length > 0 ? ": " + why : " a few minutes"), + "wrongtoken" or "needtoken" => "the wiki didn't take its own sign-in token twice; try again in a minute", + "" => "the wiki didn't answer the sign-in" + (why.Length > 0 ? ": " + why : string.Empty), + _ => "the wiki said " + Short(result) + (why.Length > 0 ? ": " + why : string.Empty), + }; + } + + // ── Reading ───────────────────────────────────────────────────────────── + + /// + /// An action=query GET as the signed-in user (assert=user). Throws : with SessionLost when + /// the wiki no longer knows the sign-in, else for the wiki's other errors. + /// + public async Task QueryAsync(CancellationToken token, params (string Key, string Value)[] args) + { + var all = new List<(string, string)>(args.Length + 2) { ("action", "query") }; + all.AddRange(args); + all.Add(("assert", "user")); + string json = await SendAsync(HttpMethod.Get, QuestWikiText.ApiUrl(_api, all.ToArray()), null, token).ConfigureAwait(false); + var (code, info) = ApiError(json); + if (code.Length == 0) return json; + if (code is "assertuserfailed" or "assertnameduserfailed" or "readapidenied" or "notloggedin" or "badtoken") + throw new WikiException("the wiki's session ended", sessionLost: true); + throw new WikiException("the wiki said " + code + (info.Length > 0 ? ": " + Short(info) : string.Empty)); + } + + private async Task SendAsync(HttpMethod method, string url, HttpContent? body, CancellationToken token) + { + if (!_robotsRead) + { + _robotsRead = true; + await ReadRobotsAsync(token).ConfigureAwait(false); + } + string text = await RawAsync(method, url, body, token).ConfigureAwait(false); + string t = text.TrimStart(); + if (t.Length == 0 || t[0] != '{') + throw new WikiException("that address didn't answer like a MediaWiki API (it should be the wiki's api.php)"); + return text; + } + + /// robots.txt's Crawl-delay for every robot (or this plugin) becomes the gap; none or no file keeps 10 s. + private async Task ReadRobotsAsync(CancellationToken token) + { + string robots = WikiAddress.RobotsOf(_api); + if (robots.Length == 0) return; + try + { + string text = await RawAsync(HttpMethod.Get, robots, null, token).ConfigureAwait(false); + if (CrawlDelay(text) is double s) Gap = TimeSpan.FromSeconds(Math.Clamp(s, MinGap.TotalSeconds, MaxGap.TotalSeconds)); + } + catch (WikiException) { /* no robots.txt: the default gap */ } + } + + /// One request, after the gap; the cookies in and out. Throws with a plain reason. + private async Task RawAsync(HttpMethod method, string url, HttpContent? body, CancellationToken token) + { + if (_anySent) await _delay(Gap, token).ConfigureAwait(false); + _anySent = true; + Requests++; + using var req = new HttpRequestMessage(method, url) { Content = body }; + var uri = new Uri(url); + string cookie = _cookies.GetCookieHeader(uri); + if (cookie.Length > 0) req.Headers.TryAddWithoutValidation("Cookie", cookie); + HttpResponseMessage resp; + try + { + resp = await _http.SendAsync(req, token).ConfigureAwait(false); + } + catch (TaskCanceledException) when (!token.IsCancellationRequested) + { + throw new WikiException($"the wiki didn't answer within {Timeout.TotalSeconds:0} s"); + } + catch (HttpRequestException ex) + { + throw new WikiException("couldn't reach the wiki (" + Short(ex.Message) + ")"); + } + using (resp) + { + if (resp.Headers.TryGetValues("Set-Cookie", out IEnumerable? setCookies)) + foreach (string c in setCookies) + { + try { _cookies.SetCookies(uri, c); } + catch (CookieException) { } + } + int status = (int)resp.StatusCode; + if (status is >= 300 and < 400) + throw new WikiException("the wiki's address sent the request somewhere else; check the address (the wiki's api.php)"); + if (status == 429 || status == 503) + throw new WikiException($"the wiki is busy (HTTP {status}); try again later"); + if (status is 401 or 403) + throw new WikiException($"the wiki refused the request (HTTP {status})", sessionLost: true); + if (status < 200 || status >= 300) + throw new WikiException($"the wiki answered HTTP {status}"); + try + { + return await resp.Content.ReadAsStringAsync(token).ConfigureAwait(false); + } + catch (HttpRequestException ex) + { + throw new WikiException("the wiki's answer couldn't be read (" + Short(ex.Message) + ")"); + } + } + } + + // ── Reading the answers (pure; the tests feed them) ───────────────────── + + internal static double? CrawlDelay(string robots) + { + bool ours = false, inAgents = false; + double? delay = null; + foreach (string raw in robots.Split('\n')) + { + string line = raw; + int hash = line.IndexOf('#'); + if (hash >= 0) line = line.Substring(0, hash); + int colon = line.IndexOf(':'); + if (colon <= 0) continue; + string key = line.Substring(0, colon).Trim().ToLowerInvariant(); + string value = line.Substring(colon + 1).Trim(); + if (key == "user-agent") + { + if (!inAgents) ours = false; + inAgents = true; + if (value == "*" || value.StartsWith("RynthILT", StringComparison.OrdinalIgnoreCase)) ours = true; + continue; + } + inAgents = false; + if (ours && key == "crawl-delay" && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double s) && s >= 0) + delay = Math.Max(delay ?? 0, s); + } + return delay; + } + + internal static string LoginToken(string json) + { + try + { + using JsonDocument d = JsonDocument.Parse(json); + return d.RootElement.TryGetProperty("query", out JsonElement q) && q.TryGetProperty("tokens", out JsonElement t) + && t.TryGetProperty("logintoken", out JsonElement lt) && lt.ValueKind == JsonValueKind.String + ? lt.GetString() ?? string.Empty : string.Empty; + } + catch (JsonException) { return string.Empty; } + } + + internal static (string Result, string Reason) LoginResult(string json) + { + try + { + using JsonDocument d = JsonDocument.Parse(json); + JsonElement r = d.RootElement; + if (r.TryGetProperty("login", out JsonElement l) && l.ValueKind == JsonValueKind.Object) + return (Str(l, "result"), Str(l, "reason")); + var (code, info) = ApiError(json); + return (string.Empty, code.Length > 0 ? code + (info.Length > 0 ? ": " + info : string.Empty) : string.Empty); + } + catch (JsonException) { return (string.Empty, string.Empty); } + } + + /// meta=userinfo|siteinfo: the user id and name, and the article address base ("https://wiki.example/" + title). + internal static (long Id, string Name, string ArticleBase) UserAndSite(string json, string api) + { + long id = 0; + string name = string.Empty, articleBase = string.Empty; + try + { + using JsonDocument d = JsonDocument.Parse(json); + if (d.RootElement.TryGetProperty("query", out JsonElement q)) + { + if (q.TryGetProperty("userinfo", out JsonElement u) && u.ValueKind == JsonValueKind.Object) + { + if (u.TryGetProperty("id", out JsonElement i) && i.TryGetInt64(out long v)) id = v; + if (u.TryGetProperty("anon", out JsonElement anon) && anon.ValueKind != JsonValueKind.False) id = 0; + name = Str(u, "name"); + } + if (q.TryGetProperty("general", out JsonElement g) && g.ValueKind == JsonValueKind.Object) + { + string server = Str(g, "server"), path = Str(g, "articlepath"); + if (server.StartsWith("//", StringComparison.Ordinal)) server = "https:" + server; + if (server.Length > 0 && path.Contains("$1", StringComparison.Ordinal)) + articleBase = server + path.Substring(0, path.IndexOf("$1", StringComparison.Ordinal)); + } + } + } + catch (JsonException) { } + if (articleBase.Length == 0 && Uri.TryCreate(api, UriKind.Absolute, out Uri? a)) + articleBase = new Uri(a, "./").ToString() + "index.php?title="; + return (id, name, articleBase); + } + + internal static (string Code, string Info) ApiError(string json) + { + try + { + using JsonDocument d = JsonDocument.Parse(json); + return d.RootElement.TryGetProperty("error", out JsonElement e) && e.ValueKind == JsonValueKind.Object + ? (Str(e, "code").ToLowerInvariant(), Str(e, "info")) : (string.Empty, string.Empty); + } + catch (JsonException) { return (string.Empty, string.Empty); } + } + + private static string Str(JsonElement o, string name) => + o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? (v.GetString() ?? string.Empty).Trim() : string.Empty; + + /// A wiki's or the network's words cut to one short line. + internal static string Short(string? text) + { + string s = (text ?? string.Empty).Replace('\r', ' ').Replace('\n', ' ').Trim(); + return s.Length > 200 ? s.Substring(0, 200).TrimEnd() + "..." : s; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/IltWiki/WikiLoginStore.cs b/Plugins/RynthCore.Plugin.RynthILT/IltWiki/WikiLoginStore.cs new file mode 100644 index 0000000..2782a2e --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthILT/IltWiki/WikiLoginStore.cs @@ -0,0 +1,204 @@ +// WikiLoginStore.cs - The Leaftide wiki sign-in, kept on this PC only (2026-11-27). +// +// The quest guide (IltWikiGuide.cs) reads the server's wiki with the player's own login: a MediaWiki +// bot password (Special:BotPasswords, "Basic rights" only), which the player can revoke on the wiki at +// any time without changing the account's own password. That login is the only secret RynthILT keeps: +// - one file, %APPDATA%\RynthCore\RynthILT\Wiki\wiki-login.dat, the whole record (address, login name, +// password) sealed with Windows DPAPI for the current Windows user (CryptProtectData, no machine +// scope), so another Windows user, or a copy of the file on another PC, can't open it; +// - never in settings.json, the Hub state, profiles, logs, the status JSON, the remote dashboard or +// anything RynthCore shares; never in a chat line or a status line; +// - Sign out (and "/ilt wiki signout") deletes the file. +// The login is tied to the wiki address it was made for: it is only ever sent to that address. +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Json; + +namespace RynthCore.Plugin.RynthILT.IltWiki; + +/// A wiki sign-in: the API address it is for, the login name ("YourName@botname") and its password. +internal sealed class WikiLogin +{ + public WikiLogin(string api, string user, string password) + { + Api = api; + User = user; + Password = password; + } + + public string Api { get; } + public string User { get; } + public string Password { get; } + + /// Never the password: a WikiLogin that ends up in a log line or a message says only whose it is. + public override string ToString() => $"wiki login {User} for {WikiAddress.HostOf(Api)}"; +} + +internal static class WikiLoginStore +{ + public const string FileName = "wiki-login.dat"; + + /// The tests' scratch folder; null is %APPDATA%\RynthCore\RynthILT\Wiki. + internal static string? FolderOverride; + + public static string Folder => FolderOverride ?? Path.Combine(RynthILTPlugin.SettingsRoot, "Wiki"); + public static string FilePath => Path.Combine(Folder, FileName); + + /// A sign-in is saved (it may still be unreadable: says). + public static bool Exists + { + get + { + try { return File.Exists(FilePath); } + catch { return false; } + } + } + + // Ties the sealed bytes to this use: another program's DPAPI blob doesn't open as a wiki login. + private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("RynthILT.WikiLogin.v1"); + + /// Seals and saves the login (written to a temporary file, then moved over the old one). + public static bool Save(WikiLogin login, out string error) + { + error = string.Empty; + byte[] plain = Array.Empty(); + try + { + plain = Serialize(login); + byte[] sealedBytes = Dpapi.Protect(plain, Entropy); + Directory.CreateDirectory(Folder); + string tmp = FilePath + ".tmp"; + File.WriteAllBytes(tmp, sealedBytes); + File.Move(tmp, FilePath, overwrite: true); + return true; + } + catch (Exception ex) + { + error = "couldn't save the sign-in: " + ex.GetType().Name; + return false; + } + finally { Array.Clear(plain); } + } + + /// The saved login, or null (none, or it can't be opened: another Windows user's, damaged). + public static WikiLogin? Load(out string error) + { + error = string.Empty; + byte[] plain = Array.Empty(); + try + { + if (!File.Exists(FilePath)) return null; + plain = Dpapi.Unprotect(File.ReadAllBytes(FilePath), Entropy); + WikiLogin? login = Deserialize(plain); + if (login == null) error = "the saved sign-in is damaged; sign in again"; + return login; + } + catch (Exception) + { + error = "the saved sign-in can't be opened by this Windows user; sign in again"; + return null; + } + finally { Array.Clear(plain); } + } + + /// Deletes the saved login (and a left-over temporary file). True when none is left. + public static bool Delete(out string error) + { + error = string.Empty; + try + { + if (File.Exists(FilePath)) File.Delete(FilePath); + if (File.Exists(FilePath + ".tmp")) File.Delete(FilePath + ".tmp"); + return true; + } + catch (Exception ex) + { + error = "couldn't delete " + FilePath + ": " + ex.GetType().Name; + return false; + } + } + + private static byte[] Serialize(WikiLogin login) + { + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms)) + { + w.WriteStartObject(); + w.WriteNumber("v", 1); + w.WriteString("api", login.Api); + w.WriteString("user", login.User); + w.WriteString("password", login.Password); + w.WriteEndObject(); + } + return ms.ToArray(); + } + + private static WikiLogin? Deserialize(byte[] plain) + { + try + { + using JsonDocument doc = JsonDocument.Parse(plain); + JsonElement r = doc.RootElement; + if (r.ValueKind != JsonValueKind.Object) return null; + string api = Str(r, "api"), user = Str(r, "user"), password = Str(r, "password"); + return api.Length == 0 || user.Length == 0 || password.Length == 0 ? null : new WikiLogin(api, user, password); + } + catch (JsonException) { return null; } + } + + private static string Str(JsonElement r, string name) => + r.TryGetProperty(name, out JsonElement e) && e.ValueKind == JsonValueKind.String ? e.GetString() ?? string.Empty : string.Empty; +} + +/// Windows DPAPI for the current user (crypt32 CryptProtectData / CryptUnprotectData), blittable P/Invoke for NativeAOT. +internal static unsafe class Dpapi +{ + [StructLayout(LayoutKind.Sequential)] + private struct DataBlob + { + public int Size; + public IntPtr Data; + } + + private const int UiForbidden = 0x1; + + [DllImport("crypt32.dll", EntryPoint = "CryptProtectData", SetLastError = true)] + private static extern int CryptProtectData(DataBlob* dataIn, IntPtr description, DataBlob* entropy, IntPtr reserved, + IntPtr prompt, int flags, DataBlob* dataOut); + + [DllImport("crypt32.dll", EntryPoint = "CryptUnprotectData", SetLastError = true)] + private static extern int CryptUnprotectData(DataBlob* dataIn, IntPtr description, DataBlob* entropy, IntPtr reserved, + IntPtr prompt, int flags, DataBlob* dataOut); + + [DllImport("kernel32.dll", EntryPoint = "LocalFree")] + private static extern IntPtr LocalFree(IntPtr mem); + + public static byte[] Protect(byte[] plain, byte[] entropy) => Run(plain, entropy, protect: true); + + public static byte[] Unprotect(byte[] sealedBytes, byte[] entropy) => Run(sealedBytes, entropy, protect: false); + + private static byte[] Run(byte[] input, byte[] entropy, bool protect) + { + fixed (byte* pIn = input) + fixed (byte* pEnt = entropy) + { + var inBlob = new DataBlob { Size = input.Length, Data = (IntPtr)pIn }; + var entBlob = new DataBlob { Size = entropy.Length, Data = (IntPtr)pEnt }; + var outBlob = new DataBlob(); + int ok = protect + ? CryptProtectData(&inBlob, IntPtr.Zero, &entBlob, IntPtr.Zero, IntPtr.Zero, UiForbidden, &outBlob) + : CryptUnprotectData(&inBlob, IntPtr.Zero, &entBlob, IntPtr.Zero, IntPtr.Zero, UiForbidden, &outBlob); + if (ok == 0) throw new InvalidOperationException((protect ? "CryptProtectData" : "CryptUnprotectData") + " failed: " + Marshal.GetLastWin32Error()); + try + { + var result = new byte[outBlob.Size]; + Marshal.Copy(outBlob.Data, result, 0, outBlob.Size); + if (!protect) new Span((void*)outBlob.Data, outBlob.Size).Clear(); + return result; + } + finally { LocalFree(outBlob.Data); } + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs index 1df4102..2de6e4a 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/PluginExports.cs @@ -18,7 +18,9 @@ public static unsafe class PluginExports // "RynthILT.Data" v1..v3, the charms list and bank balances with their actions, the pet breeding // tracker and the Temple guardians (Plugins/Shared/RynthIltDataApi.cs, DataInterface.cs), and // "RynthILT.Server" v1, the Leaftide feature / fellowship / quest bonus profile RynthOracle reads - // (Plugins/Shared/RynthIltServerApi.cs, ServerInterface.cs). + // (Plugins/Shared/RynthIltServerApi.cs, ServerInterface.cs), and "RynthServer.QuestGuide" v1, the + // Leaftide wiki quest guide RynthOracle's Guide tab shows (Plugins/Shared/RynthServerQuestGuideApi.cs, + // IltWiki/IltWikiGuide.cs; opt-in, with the player's own wiki login). // Fixed signature: void* (const char* iface, uint version). [UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })] private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version) @@ -31,7 +33,11 @@ public static unsafe class PluginExports table = ServerInterface.Query(iface, version); if (table != IntPtr.Zero) return table; table = ProfileInterface.Query(iface, version); - return table != IntPtr.Zero ? table : DataInterface.Query(iface, version); + if (table != IntPtr.Zero) return table; + // "RynthServer.QuestGuide" v1: the Leaftide wiki quest guide for RynthOracle (IltWiki/IltWikiGuide.cs). + if (iface == RynthCore.Plugin.Shared.RynthServerQuestGuideApiV1.InterfaceName) + return RynthCore.Plugin.Shared.ServerQuestGuideHost.Query(version); + return DataInterface.Query(iface, version); } catch { @@ -51,6 +57,7 @@ public static unsafe class PluginExports try { ServerInterface.Release(); } catch { } try { ProfileInterface.Release(); } catch { } try { DataInterface.Release(); } catch { } + try { RynthCore.Plugin.Shared.ServerQuestGuideHost.Release(); } catch { } foreach (IntPtr p in new[] { Interlocked.Exchange(ref _bountiesPtr, IntPtr.Zero), Interlocked.Exchange(ref _progressionPtr, IntPtr.Zero), Interlocked.Exchange(ref _statusPtr, IntPtr.Zero), Interlocked.Exchange(ref _sectionsPtr, IntPtr.Zero) }) if (p != IntPtr.Zero) Marshal.FreeCoTaskMem(p); diff --git a/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj b/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj index 856b808..06cd4de 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj +++ b/Plugins/RynthCore.Plugin.RynthILT/RynthCore.Plugin.RynthILT.csproj @@ -26,6 +26,9 @@ Moved out of RynthOracle 2026-10-21 (Hub/): the Dynamic Stamps (IltDynamicStamps, RynthILT's own Quests section page and "/ilt stamps"; SilentKelpie's) and a window for the pet breeding tracker ("/ilt breeding"). + IltWiki/ the Leaftide wiki quest guide (2026-11-27): opt-in, read with the player's own wiki + login (a bot password, sealed with DPAPI on this PC), for RynthOracle's Guide tab + ("RynthServer.QuestGuide"); "/ilt wiki", /ilt settings > Leaftide wiki quest guide. --> net10.0-windows @@ -117,6 +120,12 @@ + + + + + diff --git a/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs b/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs index 2eca621..f11791b 100644 --- a/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthILT/RynthILTPlugin.cs @@ -44,6 +44,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; +using System.Threading; using ImGuiNET; using RynthCore.Plugin.RynthILT.Bounty; using RynthCore.Plugin.RynthILT.Hub; @@ -97,9 +98,15 @@ public sealed class RynthILTPlugin : RynthPluginBase private readonly ConcurrentQueue _chatCommands = new(); private const int MaxQueuedChatCommands = 32; + // The Leaftide wiki quest guide (IltWiki/, 2026-11-27): opt-in, read with the player's own wiki login, + // handed to RynthOracle's Guide tab through "RynthServer.QuestGuide". Created in Initialize. + private IltWiki.IltWikiGuide? _wiki; + private IltWiki.IltWikiUi? _wikiUi; + public RynthILTPlugin() { - _settingsUi = new IltSettingsUi(_settingsModel, cmd => QueueChatCommand(cmd), RefreshFeatures, () => _hub); + _settingsUi = new IltSettingsUi(_settingsModel, cmd => QueueChatCommand(cmd), RefreshFeatures, () => _hub, + () => _wikiUi?.Render()); _fellowshipUi = new IltFellowshipUi(QueueChatCommand); IltEngineVerdict.Attach(_settingsModel); } @@ -135,6 +142,11 @@ public sealed class RynthILTPlugin : RynthPluginBase // "/ilt ..." lines from OnChatBarEnter and RynthAi's forwarded "/ra" verbs, run on the next tick. private readonly ConcurrentQueue _commands = new(); + // An "/ilt ..." line RynthILT has no command for, on its way to the server (2026-11-27, report + // R-20261127-142518-8004): the server has /ilt commands of its own, and every /ilt line used to + // end here as "Unknown command". RunCommand sends it on through the engine's chat parser, which + // offers it to OnChatBarEnter again; this lets that one line by, once. + private string? _passToServer; // "/bounty ..." lines from OnChatBarEnter (typed by the player, or our own coming back through // the engine's dispatcher), passed to the tracker before the next chat line or tick. private readonly ConcurrentQueue _typedBounty = new(); @@ -163,6 +175,18 @@ public sealed class RynthILTPlugin : RynthPluginBase msg.StartsWith("[RynthILT] ", StringComparison.Ordinal) ? msg.Substring(11) : msg); _ai = new RynthAiClient(Host); _settings = IltSettingsStore.Load(); + try + { + _wiki = new IltWiki.IltWikiGuide((text, ok) => { if (ok) ChatLine(text); else ChatFail(text); }, + msg => RynthLog.Write(LogCat.IltQuests, msg)) + { + // RynthOracle's "Its settings" and "/ilt wiki signin" without a saved login: the ILT settings window. + OpenSettings = () => _settingsUi.WindowOpen = true, + }; + _wiki.Load(); + _wikiUi = new IltWiki.IltWikiUi(_wiki); + } + catch (Exception ex) { RynthLog.Exception(LogCat.IltQuests, ex, "wiki guide"); } Host.Log("[RynthILT] Plugin initialized."); return 0; } @@ -206,6 +230,7 @@ public sealed class RynthILTPlugin : RynthPluginBase { SaveBounties(); StopHub(); + try { _wiki?.Shutdown(); } catch { } HubInterface.Release(); IltEngineVerdict.Attach(null); RynthLog.Shutdown(); @@ -214,12 +239,20 @@ public sealed class RynthILTPlugin : RynthPluginBase public override void OnTick() { try { RynthLog.Pump(); } catch { } + try { _wiki?.Tick(); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltQuests, ex, "wiki tick"); } Reply.Flush(); if (!_loginComplete) return; _ai?.Tick(); PollServerState(force: false); if (_bounties == null) TryStartBounties(); if (_hub == null) TryStartHub(); + // The wiki quest guide's once-a-session read, once the Hub knows this is an ILT world (cheap until then). + if (_hub != null) + { + try { _wiki?.OnLogin(_hub.Options.IsIltLikeWorld); } + catch (Exception ex) { RynthLog.Exception(LogCat.IltQuests, ex, "wiki login read"); } + } DrainTypedBounty(); while (_commands.TryDequeue(out string[]? parts)) RunCommand(parts); while (_engineCommands.TryDequeue(out string? engineCommand)) RunEngineCommand(engineCommand); @@ -571,6 +604,12 @@ public sealed class RynthILTPlugin : RynthPluginBase if (!trimmed.Equals("/ilt", StringComparison.OrdinalIgnoreCase) && !trimmed.StartsWith("/ilt ", StringComparison.OrdinalIgnoreCase)) return; + string? passing = Interlocked.CompareExchange(ref _passToServer, null, null); + if (passing != null && passing.Equals(trimmed, StringComparison.OrdinalIgnoreCase)) + { + Interlocked.CompareExchange(ref _passToServer, null, passing); + return; // ours, sent on to the server: not eaten + } eat = 1; _commands.Enqueue(trimmed.Split(' ', StringSplitOptions.RemoveEmptyEntries)); } @@ -824,6 +863,20 @@ public sealed class RynthILTPlugin : RynthPluginBase ChatLine("[RynthILT] Dynamic Stamps are an Infinite Leaftide quest line; this world isn't treated as ILT."); return; } + case "wiki": + case "guide": + { + // "/ilt wiki [status|signin|signout|refresh|address |auto on|off|help]": the Leaftide wiki quest + // guide (IltWiki/). Its own replies; never echoes the line (a login typed there stays unsaid). + if (_wiki == null) { ChatFail("[RynthILT] The Leaftide wiki quest guide didn't start (see the RynthILT log)."); return; } + try { _wiki.HandleCommand(args); } + catch (Exception ex) + { + RynthLog.Write(LogCat.IltQuests, "wiki command failed: " + ex.GetType().Name); + ChatFail("[RynthILT] Leaftide wiki: that didn't work (" + ex.GetType().Name + ")."); + } + return; + } case "breeding": case "breed": { @@ -851,6 +904,7 @@ public sealed class RynthILTPlugin : RynthPluginBase ChatLine("[RynthILT] /ilt t11 [augs |refresh|item [0xId]] - T11 loot: the /aug wield counters RynthAi's loot rules use, the item-aug override, an item's T11 text (also /ra t11),"); ChatLine("[RynthILT] /ilt settings [show|hide|toggle] - the ILT settings: the world verdict, the ILT world names and the server's features (force a server: RynthCore Options > Diagnostics),"); ChatLine("[RynthILT] /ilt fellow [show|hide|toggle] - ILT's /fship commands as buttons (also in the Mini Remote's Fellowship section),"); + ChatLine("[RynthILT] /ilt wiki [status|signin|signout|refresh|address |auto on|off|help] - the Leaftide wiki quest guide for RynthOracle's Guide tab (off until you sign in, in /ilt settings),"); ChatLine("[RynthILT] /ilt stamps [show|hide|toggle] - the Dynamic Stamps (also in the Mini Remote's Quests section); /ilt breeding [show|hide|toggle] - pet breeding (also the Mini Remote's Pets > Breeding),"); ChatLine("[RynthILT] /ilt trace [on|off], /ilt debug [on|off]."); return; @@ -868,7 +922,12 @@ public sealed class RynthILTPlugin : RynthPluginBase try { if (!_hub.HandleCommand(verb, args)) + { + // Not one of ours: the server's own (Infinite Leaftide has /ilt commands). A + // forwarded "/ra ..." verb stays ours: it never was an /ilt line. + if (!fromRa && SendToServer(string.Join(" ", parts))) return; ChatFail($"[RynthILT] Unknown command: {string.Join(" ", parts)}. /ilt help"); + } } catch (Exception ex) { @@ -877,6 +936,23 @@ public sealed class RynthILTPlugin : RynthPluginBase } } + /// + /// An "/ilt ..." line RynthILT has no command for, sent to the server as typed (its reply comes + /// back in chat). False when the engine can't send it (no chat parser): then it is unknown here. + /// + private bool SendToServer(string line) + { + if (!Host.HasInvokeChatParser) return false; + Interlocked.Exchange(ref _passToServer, line); + bool sent; + try { sent = Host.InvokeChatParser(line); } + catch { sent = false; } + // Whether or not the engine offered it to OnChatBarEnter again, the pass is over. + Interlocked.CompareExchange(ref _passToServer, null, line); + if (!sent) ChatFail("[RynthILT] RynthCore didn't take: " + line); + return true; + } + /// "/ilt settings|stamps|breeding|fellow [show|hide|toggle]": the window after it (every command answers, 2026-10-28). internal static string WindowReply(string window, bool open) => $"[RynthILT] {window} window {(open ? "shown" : "hidden")}."; diff --git a/Tools/RynthILT.Tests/Program.cs b/Tools/RynthILT.Tests/Program.cs index 94764c6..f51aefa 100644 --- a/Tools/RynthILT.Tests/Program.cs +++ b/Tools/RynthILT.Tests/Program.cs @@ -31,6 +31,8 @@ internal static class Program RynthCore.Plugin.RynthILT.Hub.IltMigration.LegacySharedRoot = Path.Combine(TempRoot, "RynthAi"); RynthCore.Plugin.RynthILT.RynthLog.Init(default, Path.Combine(TempRoot, "Logs")); RynthCore.Plugin.Shared.DataWriteGuard.PluginName = "RynthILT"; // as RynthILTPlugin.Initialize sets it + // The wiki quest guide's sealed login, settings and saved guide (each wiki test points it at its own folder). + RynthCore.Plugin.RynthILT.IltWiki.WikiLoginStore.FolderOverride = Path.Combine(TempRoot, "Wiki"); var runner = new Runner(); BountyTests.Register(runner); @@ -56,6 +58,7 @@ internal static class Program ReplyTests.Register(runner); RemoteTabTests.Register(runner); StampTests.Register(runner); + WikiGuideTests.Register(runner); BankRosterTests.Register(runner); // Before DataApiTests: its last test releases the RynthILT.Data table, which the breeding version test queries. BreedingTests.Register(runner); diff --git a/Tools/RynthILT.Tests/RynthILT.Tests.csproj b/Tools/RynthILT.Tests/RynthILT.Tests.csproj index 177c710..e868b91 100644 --- a/Tools/RynthILT.Tests/RynthILT.Tests.csproj +++ b/Tools/RynthILT.Tests/RynthILT.Tests.csproj @@ -39,6 +39,8 @@ + + diff --git a/Tools/RynthILT.Tests/WikiGuideTests.cs b/Tools/RynthILT.Tests/WikiGuideTests.cs new file mode 100644 index 0000000..055d7f3 --- /dev/null +++ b/Tools/RynthILT.Tests/WikiGuideTests.cs @@ -0,0 +1,616 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using RynthCore.Plugin.RynthILT.IltWiki; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiTests.Harness; + +namespace RynthILT.Tests; + +// The Leaftide wiki quest guide (IltWiki/, 2026-11-27): the address, the sealed login, the MediaWiki +// sign-in and the read, against a FAKE wiki (FakeWiki below; nothing here touches the network), and the +// controller's opt-in, commands and the guide it hands RynthOracle. Every page below is made up for the +// tests: invented quests, people and places, written in the wiki's page layout. No real wiki text. +internal static class WikiGuideTests +{ + private const string Api = "https://wiki.test/api.php"; + private const string User = "Tester@probe"; + private const string Password = "pw-Fake-7f3k-q9zz-Bot"; + + public static void Register(Runner r) + { + r.Add("wiki: the address the player types becomes the API address (https only)", Address); + r.Add("wiki: robots.txt's Crawl-delay sets the gap between requests", Robots); + r.Add("wiki: the login is sealed with DPAPI, opens again, and Sign out deletes it", Sealed); + r.Add("wiki: sign-in against a fake wiki (token, POST, cookie, assert=user, User-Agent, gaps)", SignIn); + r.Add("wiki: a failed sign-in says why in plain words, without the password", SignInFails); + r.Add("wiki: off by default: nothing fetched or saved, RynthOracle sees only the way to sign in", OffByDefault); + r.Add("wiki: signing in reads the guide, saves it and hands it to RynthOracle", ReadsGuide); + r.Add("wiki: a second read fetches only edited pages; Refresh waits 5 minutes", OnlyEdited); + r.Add("wiki: a lost session signs in again once; a refused sign-in ends the read plainly", LostSession); + r.Add("wiki: Sign out deletes the login and the guide; RynthOracle's guide goes", SignOut); + r.Add("wiki: /ilt wiki commands each answer, and never take a login in chat", Commands); + r.Add("wiki: a login saved for another address is never used", OtherAddress); + r.Add("wiki: the invented pages read into steps, stamps, loot, kill tasks and contracts", Parsing); + } + + // ── The invented pages ────────────────────────────────────────────────── + + private const string MothErrand = @"{{Leaftide Content}} +{{Quest Summary +| Level = 120+ +| Recommended Level = 150+ +| Quest Type = Solo +| Starts With = [[Warden Pellis]] +| Starts At = [[Hollow Reach]] +| Repeat Timer = 20 Hours +}} +== Overview == +Warden Pellis wants the glow sacs of the lantern moths that swarm the old quarry. +== Walkthrough & Notes == +# Talk to [[Warden Pellis]] at 12.3N, 45.6E. +#* {{stamped|LanternMothErrandStarted}} +# Kill lantern moths in the quarry (14.0N 47.2E) and loot a {{Itemlink|Moth Glow Sac}}. +# Return the {{Itemlink|Moth Glow Sac}} to Warden Pellis. +#* {{stamped|LanternMothErrandDone}} +== Rewards == +{{Rewards Table +| Quest Task = Hand in a glow sac +| XP Reward = 5,000,000 +| Item Reward = * {{Icon Link|Pellis Lantern}} +}} +[[Category:Invented Quests]]"; + + private const string GlimmerBeetles = @"{{Quest Summary +| Level = 80+ +| Quest Type = Solo/Fellowship +| Starts With = [[Huntmaster Orlo]] +| Repeat Timer = 7 days +| Kill Task = Yes +}} +== Discord Description == +Thin out the glimmer beetles near the salt flats. +== Walkthrough & Notes == +Speak to Huntmaster Orlo at 3.1s,70.2w to take the task. + +Kill 50 Glimmer Beetles anywhere on the salt flats. + +Return to Huntmaster Orlo for the reward. +== QB Stamps == +{{stamped|GlimmerBeetleTaskTaken}} {{stamped|GlimmerBeetleKills on first completion}} +[[Category:Kill Tasks]]"; + + private const string ThornboundInitiate = @"{{Quest Summary +| Level = 50+ +| Starts With = [[Sister Wren]] +}} +== Walkthrough == +# Bring Sister Wren three bramble cuttings. +[[Category:Society Quests: Initiate Rank]]"; + + private const string BrambleContract = @"{{Item +| Name = Contract for the Bramble Wardens +| Description = Starts the Bramble Wardens' errand again. +| Recommended Level = 60 +}} +{{Intro | Related Quests = [[Thornbound Initiate Tasks]]}} +== Notes == +* Purchased from [[Quartermaster Ivo]] in [[Hollow Reach]]. +[[Category:Contracts]]"; + + private const string MothItem = @"{{Item | Name = Moth Glow Sac}} +A pale sac that glows faintly. Not a quest page."; + + // ── A fake MediaWiki ──────────────────────────────────────────────────── + + private sealed class FakeWiki : HttpMessageHandler + { + public readonly Dictionary Pages = new(StringComparer.Ordinal) + { + ["The Lantern Moth Errand"] = (101, MothErrand), + ["Glimmer Beetle Kill Task"] = (102, GlimmerBeetles), + ["Thornbound Initiate Tasks"] = (103, ThornboundInitiate), + ["Contract for the Bramble Wardens"] = (104, BrambleContract), + ["Moth Glow Sac"] = (105, MothItem), + }; + + /// Category -> members (title, ns). + public readonly Dictionary> Categories = new(StringComparer.Ordinal) + { + ["Category:Kill_Tasks"] = new() { ("Glimmer Beetle Kill Task", 0), ("Category:Kill Tasks by Level", 14) }, + ["Category:Kill Tasks by Level"] = new() { ("Glimmer Beetle Kill Task", 0) }, + ["Category:Society_Quests"] = new() { ("Category:Society Quests: Initiate Rank", 14), ("Category:Society Items", 14) }, + ["Category:Society Quests: Initiate Rank"] = new() { ("Thornbound Initiate Tasks", 0) }, + ["Category:Society Items"] = new() { ("Moth Glow Sac", 0) }, + ["Category:Contracts"] = new() { ("Contract for the Bramble Wardens", 0) }, + }; + + public string User = WikiGuideTests.User; + public string Password = WikiGuideTests.Password; + public string? Robots = "User-agent: *\nCrawl-Delay: 12\n"; + public string? LoginResultOverride; // "Aborted" etc. + public string? HtmlInstead; // every API answer is this HTML page + public bool Redirect; + /// After this many signed-in queries the wiki forgets the session, once (0 = never). + public int DropSessionAfter; + /// The wiki takes the password once only (it was revoked mid-read). + public bool RevokeAfterFirstLogin; + + public readonly ConcurrentQueue<(string Method, string Url, string Body, string Agent, string Cookie)> Log = new(); + public readonly List ContentTitles = new(); + public int Logins; + private int _sessionNo; + private string _session = ""; + private string _signedSession = ""; + private int _queries; + private const string LoginToken = "tok+\\"; + + private static Dictionary Parse(string query) + { + var map = new Dictionary(StringComparer.Ordinal); + foreach (string part in query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + int eq = part.IndexOf('='); + string k = Uri.UnescapeDataString((eq < 0 ? part : part[..eq]).Replace('+', ' ')); + string v = eq < 0 ? "" : Uri.UnescapeDataString(part[(eq + 1)..].Replace('+', ' ')); + map[k] = v; + } + return map; + } + + private static HttpResponseMessage Json(string json, string? cookie = null) + { + var r = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + if (cookie != null) r.Headers.TryAddWithoutValidation("Set-Cookie", cookie); + return r; + } + + private static string Esc(string s) => System.Text.Json.JsonEncodedText.Encode(s).ToString(); + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + string body = request.Content == null ? "" : await request.Content.ReadAsStringAsync(cancellationToken); + string agent = request.Headers.UserAgent.ToString(); + string cookie = request.Headers.TryGetValues("Cookie", out var cs) ? string.Join("; ", cs) : ""; + Log.Enqueue((request.Method.Method, request.RequestUri!.ToString(), body, agent, cookie)); + Uri u = request.RequestUri!; + if (u.AbsolutePath == "/robots.txt") + return Robots == null ? new HttpResponseMessage(HttpStatusCode.NotFound) : new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(Robots) }; + if (Redirect) + { + var r = new HttpResponseMessage(HttpStatusCode.Found); + r.Headers.Location = new Uri("https://elsewhere.test/"); + return r; + } + if (HtmlInstead != null) return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(HtmlInstead, Encoding.UTF8, "text/html") }; + Dictionary q = Parse(request.Method == HttpMethod.Post ? body : u.Query); + bool hasSession = _session.Length > 0 && cookie.Contains("wikisession=" + _session, StringComparison.Ordinal); + + if (q.GetValueOrDefault("meta") == "tokens") + { + _session = "s" + (++_sessionNo); + return Json("{\"batchcomplete\":true,\"query\":{\"tokens\":{\"logintoken\":\"" + Esc(LoginToken) + "\"}}}", "wikisession=" + _session + "; path=/; secure; HttpOnly"); + } + if (q.GetValueOrDefault("action") == "login") + { + Logins++; + if (!hasSession || q.GetValueOrDefault("lgtoken") != LoginToken) return Json("{\"login\":{\"result\":\"WrongToken\"}}"); + if (LoginResultOverride != null) return Json("{\"login\":{\"result\":\"" + LoginResultOverride + "\",\"reason\":\"Main-password logins are switched off here.\"}}"); + bool revoked = RevokeAfterFirstLogin && Logins > 1; + if (q.GetValueOrDefault("lgname") != User || q.GetValueOrDefault("lgpassword") != Password || revoked) + return Json("{\"login\":{\"result\":\"Failed\",\"reason\":\"That login name or password is wrong (fake wiki).\"}}"); + _signedSession = _session; + _queries = 0; + return Json("{\"login\":{\"result\":\"Success\",\"lguserid\":7,\"lgusername\":\"Tester\"}}"); + } + if (q.GetValueOrDefault("action") != "query") return Json("{\"error\":{\"code\":\"badvalue\",\"info\":\"unknown action\"}}"); + bool signed = hasSession && _session == _signedSession && _signedSession.Length > 0; + if (signed && DropSessionAfter > 0 && ++_queries > DropSessionAfter) + { + _signedSession = ""; + signed = false; + DropSessionAfter = 0; // once: the session lapsed + } + if (q.GetValueOrDefault("assert") == "user" && !signed) + return Json("{\"error\":{\"code\":\"assertuserfailed\",\"info\":\"You are no longer logged in.\"}}"); + + if (q.GetValueOrDefault("meta") == "userinfo|siteinfo") + return Json("{\"query\":{\"userinfo\":{\"id\":7,\"name\":\"Tester\"},\"general\":{\"server\":\"https://wiki.test\",\"articlepath\":\"/$1\"}}}"); + if (q.GetValueOrDefault("generator") == "embeddedin") + { + // Two pages per answer, with a continuation (as a big wiki answers). + var quests = Pages.Where(p => p.Value.Text.Contains("{{Quest Summary")).Select(p => p.Key).OrderBy(t => t, StringComparer.Ordinal).ToList(); + int from = int.TryParse(q.GetValueOrDefault("geicontinue"), out int f) ? f : 0; + var part = quests.Skip(from).Take(2).ToList(); + string cont = from + 2 < quests.Count ? ",\"continue\":{\"geicontinue\":\"" + (from + 2) + "\",\"continue\":\"gei||\"}" : ""; + return Json("{\"query\":{\"pages\":[" + string.Join(",", part.Select(t => PageInfo(t, 0))) + "]}" + cont + "}"); + } + if (q.GetValueOrDefault("generator") == "categorymembers") + { + string cat = q.GetValueOrDefault("gcmtitle") ?? ""; + var members = Categories.TryGetValue(cat, out var m) ? m : new List<(string, int)>(); + return Json("{\"query\":{\"pages\":[" + string.Join(",", members.Select(x => PageInfo(x.Item1, x.Item2))) + "]}}"); + } + if (q.GetValueOrDefault("prop") == "revisions") + { + var titles = (q.GetValueOrDefault("titles") ?? "").Split('|'); + lock (ContentTitles) ContentTitles.AddRange(titles); + var parts = titles.Where(Pages.ContainsKey).Select(t => + "{\"ns\":0,\"title\":\"" + Esc(t) + "\",\"revisions\":[{\"revid\":" + Pages[t].Rev + ",\"slots\":{\"main\":{\"content\":\"" + Esc(Pages[t].Text) + "\"}}}]}"); + return Json("{\"query\":{\"pages\":[" + string.Join(",", parts) + "]}}"); + } + return Json("{\"error\":{\"code\":\"badvalue\",\"info\":\"not faked\"}}"); + } + + private string PageInfo(string title, int ns) => + "{\"ns\":" + ns + ",\"title\":\"" + Esc(title) + "\"" + (ns == 0 && Pages.TryGetValue(title, out var p) ? ",\"lastrevid\":" + p.Rev : "") + "}"; + } + + // ── Helpers ───────────────────────────────────────────────────────────── + + private sealed class Harness + { + public readonly FakeWiki Wiki = new(); + public readonly List<(string Text, bool Ok)> Said = new(); + public readonly ConcurrentQueue Waits = new(); + public DateTime Now = new(2026, 11, 27, 12, 0, 0, DateTimeKind.Utc); + public int Handlers; + public int SettingsOpened; + public readonly IltWikiGuide Guide; + + public Harness(string name, bool fresh = true) + { + string dir = Path.Combine(Program.TempRoot, "wiki-" + name); + if (fresh && Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + WikiLoginStore.FolderOverride = dir; + ServerQuestGuideHost.ResetForTests(); + Guide = new IltWikiGuide((t, ok) => Said.Add((t, ok)), null, () => { Handlers++; return Wiki; }, + (gap, _) => { Waits.Enqueue(gap); return Task.CompletedTask; }, () => Now) + { + OpenSettings = () => SettingsOpened++, + }; + Guide.Load(); + } + + public void Settle() + { + Check.True(Guide.WaitForTests(), "the background work ended"); + Guide.Tick(); + } + + public string AllSaid => string.Join(" / ", Said.Select(s => s.Text)); + } + + private static unsafe ServerQuestGuideClient ReadPublished() + { + var client = new ServerQuestGuideClient(); + client.Use((RynthServerQuestGuideApiV1*)ServerQuestGuideHost.Query(1), "RynthILT"); + return client; + } + + /// No file under the wiki folder holds the password (or the login name) in readable form, except none may. + private static void NoSecretOnDisk(string what) + { + string dir = WikiLoginStore.Folder; + if (!Directory.Exists(dir)) { Check.True(true, what + ": no files"); return; } + foreach (string f in Directory.GetFiles(dir, "*", SearchOption.AllDirectories)) + { + byte[] bytes = File.ReadAllBytes(f); + string utf8 = Encoding.UTF8.GetString(bytes), utf16 = Encoding.Unicode.GetString(bytes); + Check.False(utf8.Contains(Password) || utf16.Contains(Password), $"{what}: {Path.GetFileName(f)} doesn't hold the password"); + } + string logs = Path.Combine(Program.TempRoot, "Logs"); + if (Directory.Exists(logs)) + foreach (string f in Directory.GetFiles(logs, "*", SearchOption.AllDirectories)) + { + string text; + try + { + using var fs = new FileStream(f, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using var sr = new StreamReader(fs); + text = sr.ReadToEnd(); + } + catch (IOException) { continue; } + Check.False(text.Contains(Password), $"{what}: the log {Path.GetFileName(f)} doesn't hold the password"); + } + } + + // ── Tests ─────────────────────────────────────────────────────────────── + + private static void Address() + { + Check.True(WikiAddress.TryNormalize("https://wiki.test/", out string a, out _) && a == Api, "a site becomes its api.php"); + Check.True(WikiAddress.TryNormalize("wiki.test", out a, out _) && a == Api, "no scheme: https is assumed"); + Check.True(WikiAddress.TryNormalize("https://wiki.test/index.php?title=Main_Page#x", out a, out _) && a == Api, "index.php becomes api.php, query dropped"); + Check.True(WikiAddress.TryNormalize("https://wiki.test/w/api.php", out a, out _) && a == "https://wiki.test/w/api.php", "an api.php stays"); + Check.False(WikiAddress.TryNormalize("http://wiki.test/", out _, out string e) , "plain http is refused"); + Check.True(e.Contains("https"), "and says https"); + Check.False(WikiAddress.TryNormalize("https://me:pw@wiki.test/", out _, out _), "a login in the address is refused"); + Check.False(WikiAddress.TryNormalize("", out _, out _) || WikiAddress.TryNormalize("ht!tp:/", out _, out _), "empty or junk is refused"); + Check.True(WikiAddress.Same("https://WIKI.test/api.php", Api) && !WikiAddress.Same("https://other.test/api.php", Api), "same address, any case"); + Check.Eq(WikiAddress.FileKey(Api), "wiki.test", "the cache file key is the host"); + Check.Eq(WikiAddress.RobotsOf(Api), "https://wiki.test/robots.txt", "robots.txt beside it"); + } + + private static void Robots() + { + Check.Eq(WikiClient.CrawlDelay("User-agent: *\nCrawl-Delay: 10\n"), 10.0, "Crawl-Delay for every robot"); + Check.Eq(WikiClient.CrawlDelay("User-agent: OtherBot\nCrawl-delay: 99\n\nUser-agent: *\nDisallow: /x\n"), (double?)null, "another robot's delay isn't ours"); + Check.Eq(WikiClient.CrawlDelay("User-agent: OtherBot\nUser-agent: *\nCrawl-delay: 3 # comment\n"), 3.0, "a group naming several robots"); + Check.Eq(WikiClient.CrawlDelay("login"), (double?)null, "a login page instead: none"); + } + + private static void Sealed() + { + WikiLoginStore.FolderOverride = Path.Combine(Program.TempRoot, "wiki-sealed"); + Check.True(WikiLoginStore.Save(new WikiLogin(Api, User, Password), out string err), "saved: " + err); + byte[] raw = File.ReadAllBytes(WikiLoginStore.FilePath); + string u8 = Encoding.UTF8.GetString(raw), u16 = Encoding.Unicode.GetString(raw); + Check.False(u8.Contains(Password) || u16.Contains(Password) || u8.Contains("Tester") || u8.Contains("wiki.test"), "the file is sealed: no password, name or address readable"); + WikiLogin? back = WikiLoginStore.Load(out err); + Check.True(back != null && back.Api == Api && back.User == User && back.Password == Password, "it opens again for this Windows user"); + Check.False(back!.ToString().Contains(Password), "a login written out never shows the password"); + raw[raw.Length / 2] ^= 0x5a; + File.WriteAllBytes(WikiLoginStore.FilePath, raw); + Check.True(WikiLoginStore.Load(out err) == null && err.Contains("sign in again"), "a damaged file is no login, said plainly"); + Check.True(WikiLoginStore.Delete(out _) && !File.Exists(WikiLoginStore.FilePath) && !WikiLoginStore.Exists, "Delete removes it"); + } + + private static void SignIn() + { + var wiki = new FakeWiki(); + var waits = new List(); + using var client = new WikiClient(Api, wiki, (g, _) => { waits.Add(g); return Task.CompletedTask; }); + WikiSignIn s = client.SignInAsync(User, Password, CancellationToken.None).GetAwaiter().GetResult(); + Check.True(s.Ok && s.UserName == "Tester" && s.ArticleBase == "https://wiki.test/", "signed in: " + s.Message); + var log = wiki.Log.ToArray(); + Check.Eq(log.Length, 4, "robots, token, login, user check"); + Check.True(log[0].Url.EndsWith("/robots.txt") && log[1].Url.Contains("meta=tokens") && log[2].Method == "POST" && log[3].Url.Contains("assert=user"), + "in that order"); + Check.True(log[2].Body.Contains("lgname=Tester%40probe") && log[2].Body.Contains("lgtoken="), "the login POST carries the name and the token"); + Check.True(log.All(l => !l.Url.Contains(Password) && !l.Url.Contains("lgpassword")), "the password is never in an address"); + Check.True(log.Count(l => l.Body.Contains(Uri.EscapeDataString(Password)) || l.Body.Contains(Password)) == 1, "only the login POST carries the password"); + Check.True(log[2].Cookie.Contains("wikisession=") && log[3].Cookie.Contains("wikisession="), "the session cookie goes back"); + Check.True(log.All(l => l.Agent == WikiClient.UserAgent), "every request names only the plugin: " + log[0].Agent); + Check.True(client.Gap == TimeSpan.FromSeconds(12) && waits.Count == 3 && waits.All(w => w == TimeSpan.FromSeconds(12)), + $"robots.txt's 12 s kept between every request ({string.Join(",", waits)})"); + + var slow = new FakeWiki { Robots = "User-agent: *\nCrawl-delay: 1\n" }; + using var c2 = new WikiClient(Api, slow, (_, _) => Task.CompletedTask); + c2.SignInAsync(User, Password, CancellationToken.None).GetAwaiter().GetResult(); + Check.Eq(c2.Gap, WikiClient.MinGap, "never closer than 5 s"); + var none = new FakeWiki { Robots = null }; + using var c3 = new WikiClient(Api, none, (_, _) => Task.CompletedTask); + c3.SignInAsync(User, Password, CancellationToken.None).GetAwaiter().GetResult(); + Check.Eq(c3.Gap, WikiClient.DefaultGap, "no robots.txt: 10 s"); + } + + private static WikiSignIn Try(FakeWiki wiki, string user, string password) + { + using var client = new WikiClient(Api, wiki, (_, _) => Task.CompletedTask); + return client.SignInAsync(user, password, CancellationToken.None).GetAwaiter().GetResult(); + } + + private static void SignInFails() + { + WikiSignIn s = Try(new FakeWiki(), User, "not-the-password"); + Check.True(!s.Ok && s.Message.Contains("turned the sign-in down") && s.Message.Contains("fake wiki"), "wrong password: " + s.Message); + Check.False(s.Message.Contains("not-the-password"), "the message never holds the password"); + s = Try(new FakeWiki(), "Tester", "not-the-password"); + Check.True(s.Message.Contains("YourName@botname"), "a name without @: the bot password hint"); + s = Try(new FakeWiki { LoginResultOverride = "Aborted" }, User, Password); + Check.True(!s.Ok && s.Message.Contains("Special:BotPasswords"), "a main-password sign-in turned away: " + s.Message); + s = Try(new FakeWiki { HtmlInstead = "Login required" }, User, Password); + Check.True(!s.Ok && s.Message.Contains("api.php"), "not an API: " + s.Message); + s = Try(new FakeWiki { Redirect = true }, User, Password); + Check.True(!s.Ok && s.Message.Contains("somewhere else"), "a redirect isn't followed: " + s.Message); + } + + private static void OffByDefault() + { + var h = new Harness("off"); + h.Guide.Tick(); + Check.False(h.Guide.SignedIn, "not signed in"); + Check.False(h.Guide.OnLogin(iltActive: true), "login on ILT: no read"); + h.Guide.Tick(); + Check.Eq(h.Handlers, 0, "no connection was made"); + Check.False(Directory.Exists(WikiLoginStore.Folder) && Directory.GetFiles(WikiLoginStore.Folder).Length > 0, "nothing saved"); + Check.Eq(h.Guide.Address, "", "no wiki address built in"); + ServerQuestGuideClient c = ReadPublished(); + Check.True(c.Available && c.Guide.IsEmpty && c.Tag == "Leaftide", "RynthOracle sees the Leaftide guide, empty"); + Check.True(c.Info!.Takes("settings") && !c.Info.Takes("refresh") && c.Info.Status.Contains("Sign in"), "only the way to sign in: " + c.Info.Status); + Check.True(c.Command("settings"), "RynthOracle's Its settings is taken"); + h.Guide.Tick(); + Check.Eq(h.SettingsOpened, 1, "and opens the ILT settings"); + } + + private static Harness SignedIn(string name) + { + var h = new Harness(name); + Check.True(h.Guide.SignIn("https://wiki.test/", User, Password, fromChat: false), "sign-in started: " + h.Guide.Status); + h.Settle(); + return h; + } + + private static void ReadsGuide() + { + var h = SignedIn("reads"); + Check.True(h.Guide.SignedIn && h.Guide.User == User, "signed in: " + h.Guide.Status); + QuestGuide g = h.Guide.Guide; + Check.Eq(g.Quests.Count, 3, "three quest pages (the item page isn't one)"); + Check.True(g.Contracts.Count == 1 && g.Contracts[0].Npc == "Quartermaster Ivo", "the contract and who sells it"); + Check.True(g.KillTasks.SequenceEqual(new[] { "Glimmer Beetle Kill Task" }), "the kill task list"); + Check.True(g.Society.TryGetValue("Thornbound Initiate Tasks", out string? rank) && rank == "Initiate", "the society quest's rank"); + Check.False(g.Society.ContainsKey("Moth Glow Sac"), "an items sub-category isn't followed"); + Check.Eq(g.Source, "wiki.test", "the source is the wiki's host"); + Check.Eq(g.Find("The Lantern Moth Errand")?.Url, "https://wiki.test/The_Lantern_Moth_Errand", "page addresses from the site's article path"); + Check.True(File.Exists(IltWikiGuide.GuidePath(Api)) && WikiLoginStore.Exists, "the guide and the sealed login are saved"); + Check.True(h.Said.Any(s => s.Ok && s.Text.Contains("signed in as Tester")) && h.Said.Any(s => s.Ok && s.Text.Contains("3 quests")), + "the sign-in and the read answered in chat: " + h.AllSaid); + Check.False(h.AllSaid.Contains(Password) || h.Guide.Status.Contains(Password) || string.Join(" ", h.Guide.StatusLines()).Contains(Password), + "no chat or status line holds the password"); + NoSecretOnDisk("after the read"); + + ServerQuestGuideClient c = ReadPublished(); + Check.True(c.Available && c.Guide.Quests.Count == 3 && c.Info!.Takes("refresh") && c.Info.Takes("settings"), "RynthOracle gets the guide, with Refresh"); + Check.False(c.Info.Status.Contains(Password), "the published status holds no secret"); + + // A fresh plugin start reads the saved guide without a request. + var again = new Harness("reads", fresh: false); + Check.True(again.Guide.SignedIn && again.Guide.Guide.Quests.Count == 3 && again.Handlers == 0, "a restart: signed in, the saved guide, no request"); + Check.False(again.Guide.OnLogin(true), "a fresh guide isn't read again at login"); + var later = new Harness("reads", fresh: false); + later.Now = later.Now.AddHours(25); + Check.True(later.Guide.OnLogin(true), "a day old: read again at login"); + later.Settle(); + Check.True(later.Guide.Status.Contains("3 quests"), "and read: " + later.Guide.Status); + Check.False(later.Said.Any(), "the login read is quiet when it works"); + var off = new Harness("reads", fresh: false); + off.Now = later.Now.AddHours(30); + off.Guide.SetDaily(false); + Check.False(off.Guide.OnLogin(true), "the switch off: no login read"); + off.Guide.SetDaily(true); + Check.False(off.Guide.OnLogin(false), "not ILT: no login read"); + } + + private static void OnlyEdited() + { + var h = SignedIn("edited"); + int firstContent = h.Wiki.ContentTitles.Count; + Check.True(firstContent == 4, "the first read fetched every listed page (3 quests, 1 contract): " + firstContent); + Check.False(h.Guide.Refresh(fromChat: true), "Refresh right after a read waits"); + Check.True(h.Said.Last().Text.Contains("again in") && !h.Said.Last().Ok, "and says when: " + h.Said.Last().Text); + h.Wiki.Pages["The Lantern Moth Errand"] = (201, MothErrand.Replace("20 Hours", "18 Hours")); + h.Now = h.Now.AddMinutes(6); + h.Wiki.ContentTitles.Clear(); + Check.True(h.Guide.Refresh(fromChat: true), "Refresh after 5 minutes reads"); + h.Settle(); + // The edited quest, plus the pages that aren't quests (they are checked again each time). + Check.True(h.Wiki.ContentTitles.Contains("The Lantern Moth Errand") && !h.Wiki.ContentTitles.Contains("Glimmer Beetle Kill Task") + && !h.Wiki.ContentTitles.Contains("Thornbound Initiate Tasks") && !h.Wiki.ContentTitles.Contains("Contract for the Bramble Wardens"), + "only the edited page (and non-quest pages) fetched: " + string.Join(", ", h.Wiki.ContentTitles)); + Check.Eq(h.Guide.Guide.Find("The Lantern Moth Errand")?.Repeat, "18 Hours", "the edit is in the guide"); + Check.Eq(h.Guide.Guide.Find("Glimmer Beetle Kill Task")?.Rev, 102L, "an unchanged page kept from the saved guide"); + } + + private static void LostSession() + { + var h = new Harness("lost"); + h.Wiki.DropSessionAfter = 3; + h.Guide.SignIn(Api, User, Password, fromChat: false); + h.Settle(); + Check.True(h.Guide.Guide.Quests.Count == 3 && h.Wiki.Logins == 2, $"the session ended mid-read; signed in again and finished ({h.Wiki.Logins} sign-ins, {h.Guide.Status})"); + + var r = new Harness("revoked"); + r.Wiki.DropSessionAfter = 3; + r.Wiki.RevokeAfterFirstLogin = true; + r.Guide.SignIn(Api, User, Password, fromChat: false); + r.Settle(); + Check.True(r.Guide.Status.Contains("signing in again didn't work") && r.Guide.Status.Contains("fake wiki"), "a revoked bot password ends the read plainly: " + r.Guide.Status); + Check.True(r.Guide.Guide.IsEmpty && r.Said.Any(s => !s.Ok), "no guide from it, and chat says so"); + Check.False(r.AllSaid.Contains(Password) || r.Guide.Status.Contains(Password), "without the password"); + } + + private static void SignOut() + { + var h = SignedIn("signout"); + Check.True(h.Guide.SignOut(fromChat: true), "signed out"); + Check.True(h.Said.Last().Ok && h.Said.Last().Text.Contains("deleted"), "and says so: " + h.Said.Last().Text); + Check.False(WikiLoginStore.Exists || File.Exists(IltWikiGuide.GuidePath(Api)), "the sealed login and the saved guide are gone"); + Check.True(!h.Guide.SignedIn && h.Guide.Guide.IsEmpty, "nothing in memory either"); + h.Guide.Tick(); + ServerQuestGuideClient c = ReadPublished(); + Check.True(c.Guide.IsEmpty && !c.Info!.Takes("refresh"), "RynthOracle's copy goes"); + Check.Eq(h.Guide.Address, Api, "the address stays (it is no secret)"); + Check.True(h.Guide.SignOut(fromChat: false), "signing out again is fine"); + var restart = new Harness("signout", fresh: false); + Check.False(restart.Guide.SignedIn, "a restart stays signed out"); + } + + private static void Commands() + { + var h = new Harness("commands"); + void Run(string line, bool ok, string needle) + { + h.Said.Clear(); + h.Guide.HandleCommand(line.Split(' ', StringSplitOptions.RemoveEmptyEntries)); + Check.True(h.Said.Count > 0, $"/ilt wiki {line}: answers"); + Check.True(h.Said.All(s => s.Ok == ok), $"/ilt wiki {line}: {(ok ? "worked" : "didn't")} ({h.AllSaid})"); + Check.True(h.AllSaid.Contains(needle, StringComparison.OrdinalIgnoreCase), $"/ilt wiki {line}: says '{needle}' ({h.AllSaid})"); + } + Run("status", true, "Off until you sign in"); + Run("", true, "address: not set"); + Run("refresh", false, "not signed in"); + Run("signin", true, "settings window is open"); + Check.Eq(h.SettingsOpened, 1, "signin without a login opens the settings"); + h.Said.Clear(); + h.Guide.HandleCommand(new[] { "signin", User, Password }); + Check.True(h.Said.Count == 1 && !h.Said[0].Ok && h.Said[0].Text.Contains("aren't taken in chat"), "a login typed in chat is refused: " + h.AllSaid); + Check.False(h.AllSaid.Contains(Password) || h.AllSaid.Contains(User), "and not repeated"); + Check.Eq(h.Handlers, 0, "nothing was sent"); + Check.False(WikiLoginStore.Exists, "nothing was saved"); + Run("signout", true, "not signed in"); + Run("address http://wiki.test/", false, "https"); + Run("address wiki.test", true, Api); + Run("address", true, Api); + Run("auto off", true, "is off"); + Check.False(h.Guide.Daily, "the switch is off"); + Run("auto on", true, "is on"); + Run("help", true, "/ilt wiki signout"); + Run("frobnicate", false, "unknown"); + + var s = SignedIn("commands-signed"); + s.Said.Clear(); + s.Guide.HandleCommand(new[] { "status" }); + Check.True(s.AllSaid.Contains("signed in as " + User) && s.AllSaid.Contains("3 quests"), "status when signed in: " + s.AllSaid); + s.Said.Clear(); + s.Guide.HandleCommand(new[] { "address", "https://other.test/" }); + Check.True(s.Said.Count == 1 && !s.Said[0].Ok && s.Said[0].Text.Contains("sign out first"), "the address can't change while signed in"); + s.Now = s.Now.AddMinutes(10); + s.Said.Clear(); + s.Guide.HandleCommand(new[] { "signin" }); + Check.True(s.Said.Any(x => x.Ok && x.Text.Contains("signing in again")), "signin with a saved login signs in again: " + s.AllSaid); + s.Settle(); + Check.True(s.Guide.Status.Contains("3 quests"), "and reads: " + s.Guide.Status); + } + + private static void OtherAddress() + { + var h = new Harness("other"); + h.Guide.SetAddress("https://wiki.test/", fromChat: false); + Check.True(WikiLoginStore.Save(new WikiLogin("https://other.test/api.php", User, Password), out _), "a login for another wiki is on disk"); + var again = new Harness("other", fresh: false); + Check.False(again.Guide.SignedIn, "it isn't used for this address"); + Check.True(again.Guide.Status.Contains("another wiki address"), "and the status says why: " + again.Guide.Status); + Check.False(again.Guide.OnLogin(true) || again.Guide.Refresh(fromChat: false), "no read with it"); + Check.Eq(again.Handlers, 0, "nothing was sent anywhere"); + } + + private static void Parsing() + { + GuideQuest q = QuestWikiText.ParseQuest("The Lantern Moth Errand", MothErrand, 101, "https://wiki.test/"); + Check.True(q.Level == "120+" && q.StartsWith == "Warden Pellis" && q.StartsAt == "Hollow Reach" && q.IsDaily, "the summary box"); + Check.True(q.Overview.StartsWith("Warden Pellis wants"), "the overview"); + Check.Eq(q.Steps.Count, 3, "three numbered steps"); + Check.True(q.Steps[0].Coords.SequenceEqual(new[] { "12.3N, 45.6E" }) && q.Steps[0].Stamps.SequenceEqual(new[] { "LanternMothErrandStarted" }), "a step's place and stamp"); + Check.True(q.Steps[1].Coords.SequenceEqual(new[] { "14.0N, 47.2E" }) && q.Loot.SequenceEqual(new[] { "Moth Glow Sac" }), "the loot is the killed-for item, not the handed-in one"); + Check.True(q.Rewards.Contains("For Hand in a glow sac:") && q.Rewards.Contains("XP: 5,000,000"), "the rewards table"); + + GuideQuest k = QuestWikiText.ParseQuest("Glimmer Beetle Kill Task", GlimmerBeetles, 102, "https://wiki.test/"); + Check.True(k.IsKillTaskPage && k.IsWeekly && k.KillTarget == 50, "a weekly kill task of 50"); + Check.True(k.Overview.StartsWith("Thin out") && k.Steps.Count == 3, "the Discord description and the paragraph steps"); + Check.True(k.Steps[0].Coords.SequenceEqual(new[] { "3.1S, 70.2W" }), "coordinates written '3.1s,70.2w'"); + Check.True(k.AllStamps().Contains("GlimmerBeetleTaskTaken") && k.AllStamps().Contains("GlimmerBeetleKills"), "the QB Stamps, cut to the flag"); + + var (pages, cont) = IltWikiReader.Generated("{\"continue\":{\"gcmcontinue\":\"page|X|9\",\"continue\":\"gcm||\"},\"query\":{\"pages\":[{\"ns\":0,\"title\":\"A\",\"lastrevid\":5},{\"ns\":14,\"title\":\"Category:B\"},{\"ns\":0,\"title\":\"C\",\"missing\":true}]}}"); + Check.True(pages.Count == 2 && pages[0] == ("A", 0, 5L) && pages[1].Ns == 14 && cont.Count == 2, "a generator answer: pages, sub-categories, the continuation"); + Check.True(IltWikiReader.RankOf("Category:Society Quests: Knight Rank") == "Knight" && IltWikiReader.SkipCategory("Category:Society Items"), "ranks and skipped sub-categories"); + } +} diff --git a/Tools/RynthServerPack.Tests/DreamWeaveAbilitiesTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveAbilitiesTests.cs new file mode 100644 index 0000000..cdaa98e --- /dev/null +++ b/Tools/RynthServerPack.Tests/DreamWeaveAbilitiesTests.cs @@ -0,0 +1,507 @@ +using System; +using RynthCore.Plugin.RynthDreamWeave; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// RynthDreamWeave's class ability point calculator (Plugins\RynthCore.Plugin.RynthDreamWeave\DreamWeave\AbilityPointPrices.cs +// and DreamWeaveAbilityPoints.cs, 2026-11-17): DreamWeave's two price curves as its server computes them +// (ACE-DreamWeave ClassAbilityLumCurve.cs with the PropertyManager defaults), what a budget buys, the curve fitted to +// the server's quote, the "/abilities points" reply (worded as the source of 2026-11-02 writes it) and the grant +// lines, only its own reply hidden, and when its read goes. +internal static class DreamWeaveAbilitiesTests +{ + private const int Broadcast = 0x00, Advancement = 0x0D, Tell = 0x03; + private static readonly DateTime Utc = new(2026, 11, 17, 22, 0, 0, DateTimeKind.Utc); + + private const string Points = "Points: 12 available, 30 lifetime earned."; + private const string Lum = "Luminance purchases: 5 bought so far; the next point costs 3,051,758 Luminance. Exchange it at the reckoning-stone by the Skillmaster in the Drift Network. Prices rise with each point and there is no cap."; + private const string Xp = "Experience purchases: 2 bought so far; the next point costs 392,000,000,000 experience and you have 1,234,567 unassigned. Prices rise with each point and there is no cap."; + private const string XpLocked = "Experience purchases: unlocked at level 275 (you are 200)."; + private const string Off = "Class abilities are not currently enabled on this server."; + + public static void Register(Runner r) + { + r.Add("dw abilities: the luminance curve is the server's (1M, x1.25 to the 10th, x1.5 to the 20th, x1.75 after)", LumCurve); + r.Add("dw abilities: the experience curve is the server's (200B, x1.4 each) and stops at long.MaxValue", XpCurve); + r.Add("dw abilities: a range is the unrounded prices summed and rounded once", Ranges); + r.Add("dw abilities: what a budget buys, its cost and what the next point still needs", Affordable); + r.Add("dw abilities: the curve is scaled to a quote it doesn't give, and kept when it does", Fit); + r.Add("dw abilities: the /abilities points reply (unlocked, locked, class abilities off)", Replies); + r.Add("dw abilities: only the reply to its own request is hidden; a typed one shows and is read", OursAndTyped); + r.Add("dw abilities: player chat and a quoted copy are not read", NotRead); + r.Add("dw abilities: a purchase moves its lane on and asks for a read; other grants and learning move only the points", Grants); + r.Add("dw abilities: the read goes once when the page opens, on Read now, only when quiet and in the world", ReadTiming); + r.Add("dw abilities: a request with no reply is given up and said", Missed); + r.Add("dw abilities: the command, the numbers in words and ordinals, and the summary lines", Text); + r.Add("dw abilities: buying with experience: the command, the grant, the refusals, no answer, no read meanwhile", BuyXp); + r.Add("dw abilities: the luminance stone: its answers, what it counted, a purchase through it, one used by hand", Stone); + r.Add("dw abilities: the earning rate (purchases added back, a drop starts again) and the time to the next point", Rates); + r.Add("dw abilities: how the price grows from a point on, and the live prices of 2026-11-17", StageAndLive); + } + + private static void LumCurve() + { + AbilityCurve c = AbilityCurve.Luminance; + Check.Eq(c.Cost(0), 0L, "no 0th point"); + Check.Eq(c.Cost(1), 1_000_000L, "1st"); + Check.Eq(c.Cost(2), 1_250_000L, "2nd = x1.25"); + Check.Eq(c.Cost(3), 1_562_500L, "3rd"); + Check.Eq(c.Cost(6), 3_051_758L, "6th (3,051,757.8125 rounded)"); + Check.Eq(c.Cost(10), 7_450_581L, "10th = 1.25^9"); + Check.Eq(c.Cost(11), 11_175_871L, "11th: x1.5 from the 10th"); + Check.Eq(c.Cost(20), 429_638_021L, "20th: 1.25^9 * 1.5^10"); + Check.Eq(c.Cost(21), 751_866_537L, "21st: x1.75 from the 20th"); + Check.Eq(c.Cost(23), 2_302_591_270L, "23rd"); + // Seen live on DreamWeave (a client log, 2026-11): "You gain 1 class ability point from spending 16,763,806 Luminance." + Check.Eq(c.Cost(12), 16_763_806L, "12th, as the server charged it"); + } + + private static void XpCurve() + { + AbilityCurve c = AbilityCurve.Experience; + Check.Eq(c.Cost(1), 200_000_000_000L, "1st"); + Check.Eq(c.Cost(2), 280_000_000_000L, "2nd = x1.4 (seen live: \"from spending 280,000,000,000 experience\")"); + Check.Eq(c.Cost(3), 392_000_000_000L, "3rd (391,999,999,999.99994 rounded)"); + Check.Eq(c.Cost(10), 4_132_209_356_800L, "10th = 1.4^9"); + Check.Eq(c.Cost(54), long.MaxValue, "the 54th is past long.MaxValue: it stays there"); + Check.Eq(c.CostOfRange(50, 10), long.MaxValue, "a range past it too"); + Check.Eq(AbilityCurve.ExperienceMinLevel, 275, "the lane opens at 275"); + } + + private static void Ranges() + { + AbilityCurve c = AbilityCurve.Luminance; + Check.Eq(c.CostOfRange(5, 0), 0L, "no points, no cost"); + Check.Eq(c.CostOfRange(0, 1), 1_000_000L, "one point"); + Check.Eq(c.CostOfRange(5, 5), 25_045_872L, "points 6 to 10: 25,045,871.73 rounded once"); + long each = 0; + for (int n = 6; n <= 10; n++) each += c.Cost(n); + Check.Eq(each, 25_045_872L, "the same as the rounded prices here"); + Check.Eq(c.CostOfRange(0, 23), 5_670_039_471L, "the first 23 points"); + } + + private static void Affordable() + { + AbilityCurve c = AbilityCurve.Luminance; + int k = c.Affordable(0, 3_000_000, out long spent, out long next, out long need); + Check.Eq(k, 2, "3M buys the 1st and 2nd"); + Check.Eq(spent, 2_250_000L, "for 2,250,000"); + Check.Eq(next, 1_562_500L, "the 3rd's price"); + Check.Eq(need, 812_500L, "the 3rd needs 812,500 more"); + + k = c.Affordable(0, 2_250_000, out spent, out _, out need); + Check.Eq(k, 2, "exactly enough buys both"); + Check.Eq(need, 1_562_500L, "nothing left for the 3rd"); + + k = c.Affordable(5, 8_904_758, out spent, out _, out need); + Check.Eq(k, 2, "8,904,758 from 5 bought: the 6th and 7th"); + Check.Eq(spent, 6_866_455L, "3,051,758 + 3,814,697"); + Check.Eq(need, 2_730_069L, "the 8th (4,768,372) less what is left"); + + k = c.Affordable(0, 0, out spent, out _, out need); + Check.Eq(k, 0, "nothing buys nothing"); + Check.Eq(need, 1_000_000L, "the 1st needs all of it"); + + k = AbilityCurve.Experience.Affordable(0, long.MaxValue - 1, out spent, out _, out need); + Check.True(k > 40 && k < 54, $"the experience lane stops before long.MaxValue ({k})"); + Check.True(spent > 0 && spent < long.MaxValue, "and what it spent fits"); + } + + private static void Fit() + { + AbilityCurve c = AbilityCurve.Luminance; + AbilityCurve same = c.Fit(5, 3_051_758, out bool matches); + Check.True(matches, "the server's own price matches"); + Check.Eq(same, c, "and the curve is kept"); + + AbilityCurve scaled = c.Fit(5, 6_103_516, out matches); + Check.False(matches, "a doubled price doesn't"); + Check.Eq(scaled.Cost(6), 6_103_516L, "the scaled curve gives the quote"); + Check.Eq(scaled.Cost(1), 2_000_000L, "and doubles the rest"); + + c.Fit(5, 0, out matches); + Check.True(matches, "no quote: kept"); + } + + private static DreamWeaveAbilityPoints Asked(out long t) + { + var p = new DreamWeaveAbilityPoints(); + t = 1_000_000; + p.Login(); + p.CheckSoon(); + Check.Eq(p.Due(t, canSend: true, quiet: true), DreamWeaveAbilityPoints.Command, "the read goes"); + p.NoteChatBar(); // our own send through the chat bar + return p; + } + + private static void Replies() + { + var p = Asked(out long t); + Check.True(p.OnChatText(Points, Broadcast, t + 100, Utc), "points line hidden"); + Check.True(p.OnChatText(Lum, Broadcast, t + 110, Utc), "luminance line hidden"); + Check.True(p.OnChatText(Xp, Broadcast, t + 120, Utc), "experience line hidden"); + Check.Eq(p.Available, 12, "available"); + Check.Eq(p.Earned, 30, "earned"); + Check.Eq(p.LumBought, 5, "luminance bought"); + Check.Eq(p.LumNext, 3_051_758L, "its next price"); + Check.True(p.LumMatches, "the published curve gives it"); + Check.Eq(p.XpBought, 2, "experience bought"); + Check.Eq(p.XpNext, 392_000_000_000L, "its next price"); + Check.True(p.XpMatches, "the published curve gives it"); + Check.Eq(p.UnassignedXp, 1_234_567L, "unassigned experience from the reply"); + Check.Null(p.XpUnlockLevel, "the lane is open"); + Check.True(p.HasReading, "a reading"); + Check.Eq(p.ReadUtc, Utc, "read now"); + Check.False(p.Waiting(t + 130), "the reply is complete"); + + p = Asked(out t); + p.OnChatText(Points, Broadcast, t + 100, Utc); + p.OnChatText(Lum, Broadcast, t + 110, Utc); + Check.True(p.OnChatText(XpLocked, Broadcast, t + 120, Utc), "the locked line hidden"); + Check.Eq(p.XpUnlockLevel, 275, "opens at 275"); + Check.Eq(p.Level, 200, "the level from the line"); + Check.Eq(p.XpBought, 0, "none bought below it"); + Check.Null(p.XpNext, "no quote"); + Check.False(p.Waiting(t + 130), "the reply is complete"); + + p = Asked(out t); + Check.True(p.OnChatText(Off, Broadcast, t + 100, Utc), "the off line hidden"); + Check.True(p.Off, "class abilities are off"); + Check.False(p.Waiting(t + 110), "and that is the whole reply"); + + // A timestamped line and one message holding the whole reply. + p = Asked(out t); + Check.True(p.OnChatText("[22:01:05] " + Points + "\n" + Lum + "\r\n" + Xp, Broadcast, t + 100, Utc), "one message, hidden"); + Check.Eq(p.LumBought, 5, "read"); + Check.Eq(p.XpBought, 2, "read"); + + // A price the curve doesn't give: scaled to it. + p = Asked(out t); + p.OnChatText("Luminance purchases: 5 bought so far; the next point costs 6,103,516 Luminance. Exchange it.", Broadcast, t + 100, Utc); + Check.False(p.LumMatches, "a changed price is seen"); + Check.Eq(p.LumCurve.Cost(6), 6_103_516L, "the lane's curve gives the quote"); + } + + private static void OursAndTyped() + { + // Typed: the chat bar sees a /abilities points we didn't send. + var p = new DreamWeaveAbilityPoints(); + long t = 1_000_000; + p.Login(); + p.NoteChatBar(); + Check.False(p.OnChatText(Points, Broadcast, t, Utc), "a typed command's reply shows"); + Check.False(p.OnChatText(Lum, Broadcast, t + 10, Utc), "all of it"); + Check.False(p.OnChatText(Xp, Broadcast, t + 20, Utc), "all of it"); + Check.Eq(p.LumBought, 5, "and is read"); + + // Ours, then the player types one while it is on its way: theirs shows. + p = Asked(out t); + p.NoteChatBar(); // the player's + Check.False(p.OnChatText(Points, Broadcast, t + 100, Utc), "the player's reply shows"); + + // After our reply, the same lines (a /abilities list ends with Points:) show. + p = Asked(out t); + p.OnChatText(Points + "\n" + Lum + "\n" + Xp, Broadcast, t + 100, Utc); + Check.False(p.OnChatText(Points, Broadcast, t + 500, Utc), "a later Points line shows"); + Check.Eq(p.Available, 12, "and is read"); + + // The window: a reply 5 s late isn't ours. + p = Asked(out t); + Check.False(p.OnChatText(Lum, Broadcast, t + 6_000, Utc), "too late to be ours"); + } + + private static void NotRead() + { + var p = Asked(out long t); + Check.False(p.OnChatText(Lum, Tell, t + 100, Utc), "a tell isn't read"); + Check.Null(p.LumBought, "nothing read"); + Check.False(p.OnChatText("Someone says, \"" + Lum + "\"", Broadcast, t + 100, Utc), "a quoted copy isn't read"); + Check.Null(p.LumBought, "nothing read"); + Check.False(p.OnChatText("You gain 5 class ability points from spending 1 Luminance. Available: 99.", Tell, t + 100, Utc), "a grant in a tell isn't read"); + Check.Null(p.Available, "nothing read"); + } + + private static void Grants() + { + var p = Asked(out long t); + p.OnChatText(Points + "\n" + Lum + "\n" + Xp, Broadcast, t + 100, Utc); + int rev = p.Revision; + Check.False(p.OnChatText("You gain 1 class ability point from spending 3,051,758 Luminance. Available: 13. Use /abilities to spend them.", + Advancement, t + 10_000, Utc), "a grant shows"); + Check.Eq(p.LumBought, 6, "the luminance lane moves on"); + Check.Null(p.LumNext, "its quote is stale"); + Check.Eq(p.Available, 13, "available"); + Check.Eq(p.Earned, 31, "earned"); + Check.True(p.Wanted, "a read follows"); + Check.True(p.Revision != rev, "the page refills"); + + p = Asked(out t); + p.OnChatText(Points + "\n" + Lum + "\n" + Xp, Broadcast, t + 100, Utc); + p.OnChatText("You gain 2 class ability points from spending 672,000,000,000 experience. Available: 14. Use /abilities to spend them.", + Advancement, t + 10_000, Utc); + Check.Eq(p.XpBought, 4, "the experience lane moves on"); + Check.Eq(p.LumBought, 5, "the luminance lane doesn't"); + Check.True(p.Wanted, "a read follows"); + + p = Asked(out t); + p.OnChatText(Points + "\n" + Lum + "\n" + Xp, Broadcast, t + 100, Utc); + p.OnChatText("You gain 1 class ability point from reaching level 300. Available: 13. Use /abilities to spend them.", + Advancement, t + 10_000, Utc); + Check.Eq(p.Available, 13, "a milestone moves the points"); + Check.Eq(p.LumBought, 5, "not a lane"); + Check.False(p.Wanted, "no read"); + + p.OnChatText("You have learned Arcane Surge rank 2/5. Points: 10 available, 31 lifetime earned.", Broadcast, t + 20_000, Utc); + Check.Eq(p.Available, 10, "learning moves the points"); + Check.Eq(p.Earned, 31, "earned"); + + // A purchase before any reading: no lane to move. + var q = new DreamWeaveAbilityPoints(); + q.Login(); + q.OnChatText("You gain 1 class ability point from spending 1,000,000 Luminance. Available: 1. Use /abilities to spend them.", Advancement, t, Utc); + Check.Null(q.LumBought, "unknown stays unknown"); + Check.Eq(q.Available, 1, "available"); + Check.False(q.Wanted, "no read without the page"); + } + + private static void ReadTiming() + { + var p = new DreamWeaveAbilityPoints(); + long t = 1_000_000; + p.Login(); + Check.False(p.Wanted, "nothing at login"); + Check.Null(p.Due(t, true, true), "nothing goes"); + p.PageOpened(); + Check.True(p.Wanted, "the page's first draw wants a read"); + Check.Null(p.Due(t, canSend: false, quiet: true), "not outside the world or in portal space"); + Check.Null(p.Due(t, canSend: true, quiet: false), "not near another command"); + Check.Eq(p.Due(t, true, true), DreamWeaveAbilityPoints.Command, "then it goes"); + Check.Null(p.Due(t + 10, true, true), "once"); + p.OnChatText(Points + "\n" + Lum + "\n" + Xp, Broadcast, t + 100, Utc); + p.PageOpened(); + Check.False(p.Wanted, "the page again: no second read"); + + p.CheckSoon(); + Check.True(p.Wanted, "Read now"); + Check.Eq(p.Due(t + 1_000, true, true), DreamWeaveAbilityPoints.Command, "goes"); + p.CheckSoon(); + Check.Null(p.Due(t + 1_100, true, true), "not while the last one waits for its reply"); + + p.Logout(); + p.Login(); + Check.False(p.HasReading, "a new login forgets the reading"); + p.PageOpened(); + Check.True(p.Wanted, "and reads again when the page opens"); + + p.Login(); + Check.Eq(p.Due(t, true, true), null, "login drops a wanted read"); + p.CheckSoon(); + p.Due(t, true, true); + p.NotSent(); + Check.False(p.Waiting(t), "a send that didn't go isn't waited for"); + } + + private static void Missed() + { + var p = Asked(out long t); + Check.False(p.Tick(t + 1_000), "still in time"); + Check.True(p.Tick(t + 6_000), "given up after 5 s"); + Check.True(p.LastMiss.Contains("No reply", StringComparison.Ordinal), "and said"); + Check.False(p.Tick(t + 7_000), "once"); + p.CheckSoon(); + Check.Eq(p.LastMiss, "", "Read now clears it"); + } + + private static DreamWeaveAbilityPoints ReadIn(out long t) + { + var p = Asked(out t); + p.OnChatText("Points: 0 available, 35 lifetime earned.\n" + + "Luminance purchases: 16 bought so far; the next point costs 127,300,154 Luminance. Exchange it at the reckoning-stone.\n" + + "Experience purchases: 3 bought so far; the next point costs 548,800,000,000 experience and you have 600,000,000,000 unassigned. Prices rise.", + Broadcast, t + 100, Utc); + t += 10_000; + return p; + } + + private static void BuyXp() + { + var p = ReadIn(out long t); + Check.Eq(p.BuyXp(1, t), "/abilities buyxp 1", "the command"); + Check.True(p.Buying(t + 10), "waits for its answer"); + Check.Null(p.BuyXp(1, t + 20), "one at a time"); + p.CheckSoon(); + Check.Null(p.Due(t + 30, true, true), "no read while a purchase waits"); + Check.False(p.OnChatText("You gain 1 class ability point from spending 548,800,000,000 experience. Available: 1. Use /abilities to spend them.", + Advancement, t + 500, Utc), "the grant shows"); + Check.Eq(p.XpBought, 4, "the lane moves on"); + Check.False(p.Buying(t + 600), "answered"); + Check.False(p.BuyFailed, "bought"); + Check.True(p.BuyMessage.StartsWith("Bought 1 point with experience (548,800,000,000)", StringComparison.Ordinal), p.BuyMessage); + Check.Eq(p.Due(t + 700, true, true), DreamWeaveAbilityPoints.Command, "then the read goes"); + + p = ReadIn(out t); + Check.Eq(p.BuyXp(5, t), "/abilities buyxp 5", "five at once"); + p.OnChatText("Buying 5 points costs 5,000,000,000,000 experience; you have 600,000,000,000 unassigned.", Broadcast, t + 300, Utc); + Check.True(p.BuyFailed, "refused"); + Check.True(p.BuyMessage.Contains("Not enough unassigned experience", StringComparison.Ordinal), p.BuyMessage); + Check.False(p.Buying(t + 400), "answered"); + Check.Eq(p.XpBought, 3, "nothing bought"); + + p = ReadIn(out t); + p.BuyXp(1, t); + p.OnChatText("You must be level 275 to exchange experience for class ability points. You are level 200.", Broadcast, t + 300, Utc); + Check.True(p.BuyFailed, "refused below the level"); + Check.Eq(p.XpUnlockLevel, 275, "the lane's level"); + Check.Eq(p.Level, 200, "yours"); + + p = ReadIn(out t); + p.BuyXp(1, t); + p.Tick(t + 1_000); + Check.False(p.BuyFailed, "still in time"); + p.Tick(t + DreamWeaveAbilityPoints.BuyWindowMs + 1); + Check.True(p.BuyFailed, "no answer is said"); + Check.True(p.BuyMessage.Contains("No answer", StringComparison.Ordinal), p.BuyMessage); + Check.False(p.Buying(t + DreamWeaveAbilityPoints.BuyWindowMs + 2), "and given up"); + + p = ReadIn(out t); + Check.Null(p.BuyXp(0, t), "no points, no command"); + p.BuyXp(1, t); + p.BuyNotSent("Couldn't send it."); + Check.False(p.Buying(t + 1), "not waiting for a send that didn't go"); + Check.True(p.BuyFailed, "and said"); + + // A refusal that isn't the answer to the page's purchase (typed by hand) is read but not said. + p = ReadIn(out t); + p.OnChatText("Buying 1 point costs 548,800,000,000 experience; you have 5 unassigned.", Broadcast, t, Utc); + Check.Eq(p.BuyMessage, "", "not said"); + Check.Eq(p.UnassignedXp, 5L, "but read"); + } + + private static void Stone() + { + var p = ReadIn(out long t); + p.SetStone(known: false, near: true); + Check.False(p.StoneNear, "an unknown stone is never near"); + p.SetStone(known: true, near: true); + Check.True(p.StoneNear, "known and near"); + + p.StoneUsed(t); + Check.True(p.Buying(t + 30_000), "the walk and AC's Yes/No take a while"); + Check.False(p.OnChatText("Reckoning-Stone of Radiance: this weighs your Luminance and renders it as a class ability point. Each point costs more than the last; the only limit is the price.", + Broadcast, t + 2_000, Utc), "the stone's words show"); + Check.True(p.Buying(t + 2_100), "still waiting"); + p.OnChatText("Your next point would cost 127,300,154 Luminance; you have 56,700,791 (0 available + 56,700,791 banked).", Broadcast, t + 2_200, Utc); + Check.True(p.BuyFailed, "not enough"); + Check.True(p.BuyMessage.Contains("Not enough luminance", StringComparison.Ordinal), p.BuyMessage); + Check.Eq(p.StoneSpendable, 56_700_791L, "what the stone counted"); + Check.Eq(p.StoneOnYou, 0L, "on you"); + Check.Eq(p.LumNext, 127_300_154L, "its price"); + Check.True(p.LumMatches, "the curve's"); + + p = ReadIn(out t); + p.StoneUsed(t); + p.OnChatText("You gain 1 class ability point from spending 127,300,154 Luminance. Available: 1. Use /abilities to spend them.", Advancement, t + 9_000, Utc); + Check.Eq(p.LumBought, 17, "bought through the stone"); + Check.False(p.BuyFailed, "bought"); + Check.True(p.BuyMessage.StartsWith("Bought 1 point with luminance (127,300,154)", StringComparison.Ordinal), p.BuyMessage); + Check.False(p.Buying(t + 9_100), "answered"); + + p = ReadIn(out t); + p.StoneUsed(t); + p.OnChatText("Buying 1 point costs 127,300,154 Luminance; you have 100 (0 available + 100 banked).", Broadcast, t + 9_000, Utc); + Check.True(p.BuyFailed, "a Yes it couldn't honour"); + Check.Eq(p.StoneSpendable, 100L, "what it counted"); + + p = ReadIn(out t); + p.OnChatText("Your next point would cost 127,300,154 Luminance; you have 56,700,791 (5 available + 56,700,786 banked).", Broadcast, t, Utc); + Check.Eq(p.BuyMessage, "", "a stone used by hand: not said"); + Check.Eq(p.StoneOnYou, 5L, "but read"); + + p = ReadIn(out t); + p.StoneUsed(t); + p.Tick(t + DreamWeaveAbilityPoints.StoneWindowMs + 1); + Check.False(p.Buying(t + DreamWeaveAbilityPoints.StoneWindowMs + 2), "a stone use not answered is let go"); + Check.False(p.BuyFailed, "quietly: the player may have said No"); + } + + private static void Rates() + { + var r = new EarnRate(); + Check.Null(r.PerHour(1), "nothing yet"); + r.Add(0, 1_000); + Check.Null(r.PerHour(1), "one reading"); + r.Add(30 * 60_000, 1_600); + Check.Null(r.PerHour(60 * 60_000), "not long enough"); + Check.Near(r.PerHour(10 * 60_000) ?? -1, 1_200, 1e-9, "600 in 30 min"); + r.Spent(500); // a point bought: the bank drops by 500 + r.Add(60 * 60_000, 1_700); + Check.Near(r.PerHour(1) ?? -1, 1_200, 1e-9, "the purchase is added back"); + r.Add(70 * 60_000, 100); + Check.Null(r.PerHour(1), "a drop nothing explains starts again"); + r.Add(130 * 60_000, 700); + Check.Near(r.PerHour(1) ?? -1, 600, 1e-9, "from there"); + r.Clear(); + Check.Null(r.PerHour(1), "cleared"); + + Check.Eq(EarnRate.Time(0, 100), "now", "nothing needed"); + Check.Eq(EarnRate.Time(500, 1_000), "about 30 min", "half an hour"); + Check.Eq(EarnRate.Time(3_500, 1_000), "about 3.5 h", "hours and a half"); + Check.Eq(EarnRate.Time(70_599_363, 1_200_000), "about 59 h", "59 hours"); + Check.Eq(EarnRate.Time(100, 1), "about 4 days", "days"); + Check.Eq(EarnRate.Time(100, 0), "", "never at nothing an hour"); + Check.Eq(EarnRate.Time(1, 1e9), "about 1 min", "at least a minute"); + } + + private static void StageAndLive() + { + Check.Eq(AbilityText.Stage(AbilityCurve.Luminance, 2), "each point costs x1.25 the last up to the 10th, then x1.5 up to the 20th, then x1.75", "early"); + Check.Eq(AbilityText.Stage(AbilityCurve.Luminance, 18), "each point costs x1.5 the last up to the 20th, then x1.75", "middle"); + Check.Eq(AbilityText.Stage(AbilityCurve.Luminance, 21), "each point costs x1.75 the last, with no end", "tail"); + Check.Eq(AbilityText.Stage(AbilityCurve.Experience, 5), "each point costs x1.4 the last, with no end", "experience"); + // DreamWeave's own quotes for one character on 2026-11-17 (/abilities points): 16 bought with luminance, 3 with experience. + Check.Eq(AbilityCurve.Luminance.Cost(17), 127_300_154L, "the 17th luminance point, as quoted"); + Check.Eq(AbilityCurve.Experience.Cost(4), 548_800_000_000L, "the 4th experience point, as quoted"); + } + + private static void Text() + { + Check.True(DreamWeaveAbilityPoints.IsCommand("/abilities points"), "the command"); + Check.True(DreamWeaveAbilityPoints.IsCommand(" /Abilities POINTS "), "any case and spacing"); + Check.False(DreamWeaveAbilityPoints.IsCommand("/abilities"), "not the list"); + Check.False(DreamWeaveAbilityPoints.IsCommand("/abilities buyxp 1"), "not a purchase"); + + Check.Eq(AbilityText.Ordinal(1), "1st", "1st"); + Check.Eq(AbilityText.Ordinal(2), "2nd", "2nd"); + Check.Eq(AbilityText.Ordinal(3), "3rd", "3rd"); + Check.Eq(AbilityText.Ordinal(4), "4th", "4th"); + Check.Eq(AbilityText.Ordinal(11), "11th", "11th"); + Check.Eq(AbilityText.Ordinal(12), "12th", "12th"); + Check.Eq(AbilityText.Ordinal(13), "13th", "13th"); + Check.Eq(AbilityText.Ordinal(21), "21st", "21st"); + Check.Eq(AbilityText.Ordinal(112), "112th", "112th"); + Check.Eq(AbilityText.Num(3_051_758), "3,051,758", "under a billion: exact only"); + Check.Eq(AbilityText.Num(392_000_000_000), "392,000,000,000 (392 billion)", "with words"); + Check.Eq(AbilityText.Words(4_132_209_356_800), "4.13 trillion", "two places under ten"); + Check.Eq(AbilityText.Words(25_045_871_734), "25 billion", "one place under a hundred, dropped when 0"); + Check.Eq(AbilityText.Num(long.MaxValue), "more than 9.2 quintillion", "past the top"); + + Check.Eq(AbilityText.Lane("Luminance", AbilityCurve.Luminance, 5, 8_904_758, "banked"), + "Luminance: 5 bought; the 6th costs 3,051,758; your 8,904,758 banked buys 2 more (6,866,455), the 8th needs 2,730,069 more", + "the lane's sentence"); + Check.Eq(AbilityText.Lane("Experience", AbilityCurve.Experience, 0, 1_000, "unassigned"), + "Experience: 0 bought; the 1st costs 200,000,000,000 (200 billion); your 1,000 unassigned is 199,999,999,000 (200 billion) short of it", + "short of the next"); + Check.Eq(AbilityText.Range("Luminance", AbilityCurve.Luminance, 5, 5), + "Luminance: points 6 to 10 cost 25,045,872 in all (3,051,758, 3,814,697, 4,768,372, 5,960,464, 7,450,581)", "a range"); + Check.Eq(AbilityText.Range("Luminance", AbilityCurve.Luminance, 0, 1), "Luminance: the 1st point costs 1,000,000", "one point"); + + var p = Asked(out long t); + Check.Eq(p.Summary(null), "Your class ability points aren't read yet", "before a reading"); + p.OnChatText(Points + "\n" + Lum + "\n" + XpLocked, Broadcast, t + 100, Utc); + Check.Eq(p.Summary(8_904_758), + "Class ability points: 12 available, 30 earned. " + + "Luminance: 5 bought; the 6th costs 3,051,758; your 8,904,758 banked buys 2 more (6,866,455), the 8th needs 2,730,069 more. " + + "Experience: opens at level 275 (you are 200)", "the summary"); + } +} diff --git a/Tools/RynthServerPack.Tests/DreamWeaveTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveTests.cs index 5a32ae7..4b313d3 100644 --- a/Tools/RynthServerPack.Tests/DreamWeaveTests.cs +++ b/Tools/RynthServerPack.Tests/DreamWeaveTests.cs @@ -126,13 +126,15 @@ internal static class DreamWeaveTests Check.Eq(b.Published, (long?)150_000, "the deposit isn't earned"); b.OnChatLine("[BANK] Luminance: 180,000", t + 130_000); Check.Eq(b.Published, (long?)160_000, "earned after it counts"); + // R-20261125-230220-95f8: earned luminance goes straight into the bank, so a deposit all is a reading + // (a meta's "/b d" counted everything earned since the last reading as moved in: Lum/hr 6.6m vs 71m). b.OnChatLine("[BANK] Deposited all. Pyreals: 1,000 | Luminance: 230,000 | Keys: 1 | Promissory Notes: 0", t + 140_000); - Check.Eq(b.MovedIn, 70_000L, "deposit all: what the bank gained since the reading moved in"); - Check.Eq(b.Published, (long?)160_000, "deposit all isn't earned"); + Check.Eq(b.MovedIn, 20_000L, "deposit all moves nothing it can name"); + Check.Eq(b.Published, (long?)210_000, "what the bank gained before it counts as earned"); b.OnChatLine("[BANK] Luminance: 30,000", t + 200_000); - Check.Eq(b.Published, (long?)0, "spending from the bank is a drop (readers don't count drops), never below 0"); + Check.Eq(b.Published, (long?)10_000, "spending from the bank is a drop (readers don't count drops), never below 0"); b.OnChatLine("[BANK] Luminance: 35,000", t + 260_000); - Check.Eq(b.Published, (long?)5_000, "and what comes after it counts"); + Check.Eq(b.Published, (long?)15_000, "and what comes after it counts"); } private static void Pasted() diff --git a/Tools/RynthServerPack.Tests/Program.cs b/Tools/RynthServerPack.Tests/Program.cs index 4a8b349..474eace 100644 --- a/Tools/RynthServerPack.Tests/Program.cs +++ b/Tools/RynthServerPack.Tests/Program.cs @@ -24,6 +24,7 @@ internal static class Program DreamWeaveTests.Register(runner); DreamWeaveBoardsTests.Register(runner); DreamWeaveXpBonusTests.Register(runner); + DreamWeaveAbilitiesTests.Register(runner); ServerWebOpenTests.Register(runner); ServerWebPanelTests.Register(runner); DreamWeaveWebTests.Register(runner); diff --git a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj index 6afdf10..2ea2d2c 100644 --- a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj +++ b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj @@ -59,6 +59,9 @@ + + +