RynthServers as of 2026-11-17 (internal 2bf93a4): release 2026.11.17.1

This commit is contained in:
Tom Bohar 2026-11-17 10:32:01 -05:00
commit 4b09478f12
24 changed files with 3676 additions and 261 deletions

View file

@ -74,8 +74,12 @@ internal static class AttributesPage
public static bool CanRaiseOne(SkillsSheet sheet, AttributeLine a)
=> a.Raisable && a.CostOne > 0 && sheet.UnassignedXp >= a.CostOne;
/// <summary>"+10": ten ranks, or the last ones when fewer than ten are left, as retail (SkillsLayout.TenStep).</summary>
public static bool CanRaiseTen(SkillsSheet sheet, AttributeLine a)
=> a.Raisable && a.CostTen > 0 && sheet.UnassignedXp >= a.CostTen;
=> a.Raisable && Ten(a) is { Ranks: > 0 } t && sheet.UnassignedXp >= t.Cost;
public static (uint Ranks, long Cost) Ten(AttributeLine a)
=> SkillsLayout.TenStep(a.IsVital ? RetailData.VitalXp : RetailData.AttributeXp, a.Ranks, a.XpSpent, a.CostTen);
/// <summary>The way through the current rank (0..1) on the attribute or vital chart: the footer's blue bar.</summary>
public static float RankProgress(AttributeLine a)

View file

@ -0,0 +1,330 @@
// BoardsPage.cs - RynthDreamWeave's Leaderboards page (2026-11-15): a tab of the DreamWeave window on
// RynthCore's bar (and of the /rserver window), drawn the way the plugin's Character panel is (SkillsPanel.cs,
// through the same RetailCanvas helpers): retail's tiled page, Palatino dat fonts, the skill list's section
// banners and 20-pixel rows with the blue selected-row bar, the chain scrollbar, the rule over the footer, a
// footer with a Palatino 20 title and two label/value lines, retail's red buttons and its tooltip box.
//
// left every board, under three banners (Character, Proving Grounds, PvP Arena), with your rank on each:
// the summary, and the board picker (click a row);
// right the board picked: its title and age, the rows (yours highlighted in gold), "..." and your row when
// you are below the list, and what the server added (an empty board, a cut list, a refusal);
// footer your place on that board, the automatic refresh, and the Refresh now, Read all boards and Auto
// refresh buttons (right-click the page for the same setting as a checkbox, as on the Character panel).
// Render thread: draws holding the boards' lock, and queues what it sends for the tick.
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.ServerPack;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDreamWeave;
internal sealed class BoardsPage
{
private const int RowH = RetailCanvas.RowH, RuleH = RetailCanvas.RuleH, ScrollW = RetailCanvas.ScrollW;
private const int FooterH = 20 + 17 + 18 + 4 + 32 + 4;
private const int TwoColumnsFrom = 500, LeftW = 200, Gap = 5;
private const uint White = RetailCanvas.White;
private static readonly uint Gold = RetailCanvas.Gold, Body = RetailCanvas.Body, Grey = RetailCanvas.TabOff;
/// <summary>The left list's sections: a banner (its picture) and its boards.</summary>
private static readonly (string Title, uint Art, string[] Keys)[] Sections =
{
("Character", RetailCanvas.ArtBannerTrained, new[] { "level", "bank", "cap", "stamp", "thread", "knot", "title", "deaths" }),
("Proving Grounds", RetailCanvas.ArtBannerSpecialized, new[] { "dps", "defense", "wave", "speed", "winners" }),
("PvP Arena", RetailCanvas.ArtBannerUntrained, new[] { "1v1", "2v2", "tugak", "bg" }),
};
private readonly DreamWeaveBoards _b;
private readonly Func<bool> _active;
private readonly Func<RynthCoreHost> _host;
private readonly Func<int> _scale;
private readonly Action<Action> _runOnTick;
private readonly Action<string> _refresh;
private readonly Action _sweep;
private readonly Action<bool> _setAuto;
private RetailCanvas? _c;
private string _selected = "level";
private float _listScroll, _rowScroll;
private string _scrolledFor = "";
/// <param name="scale">The DreamWeave window's draw size in percent (Ctrl+wheel; 0 when unknown).</param>
/// <param name="refresh">Asks for one board now (pump thread, queued with runOnTick).</param>
/// <param name="sweep">Reads every board, one every few seconds (pump thread).</param>
/// <param name="setAuto">Turns the automatic refresh on or off and saves it (pump thread).</param>
public BoardsPage(DreamWeaveBoards boards, Func<bool> active, Func<RynthCoreHost> host, Func<int> scale,
Action<Action> runOnTick, Action<string> refresh, Action sweep, Action<bool> setAuto)
{
_b = boards;
_active = active;
_host = host;
_scale = scale;
_runOnTick = runOnTick;
_refresh = refresh;
_sweep = sweep;
_setAuto = setAuto;
}
public ServerPage Page() => new("boards", "Leaderboards",
"DreamWeave's leaderboards (/top), with your rank on every board (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;
}
_c ??= new RetailCanvas(_host());
Vector2 start = ImGui.GetCursorScreenPos();
Vector2 avail = ImGui.GetContentRegionAvail();
int pct = _scale();
float k = pct > 0 ? Math.Clamp(pct / 100f, 0.3f, 2.5f) : 1f;
int w = Math.Max(280, (int)(avail.X / k));
int h = avail.Y / k >= 360 ? (int)(avail.Y / k) : 460;
_c.Begin(ImGui.GetWindowDrawList(), new Vector2(MathF.Round(start.X), MathF.Round(start.Y)), k);
_c.ClearHover();
lock (_b.Gate)
{
if (DreamWeaveBoards.Def(_selected) == null) _selected = "level";
_c.PageBackground(0, 0, w, h);
int ruleY = h - FooterH - RuleH - 3;
if (w >= TwoColumnsFrom)
{
BoardList(0, 0, LeftW, ruleY - 2);
_c.Sprite(RetailCanvas.ArtColumnRule, LeftW, 0, Gap, ruleY, 0xFF54788Fu);
Board(LeftW + Gap, 0, w - LeftW - Gap, ruleY - 2);
}
else
{
int listH = Math.Min(8 * RowH, (ruleY - 2) / 2);
BoardList(0, 0, w, listH);
_c.Sprite(RetailCanvas.ArtRule, 0, listH, w, RuleH, 0xFF54788Fu);
Board(0, listH + RuleH + 2, w, ruleY - 2 - (listH + RuleH + 2));
}
Footer(w, h, ruleY);
}
_c.UpdateTooltip();
OptionsMenu(w, h);
_c.Tooltip();
ImGui.SetCursorScreenPos(start);
ImGui.Dummy(new Vector2(w * k, h * k));
}
// ── Every board and your rank on it (the board picker) ──────────────
private void BoardList(int x0, int top, int width, int height)
{
RetailCanvas c = _c!;
var rows = new List<string?>(); // null = a section banner (by order), else a board key
var banners = new List<int>();
foreach (var s in Sections)
{
banners.Add(rows.Count);
rows.Add(null);
foreach (string key in s.Keys) rows.Add(key);
}
int visible = Math.Max(1, height / RowH);
bool scroll = rows.Count > visible;
int rowW = scroll ? width - ScrollW - 1 : width;
float maxScroll = Math.Max(0, rows.Count - visible);
ImGui.SetCursorScreenPos(c.P(x0, top));
ImGui.InvisibleButton("##dw_boards_list", c.S(rowW, height));
bool hovered = ImGui.IsItemHovered(), clicked = ImGui.IsItemClicked(ImGuiMouseButton.Left);
if (hovered && !ImGui.GetIO().KeyCtrl) _listScroll -= ImGui.GetIO().MouseWheel * 3;
_listScroll = Math.Clamp(_listScroll, 0, maxScroll);
int first = (int)MathF.Round(_listScroll);
c.Dl.PushClipRect(c.P(x0, top), c.P(x0 + rowW, top + height), true);
try
{
for (int i = first, y = top; i < rows.Count && y < top + height; i++, y += RowH)
{
string? key = rows[i];
if (key == null)
{
var s = Sections[banners.IndexOf(i)];
c.SpriteCropped(s.Art, x0, y, rowW, RowH, 282, 20, 0xFF3A1E2Au);
c.Text(RetailData.Pal18, s.Title, x0 + 4, y, rowW - 8, RowH, White);
continue;
}
BoardDef d = DreamWeaveBoards.Def(key)!;
if (key == _selected) c.SpriteCropped(RetailCanvas.ArtRowSelected, x0, y, rowW, RowH, 282, 20, 0x60206080u);
BoardStanding st = _b.Standing(key);
string rank = !st.Read ? "" : st.Rank == 0 ? "-" : "#" + st.Rank;
uint rankColor = !st.Read || st.Rank == 0 ? Grey : st.OutsideList ? White : Gold;
int rankW = Math.Max(RetailData.Pal16.Measure(rank), 30);
c.Text(RetailData.Pal16, RetailCanvas.Fit(RetailData.Pal16, d.Label, rowW - rankW - 14), x0 + 6, y, rowW - rankW - 10, RowH,
_b.Result(key) != null ? White : Grey);
c.Text(RetailData.Pal16, rank, x0 + rowW - rankW - 4, y, rankW, RowH, rankColor, right: true);
if (clicked && c.Hit(x0, y, rowW, RowH)) Select(key);
if (hovered && c.Hit(x0, y, rowW, RowH))
c.Hover(100u + (uint)i, $"{d.Help}.\nYou: {_b.StandingText(key)}. {AgeText(key)}.\n{d.Command}");
}
}
finally { c.Dl.PopClipRect(); }
if (scroll) c.ScrollBar("boards_list", x0 + width - ScrollW, ref _listScroll, top, height, visible, rows.Count, maxScroll);
}
private void Select(string key)
{
_selected = key;
_rowScroll = 0;
}
// ── The board picked ────────────────────────────────────────────────
private void Board(int x0, int top, int width, int height)
{
RetailCanvas c = _c!;
BoardDef d = DreamWeaveBoards.Def(_selected)!;
BoardResult? r = _b.Result(_selected);
string title = d.Key == "speed" && r != null && r.Title.Length > 0 ? r.Title : d.Label;
c.Text(RetailData.Pal18, RetailCanvas.Fit(RetailData.Pal18, title, width - 8), x0, top, width, 20, White, center: true);
string sub = _b.PendingKey == _selected ? "Waiting for the reply..."
: _b.LastMiss.Length > 0 && r == null ? _b.LastMiss
: r == null ? "Not read yet: press Refresh now." : AgeText(_selected);
c.Text(RetailData.Pal14, sub, x0, top + 20, width, 16, Body, center: true);
c.Sprite(RetailCanvas.ArtRule, x0, top + 37, width, RuleH, 0xFF54788Fu);
int listTop = top + 37 + RuleH + 2, listH = height - (listTop - top);
if (listH < RowH) return;
var lines = new List<(BoardRow? Row, string Text)>(); // a row, or a line of text ("..." or a note)
if (r != null)
{
foreach (BoardRow row in r.Rows) lines.Add((row, ""));
if (r.Below != null) { lines.Add((null, "...")); lines.Add((r.Below, "")); }
if (r.Note.Length > 0)
foreach (string l in RetailData.Pal14.Wrap(r.Note, width - ScrollW - 12)) lines.Add((null, l));
}
if (_scrolledFor != _selected) { _scrolledFor = _selected; _rowScroll = 0; }
int visible = Math.Max(1, listH / RowH);
bool scroll = lines.Count > visible;
int rowW = scroll ? width - ScrollW - 1 : width;
float maxScroll = Math.Max(0, lines.Count - visible);
ImGui.SetCursorScreenPos(c.P(x0, listTop));
ImGui.InvisibleButton("##dw_board_rows", c.S(rowW, listH));
bool hovered = ImGui.IsItemHovered();
if (hovered && !ImGui.GetIO().KeyCtrl) _rowScroll -= ImGui.GetIO().MouseWheel * 3;
_rowScroll = Math.Clamp(_rowScroll, 0, maxScroll);
int first = (int)MathF.Round(_rowScroll);
c.Dl.PushClipRect(c.P(x0, listTop), c.P(x0 + rowW, listTop + listH), true);
try
{
if (r == null || (r.Rows.Count == 0 && r.Below == null && r.Note.Length == 0))
c.Text(RetailData.Pal16, r == null ? "Nothing read yet." : "Nobody is on this board yet.", x0, listTop, rowW, RowH * 2, White, center: true);
for (int i = first, y = listTop; i < lines.Count && y < listTop + listH; i++, y += RowH)
{
(BoardRow? row, string text) = lines[i];
if (row == null)
{
if (text == "...") c.Text(RetailData.Pal16, text, x0, y, rowW, RowH, Grey, center: true);
else c.Text(RetailData.Pal14, text, x0 + 6, y, rowW - 12, RowH, Body);
continue;
}
bool you = _b.IsYou(row);
if (you) c.SpriteCropped(RetailCanvas.ArtRowSelected, x0, y, rowW, RowH, 282, 20, 0x60206080u);
(string name, string value, string tip) = Cells(d, row);
uint color = you ? Gold : White;
int valueW = Math.Min(RetailData.Pal16.Measure(value), (rowW - 40) / 2);
c.Text(RetailData.Pal16, row.Rank.ToString(System.Globalization.CultureInfo.InvariantCulture), x0, y, 30, RowH, color, right: true);
c.Text(RetailData.Pal16, RetailCanvas.Fit(RetailData.Pal16, name, rowW - 40 - valueW - 10), x0 + 38, y, rowW - 48 - valueW, RowH, color);
c.Text(RetailData.Pal16, RetailCanvas.Fit(RetailData.Pal16, value, valueW), x0 + rowW - valueW - 4, y, valueW, RowH, color, right: true);
if (hovered && c.Hit(x0, y, rowW, RowH)) c.Hover(1000u + (uint)i, tip);
}
}
finally { c.Dl.PopClipRect(); }
if (scroll) c.ScrollBar("board_rows", x0 + width - ScrollW, ref _rowScroll, listTop, listH, visible, lines.Count, maxScroll);
}
/// <summary>A row's name and value columns, and its tooltip (the whole line).</summary>
private static (string Name, string Value, string Tip) Cells(BoardDef d, BoardRow row)
{
string you = row.Account ? " (your account)" : row.Marked ? " (you)" : "";
return d.Kind switch
{
BoardKind.Arena => (row.Name, row.Value, $"{row.Rank}. {row.Name}: rating {row.Value} ({row.Detail})"),
BoardKind.SpeedWinners => (row.Detail, row.Name, row.Value.Length > 0
? $"{row.Detail}: won by {row.Name} in {row.Value}" : $"{row.Detail}: unclaimed"),
_ => (row.Name + you, row.Value, $"{row.Rank}. {row.Name}{you}: {row.Value}"),
};
}
private string AgeText(string key)
{
BoardResult? r = _b.Result(key);
if (r == null) return "Not read yet";
string age = DreamWeaveBoards.Age(r.UpdatedUtc, DateTime.UtcNow);
age = char.ToUpperInvariant(age[0]) + age[1..];
return r.Cut ? age + " (cut short; left out of the automatic refresh)" : age;
}
// ── The footer: your place, the automatic refresh, the buttons ─────
private void Footer(int w, int h, int ruleY)
{
RetailCanvas c = _c!;
c.Sprite(RetailCanvas.ArtRule, 0, ruleY, w, RuleH, 0xFF54788Fu);
int y = h - FooterH;
BoardDef d = DreamWeaveBoards.Def(_selected)!;
BoardStanding st = _b.Standing(_selected);
string place = _b.StandingText(_selected);
c.Text(RetailData.Pal20, $"{d.Label}: {place}", 0, y, w, 20, st.Read && st.Rank > 0 ? White : Body, center: true);
c.Text(RetailData.Pal16, "Your place", 5, y + 20, 140, 17, White);
string value = !st.Read ? "Press Refresh now" : st.Rank == 0 ? "-" : st.Value;
c.Text(RetailData.Pal16, RetailCanvas.Fit(RetailData.Pal16, value, w - 155), 145, y + 20, w - 150, 17, White, right: true);
c.Text(RetailData.Pal16, "Refresh automatically", 5, y + 37, 160, 18, White);
string auto = !_b.AutoRefresh ? "Off"
: _b.SweepLeft > 0 ? $"On (reading all: {_b.SweepLeft} left)" : "On: every board about every 10 min";
if (!_b.AutoRefresh && _b.SweepLeft > 0) auto = $"Off (reading all: {_b.SweepLeft} left)";
c.Text(RetailData.Pal16, RetailCanvas.Fit(RetailData.Pal16, auto, w - 175), 165, y + 37, w - 170, 18, White, right: true);
if (c.Hit(0, y + 37, w, 18))
c.Hover(3u, "On: RynthDreamWeave sends one board's /top every 35 seconds while you are in the world, so each "
+ "board is about ten minutes old at most, and keeps its replies out of chat. A /top you type "
+ "always shows. A board too long for RynthCore to hide is left out. Off by default.");
int by = y + 20 + 17 + 18 + 4;
int bw = (w - 4 * 6) / 3;
bool shortLabels = bw < 150;
bool waiting = _b.Pending;
if (c.RedButton("##dw_boards_refresh", shortLabels ? "Refresh" : "Refresh now", 6, by, bw, !waiting))
{
string key = _selected;
_runOnTick(() => _refresh(key));
}
if (c.Hit(6, by, bw, 32)) c.Hover(4u, $"Sends {d.Command} now and reads the reply (kept out of chat).");
if (c.RedButton("##dw_boards_all", shortLabels ? "Read all" : "Read all boards", 12 + bw, by, bw, _b.SweepLeft == 0))
_runOnTick(_sweep);
if (c.Hit(12 + bw, by, bw, 32))
c.Hover(5u, $"Reads every board once, one every {DreamWeaveBoards.SweepIntervalMs / 1000} seconds (about two minutes), replies kept out of chat.");
bool on = _b.AutoRefresh;
string autoLabel = shortLabels ? (on ? "Auto: On" : "Auto: Off") : (on ? "Auto refresh: On" : "Auto refresh: Off");
if (c.RedButton("##dw_boards_auto", autoLabel, 18 + 2 * bw, by, bw, true)) _runOnTick(() => _setAuto(!on));
if (c.Hit(18 + 2 * bw, by, bw, 32)) c.Hover(6u, "Refresh leaderboards automatically: one board every 35 seconds, each about every ten minutes.");
}
/// <summary>Right-click the page: its setting as a checkbox (the Character panel's options menu).</summary>
private void OptionsMenu(int w, int h)
{
RetailCanvas c = _c!;
if (ImGui.IsMouseClicked(ImGuiMouseButton.Right) && c.Hit(0, 0, w, h) && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows))
ImGui.OpenPopup("##dw_boards_options");
if (!ImGui.BeginPopup("##dw_boards_options")) return;
try
{
bool on;
lock (_b.Gate) on = _b.AutoRefresh;
if (ImGui.Checkbox("Refresh leaderboards automatically", ref on)) _runOnTick(() => _setAuto(on));
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("One board's /top every 35 seconds while in the world (each board about every ten minutes); its replies stay out of chat.");
}
finally { ImGui.EndPopup(); }
}
}

View file

@ -1,7 +1,8 @@
// CharacterPage.cs - RynthDreamWeave's "Character" page (2026-11-07, Tom: "add this to the actual Dreamweave
// plugin UI. The settings and the ability to open the new skills panel ... to not have to use chat
// commands"): a tab of the DreamWeave window on RynthCore's bar (and of the /rserver window) that opens and
// closes the Character panel (SkillsPanel), on any of its pages, and holds its setting.
// closes the Character panel (SkillsPanel), on any of its pages, and holds its setting. Since 2026-11-15 its top
// row is the offline bonus ("double XP time") tracker (XpBonusStrip, drawn retail like the Leaderboards page).
using System;
using ImGuiNET;
using RynthCore.Plugin.ServerPack;
@ -20,10 +21,12 @@ internal sealed class CharacterPage
private readonly Action<bool> _setReplacesAc;
private readonly Func<bool> _onePanel;
private readonly Action<bool> _setOnePanel;
private readonly Action? _drawTop; // the offline bonus tracker's row (XpBonusStrip), drawn first
public CharacterPage(Func<bool> active, Func<int> panelState, Action<int> open, Action close,
Func<bool> replacesAc, Action<bool> setReplacesAc, Func<bool> onePanel, Action<bool> setOnePanel)
Func<bool> replacesAc, Action<bool> setReplacesAc, Func<bool> onePanel, Action<bool> setOnePanel, Action? drawTop = null)
{
_drawTop = drawTop;
_active = active;
_panelState = panelState;
_open = open;
@ -35,7 +38,7 @@ internal sealed class CharacterPage
}
public ServerPage Page() => new("character", "Character",
"The retail Character window, whose XP for next level keeps reading past level 275 (RynthDreamWeave).", Draw);
"Your offline bonus (double XP) time, and the retail Character window, whose XP for next level keeps reading past level 275 (RynthDreamWeave).", Draw);
private void Draw()
{
@ -45,6 +48,11 @@ internal sealed class CharacterPage
+ "(check RynthCore Options > Diagnostics, or /rserver info).");
return;
}
if (_drawTop != null)
{
_drawTop();
ImGui.Spacing();
}
SafeImGui.TextWrapped("AC's Character window (Attributes, Skills and Titles), drawn as retail draws it, with "
+ "\"XP for next level\" read from DreamWeave's own chart past level 275, where AC's "
+ "own window shows a negative number.");

View file

@ -108,6 +108,10 @@ internal sealed class DreamWeaveBank
Interlocked.Exchange(ref _typedByPlayer, 0);
}
/// <summary>When the next every-minute /b goes (Environment.TickCount64); long.MaxValue when none is coming.
/// The offline bonus read keeps clear of it (DreamWeaveXpBonus.GapMs).</summary>
public long NextCheckMs => CheckEveryMinute ? _nextCheckMs : long.MaxValue;
/// <summary>The every-minute check: "/b" when one is due now (and the setting is on), else null.</summary>
public string? CheckDue(long nowMs)
{

View file

@ -0,0 +1,682 @@
// DreamWeaveBoards.cs - DreamWeave's leaderboards (2026-11-15), read from the replies of the server's own
// /top command, for the Leaderboards page (BoardsPage.cs). The formats come from DreamWeave's source
// (ACE-DreamWeave, Command/Handlers/PlayerCommands.cs HandleTop + SendLeaderboard + SendSpeedLeaderboard +
// SendSpeedWinners, PvpArenaCommands.HandleArenaTop) and were checked against a live client on 2026-11-15.
// Each board is ONE chat message whose lines are separated by '\n':
// /top <board> "=== <Title> Leaderboard (Top 20) ===" then "N. Name - value" (20 at most),
// and when you are below the cut "..." then "N. Name (you) - value"
// ("(your account)" on the per-account bank board). An empty board says
// "No scores have been recorded yet."; an exempt (staff) requester gets
// "You are exempt from the leaderboards, ...".
// /top speed the same, titled with the season ("=== Season - Dungeon Leaderboard (Top 20) ==="),
// plus "That season has ended. ..." between rotations.
// /top speed winners "=== Speed Trial Winners (Last 20 Seasons) ===" then "N. Season - Dungeon - Name - m:ss.cc"
// or "N. Season - Dungeon - unclaimed".
// /top 1v1|2v2|tugak|bg "[Arena] Top 10 - <mode>:" then "N. Name (template) rating (W-L)" (Broadcast, no "(you)" row);
// "[Arena] No one is ranked in <mode> yet." when empty.
// refusals one line: "Bank balances are unavailable right now, ...", "... are not currently enabled on
// this server.", "No speed trial season has been run yet.", "[Arena] Arena ratings are unavailable ...".
// RynthCore hands a plugin at most the first 1024 characters of a chat message, and can't keep a longer one
// out of the chat window (Compatibility/ChatCallbackHooks.cs MaxIncomingChatChars). Such a board is read up to
// its last whole line and marked Cut; the automatic refresh leaves it out, so it doesn't print every ten minutes.
//
// A reply is RynthDreamWeave's own (hidden) only when it answers the board RynthDreamWeave asked for, within
// ReplyTimeoutMs; a /top the player types shows as usual and still updates the page. One request at a time.
// The header must start the message, and a player's chat types are never read, so a pasted copy can't add rows.
// Pure (no host calls): RynthServerPack.Tests covers it. Threads: everything here runs under Gate.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthDreamWeave;
internal enum BoardKind { Standard, SpeedWinners, Arena }
/// <summary>One of DreamWeave's boards: its key, the page's label, the command, and how the server titles it.</summary>
internal sealed record BoardDef(string Key, string Label, string Command, BoardKind Kind, string ServerTitle, string Help);
/// <summary>A row of a board. Arena: Value is the rating, Detail "template, W-L". Speed winners: Detail is the season.</summary>
internal sealed class BoardRow
{
public int Rank;
public string Name = "";
public string Value = "";
public string Detail = "";
/// <summary>The server marked it "(you)" or "(your account)".</summary>
public bool Marked;
/// <summary>"(your account)": the bank board's row for this account (another character's name).</summary>
public bool Account;
}
/// <summary>The last reading of one board.</summary>
internal sealed class BoardResult
{
public string Key = "";
/// <summary>The title the server gave it (the season's name on the speed board).</summary>
public string Title = "";
public readonly List<BoardRow> Rows = new();
/// <summary>Your row below the cut ("..." then "N. Name (you) - value"), else null.</summary>
public BoardRow? Below;
/// <summary>What the server added: an empty board, the season ended, a refusal.</summary>
public string Note = "";
public DateTime UpdatedUtc = DateTime.MinValue;
/// <summary>Environment.TickCount64 of the reading; 0 for one loaded from disk.</summary>
public long UpdatedMs;
/// <summary>The message ran past what RynthCore hands a plugin: the rows after the cut are missing.</summary>
public bool Cut;
}
/// <summary>Where you stand on a board.</summary>
internal readonly record struct BoardStanding(bool Read, int Rank, string Value, bool OutsideList, bool AccountRow);
internal sealed class DreamWeaveBoards
{
public const string SettingAutoRefresh = "autoRefreshLeaderboards";
/// <summary>A reply this long after the request isn't ours any more (and the next request may go).</summary>
public const long ReplyTimeoutMs = 6_000;
/// <summary>Lines in a later message still belong to a header for this long (an engine that splits lines).</summary>
public const long BlockMs = 4_000;
/// <summary>Automatic refresh: one board this often, so each of the 17 is read about every ten minutes.</summary>
public const long AutoIntervalMs = 35_000;
/// <summary>After login, before the first automatic request (the welcome and the bank's first /b go first).</summary>
public const long FirstAutoDelayMs = 45_000;
/// <summary>"Read all boards": one board this often.</summary>
public const long SweepIntervalMs = 6_000;
/// <summary>RynthCore hands a plugin at most this many characters of a chat message.</summary>
public const int EngineMaxChars = 1024;
public static readonly BoardDef[] Defs =
{
new("level", "Level", "/top level", BoardKind.Standard, "Level", "Highest character level"),
new("bank", "Bank", "/top bank", BoardKind.Standard, "Banked Pyreals", "Most pyreals banked (one entry per account)"),
new("cap", "Class ability points", "/top cap", BoardKind.Standard, "Class Ability Points", "Most class ability points earned, lifetime"),
new("stamp", "Quest stamps", "/top stamp", BoardKind.Standard, "Quest Stamps", "Most quest stamps earned by a single character"),
new("thread", "Thread-Guide", "/top thread", BoardKind.Standard, "Thread-Guide", "Highest Thread-Guide rung won, ties broken by lifetime Thread clears"),
new("knot", "Knot clears", "/top knot", BoardKind.Standard, "Knot Clears", "Best Knot clear: highest Knot level, then fastest time"),
new("title", "Titles", "/top title", BoardKind.Standard, "Titles", "Most character titles earned"),
new("deaths", "Deaths", "/top deaths", BoardKind.Standard, "Deaths", "Most deaths"),
new("dps", "DPS", "/top dps", BoardKind.Standard, "DPS Challenge", "Attack arena: highest damage dealt in the 60 s trial"),
new("defense", "Defense", "/top defense", BoardKind.Standard, "Defense Challenge", "Defense arena: longest survival against the Squall"),
new("wave", "Wave", "/top wave", BoardKind.Standard, "Wave Challenge", "Wave gauntlet: highest wave reached"),
new("speed", "Speed trial", "/top speed", BoardKind.Standard, "", "Speed trial: fastest run of the current season's dungeon"),
new("winners", "Speed trial winners", "/top speed winners", BoardKind.SpeedWinners, "Speed Trial Winners", "Speed trial: the winner of each of the 20 most recent seasons"),
new("1v1", "Arena 1v1", "/top 1v1", BoardKind.Arena, "1v1", "PvP arena ladder, ranked by rating"),
new("2v2", "Arena 2v2", "/top 2v2", BoardKind.Arena, "2v2", "PvP arena ladder, ranked by rating"),
new("tugak", "Tugak Brawl", "/top tugak", BoardKind.Arena, "Tugak Brawl", "PvP free-for-all ladder, ranked by rating"),
new("bg", "Battleground", "/top bg", BoardKind.Arena, "Battleground", "PvP battleground ladder, ranked by rating"),
};
private static readonly Regex Header = new(@"^=== (.+) Leaderboard \(Top \d+\) ===$");
private static readonly Regex WinnersHeader = new(@"^=== Speed Trial Winners \(Last \d+ Seasons\) ===$");
private static readonly Regex ArenaHeader = new(@"^\[Arena\] Top \d+ - (.+):$");
private static readonly Regex ArenaEmpty = new(@"^\[Arena\] No one is ranked in (.+) yet\.$");
private static readonly Regex Row = new(@"^(\d+)\. (.+?)(?: \((you|your account)\))? - (.+)$");
private static readonly Regex ArenaRow = new(@"^(\d+)\. (.+?)(?: \(([^()]+)\))? (-?\d+) \((\d+)-(\d+)\)$");
private static readonly Regex Refusal = new(@"^(?:Bank balances are unavailable right now|Class abilities are not currently enabled|Quest stamps are not currently enabled"
+ @"|Threads are not currently enabled|No speed trial season has been run yet|\[Arena\] Arena ratings are unavailable"
+ @"|Usage: /top <1v1\|2v2\|tugak\|bg>)");
/// <summary>Held for everything here (pump and render thread).</summary>
public readonly object Gate = new();
/// <summary>Refresh the boards automatically (one every <see cref="AutoIntervalMs"/>). Off by default.</summary>
public bool AutoRefresh;
/// <summary>The character's name, to find your row inside the list (set at login).</summary>
public string YourName = "";
/// <summary>Bumped on every change (the page's Refresh row and the save watch it).</summary>
public int Revision { get; private set; }
/// <summary>The boards read since the last save.</summary>
public bool Dirty { get; private set; }
/// <summary>What the last request came to, for the page ("" before one).</summary>
public string LastMiss { get; private set; } = "";
private readonly Dictionary<string, BoardResult> _results = new(StringComparer.Ordinal);
private string? _pendingKey; // RynthDreamWeave's own request, waiting for its reply
private long _pendingMs;
private string? _expectKey; // the last /top anyone sent (a typed one too), for a reply's unnamed parts
private long _expectMs;
private BoardResult? _block; // the board whose rows are being read
private bool _blockOurs;
private long _blockMs;
private int _rowsSeen; // rows read into _block (a header with none stays as it was if cut)
private bool _belowNext; // a "..." line: the next row is your row below the cut
private long _nextAutoMs = long.MaxValue;
private int _rotation;
private readonly Queue<string> _sweep = new();
private long _nextSweepMs;
public static BoardDef? Def(string key)
{
foreach (BoardDef d in Defs) if (d.Key == key) return d;
return null;
}
/// <summary>The last reading of a board, or null.</summary>
public BoardResult? Result(string key) => _results.TryGetValue(key, out BoardResult? r) ? r : null;
public int ReadCount => _results.Count;
/// <summary>RynthDreamWeave's own request is waiting for its reply.</summary>
public bool Pending => _pendingKey != null;
public string? PendingKey => _pendingKey;
/// <summary>"Read all boards" still has boards to ask for.</summary>
public int SweepLeft => _sweep.Count;
/// <summary>When the automatic refresh's next /top goes (Environment.TickCount64); long.MaxValue when it is off.
/// The offline bonus read keeps clear of it (DreamWeaveXpBonus.GapMs).</summary>
public long NextAutoMs => AutoRefresh ? _nextAutoMs : long.MaxValue;
// ── Settings and the saved boards ─────────────────────────────────────
public void LoadSettings(Func<string, bool, bool> getBool) => AutoRefresh = getBool(SettingAutoRefresh, false);
/// <summary>The boards saved for a character (the page isn't empty after a reload). Replaces what is held.</summary>
public void LoadSaved(string? json)
{
_results.Clear();
foreach (BoardResult r in FromJson(json)) _results[r.Key] = r;
Dirty = false;
Revision++;
}
public string SaveJson()
{
Dirty = false;
return ToJson(_results.Values);
}
// ── Login, logout, requests ───────────────────────────────────────────
/// <summary>A character is in the world (or the plugin reloaded in game).</summary>
public void Login(long nowMs)
{
ClearRequests();
_nextAutoMs = nowMs + FirstAutoDelayMs;
}
public void Logout()
{
ClearRequests();
_nextAutoMs = long.MaxValue;
_results.Clear();
YourName = "";
LastMiss = "";
Dirty = false;
Revision++;
}
private void ClearRequests()
{
_pendingKey = _expectKey = null;
_block = null;
_sweep.Clear();
_nextSweepMs = 0;
}
/// <summary>
/// Marks a request for <paramref name="key"/> as RynthDreamWeave's own and returns its command, or null for an
/// unknown board. The caller sends it (and calls <see cref="NotSent"/> when it didn't go).
/// </summary>
public string? Request(string key, long nowMs)
{
BoardDef? d = Def(key);
if (d == null) return null;
_pendingKey = _expectKey = key;
_pendingMs = _expectMs = nowMs;
LastMiss = "";
return d.Command;
}
/// <summary>The request didn't go out (not in the world).</summary>
public void NotSent()
{
_pendingKey = _expectKey = null;
}
/// <summary>Queues every board for "Read all boards" (one every <see cref="SweepIntervalMs"/>).</summary>
public void SweepAll()
{
_sweep.Clear();
foreach (BoardDef d in Defs) _sweep.Enqueue(d.Key);
}
/// <summary>The board a typed "/top ..." asks for ("winners" for "/top speed winners", "" for the list), else null.</summary>
public static string? KeyOfCommand(string? text)
{
string[] w = (text ?? "").Trim().ToLowerInvariant().Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (w.Length == 0 || w[0] != "/top") return null;
if (w.Length == 1) return "";
return w[1] switch
{
"speed" => w.Length > 2 && w[2] == "winners" ? "winners" : "speed",
"stamps" => "stamp",
"threads" => "thread",
"titles" => "title",
"knots" => "knot",
"ffa" or "brawl" => "tugak",
"battleground" => "bg",
var k => Def(k) != null ? k : null,
};
}
/// <summary>A board named by a player ("level", "speed winners", "Arena 1v1", ...), else null.</summary>
public static string? KeyOfName(string? text)
{
string t = (text ?? "").Trim();
if (t.Length == 0) return null;
string? k = KeyOfCommand("/top " + t);
if (!string.IsNullOrEmpty(k)) return k;
foreach (BoardDef d in Defs)
if (d.Label.Equals(t, StringComparison.OrdinalIgnoreCase) || d.Key.Equals(t, StringComparison.OrdinalIgnoreCase)) return d.Key;
return null;
}
/// <summary>
/// The player typed a /top (AC's chat bar; the pump calls this). Its reply is theirs and shows, and still
/// updates the page; RynthDreamWeave's own request for the same board stops being its own.
/// </summary>
public void NoteTyped(string text, long nowMs)
{
string? key = KeyOfCommand(text);
if (key == null) return;
_expectKey = key.Length > 0 ? key : null;
_expectMs = nowMs;
if (_pendingKey != null && _pendingKey == key) _pendingKey = null;
}
/// <summary>
/// The pump's tick: what to send now (a "Read all boards" step, or the automatic refresh's next board), else
/// null. Never while a request waits, or while a typed /top's reply may still come. <paramref name="canSend"/>
/// is false outside the world and in portal space.
/// </summary>
public string? Due(long nowMs, bool canSend)
{
Expire(nowMs);
if (!canSend || _pendingKey != null) return null;
if (_expectKey != null && nowMs - _expectMs < ReplyTimeoutMs) return null;
if (_sweep.Count > 0)
{
if (nowMs < _nextSweepMs) return null;
_nextSweepMs = nowMs + SweepIntervalMs;
return Request(_sweep.Dequeue(), nowMs);
}
if (!AutoRefresh || nowMs < _nextAutoMs) return null;
_nextAutoMs = nowMs + AutoIntervalMs;
for (int i = 0; i < Defs.Length; i++)
{
int at = (_rotation + i) % Defs.Length;
if (SkipAuto(Defs[at].Key, nowMs)) continue;
_rotation = at + 1;
return Request(Defs[at].Key, nowMs);
}
return null;
}
/// <summary>The automatic refresh leaves out a board too long to hide, and one read in the last half round.</summary>
private bool SkipAuto(string key, long nowMs)
{
BoardResult? r = Result(key);
if (r == null) return false;
if (r.Cut) return true;
return r.UpdatedMs != 0 && nowMs - r.UpdatedMs < AutoIntervalMs * Defs.Length / 2;
}
/// <summary>A request that got no reply in time is given up (the next may go).</summary>
public void Expire(long nowMs)
{
if (_pendingKey == null || nowMs - _pendingMs < ReplyTimeoutMs) return;
LastMiss = $"No reply to {Def(_pendingKey)?.Command ?? "/top"}.";
_pendingKey = null;
Revision++;
}
/// <summary>Turns the automatic refresh on or off; turned on, the first board goes soon.</summary>
public void SetAutoRefresh(bool on, long nowMs)
{
AutoRefresh = on;
if (on && _nextAutoMs != long.MaxValue && _nextAutoMs > nowMs + 5_000) _nextAutoMs = nowMs + 5_000;
}
// ── Reading the replies ───────────────────────────────────────────────
/// <summary>
/// An incoming chat message on DreamWeave. True when it should be kept out of the chat window: it answers
/// RynthDreamWeave's own request. Any board reply (a typed one too) updates the boards.
/// </summary>
public bool OnChatText(string? text, int chatType, long nowMs, DateTime utcNow)
{
if (string.IsNullOrEmpty(text) || ChatSource.IsPlayerAuthored(chatType)) return false;
Expire(nowMs);
bool cut = text.Length >= EngineMaxChars;
string[] lines = text.Split('\n');
int count = lines.Length;
if (cut && count > 1) count--; // the last line is incomplete
bool any = false, ours = false;
BoardResult? headed = null;
for (int i = 0; i < count; i++)
{
string line = lines[i].TrimEnd('\r', ' ', '\t');
if (i == 0) line = line.TrimStart();
if (line.Length == 0) continue;
if (i == 0 && ReadFirstLine(line, nowMs, utcNow, ref ours, out headed))
{
any = true;
continue;
}
if (i == 0) { if (!ReadBlockLine(line, nowMs, ref ours)) return false; any = true; continue; }
if (_block == null) break;
if (ReadBlockLine(line, nowMs, ref ours)) any = true;
}
if (cut && headed != null && ReferenceEquals(headed, _block))
{
headed.Cut = true;
if (headed.Below == null && headed.Note.Length == 0) headed.Note = "The list was cut short: it is longer than RynthCore hands a plugin.";
}
if (any) { Revision++; }
return any && ours;
}
/// <summary>A header or a one-line answer. False when the line isn't one (it may continue a board).</summary>
private bool ReadFirstLine(string line, long nowMs, DateTime utcNow, ref bool ours, out BoardResult? headed)
{
headed = null;
Match m;
string? key = null;
string title = "";
if (WinnersHeader.IsMatch(line)) { key = "winners"; title = "Speed Trial Winners"; }
else if ((m = Header.Match(line)).Success)
{
title = m.Groups[1].Value;
key = KeyOfTitle(title, BoardKind.Standard);
// Any other title is the speed trial's season ("Season - Dungeon"), when /top speed was just asked.
if (key == null && Expecting("speed", nowMs)) key = "speed";
}
else if ((m = ArenaHeader.Match(line)).Success)
{
title = m.Groups[1].Value;
key = KeyOfTitle(title, BoardKind.Arena);
}
else if ((m = ArenaEmpty.Match(line)).Success)
{
string? k = KeyOfTitle(m.Groups[1].Value, BoardKind.Arena);
if (k == null) return false;
BoardResult empty = Start(k, m.Groups[1].Value, nowMs, utcNow, ref ours);
empty.Note = "No one is ranked yet.";
_block = null;
return true;
}
else if (Refusal.IsMatch(line))
{
// A one-line refusal answers whichever /top was just sent; the rows read before stay.
string? k = _pendingKey ?? (_expectKey != null && nowMs - _expectMs < ReplyTimeoutMs ? _expectKey : null);
if (k == null) return false;
ours = Answer(k, nowMs) || ours;
BoardResult r = Get(k);
r.Note = line;
Dirty = true;
_block = null;
return true;
}
if (key == null) return false;
headed = Start(key, title, nowMs, utcNow, ref ours);
return true;
}
private BoardResult Start(string key, string title, long nowMs, DateTime utcNow, ref bool ours)
{
bool mine = Answer(key, nowMs);
ours = mine || ours;
var r = new BoardResult { Key = key, Title = title, UpdatedUtc = utcNow, UpdatedMs = nowMs };
_results[key] = r;
_block = r;
_blockOurs = mine;
_blockMs = nowMs;
_rowsSeen = 0;
_belowNext = false;
Dirty = true;
return r;
}
/// <summary>The reply for <paramref name="key"/> came: true when it answers RynthDreamWeave's own request.</summary>
private bool Answer(string key, long nowMs)
{
bool mine = _pendingKey == key && nowMs - _pendingMs < ReplyTimeoutMs;
if (mine) _pendingKey = null;
if (_expectKey == key) _expectKey = null;
return mine;
}
private bool Expecting(string key, long nowMs)
=> (_pendingKey == key && nowMs - _pendingMs < ReplyTimeoutMs) || (_expectKey == key && nowMs - _expectMs < ReplyTimeoutMs);
private BoardResult Get(string key)
{
if (!_results.TryGetValue(key, out BoardResult? r)) _results[key] = r = new BoardResult { Key = key };
return r;
}
/// <summary>A line of the board being read. False when there is none, or the line isn't part of one.</summary>
private bool ReadBlockLine(string line, long nowMs, ref bool ours)
{
BoardResult? b = _block;
if (b == null || nowMs - _blockMs > BlockMs) { _block = null; return false; }
BoardDef? d = Def(b.Key);
if (d == null) return false;
Match m;
if (line == "...") { _belowNext = true; return Took(ref ours, nowMs); }
if (d.Kind == BoardKind.Arena)
{
if (!(m = ArenaRow.Match(line)).Success) return false;
string detail = m.Groups[3].Success ? $"{m.Groups[3].Value}, {m.Groups[5].Value}-{m.Groups[6].Value}" : $"{m.Groups[5].Value}-{m.Groups[6].Value}";
Add(b, new BoardRow { Rank = Int(m.Groups[1].Value), Name = m.Groups[2].Value, Value = m.Groups[4].Value, Detail = detail });
return Took(ref ours, nowMs);
}
if (line.StartsWith("No scores have been recorded yet", StringComparison.Ordinal)
|| line.StartsWith("You are exempt from the leaderboards", StringComparison.Ordinal)
|| line.StartsWith("That season has ended", StringComparison.Ordinal))
{
b.Note = b.Note.Length > 0 ? b.Note + " " + line : line;
return Took(ref ours, nowMs);
}
if (!(m = Row.Match(line)).Success) return false;
if (d.Kind == BoardKind.SpeedWinners)
{
Add(b, Winner(Int(m.Groups[1].Value), line.Substring(m.Groups[1].Value.Length + 2)));
return Took(ref ours, nowMs);
}
var row = new BoardRow
{
Rank = Int(m.Groups[1].Value), Name = m.Groups[2].Value, Value = m.Groups[4].Value,
Marked = m.Groups[3].Success, Account = m.Groups[3].Value == "your account",
};
if (_belowNext || row.Marked) { b.Below = row; _belowNext = false; }
else Add(b, row);
return Took(ref ours, nowMs);
}
private void Add(BoardResult b, BoardRow row)
{
b.Rows.Add(row);
_rowsSeen++;
}
private bool Took(ref bool ours, long nowMs)
{
ours = _blockOurs || ours;
_blockMs = nowMs;
Dirty = true;
return true;
}
/// <summary>"Season - Dungeon - Name - 3:55.55" or "Season - Dungeon - unclaimed": the season's winner.</summary>
private static BoardRow Winner(int rank, string rest)
{
var row = new BoardRow { Rank = rank };
if (rest.EndsWith(" - unclaimed", StringComparison.Ordinal))
{
row.Detail = rest[..^" - unclaimed".Length];
row.Name = "unclaimed";
return row;
}
int t = rest.LastIndexOf(" - ", StringComparison.Ordinal);
int n = t > 0 ? rest.LastIndexOf(" - ", t - 1, StringComparison.Ordinal) : -1;
if (t < 0 || n < 0) { row.Detail = rest; return row; }
row.Detail = rest[..n];
row.Name = rest[(n + 3)..t];
row.Value = rest[(t + 3)..];
return row;
}
private static string? KeyOfTitle(string title, BoardKind kind)
{
foreach (BoardDef d in Defs)
if (d.Kind == kind && d.ServerTitle.Length > 0 && d.ServerTitle.Equals(title, StringComparison.Ordinal)) return d.Key;
return null;
}
private static int Int(string s) => int.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out int v) ? v : 0;
// ── Where you stand ───────────────────────────────────────────────────
/// <summary>True for your row: marked "(you)"/"(your account)" by the server, or your name inside the list.</summary>
public bool IsYou(BoardRow row)
=> row.Marked || (YourName.Length > 0 && row.Name.Equals(YourName, StringComparison.OrdinalIgnoreCase));
public BoardStanding Standing(string key)
{
BoardResult? r = Result(key);
if (r == null) return new BoardStanding(false, 0, "", false, false);
foreach (BoardRow row in r.Rows)
if (IsYou(row)) return new BoardStanding(true, row.Rank, StandingValue(key, row), false, row.Account);
if (r.Below != null) return new BoardStanding(true, r.Below.Rank, r.Below.Value, true, r.Below.Account);
return new BoardStanding(true, 0, "", false, false);
}
private static string StandingValue(string key, BoardRow row) => Def(key)?.Kind switch
{
BoardKind.Arena => $"rating {row.Value} ({row.Detail})",
BoardKind.SpeedWinners => $"{row.Detail} - {row.Value}",
_ => row.Value,
};
/// <summary>"#5", "#104 (below the list)", "not on it", "not read yet".</summary>
public string StandingText(string key)
{
BoardStanding s = Standing(key);
if (!s.Read) return "not read yet";
if (s.Rank == 0) return Result(key)?.Cut == true ? "not in the part read" : "not on it";
return "#" + s.Rank.ToString(CultureInfo.InvariantCulture) + (s.OutsideList ? " (below the list)" : "") + (s.AccountRow ? " (your account)" : "");
}
/// <summary>"updated 3 min ago" for a reading, from <paramref name="utcNow"/>.</summary>
public static string Age(DateTime updatedUtc, DateTime utcNow)
{
if (updatedUtc == DateTime.MinValue) return "not read yet";
TimeSpan a = utcNow - updatedUtc;
if (a < TimeSpan.FromMinutes(1)) return "updated just now";
if (a < TimeSpan.FromHours(1)) return $"updated {(int)a.TotalMinutes} min ago";
if (a < TimeSpan.FromDays(1)) return $"updated {(int)a.TotalHours} h ago";
return $"updated {(int)a.TotalDays} d ago";
}
// ── The saved boards (hand-written JSON: plugin types never go through the serializer) ──
public static string SavePath(string settingsFile, uint characterId)
=> Path.Combine(Path.GetDirectoryName(settingsFile) ?? "", "rynthdreamweave.boards." + characterId.ToString("X8", CultureInfo.InvariantCulture) + ".json");
public static string ToJson(IEnumerable<BoardResult> results)
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = false }))
{
w.WriteStartObject();
w.WriteNumber("v", 1);
w.WriteStartArray("boards");
foreach (BoardResult r in results)
{
w.WriteStartObject();
w.WriteString("key", r.Key);
w.WriteString("title", r.Title);
w.WriteString("note", r.Note);
w.WriteString("updated", r.UpdatedUtc == DateTime.MinValue ? "" : r.UpdatedUtc.ToString("o", CultureInfo.InvariantCulture));
w.WriteBoolean("cut", r.Cut);
w.WriteStartArray("rows");
foreach (BoardRow row in r.Rows) WriteRow(w, row);
w.WriteEndArray();
if (r.Below != null) { w.WritePropertyName("below"); WriteRow(w, r.Below); }
w.WriteEndObject();
}
w.WriteEndArray();
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray());
}
private static void WriteRow(Utf8JsonWriter w, BoardRow row)
{
w.WriteStartObject();
w.WriteNumber("r", row.Rank);
w.WriteString("n", row.Name);
w.WriteString("v", row.Value);
if (row.Detail.Length > 0) w.WriteString("d", row.Detail);
if (row.Marked) w.WriteBoolean("you", true);
if (row.Account) w.WriteBoolean("acct", true);
w.WriteEndObject();
}
/// <summary>The boards in a saved file; a missing or broken one (or an unknown board) is left out. Never throws.</summary>
public static List<BoardResult> FromJson(string? json)
{
var list = new List<BoardResult>();
if (string.IsNullOrWhiteSpace(json)) return list;
try
{
using JsonDocument doc = JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("boards", out JsonElement boards) || boards.ValueKind != JsonValueKind.Array) return list;
foreach (JsonElement b in boards.EnumerateArray())
{
string key = Str(b, "key");
if (Def(key) == null || list.Exists(x => x.Key == key)) continue;
var r = new BoardResult { Key = key, Title = Str(b, "title"), Note = Str(b, "note") };
if (DateTime.TryParse(Str(b, "updated"), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime u)) r.UpdatedUtc = u.ToUniversalTime();
r.Cut = b.TryGetProperty("cut", out JsonElement c) && c.ValueKind == JsonValueKind.True;
if (b.TryGetProperty("rows", out JsonElement rows) && rows.ValueKind == JsonValueKind.Array)
foreach (JsonElement row in rows.EnumerateArray()) r.Rows.Add(ReadRow(row));
if (b.TryGetProperty("below", out JsonElement below) && below.ValueKind == JsonValueKind.Object) r.Below = ReadRow(below);
list.Add(r);
}
}
catch (JsonException)
{
list.Clear();
}
return list;
}
private static BoardRow ReadRow(JsonElement e) => new()
{
Rank = e.TryGetProperty("r", out JsonElement r) && r.TryGetInt32(out int rank) ? rank : 0,
Name = Str(e, "n"),
Value = Str(e, "v"),
Detail = Str(e, "d"),
Marked = e.TryGetProperty("you", out JsonElement y) && y.ValueKind == JsonValueKind.True,
Account = e.TryGetProperty("acct", out JsonElement a) && a.ValueKind == JsonValueKind.True,
};
private static string Str(JsonElement e, string name)
=> e.ValueKind == JsonValueKind.Object && e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
}

View file

@ -0,0 +1,535 @@
// DreamWeaveXpBonus.cs - DreamWeave's offline bonus ("double XP time", 2026-11-15), for the Character page's
// tracker (XpBonusStrip.cs). The server's rules and wording come from its source (ACE-DreamWeave, 2026-11-02:
// Entity/OfflineBonus.cs, WorldObjects/Player_OfflineBonus.cs, Player_BonusSummary.cs, Player_Networking.cs,
// Command/Handlers/PlayerCommands.cs HandleOfflineBonus + ShowBankBalances):
// - a character banks bonus time 1:1 while logged out, and while online but idle (no combat XP or luminance
// for offline_bonus_idle_timeout_seconds, 5 min), up to offline_bonus_max_seconds (24 h);
// - it drains 1:1 while active (fighting, and for the 5 min after the last combat XP);
// - while any is left, combat XP and luminance get +offline_bonus_multiplier (1.0 = +100%).
// What it says (every line Broadcast, one chat message each; the [BANK] line System):
// /offlinebonus "Offline experience bonus: +100% to your combat experience and Luminance for the next 48m 31s,
// currently being SPENT (draining while you fight)." or "..., currently BANKING (idle for longer
// than the 5m 0s timeout, so it's growing again instead of draining)."
// "You have no offline experience bonus banked. Log this character out to bank bonus time ..."
// "The offline experience bonus is not enabled on this server."
// (the same status line also comes by itself 3 s after login when anything is banked)
// pushes "Your offline experience bonus is now active - 48m 31s remaining."
// "Your offline experience bonus is now idle and banking again - 3h 10m stored."
// "Your offline experience bonus is exhausted."
// "Welcome back - you were away for 9h 2m. Your offline experience bonus bank has been increased to 9h 2m."
// /b "[BANK] Offline Bonus Time: 48m 31s" or "... none" (the bank check sends /b every minute)
// /bonus " Offline bonus: +100% (48m 31s remaining)" or " Offline bonus: +0% (none banked)"
// Durations are FormatOfflineBonusDuration's: "Xh Ym" (hours are total hours, so "37h 5m" for a long absence),
// "Xm Ys", "Xs"; "Xm" and "Xh" are read too.
//
// Between readings a local clock runs: down while active, up while banking (to the cap), never below 0. A reading
// loaded from disk doesn't run (the time since may have been online or off). A remaining-only reading (/b, /bonus)
// keeps the state, and two of them a minute apart that disagree with it by 30 s or more set it (a push missed, or a
// plugin loaded mid-session). Only the reply to RynthDreamWeave's own /offlinebonus is kept out of chat, within
// ServerChatRequest's window; a /offlinebonus the player types shows, and every reading of any kind updates it.
// Every line is anchored at the start and a player's chat types are never read, so a pasted copy can't set it.
// Pure (no host calls): RynthServerPack.Tests covers it. Threads: everything here runs under Gate, except
// NoteChatBar (AC's thread; interlocked fields only).
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using RynthCore.Plugin.ServerPack;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthDreamWeave;
internal enum XpBonusState { Unknown, Disabled, Empty, Active, Banking }
/// <summary>Which of the server's offline-bonus lines a chat line was.</summary>
internal enum XpBonusLine { None, Status, NoneBanked, Disabled, Activated, Banking, Exhausted, Welcome, Bank, Summary }
internal sealed class DreamWeaveXpBonus
{
public const string SettingAutoRead = "autoReadXpBonus";
public const string Command = "/offlinebonus";
/// <summary>After login, before the first automatic read: the bank's first /b goes at 20 s, the boards' first /top at 45 s.</summary>
public const long FirstReadDelayMs = 35_000;
/// <summary>An automatic read this often; any full reading (a typed /offlinebonus, the login line) starts it again.</summary>
public const long ReadIntervalMs = 600_000;
/// <summary>No two of RynthDreamWeave's server commands within this of each other.</summary>
public const long GapMs = 5_000;
/// <summary>offline_bonus_max_seconds' default (24 h); raised by any reading above it.</summary>
public const double DefaultCapSeconds = 86_400;
/// <summary>Two remaining-only readings this far apart can set the state from their difference.</summary>
private const long InferAfterMs = 50_000;
private const double InferSeconds = 30;
private const string Ts = @"^\s*(?:\[[^\]]*\][\s:]*)?";
private const string Dur = @"(\d+h \d+m|\d+m \d+s|\d+[hms])";
private static readonly Regex StatusLine = new(Ts + @"Offline experience bonus: \+(\d+)% to your combat experience and Luminance for the next " + Dur + @", (.*)$");
private static readonly Regex NoneLine = new(Ts + @"You have no offline experience bonus banked\.");
private static readonly Regex DisabledLine = new(Ts + @"The offline experience bonus is not enabled on this server\.");
private static readonly Regex ActivatedLine = new(Ts + @"Your offline experience bonus is now active - " + Dur + @" remaining\.\s*$");
private static readonly Regex BankingLine = new(Ts + @"Your offline experience bonus is now idle and banking again - " + Dur + @" stored\.\s*$");
private static readonly Regex ExhaustedLine = new(Ts + @"Your offline experience bonus is exhausted\.\s*$");
private static readonly Regex WelcomeLine = new(Ts + @"Welcome back - you were away for " + Dur + @"\. Your offline experience bonus bank has been increased to " + Dur + @"\.\s*$");
private static readonly Regex BankLine = new(Ts + @"\[BANK\]\s+Offline Bonus Time:\s*(none|" + Dur[1..^1] + @")\s*$");
private static readonly Regex SummaryLine = new(@"^\s*Offline bonus: \+(\d+(?:\.\d+)?)% \(" + Dur + @" remaining\)\s*$");
private static readonly Regex SummaryNoneLine = new(@"^\s*Offline bonus: \+0% \(none banked\)\s*$");
private static readonly Regex DurationText = new(@"^(?:(\d+)h (\d+)m|(\d+)m (\d+)s|(\d+)([hms]))$");
/// <summary>Held for everything here (pump and render thread).</summary>
public readonly object Gate = new();
/// <summary>Send /offlinebonus by itself (after login, then every ten minutes). Off by default.</summary>
public bool AutoRead;
public XpBonusState State { get; private set; }
/// <summary>The bank, in seconds, at the last reading.</summary>
public double Seconds { get; private set; }
/// <summary>Environment.TickCount64 of the last reading; 0 before one, or for one loaded from disk (the clock doesn't run).</summary>
public long ReadMs { get; private set; }
public DateTime ReadUtc { get; private set; } = DateTime.MinValue;
/// <summary>The bonus in percent (+100 = double), from a status or /bonus line; kept with the reading.</summary>
public int? Percent { get; private set; }
/// <summary>The cap the clock counts up to.</summary>
public double CapSeconds { get; private set; } = DefaultCapSeconds;
public XpBonusLine LastLine { get; private set; }
/// <summary>What the last own request came to, for the page ("" before one).</summary>
public string LastMiss { get; private set; } = "";
/// <summary>Bumped on every change.</summary>
public int Revision { get; private set; }
/// <summary>Read since the last save.</summary>
public bool Dirty { get; private set; }
public bool HasReading => ReadUtc != DateTime.MinValue;
private readonly ServerChatRequest _request = new();
private bool _asked; // an own request went out and hasn't been answered or given up
private long _nextReadMs = long.MaxValue;
private bool _forced; // a Check now waiting for a quiet moment (also with the automatic read off)
private int _selfSends; // our /offlinebonus not yet seen by the chat bar (0 or 1)
private int _typed; // the player typed /offlinebonus (AC's thread sets it)
private double _lastRemainingOnly = -1; // the last /b or /bonus value, for the state from two of them
private long _lastRemainingOnlyMs;
// ── Settings, login, logout ────────────────────────────────────────────
public void LoadSettings(Func<string, bool, bool> getBool) => AutoRead = getBool(SettingAutoRead, false);
/// <summary>A character is in the world (or the plugin reloaded in game). The reading stays (a push may have come first).</summary>
public void Login(long nowMs)
{
ClearRequest();
_nextReadMs = nowMs + FirstReadDelayMs;
}
public void Logout()
{
ClearRequest();
_nextReadMs = long.MaxValue;
State = XpBonusState.Unknown;
Seconds = 0;
ReadMs = 0;
ReadUtc = DateTime.MinValue;
Percent = null;
CapSeconds = DefaultCapSeconds;
LastLine = XpBonusLine.None;
LastMiss = "";
_lastRemainingOnly = -1;
Dirty = false;
Revision++;
}
private void ClearRequest()
{
_request.Clear();
_asked = false;
_forced = false;
Interlocked.Exchange(ref _selfSends, 0);
Interlocked.Exchange(ref _typed, 0);
}
// ── Requests ───────────────────────────────────────────────────────────
/// <summary>The next automatic (or asked-for) read, Environment.TickCount64; long.MaxValue when none is coming.</summary>
public long NextReadMs => AutoRead || _forced ? _nextReadMs : long.MaxValue;
/// <summary>An own request waits for its reply, or a Check now waits to go.</summary>
public bool Waiting(long nowMs) => _forced || (_asked && _request.Awaiting(nowMs));
/// <summary>
/// The pump's tick: "/offlinebonus" when a read is due now, else null. <paramref name="canSend"/> is false outside the
/// world and in portal space; <paramref name="quiet"/> false while another of RynthDreamWeave's commands is within
/// <see cref="GapMs"/> (the read then goes on a later tick).
/// </summary>
public string? Due(long nowMs, bool canSend, bool quiet)
{
if ((!AutoRead && !_forced) || nowMs < _nextReadMs) return null;
if (!canSend || !quiet || (_asked && _request.Awaiting(nowMs))) return null;
_forced = false;
_nextReadMs = nowMs + ReadIntervalMs;
return Request(nowMs);
}
/// <summary>Check now: the read goes at the next quiet moment, the automatic read on or off.</summary>
public void CheckSoon(long nowMs)
{
_forced = true;
_nextReadMs = nowMs;
LastMiss = "";
Revision++;
}
/// <summary>Marks a request as RynthDreamWeave's own (its reply is hidden) and returns the command to send.</summary>
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;
}
/// <summary>The request didn't go out (not in the world, no chat parser).</summary>
public void NotSent()
{
_request.Clear();
_asked = false;
Interlocked.Exchange(ref _selfSends, 0);
}
/// <summary>True for "/offlinebonus" with or without words after it (the server ignores them).</summary>
public static bool IsCommand(string? text)
{
string t = (text ?? "").Trim();
if (!t.StartsWith(Command, StringComparison.OrdinalIgnoreCase)) return false;
return t.Length == Command.Length || char.IsWhiteSpace(t[Command.Length]);
}
/// <summary>AC's thread (chat bar): a /offlinebonus went through it. Ours, or typed by the player?</summary>
public void NoteChatBar()
{
if (Interlocked.Decrement(ref _selfSends) >= 0) return;
Interlocked.Exchange(ref _selfSends, 0);
Interlocked.Exchange(ref _typed, 1);
}
/// <summary>
/// The pump's tick: a typed /offlinebonus makes the reply the player's; an own request with no reply in time is
/// given up. True when one was given up just now.
/// </summary>
public bool Tick(long nowMs)
{
TakeTyped();
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;
}
/// <summary>Turns the automatic read on or off; turned on, the first read goes soon (at the next quiet moment).</summary>
public void SetAutoRead(bool on, long nowMs)
{
AutoRead = on;
if (on && _nextReadMs != long.MaxValue && _nextReadMs > nowMs + GapMs) _nextReadMs = nowMs + GapMs;
Revision++;
}
// ── Reading the server's lines ─────────────────────────────────────────
/// <summary>
/// An incoming chat message on DreamWeave. True when it should be kept out of the chat window: the reply to
/// RynthDreamWeave's own /offlinebonus. Every offline-bonus line of the server's updates the reading.
/// </summary>
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;
XpBonusLine kind = ReadLine(line, nowMs, utcNow);
if (kind is XpBonusLine.Status or XpBonusLine.NoneBanked or XpBonusLine.Disabled)
{
// A full reading: the next automatic read is ten minutes away.
if (_nextReadMs != long.MaxValue && !_forced) _nextReadMs = nowMs + ReadIntervalMs;
if (_asked && _request.Awaiting(nowMs))
{
hide = true;
_asked = false;
_request.Clear();
}
}
}
return hide;
}
/// <summary>Reads one line; what it was (None when it isn't one of the server's offline-bonus lines).</summary>
private XpBonusLine ReadLine(string line, long nowMs, DateTime utcNow)
{
Match m;
if ((m = StatusLine.Match(line)).Success && TryDuration(m.Groups[2].Value, out double s, out double res))
{
string state = m.Groups[3].Value;
XpBonusState st = state.Contains("BANKING", StringComparison.Ordinal) ? XpBonusState.Banking
: state.Contains("SPENT", StringComparison.Ordinal) || state.Contains("ACTIVE", StringComparison.Ordinal) ? XpBonusState.Active
: XpBonusState.Unknown;
if (st == XpBonusState.Unknown && State is XpBonusState.Active or XpBonusState.Banking) st = State;
Apply(XpBonusLine.Status, st, s, res, Int(m.Groups[1].Value), nowMs, utcNow);
return XpBonusLine.Status;
}
if (NoneLine.IsMatch(line)) { Apply(XpBonusLine.NoneBanked, XpBonusState.Empty, 0, 1, null, nowMs, utcNow); return XpBonusLine.NoneBanked; }
if (DisabledLine.IsMatch(line)) { Apply(XpBonusLine.Disabled, XpBonusState.Disabled, 0, 1, null, nowMs, utcNow); return XpBonusLine.Disabled; }
if ((m = ActivatedLine.Match(line)).Success && TryDuration(m.Groups[1].Value, out s, out res))
{
Apply(XpBonusLine.Activated, XpBonusState.Active, s, res, null, nowMs, utcNow);
return XpBonusLine.Activated;
}
if ((m = BankingLine.Match(line)).Success && TryDuration(m.Groups[1].Value, out s, out res))
{
Apply(XpBonusLine.Banking, XpBonusState.Banking, s, res, null, nowMs, utcNow);
return XpBonusLine.Banking;
}
if (ExhaustedLine.IsMatch(line)) { Apply(XpBonusLine.Exhausted, XpBonusState.Empty, 0, 1, null, nowMs, utcNow); return XpBonusLine.Exhausted; }
if ((m = WelcomeLine.Match(line)).Success && TryDuration(m.Groups[2].Value, out s, out res))
{
// A fresh login is idle (banking) until its first kill.
Apply(XpBonusLine.Welcome, XpBonusState.Banking, s, res, null, nowMs, utcNow);
return XpBonusLine.Welcome;
}
if ((m = BankLine.Match(line)).Success)
{
if (m.Groups[1].Value == "none") RemainingOnly(XpBonusLine.Bank, 0, 1, null, nowMs, utcNow);
else if (TryDuration(m.Groups[1].Value, out s, out res)) RemainingOnly(XpBonusLine.Bank, s, res, null, nowMs, utcNow);
else return XpBonusLine.None;
return XpBonusLine.Bank;
}
if (SummaryNoneLine.IsMatch(line)) { RemainingOnly(XpBonusLine.Summary, 0, 1, null, nowMs, utcNow); return XpBonusLine.Summary; }
if ((m = SummaryLine.Match(line)).Success && TryDuration(m.Groups[2].Value, out s, out res))
{
int? pct = double.TryParse(m.Groups[1].Value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out double p) ? (int)Math.Round(p, MidpointRounding.AwayFromZero) : null;
RemainingOnly(XpBonusLine.Summary, s, res, pct, nowMs, utcNow);
return XpBonusLine.Summary;
}
return XpBonusLine.None;
}
/// <summary>A /b or /bonus reading: the bank without its state. The state stays, or is set from two such readings.</summary>
private void RemainingOnly(XpBonusLine kind, double seconds, double res, int? pct, long nowMs, DateTime utcNow)
{
XpBonusState st = State;
if (seconds <= 0) st = XpBonusState.Empty;
else
{
if (st is XpBonusState.Empty or XpBonusState.Disabled) st = XpBonusState.Banking; // only idle time grows an empty bank
if (_lastRemainingOnly >= 0 && nowMs - _lastRemainingOnlyMs >= InferAfterMs)
{
double delta = seconds - _lastRemainingOnly;
if (delta <= -InferSeconds) st = XpBonusState.Active;
else if (delta >= InferSeconds) st = XpBonusState.Banking;
else if (st == XpBonusState.Unknown && seconds >= CapSeconds) st = XpBonusState.Banking; // full and not draining
}
}
if (_lastRemainingOnly < 0 || nowMs - _lastRemainingOnlyMs >= InferAfterMs)
{
_lastRemainingOnly = seconds;
_lastRemainingOnlyMs = nowMs;
}
Apply(kind, st, seconds, res, pct, nowMs, utcNow);
}
private void Apply(XpBonusLine kind, XpBonusState state, double seconds, double res, int? pct, long nowMs, DateTime utcNow)
{
// A reading shown to the minute ("3h 10m") that the running clock is inside of keeps the clock's seconds.
if (state == State && ReadMs != 0 && res > 1 && seconds > 0)
{
double e = Remaining(nowMs);
if (e >= seconds && e < seconds + res) seconds = e;
}
// A line that says the state (a push, the status reply) starts the two-reading comparison again: a /b a
// minute later must not undo a push that came between.
if (kind is not (XpBonusLine.Bank or XpBonusLine.Summary)) _lastRemainingOnly = -1;
State = state;
Seconds = Math.Max(0, seconds);
if (Seconds > CapSeconds) CapSeconds = Seconds;
ReadMs = nowMs == 0 ? 1 : nowMs;
ReadUtc = utcNow;
if (pct is int p && p > 0) Percent = p;
LastLine = kind;
LastMiss = "";
Dirty = true;
Revision++;
}
private static int? Int(string s) => int.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out int v) ? v : null;
/// <summary>
/// A duration in FormatOfflineBonusDuration's words ("3h 10m", "48m 31s", "12s", also "5m" and "2h"): its seconds,
/// and the step it is shown to (60 for "3h 10m", 1 for "48m 31s").
/// </summary>
public static bool TryDuration(string? text, out double seconds, out double resolution)
{
seconds = 0;
resolution = 1;
Match m = DurationText.Match((text ?? "").Trim());
if (!m.Success) return false;
static long N(Group g) => long.Parse(g.Value, NumberStyles.None, CultureInfo.InvariantCulture);
if (m.Groups[1].Success) { seconds = N(m.Groups[1]) * 3600 + N(m.Groups[2]) * 60; resolution = 60; }
else if (m.Groups[3].Success) { seconds = N(m.Groups[3]) * 60 + N(m.Groups[4]); }
else
{
long n = N(m.Groups[5]);
switch (m.Groups[6].Value)
{
case "h": seconds = n * 3600; resolution = 3600; break;
case "m": seconds = n * 60; resolution = 60; break;
default: seconds = n; break;
}
}
return true;
}
/// <summary>A number of seconds the way the server writes it ("3h 10m", "48m 31s", "12s").</summary>
public static string Format(double seconds)
{
var span = TimeSpan.FromSeconds(Math.Max(0, Math.Floor(seconds)));
if (span.TotalHours >= 1) return $"{(int)span.TotalHours}h {span.Minutes}m";
if (span.TotalMinutes >= 1) return $"{span.Minutes}m {span.Seconds}s";
return $"{span.Seconds}s";
}
// ── The local clock and what the tracker says ─────────────────────────
/// <summary>The clock runs: a live reading, active or banking.</summary>
public bool Running => ReadMs != 0 && State is XpBonusState.Active or XpBonusState.Banking;
/// <summary>The bank now: down while active, up while banking (to the cap), never below 0.</summary>
public double Remaining(long nowMs)
{
if (ReadMs == 0 || nowMs <= ReadMs) return Seconds;
double elapsed = (nowMs - ReadMs) / 1000.0;
return State switch
{
XpBonusState.Active => Math.Max(0, Seconds - elapsed),
XpBonusState.Banking => Math.Min(Math.Max(CapSeconds, Seconds), Seconds + elapsed),
_ => Seconds,
};
}
/// <summary>"Double XP +100%", "XP bonus +50%", or "Double XP" before the percent is known.</summary>
public string Title => Percent is int p && p != 100 ? $"XP bonus +{p}%" : Percent == 100 ? "Double XP +100%" : "Double XP";
/// <summary>True while the bonus is being spent (the tracker colours it).</summary>
public bool IsActive(long nowMs) => State == XpBonusState.Active && Remaining(nowMs) > 0;
/// <summary>The tracker's line: "Double XP +100%: 48m 31s left (active)", "...: 3h 10m banked (idle)", "...: None banked".</summary>
public string Line(long nowMs)
{
if (!HasReading) return "Double XP: not read yet";
if (State == XpBonusState.Disabled) return "Offline XP bonus: not enabled on this server";
double r = Remaining(nowMs);
if (State == XpBonusState.Empty || r <= 0) return Title + ": None banked";
string d = Format(r);
return State switch
{
XpBonusState.Active => $"{Title}: {d} left (active)",
XpBonusState.Banking => r >= CapSeconds ? $"{Title}: {d} banked (idle, full)" : $"{Title}: {d} banked (idle)",
_ => $"{Title}: {d} banked",
};
}
/// <summary>How old the reading is and whether the clock runs: "Server read 3 min ago; counting down".</summary>
public string Detail(long nowMs, DateTime utcNow)
{
if (!HasReading) return LastMiss.Length > 0 ? LastMiss : "Not read yet: press Check now.";
string age = Age(ReadUtc, utcNow);
if (ReadMs == 0) return $"Saved reading, {age}; not counting until the next one.";
string clock = State == XpBonusState.Active && Remaining(nowMs) > 0 ? "; counting down"
: State == XpBonusState.Banking && Remaining(nowMs) < CapSeconds ? "; counting up"
: State == XpBonusState.Unknown && Seconds > 0 ? "; active or idle not known yet" : "";
return "Server read " + age + clock + (LastMiss.Length > 0 ? " (" + LastMiss + ")" : "");
}
/// <summary>"just now", "3 min ago", "2 h ago", "4 d ago".</summary>
public static string Age(DateTime readUtc, DateTime utcNow)
{
TimeSpan a = utcNow - readUtc;
if (a < TimeSpan.FromMinutes(1)) return "just now";
if (a < TimeSpan.FromHours(1)) return $"{(int)a.TotalMinutes} min ago";
if (a < TimeSpan.FromDays(1)) return $"{(int)a.TotalHours} h ago";
return $"{(int)a.TotalDays} d ago";
}
// ── The saved reading (hand-written JSON: plugin types never go through the serializer) ──
public static string SavePath(string settingsFile, uint characterId)
=> Path.Combine(Path.GetDirectoryName(settingsFile) ?? "", "rynthdreamweave.xpbonus." + characterId.ToString("X8", CultureInfo.InvariantCulture) + ".json");
public string SaveJson()
{
Dirty = false;
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms))
{
w.WriteStartObject();
w.WriteNumber("v", 1);
w.WriteString("state", State.ToString().ToLowerInvariant());
w.WriteNumber("seconds", Math.Round(Seconds, 1));
if (Percent is int p) w.WriteNumber("percent", p);
w.WriteNumber("cap", CapSeconds);
w.WriteString("updated", ReadUtc == DateTime.MinValue ? "" : ReadUtc.ToString("o", CultureInfo.InvariantCulture));
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray());
}
/// <summary>
/// The reading saved for this character. It doesn't replace a newer one read this session (the login lines may
/// come before the character is known), and the clock doesn't run on it. A broken file is left out. Never throws.
/// </summary>
public void LoadSaved(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return;
try
{
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement e = doc.RootElement;
if (e.ValueKind != JsonValueKind.Object) return;
if (!DateTime.TryParse(Str(e, "updated"), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime u)) return;
u = u.ToUniversalTime();
int? pct = e.TryGetProperty("percent", out JsonElement pe) && pe.TryGetInt32(out int p) && p > 0 ? p : null;
if (HasReading && ReadUtc >= u)
{
Percent ??= pct; // the percent is the server's setting: an older reading still knows it
return;
}
if (!Enum.TryParse(Str(e, "state"), ignoreCase: true, out XpBonusState state)) state = XpBonusState.Unknown;
State = state;
Seconds = e.TryGetProperty("seconds", out JsonElement s) && s.TryGetDouble(out double sec) && sec > 0 ? sec : 0;
CapSeconds = e.TryGetProperty("cap", out JsonElement c) && c.TryGetDouble(out double cap) && cap > 0 ? Math.Max(cap, Seconds) : DefaultCapSeconds;
Percent = pct ?? Percent;
ReadUtc = u;
ReadMs = 0;
Dirty = false;
Revision++;
}
catch (JsonException)
{
}
}
private static string Str(JsonElement e, string name)
=> e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
}

View file

@ -0,0 +1,63 @@
// ReadGate.cs - when the Character panel asks the plugin tick for a read of the character (2026-11-14,
// report R-20261114-190620-f744: a level-497 character's panel still said level 495, with level 495's
// "XP for next level", while AC's own appraisal of the character said 497).
//
// The panel (render thread) queues one read at a time for the tick and queues the next only once that one
// has run. The wait used to be a plain flag, set when a read was queued and cleared when it ran. A read that
// never ran left it set for good: the shared plugin empties the tick's queue at logout
// (ServerPackPlugin.OnLogout), so a read the panel queued in the last frames before a logout or character
// switch was dropped, and from then on no read was ever queued again while the plugin stayed loaded. The
// panel kept drawing the last numbers it had read (level, total XP, XP for next level, skills) through
// every level gained since. Now a read still waiting after LostAfterMs is taken as lost and queued again,
// and logout resets the gate (SkillsReader.Clear).
//
// Pure: SkillsReader asks Due on the render thread and calls Done on the tick.
using System;
using System.Threading;
namespace RynthCore.Plugin.RynthDreamWeave;
internal sealed class ReadGate
{
/// <summary>At most this often while nothing is on its way (four reads a second).</summary>
public const long EveryMs = 250;
/// <summary>A queued read that hasn't run this long after it was queued is lost (its queue was dropped).</summary>
public const long LostAfterMs = 3000;
// When the last read was queued; AskNow puts it far back so the next Due says yes.
private long _lastAskMs = long.MinValue / 4;
// When the read waiting for the tick was queued; 0 while none is.
private long _queuedAtMs;
/// <summary>A read is queued and hasn't run yet (any thread).</summary>
public bool Waiting => Volatile.Read(ref _queuedAtMs) != 0;
/// <summary>
/// Render thread, each frame the panel draws: true when a read is due (the caller then queues one for
/// the tick, which calls <see cref="Done"/>). <paramref name="everyFrame"/>: a raise is on its way or a
/// press waits, so no 250 ms spacing. Never while a queued read is still within <see cref="LostAfterMs"/>.
/// </summary>
public bool Due(long nowMs, bool everyFrame)
{
long queued = Volatile.Read(ref _queuedAtMs);
if (queued != 0 && nowMs - queued < LostAfterMs) return false;
if (nowMs - Volatile.Read(ref _lastAskMs) < (everyFrame ? 0 : EveryMs)) return false;
// 0 means "none waiting", so a clock reading of 0 is kept as 1.
if (Interlocked.CompareExchange(ref _queuedAtMs, nowMs == 0 ? 1 : nowMs, queued) != queued) return false;
Volatile.Write(ref _lastAskMs, nowMs);
return true;
}
/// <summary>Tick: the queued read ran (whatever it found).</summary>
public void Done() => Volatile.Write(ref _queuedAtMs, 0);
/// <summary>Read again at the next frame (after a raise, a title, a set title). Any thread.</summary>
public void AskNow() => Volatile.Write(ref _lastAskMs, long.MinValue / 4);
/// <summary>Logout: nothing waiting, the next login's first frame reads.</summary>
public void Reset()
{
Volatile.Write(ref _queuedAtMs, 0);
AskNow();
}
}

View file

@ -0,0 +1,297 @@
// RetailCanvas.cs - RynthDreamWeave's retail drawing helpers, shared by the Character panel (SkillsPanel.cs)
// and the Leaderboards page (BoardsPage.cs) so both look like retail's own panels (2026-11-15: moved out of
// SkillsPanel unchanged, so the leaderboards use the same pictures, dat fonts, rows, scrollbar, red buttons
// and tooltip). Design pixels in, screen pixels out: Begin sets where the content's top-left is and how many
// screen pixels a design pixel is.
//
// The pictures are the retail client's own 0x06 textures (GetIconTexture kind UiSprite) and the text its
// dat fonts drawn glyph by glyph from their sheets (kind FontSheet, glyph tables in RetailData.g.cs). An
// engine without those kinds (before 2026-11-07) gets flat stand-ins and ImGui's font.
// AC's render thread only.
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDreamWeave;
internal sealed class RetailCanvas
{
// ── Retail pictures both panels draw ────────────────────────────────
public const uint ArtPage = 0x06004CC2u, ArtRule = 0x06004CC7u, ArtRowSelected = 0x06000F93u, ArtTitleRule = 0x06001420u,
ArtTrack = 0x06004C5Fu, ArtThumbTop = 0x06004C60u, ArtThumbMid = 0x06004C63u, ArtThumbBottom = 0x06004C66u,
ArtScrollUp = 0x06004C69u, ArtScrollDown = 0x06004C6Cu,
// The upright rule between the Character panel's header and its level box (5 wide).
ArtColumnRule = 0x06004CB8u;
public const int RuleH = 7;
/// <summary>The skill list's section banners (282x20): Specialized, Trained, Untrained, Unusable.</summary>
public const uint ArtBannerSpecialized = 0x06000F90u, ArtBannerTrained = 0x06000F86u, ArtBannerUntrained = 0x06000F98u, ArtBannerOther = 0x06000F89u;
/// <summary>The red button, a 3-slice: left 32, a stretched 15-wide middle, right 32; pressed -1, ghosted -2.</summary>
public static readonly uint[] ArtRedButton = { 0x06004C96u, 0x06004C99u, 0x06004C9Cu };
public const int ScrollW = 16, ScrollBtn = 16, ScrollCap = 3, RowH = 20;
// ── Colours (ImGui ABGR) ────────────────────────────────────────────
public const uint White = 0xFFFFFFFFu, Black = 0xFF000000u;
public static readonly uint Body = Rgb(235, 230, 209); // OpenAC's "parchment" for the footer prompt
public static readonly uint TabOn = Rgb(204, 204, 204), TabOff = Rgb(127, 127, 127);
public static readonly uint Gold = Rgb(255, 242, 127); // the level number (the layout's 1, .949, .498)
public static readonly uint Green = Rgb(0, 255, 0), Red = Rgb(255, 0, 0);
public static uint Rgb(int r, int g, int b) => 0xFF000000u | ((uint)b << 16) | ((uint)g << 8) | (uint)r;
private readonly RynthCoreHost _host;
public RetailCanvas(RynthCoreHost host) => _host = host;
/// <summary>The draw list being drawn into (the window's; the tooltip swaps in the foreground's).</summary>
public ImDrawListPtr Dl;
/// <summary>The content's top-left, screen pixels.</summary>
public Vector2 Origin;
/// <summary>Screen pixels per design pixel.</summary>
public float K = 1f;
/// <summary>Starts a frame: draws into <paramref name="dl"/> with design (0,0) at <paramref name="origin"/>.</summary>
public void Begin(ImDrawListPtr dl, Vector2 origin, float k)
{
Dl = dl;
Origin = origin;
K = k;
}
public Vector2 P(float x, float y) => new(Origin.X + x * K, Origin.Y + y * K);
public Vector2 S(float w, float h) => new(Math.Max(1, w * K), Math.Max(1, h * K));
public bool Hit(int x, int y, int w, int h)
{
Vector2 m = ImGui.GetMousePos(), a = P(x, y), b = P(x + w, y + h);
return m.X >= a.X && m.X < b.X && m.Y >= a.Y && m.Y < b.Y;
}
public IntPtr Tex(RynthIconKind kind, uint id) => id == 0 ? IntPtr.Zero : _host.GetIconTexture(kind, id);
/// <summary>A retail picture stretched over the box (a flat stand-in until the engine has made it).</summary>
public void Sprite(uint id, int x, int y, int w, int h, uint fallback)
{
if (w <= 0 || h <= 0) return;
IntPtr t = Tex(RynthIconKind.UiSprite, id);
if (t == IntPtr.Zero) { Dl.AddRectFilled(P(x, y), P(x + w, y + h), fallback); return; }
Dl.AddImage(t, P(x, y), P(x + w, y + h));
}
/// <summary>The top-left <paramref name="w"/> x <paramref name="h"/> of a <paramref name="texW"/> x <paramref name="texH"/> picture, unscaled.</summary>
public void SpriteCropped(uint id, int x, int y, int w, int h, int texW, int texH, uint fallback)
{
IntPtr t = Tex(RynthIconKind.UiSprite, id);
if (t == IntPtr.Zero) { Dl.AddRectFilled(P(x, y), P(x + w, y + h), fallback); return; }
Dl.AddImage(t, P(x, y), P(x + w, y + h), Vector2.Zero, new Vector2(Math.Min(1f, w / (float)texW), Math.Min(1f, h / (float)texH)));
}
public void Icon(uint id, int x, int y, int size)
{
IntPtr t = Tex(RynthIconKind.Icon, id);
if (t != IntPtr.Zero) Dl.AddImage(t, P(x, y), P(x + size, y + size));
}
/// <summary>A retail button: its picture, and true when clicked.</summary>
public bool Button(string imguiId, uint art, int x, int y, int w, int h)
{
ImGui.SetCursorScreenPos(P(x, y));
bool clicked = ImGui.InvisibleButton(imguiId, S(w, h));
Sprite(art, x, y, w, h, 0xFF3C8A3Cu);
return clicked;
}
/// <summary>
/// Retail's red button (the Titles page's "Set as Display Title"): the 3-slice art, ghosted when not
/// <paramref name="enabled"/>, pressed while held, its label in Palatino 18. True when clicked while enabled.
/// </summary>
public bool RedButton(string imguiId, string label, int x, int y, int w, bool enabled)
{
w = Math.Max(w, 64);
ImGui.SetCursorScreenPos(P(x, y));
bool pressed = ImGui.InvisibleButton(imguiId, S(w, 32));
bool held = ImGui.IsItemActive();
uint d = !enabled ? 2u : held ? 1u : 0u;
Sprite(ArtRedButton[0] - d, x, y, 32, 32, 0xFF20208Cu);
Sprite(ArtRedButton[1] - d, x + 32, y, w - 64, 32, 0xFF20208Cu);
Sprite(ArtRedButton[2] - d, x + w - 32, y, 32, 32, 0xFF20208Cu);
Text(RetailData.Pal18, label, x, y, w, 32, enabled ? White : TabOff, center: true);
return pressed && enabled;
}
/// <summary>The page background: a 48x48 black at alpha 175, tiled, so the world shows through as retail.</summary>
public void PageBackground(int x0, int y0, int w, int h)
{
IntPtr t = Tex(RynthIconKind.UiSprite, ArtPage);
for (int y = 0; y < h; y += 48)
for (int x = 0; x < w; x += 48)
{
int tw = Math.Min(48, w - x), th = Math.Min(48, h - y);
if (t != IntPtr.Zero)
Dl.AddImage(t, P(x0 + x, y0 + y), P(x0 + x + tw, y0 + y + th), Vector2.Zero, new Vector2(tw / 48f, th / 48f));
else
Dl.AddRectFilled(P(x0 + x, y0 + y), P(x0 + x + tw, y0 + y + th), 0xAF000000u);
}
}
/// <summary>
/// Text in a retail dat font, left-aligned (or <paramref name="right"/> / <paramref name="center"/>)
/// in the box and centred down it, glyph by glyph from the font's sheet; <paramref name="outline"/>
/// draws the font's outline sheet in black under it (the level number). ImGui's font stands in on an
/// engine without font sheets.
/// </summary>
public void Text(RetailFont font, string? text, int x, int y, int w, int h, uint color,
bool right = false, bool center = false, bool outline = false)
{
if (string.IsNullOrEmpty(text)) return;
int width = font.Measure(text);
float left = right ? x + w - width : center ? x + (w - width) / 2f : x;
float top = y + (h - font.LineHeight) / 2f;
IntPtr sheet = Tex(RynthIconKind.FontSheet, font.Sheet);
if (sheet == IntPtr.Zero)
{
Vector2 sz = ImGui.CalcTextSize(text);
float fx = right ? P(x + w, 0).X - sz.X : center ? P(x + w / 2f, 0).X - sz.X / 2 : P(x, 0).X;
Dl.AddText(new Vector2(fx, P(0, y + h / 2f).Y - sz.Y / 2), color, text);
return;
}
left = MathF.Round(left);
top = MathF.Round(top);
if (outline && font.OutlineSheet != 0)
{
IntPtr back = Tex(RynthIconKind.FontSheet, font.OutlineSheet);
if (back != IntPtr.Zero) Glyphs(font, text, left, top, back, font.OutlineWidth, font.OutlineHeight, Black, font.BorderX, font.BorderY);
}
Glyphs(font, text, left, top, sheet, font.SheetWidth, font.SheetHeight, color, 0, 0);
}
/// <summary><paramref name="text"/> cut to fit <paramref name="width"/> design px in <paramref name="font"/>, "..." added.</summary>
public static string Fit(RetailFont font, string? text, int width)
{
string t = text ?? "";
if (font.Measure(t) <= width) return t;
int dots = font.Measure("...");
while (t.Length > 0 && font.Measure(t) + dots > width) t = t[..^1];
return t.TrimEnd() + "...";
}
private void Glyphs(RetailFont font, string text, float x, float y, IntPtr sheet, int sheetW, int sheetH, uint color, int bx, int by)
{
float pen = x;
foreach (char c in text)
{
if (!font.TryGlyph(c, out RetailGlyph g)) continue;
if (g.Width > 0 && g.Height > 0)
{
float gx = pen + g.Before - bx, gy = y + g.Top - by;
int sx = g.SheetX - bx, sy = g.SheetY - by, gw = g.Width + 2 * bx, gh = g.Height + 2 * by;
if (sx < 0) { gx -= sx; gw += sx; sx = 0; }
if (sy < 0) { gy -= sy; gh += sy; sy = 0; }
if (gw > 0 && gh > 0)
Dl.AddImage(sheet, P(gx, gy), P(gx + gw, gy + gh),
new Vector2(sx / (float)sheetW, sy / (float)sheetH),
new Vector2((sx + gw) / (float)sheetW, (sy + gh) / (float)sheetH), color);
}
pen += g.Advance;
}
}
// ── The scrollbar (the Character panel's 0x1000023E) ─────────────────
private bool _thumbDrag;
private float _thumbGrab;
/// <summary>Retail's chain-link scrollbar at design x <paramref name="x"/>, beside a list of <paramref name="total"/> rows.</summary>
public void ScrollBar(string id, int x, ref float scroll, int top, int h, int visible, int total, float maxScroll)
{
// The track: a chain of 16x32 links, tiled.
IntPtr track = Tex(RynthIconKind.UiSprite, ArtTrack);
for (int y = top + ScrollBtn; y < top + h - ScrollBtn; y += 32)
{
int th = Math.Min(32, top + h - ScrollBtn - y);
if (track != IntPtr.Zero) Dl.AddImage(track, P(x, y), P(x + ScrollW, y + th), Vector2.Zero, new Vector2(1, th / 32f));
else Dl.AddRectFilled(P(x + 6, y), P(x + 10, y + th), 0xFF3C6A8Au);
}
// The arrows.
if (Button("##dw_up_" + id, ArtScrollUp, x, top, ScrollW, ScrollBtn)) scroll = Math.Max(0, scroll - 1);
if (Button("##dw_dn_" + id, ArtScrollDown, x, top + h - ScrollBtn, ScrollW, ScrollBtn)) scroll = Math.Min(maxScroll, scroll + 1);
// The thumb: caps and a stretched blue middle, sized to the share of the list that shows.
int trackTop = top + ScrollBtn, trackH = h - 2 * ScrollBtn;
if (trackH <= 8) return;
int thumbH = Math.Clamp((int)(trackH * visible / (float)total), 16, trackH);
int thumbY = trackTop + (int)((trackH - thumbH) * (maxScroll > 0 ? scroll / maxScroll : 0));
ImGui.SetCursorScreenPos(P(x, trackTop));
ImGui.InvisibleButton("##dw_track_" + id, S(ScrollW, trackH));
float mouseY = (ImGui.GetMousePos().Y - Origin.Y) / K;
if (ImGui.IsItemActivated())
{
if (mouseY >= thumbY && mouseY < thumbY + thumbH) { _thumbDrag = true; _thumbGrab = mouseY - thumbY; }
else scroll = Math.Clamp(scroll + (mouseY < thumbY ? -visible : visible), 0, maxScroll);
}
if (_thumbDrag && ImGui.IsItemActive() && trackH > thumbH)
scroll = Math.Clamp((mouseY - _thumbGrab - trackTop) / (trackH - thumbH) * maxScroll, 0, maxScroll);
if (!ImGui.IsItemActive()) _thumbDrag = false;
Sprite(ArtThumbTop, x, thumbY, ScrollW, ScrollCap, 0xFF8C5A1Eu);
Sprite(ArtThumbMid, x, thumbY + ScrollCap, ScrollW, thumbH - 2 * ScrollCap, 0xFF8C3A10u);
Sprite(ArtThumbBottom, x, thumbY + thumbH - ScrollCap, ScrollW, ScrollCap, 0xFF8C5A1Eu);
}
// ── The tooltip (drawn last, over everything) ───────────────────────
// Hovering something a moment shows retail's tooltip box: Palatino 14 on black in a gold line.
private const long TooltipDelayMs = 400;
private const int TooltipWrap = 230; // design px: retail breaks the description at about this width
private static readonly uint TooltipBorder = Rgb(196, 164, 92), TooltipBack = 0xE0000000u;
private uint _hoverId, _tipKey;
private long _hoverSince;
private string _tipCandidate = "";
private string? _tipText;
/// <summary>Starts a frame's hover tracking (nothing hovered yet).</summary>
public void ClearHover() => _tipKey = 0;
/// <summary>This frame, the mouse is on something with a tooltip (<paramref name="key"/> tells one row from another).</summary>
public void Hover(uint key, string text)
{
_tipKey = key;
_tipCandidate = text;
}
public void UpdateTooltip()
{
long now = Environment.TickCount64;
if (_tipKey != _hoverId) { _hoverId = _tipKey; _hoverSince = now; }
_tipText = _tipKey != 0 && now - _hoverSince >= TooltipDelayMs && _tipCandidate.Length > 0 ? _tipCandidate : null;
}
public void Tooltip()
{
if (_tipText == null) return;
RetailFont f = RetailData.Pal14;
List<string> lines = f.Wrap(_tipText, TooltipWrap);
if (lines.Count == 0) return;
int w = 0;
foreach (string l in lines) w = Math.Max(w, f.Measure(l));
int boxW = w + 8, boxH = lines.Count * f.LineHeight + 6;
// Below and right of the cursor, kept on screen. Design px from the panel's origin.
Vector2 mouse = ImGui.GetMousePos(), screen = ImGui.GetIO().DisplaySize;
float x = (mouse.X - Origin.X) / K + 14, y = (mouse.Y - Origin.Y) / K + 16;
float maxX = (screen.X - Origin.X) / K - boxW - 2, maxY = (screen.Y - Origin.Y) / K - boxH - 2;
int bx = (int)MathF.Round(Math.Max(-Origin.X / K, Math.Min(x, maxX)));
int by = (int)MathF.Round(Math.Max(-Origin.Y / K, Math.Min(y, maxY)));
ImDrawListPtr saved = Dl;
Dl = ImGui.GetForegroundDrawList();
try
{
Dl.AddRectFilled(P(bx, by), P(bx + boxW, by + boxH), TooltipBack);
Dl.AddRect(P(bx, by), P(bx + boxW, by + boxH), TooltipBorder, 0, ImDrawFlags.None, Math.Max(1f, K));
for (int i = 0; i < lines.Count; i++)
Text(f, lines[i], bx + 4, by + 3 + i * f.LineHeight, boxW - 8, f.LineHeight, White);
}
finally { Dl = saved; }
}
}

View file

@ -32,11 +32,11 @@ internal sealed class SkillsPanel
private const int HeaderH = 105, RuleH = 7, ListTop = 112, FooterH = 55, RowH = 20, BannerW = 280;
private const int ScrollX = 281, ScrollW = 16, ScrollBtn = 16, ScrollCap = 3;
// The pictures the Leaderboards page shares are RetailCanvas's (moved there 2026-11-15, unchanged).
private const uint ArtEdgeTop = 0x0600612Au, ArtEdgeLeft = 0x0600612Bu, ArtEdgeBottom = 0x0600612Cu, ArtEdgeRight = 0x0600612Du,
ArtCorner = 0x06006129u, ArtPage = 0x06004CC2u, ArtClose = 0x06001393u, ArtClosePressed = 0x06001394u,
ArtHeaderRule = 0x06004CB8u, ArtPlate = 0x060011A6u, ArtXpFill = 0x060011A5u, ArtRankFill = 0x06000F8Au, ArtRule = 0x06004CC7u, ArtRowSelected = 0x06000F93u,
ArtTrack = 0x06004C5Fu, ArtThumbTop = 0x06004C60u, ArtThumbMid = 0x06004C63u, ArtThumbBottom = 0x06004C66u,
ArtScrollUp = 0x06004C69u, ArtScrollDown = 0x06004C6Cu,
ArtCorner = 0x06006129u, ArtClose = 0x06001393u, ArtClosePressed = 0x06001394u,
ArtHeaderRule = 0x06004CB8u, ArtPlate = 0x060011A6u, ArtXpFill = 0x060011A5u, ArtRankFill = 0x06000F8Au,
ArtRule = RetailCanvas.ArtRule, ArtRowSelected = RetailCanvas.ArtRowSelected,
ArtRaise = 0x06004CB6u, ArtRaiseGhost = 0x06004CB7u, ArtRaiseTen = 0x0600712Bu, ArtRaiseTenGhost = 0x0600712Cu;
// Tab 3-slices: "Open" (the shown page) and "Closed" states.
private static readonly uint[] TabOpen = { 0x06005D92u, 0x06005D94u, 0x06005D96u };
@ -44,22 +44,24 @@ internal sealed class SkillsPanel
private static uint Banner(SkillSection s) => s switch
{
SkillSection.Specialized => 0x06000F90u,
SkillSection.Trained => 0x06000F86u,
SkillSection.Untrained => 0x06000F98u,
_ => 0x06000F89u,
SkillSection.Specialized => RetailCanvas.ArtBannerSpecialized,
SkillSection.Trained => RetailCanvas.ArtBannerTrained,
SkillSection.Untrained => RetailCanvas.ArtBannerUntrained,
_ => RetailCanvas.ArtBannerOther,
};
// ── Colours (ImGui ABGR) ────────────────────────────────────────────
private const uint White = 0xFFFFFFFFu, Black = 0xFF000000u;
private static readonly uint Body = Rgb(235, 230, 209); // OpenAC's "parchment" for the footer prompt
private static readonly uint TabOn = Rgb(204, 204, 204), TabOff = Rgb(127, 127, 127);
private static readonly uint Gold = Rgb(255, 242, 127); // the level number (the layout's 1, .949, .498)
private static readonly uint Green = Rgb(0, 255, 0), Red = Rgb(255, 0, 0);
// ── Colours (ImGui ABGR): RetailCanvas's ────────────────────────────
private const uint White = RetailCanvas.White, Black = RetailCanvas.Black;
private static readonly uint Body = RetailCanvas.Body;
private static readonly uint TabOn = RetailCanvas.TabOn, TabOff = RetailCanvas.TabOff;
private static readonly uint Gold = RetailCanvas.Gold;
private static readonly uint Green = RetailCanvas.Green, Red = RetailCanvas.Red;
private static uint Rgb(int r, int g, int b) => 0xFF000000u | ((uint)b << 16) | ((uint)g << 8) | (uint)r;
private static uint Rgb(int r, int g, int b) => RetailCanvas.Rgb(r, g, b);
private readonly RynthCoreHost _host;
// The drawing helpers (RetailCanvas.cs, shared with the Leaderboards page).
private readonly RetailCanvas _c;
private readonly SkillsReader _reader;
private readonly Action<Action> _onTick;
private readonly Action<string> _chat;
@ -73,8 +75,6 @@ internal sealed class SkillsPanel
private float _attrScroll, _titleScroll;
private readonly Func<bool> _replacesAc;
private readonly Action<bool> _setReplacesAc;
private bool _thumbDrag;
private float _thumbGrab;
// Resizing from the bottom edge (retail's Character window: height only). Design px, frame included.
private bool _resizing;
private float _resizeStartH, _resizeStartY, _dragH;
@ -88,6 +88,7 @@ internal sealed class SkillsPanel
Func<bool> replacesAc, Action<bool> setReplacesAc)
{
_host = host;
_c = new RetailCanvas(host);
_reader = reader;
_title = title;
_onTick = onTick;
@ -133,6 +134,7 @@ internal sealed class SkillsPanel
_k = pct > 0 ? Math.Clamp(pct / 100f, 0.3f, 2.5f) : 1f;
_dl = ImGui.GetWindowDrawList();
_origin = new Vector2(MathF.Round(start.X + Frame * _k), MathF.Round(start.Y + Frame * _k));
_c.Begin(_dl, _origin, _k);
// The height drawn: the window's, or while the bottom edge is dragged the dragged one (drawn past the
// window's edge, the way retail's frame follows the mouse), and after the release the asked-for one
@ -164,7 +166,7 @@ internal sealed class SkillsPanel
{
Page(pageH);
Tabs();
_tipKey = 0;
_c.ClearHover();
if (_tab == 2) TitlesPage(sheet, pageH);
else
{
@ -243,9 +245,7 @@ internal sealed class SkillsPanel
// ── The Titles page (0x10000539) ────────────────────────────────────
private const uint ArtTitleRule = 0x06001420u;
// The red button, a 3-slice: left 32, a stretched 15-wide middle, right 32; pressed -1, ghosted -2.
private static readonly uint[] ArtRedButton = { 0x06004C96u, 0x06004C99u, 0x06004C9Cu };
private const uint ArtTitleRule = RetailCanvas.ArtTitleRule;
private const int TitleRowH = 24;
private void TitlesPage(SkillsSheet sheet, int pageH)
@ -295,15 +295,7 @@ internal sealed class SkillsPanel
Sprite(ArtTitleRule, 0, ruleY, PanelW, 9, 0xFF54788Fu);
// "Set as Display Title": ghosted until another title than the displayed one is selected.
bool can = _titleSelected != 0 && _titleSelected != book.Displayed;
ImGui.SetCursorScreenPos(P(53, buttonY));
bool pressed = ImGui.InvisibleButton("##dw_set_title", S(200, 32));
bool held = ImGui.IsItemActive();
uint d = !can ? 2u : held ? 1u : 0u;
Sprite(ArtRedButton[0] - d, 53, buttonY, 32, 32, 0xFF20208Cu);
Sprite(ArtRedButton[1] - d, 85, buttonY, 136, 32, 0xFF20208Cu);
Sprite(ArtRedButton[2] - d, 221, buttonY, 32, 32, 0xFF20208Cu);
Text(RetailData.Pal18, "Set as Display Title", 53, buttonY, 200, 32, can ? White : TabOff, center: true);
if (pressed && can)
if (_c.RedButton("##dw_set_title", "Set as Display Title", 53, buttonY, 200, can))
{
uint id = _titleSelected;
_onTick(() => _reader.SetDisplayTitle(_host, id, _chat));
@ -399,17 +391,7 @@ internal sealed class SkillsPanel
{
// The page background is a 48x48 black at alpha 175, tiled: the world shows through, as retail.
// It runs under the tab row too (retail's slanted tab corners show it, not the world).
IntPtr t = Tex(RynthIconKind.UiSprite, ArtPage);
int fullH = TabH + pageH;
for (int y = 0; y < fullH; y += 48)
for (int x = 0; x < PanelW; x += 48)
{
int w = Math.Min(48, PanelW - x), h = Math.Min(48, fullH - y);
if (t != IntPtr.Zero)
_dl.AddImage(t, P(x, y), P(x + w, y + h), Vector2.Zero, new Vector2(w / 48f, h / 48f));
else
_dl.AddRectFilled(P(x, y), P(x + w, y + h), 0xAF000000u);
}
_c.PageBackground(0, 0, PanelW, TabH + pageH);
}
private void Tabs()
@ -529,97 +511,16 @@ internal sealed class SkillsPanel
if (rows.Count > visible) ScrollBar("skills", ref _scroll, top, listH, visible, rows.Count, maxScroll);
}
// ── The tooltip (drawn last, over everything) ───────────────────────
// ── The tooltip (drawn last, over everything) and the scrollbar: RetailCanvas's ──
// Hovering a row a moment shows retail's tooltip: a skill's formula and description, an attribute's
// or vital's text, the displayed title's explanation.
private const long TooltipDelayMs = 400;
private const int TooltipWrap = 230; // design px: retail breaks the description at about this width
private static readonly uint TooltipBorder = Rgb(196, 164, 92), TooltipBack = 0xE0000000u;
private uint _hoverId, _tipKey;
private long _hoverSince;
private string _tipCandidate = "";
private string? _tipText;
/// <summary>This frame, the mouse is on something with a tooltip (<paramref name="key"/> tells one row from another).</summary>
private void Hover(uint key, string text)
{
_tipKey = key;
_tipCandidate = text;
}
private void UpdateTooltip()
{
long now = Environment.TickCount64;
if (_tipKey != _hoverId) { _hoverId = _tipKey; _hoverSince = now; }
_tipText = _tipKey != 0 && now - _hoverSince >= TooltipDelayMs && _tipCandidate.Length > 0 ? _tipCandidate : null;
}
private void Tooltip()
{
if (_tipText == null) return;
RetailFont f = RetailData.Pal14;
List<string> lines = f.Wrap(_tipText, TooltipWrap);
if (lines.Count == 0) return;
int w = 0;
foreach (string l in lines) w = Math.Max(w, f.Measure(l));
int boxW = w + 8, boxH = lines.Count * f.LineHeight + 6;
// Below and right of the cursor, kept on screen. Design px from the panel's origin.
Vector2 mouse = ImGui.GetMousePos(), screen = ImGui.GetIO().DisplaySize;
float x = (mouse.X - _origin.X) / _k + 14, y = (mouse.Y - _origin.Y) / _k + 16;
float maxX = (screen.X - _origin.X) / _k - boxW - 2, maxY = (screen.Y - _origin.Y) / _k - boxH - 2;
int bx = (int)MathF.Round(Math.Max(-_origin.X / _k, Math.Min(x, maxX)));
int by = (int)MathF.Round(Math.Max(-_origin.Y / _k, Math.Min(y, maxY)));
ImDrawListPtr saved = _dl;
_dl = ImGui.GetForegroundDrawList();
try
{
_dl.AddRectFilled(P(bx, by), P(bx + boxW, by + boxH), TooltipBack);
_dl.AddRect(P(bx, by), P(bx + boxW, by + boxH), TooltipBorder, 0, ImDrawFlags.None, Math.Max(1f, _k));
for (int i = 0; i < lines.Count; i++)
Text(f, lines[i], bx + 4, by + 3 + i * f.LineHeight, boxW - 8, f.LineHeight, White);
}
finally { _dl = saved; }
}
private void Hover(uint key, string text) => _c.Hover(key, text);
private void UpdateTooltip() => _c.UpdateTooltip();
private void Tooltip() => _c.Tooltip();
private void ScrollBar(string id, ref float scroll, int top, int h, int visible, int total, float maxScroll)
{
// The track: a chain of 16x32 links, tiled.
IntPtr track = Tex(RynthIconKind.UiSprite, ArtTrack);
for (int y = top + ScrollBtn; y < top + h - ScrollBtn; y += 32)
{
int th = Math.Min(32, top + h - ScrollBtn - y);
if (track != IntPtr.Zero) _dl.AddImage(track, P(ScrollX, y), P(ScrollX + ScrollW, y + th), Vector2.Zero, new Vector2(1, th / 32f));
else _dl.AddRectFilled(P(ScrollX + 6, y), P(ScrollX + 10, y + th), 0xFF3C6A8Au);
}
// The arrows.
if (Button("##dw_up_" + id, ArtScrollUp, ScrollX, top, ScrollW, ScrollBtn)) scroll = Math.Max(0, scroll - 1);
if (Button("##dw_dn_" + id, ArtScrollDown, ScrollX, top + h - ScrollBtn, ScrollW, ScrollBtn)) scroll = Math.Min(maxScroll, scroll + 1);
// The thumb: caps and a stretched blue middle, sized to the share of the list that shows.
int trackTop = top + ScrollBtn, trackH = h - 2 * ScrollBtn;
if (trackH <= 8) return;
int thumbH = Math.Clamp((int)(trackH * visible / (float)total), 16, trackH);
int thumbY = trackTop + (int)((trackH - thumbH) * (maxScroll > 0 ? scroll / maxScroll : 0));
ImGui.SetCursorScreenPos(P(ScrollX, trackTop));
ImGui.InvisibleButton("##dw_track_" + id, S(ScrollW, trackH));
float mouseY = (ImGui.GetMousePos().Y - _origin.Y) / _k;
if (ImGui.IsItemActivated())
{
if (mouseY >= thumbY && mouseY < thumbY + thumbH) { _thumbDrag = true; _thumbGrab = mouseY - thumbY; }
else scroll = Math.Clamp(scroll + (mouseY < thumbY ? -visible : visible), 0, maxScroll);
}
if (_thumbDrag && ImGui.IsItemActive() && trackH > thumbH)
scroll = Math.Clamp((mouseY - _thumbGrab - trackTop) / (trackH - thumbH) * maxScroll, 0, maxScroll);
if (!ImGui.IsItemActive()) _thumbDrag = false;
Sprite(ArtThumbTop, ScrollX, thumbY, ScrollW, ScrollCap, 0xFF8C5A1Eu);
Sprite(ArtThumbMid, ScrollX, thumbY + ScrollCap, ScrollW, thumbH - 2 * ScrollCap, 0xFF8C3A10u);
Sprite(ArtThumbBottom, ScrollX, thumbY + thumbH - ScrollCap, ScrollW, ScrollCap, 0xFF8C5A1Eu);
}
=> _c.ScrollBar(id, ScrollX, ref scroll, top, h, visible, total, maxScroll);
// ── The footer (0x10000240 with nothing selected, 0x10000247 with a row), shared by both pages ──
@ -684,102 +585,20 @@ internal sealed class SkillsPanel
if (Button("##dw_raise", canOne ? ArtRaise : ArtRaiseGhost, 260, y + 26, 30, 26) && canOne) raiseOne?.Invoke();
if (showTen && Button("##dw_raise10", canTen ? ArtRaiseTen : ArtRaiseTenGhost, 260, y, 30, 26) && canTen) raiseTen?.Invoke();
}
// ── Drawing helpers (design pixels in, screen pixels out) ───────────
// ── Drawing helpers (design pixels in, screen pixels out): RetailCanvas's ──
private Vector2 P(float x, float y) => new(_origin.X + x * _k, _origin.Y + y * _k);
private Vector2 S(float w, float h) => new(Math.Max(1, w * _k), Math.Max(1, h * _k));
private bool Hit(int x, int y, int w, int h)
{
Vector2 m = ImGui.GetMousePos(), a = P(x, y), b = P(x + w, y + h);
return m.X >= a.X && m.X < b.X && m.Y >= a.Y && m.Y < b.Y;
}
private IntPtr Tex(RynthIconKind kind, uint id) => id == 0 ? IntPtr.Zero : _host.GetIconTexture(kind, id);
/// <summary>A retail picture stretched over the box (a flat stand-in until the engine has made it).</summary>
private void Sprite(uint id, int x, int y, int w, int h, uint fallback)
{
if (w <= 0 || h <= 0) return;
IntPtr t = Tex(RynthIconKind.UiSprite, id);
if (t == IntPtr.Zero) { _dl.AddRectFilled(P(x, y), P(x + w, y + h), fallback); return; }
_dl.AddImage(t, P(x, y), P(x + w, y + h));
}
/// <summary>The top-left <paramref name="w"/> x <paramref name="h"/> of a <paramref name="texW"/> x <paramref name="texH"/> picture, unscaled.</summary>
private Vector2 P(float x, float y) => _c.P(x, y);
private Vector2 S(float w, float h) => _c.S(w, h);
private bool Hit(int x, int y, int w, int h) => _c.Hit(x, y, w, h);
private IntPtr Tex(RynthIconKind kind, uint id) => _c.Tex(kind, id);
private void Sprite(uint id, int x, int y, int w, int h, uint fallback) => _c.Sprite(id, x, y, w, h, fallback);
private void SpriteCropped(uint id, int x, int y, int w, int h, int texW, int texH, uint fallback)
{
IntPtr t = Tex(RynthIconKind.UiSprite, id);
if (t == IntPtr.Zero) { _dl.AddRectFilled(P(x, y), P(x + w, y + h), fallback); return; }
_dl.AddImage(t, P(x, y), P(x + w, y + h), Vector2.Zero, new Vector2(Math.Min(1f, w / (float)texW), Math.Min(1f, h / (float)texH)));
}
private void Icon(uint id, int x, int y, int size)
{
IntPtr t = Tex(RynthIconKind.Icon, id);
if (t != IntPtr.Zero) _dl.AddImage(t, P(x, y), P(x + size, y + size));
}
/// <summary>A retail button: its picture, and true when clicked.</summary>
private bool Button(string imguiId, uint art, int x, int y, int w, int h)
{
ImGui.SetCursorScreenPos(P(x, y));
bool clicked = ImGui.InvisibleButton(imguiId, S(w, h));
Sprite(art, x, y, w, h, 0xFF3C8A3Cu);
return clicked;
}
/// <summary>
/// Text in a retail dat font, left-aligned (or <paramref name="right"/> / <paramref name="center"/>)
/// in the box and centred down it, glyph by glyph from the font's sheet; <paramref name="outline"/>
/// draws the font's outline sheet in black under it (the level number). ImGui's font stands in on an
/// engine without font sheets.
/// </summary>
=> _c.SpriteCropped(id, x, y, w, h, texW, texH, fallback);
private void Icon(uint id, int x, int y, int size) => _c.Icon(id, x, y, size);
private bool Button(string imguiId, uint art, int x, int y, int w, int h) => _c.Button(imguiId, art, x, y, w, h);
private void Text(RetailFont font, string? text, int x, int y, int w, int h, uint color,
bool right = false, bool center = false, bool outline = false)
{
if (string.IsNullOrEmpty(text)) return;
int width = font.Measure(text);
float left = right ? x + w - width : center ? x + (w - width) / 2f : x;
float top = y + (h - font.LineHeight) / 2f;
IntPtr sheet = Tex(RynthIconKind.FontSheet, font.Sheet);
if (sheet == IntPtr.Zero)
{
Vector2 sz = ImGui.CalcTextSize(text);
float fx = right ? P(x + w, 0).X - sz.X : center ? P(x + w / 2f, 0).X - sz.X / 2 : P(x, 0).X;
_dl.AddText(new Vector2(fx, P(0, y + h / 2f).Y - sz.Y / 2), color, text);
return;
}
left = MathF.Round(left);
top = MathF.Round(top);
if (outline && font.OutlineSheet != 0)
{
IntPtr back = Tex(RynthIconKind.FontSheet, font.OutlineSheet);
if (back != IntPtr.Zero) Glyphs(font, text, left, top, back, font.OutlineWidth, font.OutlineHeight, Black, font.BorderX, font.BorderY);
}
Glyphs(font, text, left, top, sheet, font.SheetWidth, font.SheetHeight, color, 0, 0);
}
private void Glyphs(RetailFont font, string text, float x, float y, IntPtr sheet, int sheetW, int sheetH, uint color, int bx, int by)
{
float pen = x;
foreach (char c in text)
{
if (!font.TryGlyph(c, out RetailGlyph g)) continue;
if (g.Width > 0 && g.Height > 0)
{
float gx = pen + g.Before - bx, gy = y + g.Top - by;
int sx = g.SheetX - bx, sy = g.SheetY - by, gw = g.Width + 2 * bx, gh = g.Height + 2 * by;
if (sx < 0) { gx -= sx; gw += sx; sx = 0; }
if (sy < 0) { gy -= sy; gh += sy; sy = 0; }
if (gw > 0 && gh > 0)
_dl.AddImage(sheet, P(gx, gy), P(gx + gw, gy + gh),
new Vector2(sx / (float)sheetW, sy / (float)sheetH),
new Vector2((sx + gw) / (float)sheetW, (sy + gh) / (float)sheetH), color);
}
pen += g.Advance;
}
}
=> _c.Text(font, text, x, y, w, h, color, right, center, outline);
private static SkillLine? Find(SkillsSheet sheet, uint id)
{

View file

@ -1,9 +1,10 @@
// SkillsReader.cs - Reads the character for the Skills panel and spends XP for it, on the plugin tick.
//
// Reading: while the panel is drawn it asks for a read about four times a second (RequestRead, render
// thread); the tick then reads the engine's training numbers (GetTrainingInfo, v79: the engine refreshes
// them every 2 s while asked, and at once after a raise) and the header's properties, and publishes one
// SkillsSheet. Nothing is read while the panel is closed.
// Reading: while the panel is drawn it asks for a read about four times a second (ReadDue, render
// thread; ReadGate keeps one in flight and re-asks for one that was lost); the tick then reads the
// engine's training numbers (GetTrainingInfo, v79: the engine refreshes them every 2 s while asked, and
// at once after a raise) and the header's properties, and publishes one SkillsSheet. Nothing is read
// while the panel is closed. Logout forgets the character (Clear).
//
// Spending: the panel's raise arrow and "+10" queue a press (a raise, or a train for an untrained skill);
// the tick sends it at the cost the newest numbers say, and the engine refuses it when its own numbers
@ -20,12 +21,11 @@ internal sealed class SkillsReader
{
private const uint IntGender = 113, IntHeritage = 188, IntPkStatus = 134, IntAllegianceRank = 30, IntCharacterTitleId = 261;
private const uint QuadAvailableLuminance = 6, QuadMaximumLuminance = 7;
private const long ReadEveryMs = 250;
private const uint IntLevel = 25, QuadTotalExperience = 1;
private readonly TrainingEntryNative[] _entries = new TrainingEntryNative[128];
private SkillsSheet _sheet = SkillsSheet.Empty;
private long _lastAsk;
private int _readQueued;
private readonly ReadGate _gate = new();
private string _message = "";
private readonly HeldRaises _held = new();
private Action<string>? _chat;
@ -38,25 +38,23 @@ internal sealed class SkillsReader
/// <summary>
/// Render thread, each frame the panel draws: true when a read is due (the caller queues
/// <see cref="Read"/> for the tick). At most four a second, one in flight.
/// <see cref="Read"/> for the tick). At most four a second, one in flight (ReadGate); every frame while
/// a raise is on its way or a press waits, to send the next one as soon as it may go.
/// </summary>
public bool ReadDue()
{
long now = Environment.TickCount64;
// A raise on its way or a press waiting: every frame, to send the next one as soon as it may go.
long every = _held.Count > 0 || Volatile.Read(ref _sheet).Busy ? 0 : ReadEveryMs;
if (now - Volatile.Read(ref _lastAsk) < every) return false;
if (Interlocked.Exchange(ref _readQueued, 1) == 1) return false;
Volatile.Write(ref _lastAsk, now);
return true;
}
=> _gate.Due(Environment.TickCount64, _held.Count > 0 || Volatile.Read(ref _sheet).Busy);
/// <summary>Logout: forget the character.</summary>
/// <summary>
/// Logout (pump thread): forget the character, and any read the logout dropped from the tick's queue.
/// 2026-11-14 (R-20261114-190620-f744): nothing called this, so the last character's numbers stayed on
/// the panel after a relog until a read replaced them, and with a dropped read none ever did (ReadGate).
/// </summary>
public void Clear()
{
Volatile.Write(ref _sheet, SkillsSheet.Empty);
Volatile.Write(ref _message, "");
_held.Drop();
_gate.Reset();
}
/// <summary>Plugin tick: reads the numbers and publishes a new sheet when they are in.</summary>
@ -103,12 +101,20 @@ internal sealed class SkillsReader
string title = SkillsLayout.Title(titleId);
long? lumMax = Quad(host, me, QuadMaximumLuminance);
long? lumAvail = Quad(host, me, QuadAvailableLuminance);
// Level and total XP straight from the player's properties (2026-11-14, R-20261114-190620-f744):
// the engine's property caches take the server's private updates (Level 25 on a level-up,
// TotalExperience 1 on every award) as they land, while the training numbers are a snapshot the
// engine republishes every 2 s at best, and only while its main-thread read of the character
// succeeds. The snapshot's own values (the same caches, read on AC's main thread) stand in when
// a property isn't known.
int level = Int(host, me, IntLevel) is int lv and > 0 ? lv : info.Level;
long totalXp = Quad(host, me, QuadTotalExperience) is long tx and >= 0 ? tx : info.TotalXp;
TitleList titles = TitlesFor(me).WithDisplayed((uint)Math.Max(0, titleId));
var attrList = new System.Collections.Generic.List<AttributeLine>(attrs.Length);
foreach (AttributeLine? a in attrs) if (a != null) attrList.Add(a);
var sheet = new SkillsSheet(name, SkillsLayout.Identity(gender, heritage, title), SkillsLayout.PkStatus(pk),
info.Level, info.TotalXp, info.UnassignedXp, info.SkillCredits,
level, totalXp, info.UnassignedXp, info.SkillCredits,
lumMax is > 0 ? lumAvail ?? 0 : null, lumMax is > 0 ? lumMax : null,
skills, info.Busy, info.SnapshotVersion, attrList, titles);
Volatile.Write(ref _sheet, sheet);
@ -116,7 +122,7 @@ internal sealed class SkillsReader
}
finally
{
Volatile.Write(ref _readQueued, 0);
_gate.Done();
}
}
@ -147,9 +153,15 @@ internal sealed class SkillsReader
// Trained meanwhile (a train press) or not trained (a raise press): not what was clicked.
if (skill == null || (t.Kind == RaiseTarget.Train) != (skill.Class < SkillClass.Trained)) { _held.Drop(); return; }
name = skill.Name;
r = t.Kind == RaiseTarget.Train
? host.TrainSkill(skill.Id, skill.TrainCredits)
: host.Raise(TrainingKind.Skill, skill.Id, t.Ten ? 10u : 1u, t.Ten ? skill.CostTen : skill.CostOne, out _);
if (t.Kind == RaiseTarget.Train)
r = host.TrainSkill(skill.Id, skill.TrainCredits);
else
{
// +10 is ten ranks, or the last ones when fewer than ten are left (retail's; SkillsLayout.TenStep).
(uint ranks, long cost) = t.Ten ? SkillsLayout.Ten(skill) : (1u, skill.CostOne);
if (ranks == 0) { _held.Drop(); return; } // at the top now: the rest of the presses buy nothing
r = host.Raise(TrainingKind.Skill, skill.Id, ranks, cost, out _);
}
}
else
{
@ -157,10 +169,11 @@ internal sealed class SkillsReader
foreach (AttributeLine x in sheet.AttributeRows) if (x.Kind == t.Kind && x.Stype == t.Id) { a = x; break; }
if (a == null) { _held.Drop(); return; }
name = a.Name;
r = host.Raise(a.IsVital ? TrainingKind.Vital : TrainingKind.Attribute, a.Stype, t.Ten ? 10u : 1u,
t.Ten ? a.CostTen : a.CostOne, out _);
(uint ranks, long cost) = t.Ten ? AttributesPage.Ten(a) : (1u, a.CostOne);
if (ranks == 0) { _held.Drop(); return; }
r = host.Raise(a.IsVital ? TrainingKind.Vital : TrainingKind.Attribute, a.Stype, ranks, cost, out _);
}
Volatile.Write(ref _lastAsk, 0); // read again at once
_gate.AskNow(); // read again at once
switch (r)
{
case RaiseResult.Sent:
@ -223,7 +236,7 @@ internal sealed class SkillsReader
_titles[me] = next;
}
_saveTitles?.Invoke(me, next.Save());
Volatile.Write(ref _lastAsk, 0); // show it at once
_gate.AskNow(); // show it at once
}
/// <summary>Plugin tick: show <paramref name="titleId"/> as the character's title (retail's "Set as Display Title").</summary>
@ -232,7 +245,7 @@ internal sealed class SkillsReader
if (titleId == 0) return;
if (!host.HasInvokeChatParser || !host.InvokeChatParser("/rc title " + titleId.ToString(System.Globalization.CultureInfo.InvariantCulture)))
chat("Couldn't set the title: this RynthCore can't send it (needs the engine from 2026-11-07).");
Volatile.Write(ref _lastAsk, 0);
_gate.AskNow();
}
private static int Int(RynthCoreHost host, uint id, uint stype)

View file

@ -141,9 +141,36 @@ internal static class SkillsLayout
return s.Trainable && s.TrainCredits > 0 && sheet.SkillCredits >= s.TrainCredits;
}
/// <summary>Whether "+10" can be pressed now (trained or specialized, ten ranks left and affordable).</summary>
/// <summary>Whether "+10" can be pressed now (trained or specialized, a rank left and the step affordable).</summary>
public static bool CanRaiseTen(SkillsSheet sheet, SkillLine s)
=> s.Class >= SkillClass.Trained && s.Raisable && s.CostTen > 0 && sheet.UnassignedXp >= s.CostTen;
=> s.Class >= SkillClass.Trained && s.Raisable && Ten(s) is { Ranks: > 0 } t && sheet.UnassignedXp >= t.Cost;
/// <summary>What "+10" buys for a trained or specialized skill (<see cref="TenStep"/> on its chart).</summary>
public static (uint Ranks, long Cost) Ten(SkillLine s) => TenStep(s.Class switch
{
SkillClass.Specialized => RetailData.SpecializedSkillXp,
SkillClass.Trained => RetailData.TrainedSkillXp,
_ => Array.Empty<uint>(),
}, s.Ranks, s.XpSpent, s.CostTen);
/// <summary>
/// Retail's "+10" (gmSkillUI / gmAttributeUI GetCostToRaise10, acclient 0x0049B130 / 0x0049CEE0): ten
/// ranks, or every rank left when fewer than ten are, for chart[ranks + n] - spent. The engine's +10
/// (<paramref name="costTen"/>) is -1 when fewer than ten are left, so the panel ghosted +10 for the last
/// nine ranks and a stat raised by tens stuck there (a #rynth-issues report, 2026-11-11, "Can't max
/// skills": a skill untrained and trained again comes back at rank 0, and twenty +10s leave a trained one
/// at 200 of 208). The engine's cost is used whenever it has one; the last ranks are priced from the same
/// portal chart, and the engine checks that price against its own before anything is sent. (0, -1): none.
/// </summary>
public static (uint Ranks, long Cost) TenStep(uint[] chart, uint ranks, uint spent, long costTen)
{
if (costTen > 0) return (10, costTen);
if (chart.Length == 0 || ranks + 1L >= chart.Length) return (0, -1); // at the top (or no chart)
uint left = (uint)(chart.Length - 1 - ranks);
if (left >= 10) return (0, -1); // ten are left yet the engine priced none: don't guess
long cost = (long)chart[ranks + left] - spent;
return cost > 0 ? (left, cost) : (0, -1);
}
/// <summary>
/// Retail's header line one: the allegiance rank's title for the heritage and sex, then the name

View file

@ -0,0 +1,115 @@
// XpBonusStrip.cs - RynthDreamWeave's offline bonus tracker (2026-11-15): the row at the top of the DreamWeave
// window's Character page, drawn the way the Leaderboards page and the Character panel are (RetailCanvas): retail's
// tiled page, a section banner, the bonus in Palatino 16 (green while it is being spent), how old the server's
// reading is in Palatino 14, and retail's red Check now and Auto read buttons; right-click it for the setting as a
// checkbox, as on the Leaderboards page. Hovering a line shows retail's tooltip box.
// Render thread: draws holding the reader's lock, and queues what it sends for the tick.
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDreamWeave;
internal sealed class XpBonusStrip
{
private const int H = 20 + 20 + 18 + 4 + 32 + 4;
private static readonly uint Grey = RetailCanvas.TabOff;
private readonly DreamWeaveXpBonus _x;
private readonly Func<RynthCoreHost> _host;
private readonly Func<int> _scale;
private readonly Action<Action> _runOnTick;
private readonly Action _check;
private readonly Action<bool> _setAuto;
private RetailCanvas? _c;
/// <param name="scale">The DreamWeave window's draw size in percent (Ctrl+wheel; 0 when unknown).</param>
/// <param name="check">Check now (pump thread, queued with runOnTick).</param>
/// <param name="setAuto">Turns the automatic read on or off and saves it (pump thread).</param>
public XpBonusStrip(DreamWeaveXpBonus reader, Func<RynthCoreHost> host, Func<int> scale, Action<Action> runOnTick,
Action check, Action<bool> setAuto)
{
_x = reader;
_host = host;
_scale = scale;
_runOnTick = runOnTick;
_check = check;
_setAuto = setAuto;
}
public void Draw()
{
_c ??= new RetailCanvas(_host());
RetailCanvas c = _c;
Vector2 start = ImGui.GetCursorScreenPos();
Vector2 avail = ImGui.GetContentRegionAvail();
int pct = _scale();
float k = pct > 0 ? Math.Clamp(pct / 100f, 0.3f, 2.5f) : 1f;
int w = Math.Max(280, (int)(avail.X / k));
c.Begin(ImGui.GetWindowDrawList(), new Vector2(MathF.Round(start.X), MathF.Round(start.Y)), k);
c.ClearHover();
long now = Environment.TickCount64;
bool auto;
lock (_x.Gate)
{
auto = _x.AutoRead;
c.PageBackground(0, 0, w, H);
c.SpriteCropped(RetailCanvas.ArtBannerSpecialized, 0, 0, w, 20, 282, 20, 0xFF3A1E2Au);
c.Text(RetailData.Pal18, "Double XP (offline bonus)", 4, 0, w - 8, 20, RetailCanvas.White);
string line = _x.Line(now);
uint color = _x.IsActive(now) ? RetailCanvas.Green
: _x.HasReading && (_x.State is XpBonusState.Banking or XpBonusState.Unknown) && _x.Remaining(now) > 0 ? RetailCanvas.White
: Grey;
c.Text(RetailData.Pal16, RetailCanvas.Fit(RetailData.Pal16, line, w - 12), 6, 20, w - 12, 20, color);
if (c.Hit(0, 20, w, 20))
c.Hover(1u, "DreamWeave's offline bonus: while any time is left, your combat experience and luminance get "
+ $"{(_x.Percent is int p ? "+" + p + "%" : "the bonus (+100% by default)")}. It banks 1:1 while this "
+ "character is logged out, or online but idle (no combat XP for 5 minutes), up to 24 hours, and "
+ "drains 1:1 while you fight. /offlinebonus asks the server.");
string waiting = _x.Waiting(now) ? "Asking the server..." : _x.Detail(now, DateTime.UtcNow);
c.Text(RetailData.Pal14, RetailCanvas.Fit(RetailData.Pal14, waiting, w - 12), 6, 40, w - 12, 18, RetailCanvas.Body);
if (c.Hit(0, 40, w, 18))
c.Hover(2u, "Between readings the row counts down while the bonus is spent and up while it banks. The server's "
+ "own lines keep it right: the login lines, \"now active\", \"now idle and banking again\", "
+ "\"exhausted\", /bonus and the [BANK] line of every /b (the bank check sends one a minute).");
int by = 20 + 20 + 18 + 4;
int bw = (w - 3 * 6) / 2;
bool busy = _x.Waiting(now);
if (c.RedButton("##dw_xpbonus_check", "Check now", 6, by, bw, !busy)) _runOnTick(_check);
if (c.Hit(6, by, bw, 32)) c.Hover(3u, $"Sends {DreamWeaveXpBonus.Command} at the next quiet moment and reads the reply (kept out of chat).");
string autoLabel = bw < 150 ? (auto ? "Auto: On" : "Auto: Off") : (auto ? "Auto read: On" : "Auto read: Off");
if (c.RedButton("##dw_xpbonus_auto", autoLabel, 12 + bw, by, bw, true)) _runOnTick(() => _setAuto(!auto));
if (c.Hit(12 + bw, by, bw, 32))
c.Hover(4u, $"Read the offline bonus automatically: {DreamWeaveXpBonus.Command} 35 seconds after login, then every "
+ "ten minutes, kept out of chat and never within a few seconds of the bank's /b or the leaderboards' /top. "
+ "Off by default: the server's own lines and the bank check's /b keep the row current without it.");
}
c.UpdateTooltip();
OptionsMenu(w, auto);
c.Tooltip();
ImGui.SetCursorScreenPos(start);
ImGui.Dummy(new Vector2(w * k, H * k));
}
/// <summary>Right-click the row: its setting as a checkbox (the Leaderboards page's options menu).</summary>
private void OptionsMenu(int w, bool auto)
{
RetailCanvas c = _c!;
if (ImGui.IsMouseClicked(ImGuiMouseButton.Right) && c.Hit(0, 0, w, H) && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows))
ImGui.OpenPopup("##dw_xpbonus_options");
if (!ImGui.BeginPopup("##dw_xpbonus_options")) return;
try
{
bool on = auto;
if (ImGui.Checkbox("Read the offline bonus automatically", ref on)) _runOnTick(() => _setAuto(on));
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip($"{DreamWeaveXpBonus.Command} after login and every ten minutes; its replies stay out of chat.");
}
finally { ImGui.EndPopup(); }
}
}

View file

@ -0,0 +1,256 @@
// DreamWeaveBoardsHost.cs - RynthDreamWeave's Leaderboards (2026-11-15), through the shared server plugin's
// hooks (Plugins/Shared/ServerPack/ServerPackPlugin.cs): the Leaderboards page (DreamWeave/BoardsPage.cs) and
// "/rserver boards", fed by DreamWeave's own /top (DreamWeave/DreamWeaveBoards.cs reads the replies).
//
// With "Refresh leaderboards automatically" on (off by default) one board's /top goes every 35 s while the
// character is in the world and not in portal space, so each of the 17 boards is about ten minutes old at most;
// the replies to RynthDreamWeave's own requests are kept out of chat, a /top the player types shows as usual and
// still updates the page. One request at a time; a reply that doesn't come in 6 s is given up.
// The last reading of every board is kept per character beside the plugin's settings
// (%APPDATA%\RynthCore\rynthdreamweave.boards.<character id>.json), so the page isn't empty after a reload.
//
// The hooks it shares with the bank, the Skills panel and the web tools are implemented once (DreamWeavePlugin.cs,
// DreamWeaveSkills.cs, DreamWeaveWebTools.cs) and call the Boards* methods here.
// Threads: the chat bar note runs on AC's thread (interlocked counter and a queue only); everything else on the
// pump, holding _boards.Gate around the reader only (never around Send, Reply or file I/O).
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using RynthCore.Plugin.RynthDreamWeave;
namespace RynthCore.Plugin.ServerPack;
public sealed partial class ServerPackPlugin
{
private readonly DreamWeaveBoards _boards = new();
// Our own "/top" sends not yet seen by the chat bar (0 or 1): tells them from a /top the player typed.
private int _boardSelfSends;
// /top lines the player typed (AC's thread), read on the pump.
private readonly ConcurrentQueue<string> _typedTops = new();
private uint _boardsCharacter;
private long _boardsSaveDueMs;
private bool _boardsSaveFailed;
private const long BoardsSaveEveryMs = 30_000;
private void AddBoardsPage(List<ServerPage> pages)
{
var page = new BoardsPage(_boards, () => Active, () => Host,
() => Host.PanelScale(ServerPackModel.WindowTitle(Info)), RunOnTick,
key => BoardsRefresh(key, typed: false), () => BoardsSweep(typed: false), on => BoardsSetAuto(on, typed: false));
pages.Add(page.Page());
}
private void BoardsInitialize()
{
lock (_boards.Gate) _boards.LoadSettings(Settings.GetBool);
}
private void BoardsLogin()
{
while (_typedTops.TryDequeue(out _)) { }
Interlocked.Exchange(ref _boardSelfSends, 0);
_boardsCharacter = 0;
lock (_boards.Gate) _boards.Login(Environment.TickCount64);
}
private void BoardsLogout()
{
BoardsSave(force: true);
lock (_boards.Gate) _boards.Logout();
_boardsCharacter = 0;
}
private void BoardsShutdown() => BoardsSave(force: true);
/// <summary>AC's thread: a line through the chat bar. Our own /top, or one the player typed?</summary>
private void BoardsChatBar(string text)
{
if (DreamWeaveBoards.KeyOfCommand(text) == null) return;
if (Interlocked.Decrement(ref _boardSelfSends) >= 0) return;
Interlocked.Exchange(ref _boardSelfSends, 0);
_typedTops.Enqueue(text);
}
/// <summary>An incoming chat line on DreamWeave: true when it answers RynthDreamWeave's own /top.</summary>
private bool BoardsChatText(string text, int chatType)
{
long now = Environment.TickCount64;
lock (_boards.Gate)
{
while (_typedTops.TryDequeue(out string? typed)) _boards.NoteTyped(typed, now);
return _boards.OnChatText(text, chatType, now, DateTime.UtcNow);
}
}
private void BoardsTick()
{
long now = Environment.TickCount64;
uint player = Host.HasGetPlayerId ? Host.GetPlayerId() : 0;
if (player != 0 && player != _boardsCharacter) BoardsLoadFor(player);
bool canSend = player != 0 && Host.HasInvokeChatParser && !(Host.HasIsPortaling && Host.IsPortaling());
string? command;
lock (_boards.Gate)
{
while (_typedTops.TryDequeue(out string? typed)) _boards.NoteTyped(typed, now);
if (!_boards.Pending) Interlocked.Exchange(ref _boardSelfSends, 0);
command = _boards.Due(now, canSend);
}
if (command != null) SendBoardCommand(command);
if (now >= _boardsSaveDueMs) BoardsSave(force: false);
}
/// <summary>Sends a /top the boards asked for (marked as ours first); false when it didn't go.</summary>
private bool SendBoardCommand(string command)
{
Interlocked.Exchange(ref _boardSelfSends, 1);
if (Send(command)) { NoteServerSend(); return true; } // DreamWeaveXpBonusHost.cs keeps clear of it
Interlocked.Exchange(ref _boardSelfSends, 0);
lock (_boards.Gate) _boards.NotSent();
return false;
}
/// <summary>The boards saved for this character, and its name (to find your row inside a list).</summary>
private void BoardsLoadFor(uint player)
{
_boardsCharacter = player;
string name = Host.HasGetObjectName && Host.TryGetObjectName(player, out string n) ? n.Trim() : "";
string? json = null;
try
{
string path = DreamWeaveBoards.SavePath(Settings.FilePath, player);
if (File.Exists(path)) json = File.ReadAllText(path);
}
catch (Exception ex)
{
LogTagged("The saved leaderboards weren't read: " + ex.GetType().Name);
}
lock (_boards.Gate)
{
_boards.YourName = name;
_boards.LoadSaved(json);
}
}
/// <summary>Writes the boards read since the last save (at most every 30 s, and at logout). Pump thread.</summary>
private void BoardsSave(bool force)
{
_boardsSaveDueMs = Environment.TickCount64 + BoardsSaveEveryMs;
uint player = _boardsCharacter;
if (player == 0) return;
string json;
lock (_boards.Gate)
{
if (!_boards.Dirty || (!force && _boards.Pending)) return;
json = _boards.SaveJson();
}
try
{
string path = DreamWeaveBoards.SavePath(Settings.FilePath, player);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + ".tmp";
File.WriteAllText(tmp, json);
File.Move(tmp, path, overwrite: true);
_boardsSaveFailed = false;
}
catch (Exception ex)
{
if (!_boardsSaveFailed) LogTagged("The leaderboards weren't saved: " + ex.GetType().Name + ": " + ex.Message);
_boardsSaveFailed = true;
}
}
// ── What the page's buttons and "/rserver boards" do (pump thread) ──
private void BoardsRefresh(string key, bool typed)
{
BoardDef? d = DreamWeaveBoards.Def(key);
if (d == null) return;
if (!Active) { Reply.Fail("The leaderboards are DreamWeave's; RynthCore doesn't see this world as DreamWeave."); return; }
string? command;
lock (_boards.Gate)
{
if (_boards.Pending) command = null;
else command = _boards.Request(key, Environment.TickCount64);
}
if (command == null) { Reply.Fail("Still waiting for the last leaderboard reply; try again in a few seconds."); return; }
if (!SendBoardCommand(command)) { Reply.Fail($"Couldn't send {command} (not in the world)."); return; }
if (typed) Reply.Ok($"Reading the {d.Label} board ({command}).");
}
private void BoardsSweep(bool typed)
{
if (!Active) { Reply.Fail("The leaderboards are DreamWeave's; RynthCore doesn't see this world as DreamWeave."); return; }
lock (_boards.Gate) _boards.SweepAll();
if (typed)
Reply.Ok($"Reading all {DreamWeaveBoards.Defs.Length} boards, one every {DreamWeaveBoards.SweepIntervalMs / 1000} seconds; their replies stay out of chat.");
}
private void BoardsSetAuto(bool on, bool typed)
{
lock (_boards.Gate) _boards.SetAutoRefresh(on, Environment.TickCount64);
if (Settings.SetBool(DreamWeaveBoards.SettingAutoRefresh, on)) Settings.Save();
if (typed)
Reply.Ok(on ? "Leaderboards refresh automatically: one board every 35 seconds, each about every ten minutes."
: "Leaderboards no longer refresh automatically.");
}
private void BoardsCommandVerbs(List<string> verbs) => verbs.Add("boards");
private const string BoardsUsage = "/rserver boards [<board> | refresh <board>|all | auto on|off]: DreamWeave's leaderboards (/top), also the window's Leaderboards tab";
private void BoardsChatCommand(string[] parts, ref bool handled)
{
if (parts.Length < 2 || !parts[1].Equals("boards", StringComparison.OrdinalIgnoreCase)) return;
handled = true;
string verb = parts.Length > 2 ? parts[2].ToLowerInvariant() : "";
string rest = parts.Length > 3 ? string.Join(' ', parts.Skip(3)) : "";
switch (verb)
{
case "":
{
int read;
bool auto;
lock (_boards.Gate) { read = _boards.ReadCount; auto = _boards.AutoRefresh; }
Reply.Ok($"Leaderboards: {read} of {DreamWeaveBoards.Defs.Length} boards read; automatic refresh {(auto ? "on" : "off")}. "
+ "The DreamWeave window's Leaderboards tab shows them.");
return;
}
case "auto":
if (rest.Equals("on", StringComparison.OrdinalIgnoreCase)) BoardsSetAuto(true, typed: true);
else if (rest.Equals("off", StringComparison.OrdinalIgnoreCase)) BoardsSetAuto(false, typed: true);
else Reply.Fail("Usage: /rserver boards auto on|off");
return;
case "refresh":
if (rest.Equals("all", StringComparison.OrdinalIgnoreCase)) { BoardsSweep(typed: true); return; }
if (DreamWeaveBoards.KeyOfName(rest) is string key) { BoardsRefresh(key, typed: true); return; }
Reply.Fail(rest.Length == 0 ? "Usage: /rserver boards refresh <board>|all" : UnknownBoard(rest));
return;
}
string name = string.Join(' ', parts.Skip(2));
if (DreamWeaveBoards.KeyOfName(name) is not string k) { Reply.Fail(UnknownBoard(name)); return; }
BoardDef d = DreamWeaveBoards.Def(k)!;
string line;
lock (_boards.Gate)
{
BoardResult? r = _boards.Result(k);
BoardStanding st = _boards.Standing(k);
line = r == null
? $"{d.Label}: not read yet. /rserver boards refresh {k} reads it."
: $"{d.Label}: {_boards.StandingText(k)}{(st.Rank > 0 && st.Value.Length > 0 ? " (" + st.Value + ")" : "")}, "
+ DreamWeaveBoards.Age(r.UpdatedUtc, DateTime.UtcNow) + ".";
}
Reply.Ok(line);
}
private static string UnknownBoard(string name)
=> $"No board called '{name}'. Boards: {string.Join(", ", DreamWeaveBoards.Defs.Select(d => d.Key == "winners" ? "speed winners" : d.Key))}.";
private void BoardsInfoLines(Action<string> line)
{
lock (_boards.Gate)
line($"Leaderboards: {_boards.ReadCount} of {DreamWeaveBoards.Defs.Length} read; automatic refresh {(_boards.AutoRefresh ? "on" : "off")} (/rserver boards).");
}
}

View file

@ -2,6 +2,9 @@
// (Plugins/Shared/ServerPack/ServerPackPlugin.cs): the every-minute bank check that gives Lum/hr its
// luminance on DreamWeave (DreamWeave/DreamWeaveBank.cs, 2026-11-02), published as the profile value
// "bankLuminance" for the session stats, and its Bank page (DreamWeave/DreamWeavePages.cs).
// 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 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.
@ -18,12 +21,15 @@ 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
AddCharacterPage(pages); // DreamWeaveSkills.cs: the Character panel's page
}
partial void ServerInitialize()
{
lock (_bank.Gate) _bank.LoadSettings(Settings);
BoardsInitialize();
XpBonusInitialize();
}
private void SaveDreamWeaveSettings()
@ -35,24 +41,34 @@ public sealed partial class ServerPackPlugin
{
WebLoginComplete();
lock (_bank.Gate) _bank.Login(Environment.TickCount64);
BoardsLogin();
XpBonusLogin();
}
partial void ServerLogout()
{
WebLogout();
lock (_bank.Gate) _bank.Logout();
SkillsLogout();
BoardsLogout();
XpBonusLogout();
}
partial void ServerShutdown()
{
WebShutdown();
SaveDreamWeaveSettings();
BoardsShutdown();
XpBonusShutdown();
}
partial void ServerChatText(string text, int chatType, ref bool eat)
{
WebChatText(text, chatType, ref eat);
if (!Active) return;
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;
bool ours;
long? value;
lock (_bank.Gate)
@ -68,19 +84,27 @@ public sealed partial class ServerPackPlugin
{
// The player's own /b: its reply shows (DreamWeaveBank tells it from RynthDreamWeave's).
if (DreamWeaveBank.IsBalanceCommand(text)) _bank.NoteTypedCommand();
BoardsChatBar(text);
XpBonusChatBar(text);
}
partial void ServerTick(bool active)
{
WebTick();
if (!active) return;
BoardsTick();
string? check;
lock (_bank.Gate)
{
_bank.Tick();
check = _bank.CheckDue(Environment.TickCount64);
}
if (check != null && !Send(check)) lock (_bank.Gate) _bank.NotSent();
if (check != null)
{
if (Send(check)) NoteServerSend();
else lock (_bank.Gate) _bank.NotSent();
}
XpBonusTick(); // after the bank and the boards: it goes only when neither just went or is about to
}
/// <summary>The page's Check now (on the tick).</summary>
@ -89,7 +113,8 @@ public sealed partial class ServerPackPlugin
if (!Active) return;
string command;
lock (_bank.Gate) command = _bank.Request(Environment.TickCount64);
if (!Send(command))
if (Send(command)) NoteServerSend();
else
{
lock (_bank.Gate) _bank.NotSent();
ChatFail($"[{RynthPluginInfo.Name}] Couldn't send {command}.");
@ -103,6 +128,8 @@ public sealed partial class ServerPackPlugin
string lum = _bank.Luminance is long l ? l.ToString("N0", System.Globalization.CultureInfo.InvariantCulture) : "not read yet";
line($"Bank check every minute {(_bank.CheckEveryMinute ? "on" : "off")}; banked luminance {lum}.");
}
BoardsInfoLines(line);
XpBonusInfoLines(line);
WebInfoLines(line);
}
}

View file

@ -14,7 +14,8 @@
// "/rc title <id>" (the engine calls AC's own sender).
//
// Hooks used: ServerWindows, ServerCommandVerbs, ServerChatCommand, ServerMessageInterest, ServerMessage,
// ServerRender - none of the other DreamWeave features' (the bank check's), so they sit side by side.
// ServerRender - none of the other DreamWeave features' (the bank check's), so they sit side by side - and
// ServerLogout, shared with them, which calls SkillsLogout (2026-11-14).
using System;
using System.Collections.Generic;
using System.Globalization;
@ -88,7 +89,8 @@ public sealed partial class ServerPackPlugin
replacesAc: () => Volatile.Read(ref _replaceAc) != 0,
setReplacesAc: SetReplaceAc,
onePanel: () => Volatile.Read(ref _onePanel) != 0,
setOnePanel: SetOnePanel);
setOnePanel: SetOnePanel,
drawTop: DrawXpBonusStrip); // DreamWeaveXpBonusHost.cs: the offline bonus tracker
pages.Add(page.Page());
}
@ -219,6 +221,13 @@ public sealed partial class ServerPackPlugin
// ── Titles from the server ──────────────────────────────────────────
/// <summary>
/// Logout or character switch (pump thread, from ServerLogout): the reader forgets the character and
/// any read the logout dropped. 2026-11-14 (R-20261114-190620-f744): without it the panel could keep the
/// last read's level and XP for the rest of the session (ReadGate.cs).
/// </summary>
private void SkillsLogout() => _skillsReader.Clear();
partial void ServerMessageInterest(List<uint> gameEvents)
{
gameEvents.Add(EventCharacterTitle);
@ -239,12 +248,18 @@ public sealed partial class ServerPackPlugin
{
verbs.Add("skills");
WebCommandVerbs(verbs); // DreamWeaveWebTools.cs: the website verbs
BoardsCommandVerbs(verbs); // DreamWeaveBoardsHost.cs: /rserver boards
XpBonusCommandVerbs(verbs); // DreamWeaveXpBonusHost.cs: /rserver xpbonus
}
partial void ServerChatCommand(string[] parts, ref bool handled)
{
WebChatCommand(parts, ref handled); // DreamWeaveWebTools.cs: a website verb
if (handled) return;
BoardsChatCommand(parts, ref handled); // DreamWeaveBoardsHost.cs: /rserver boards
if (handled) return;
XpBonusChatCommand(parts, ref handled); // DreamWeaveXpBonusHost.cs: /rserver xpbonus
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

View file

@ -52,6 +52,8 @@ public sealed partial class ServerPackPlugin
try
{
add(DreamWeaveWeb.UsageLine());
add(BoardsUsage); // DreamWeaveBoardsHost.cs
add(XpBonusUsage); // DreamWeaveXpBonusHost.cs
}
catch (Exception)
{

View file

@ -0,0 +1,273 @@
// DreamWeaveXpBonusHost.cs - RynthDreamWeave's offline bonus tracker ("double XP time", 2026-11-15), through the
// shared server plugin's hooks (Plugins/Shared/ServerPack/ServerPackPlugin.cs): the row at the top of the
// DreamWeave window's Character page (DreamWeave/XpBonusStrip.cs) and "/rserver xpbonus", fed by the server's own
// lines (DreamWeave/DreamWeaveXpBonus.cs reads them).
//
// Passive: every offline-bonus line the server sends is read and shows as usual - the login line and the status
// line 3 s after it, "now active", "now idle and banking again", "exhausted", /bonus, and the "[BANK] Offline Bonus
// Time" line of every /b (the bank check's own every-minute /b, whose reply the bank keeps out of chat, included).
// With "Read the offline bonus automatically" on (off by default) /offlinebonus also goes 35 s after login and then
// every ten minutes, never within 5 s of the bank's /b or the leaderboards' /top, and its reply is kept out of chat;
// a /offlinebonus the player types shows as usual and still updates the row. Check now (and "/rserver xpbonus
// check") asks once, at the next quiet moment, the automatic read on or off.
// The last reading is kept per character beside the plugin's settings
// (%APPDATA%\RynthCore\rynthdreamweave.xpbonus.<character id>.json), so the row isn't empty after a reload.
//
// The hooks it shares with the bank, the leaderboards, the Skills panel and the web tools are implemented once
// (DreamWeavePlugin.cs, DreamWeaveSkills.cs, DreamWeaveWebTools.cs) and call the XpBonus* methods here.
// Threads: the chat bar note runs on AC's thread (interlocked fields only); everything else on the pump, holding
// _xpBonus.Gate around the reader only (never around Send, Reply or file I/O).
using System;
using System.Collections.Generic;
using System.IO;
using RynthCore.Plugin.RynthDreamWeave;
namespace RynthCore.Plugin.ServerPack;
public sealed partial class ServerPackPlugin
{
private readonly DreamWeaveXpBonus _xpBonus = new();
private uint _xpBonusCharacter;
private long _xpBonusSaveDueMs;
private bool _xpBonusSaveFailed;
// A typed "/rserver xpbonus check": its answer (or that none came) is said in chat.
private bool _xpBonusAnnounce;
// The last of RynthDreamWeave's own server commands (/b, /top, /offlinebonus), for the gap between them.
private long _lastServerSendMs = long.MinValue / 2;
private XpBonusStrip? _xpBonusStrip;
private const long XpBonusSaveEveryMs = 30_000;
/// <summary>The Character page's top row (DreamWeaveSkills.AddCharacterPage). Render thread.</summary>
private void DrawXpBonusStrip()
{
_xpBonusStrip ??= new XpBonusStrip(_xpBonus, () => Host, () => Host.PanelScale(ServerPackModel.WindowTitle(Info)),
RunOnTick, () => XpBonusCheck(typed: false), on => XpBonusSetAuto(on, typed: false));
_xpBonusStrip.Draw();
}
/// <summary>One of RynthDreamWeave's own server commands just went out (the gap the offline bonus read keeps).</summary>
private void NoteServerSend() => _lastServerSendMs = Environment.TickCount64;
private void XpBonusInitialize()
{
lock (_xpBonus.Gate) _xpBonus.LoadSettings(Settings.GetBool);
}
private void XpBonusLogin()
{
_xpBonusCharacter = 0;
_xpBonusAnnounce = false;
lock (_xpBonus.Gate) _xpBonus.Login(Environment.TickCount64);
}
private void XpBonusLogout()
{
XpBonusSave();
lock (_xpBonus.Gate) _xpBonus.Logout();
_xpBonusCharacter = 0;
_xpBonusAnnounce = false;
}
private void XpBonusShutdown() => XpBonusSave();
/// <summary>AC's thread: a line through the chat bar. Our own /offlinebonus, or one the player typed?</summary>
private void XpBonusChatBar(string text)
{
if (DreamWeaveXpBonus.IsCommand(text)) _xpBonus.NoteChatBar();
}
/// <summary>An incoming chat line on DreamWeave: true when it answers RynthDreamWeave's own /offlinebonus.</summary>
private bool XpBonusChatText(string text, int chatType)
{
bool ours;
string line;
lock (_xpBonus.Gate)
{
ours = _xpBonus.OnChatText(text, chatType, Environment.TickCount64, DateTime.UtcNow);
line = _xpBonus.Line(Environment.TickCount64);
}
if (ours && _xpBonusAnnounce)
{
_xpBonusAnnounce = false;
Reply.Ok(line + ".");
}
return ours;
}
/// <summary>
/// The pump's tick, after the bank's and the boards': the automatic (or asked-for) read when one is due and none
/// of RynthDreamWeave's other commands went or is going within DreamWeaveXpBonus.GapMs.
/// </summary>
private void XpBonusTick()
{
long now = Environment.TickCount64;
uint player = Host.HasGetPlayerId ? Host.GetPlayerId() : 0;
if (player != 0 && player != _xpBonusCharacter) XpBonusLoadFor(player);
bool canSend = player != 0 && Host.HasInvokeChatParser && !(Host.HasIsPortaling && Host.IsPortaling());
long next;
lock (_xpBonus.Gate) next = _xpBonus.NextReadMs;
bool quiet = next <= now && XpBonusQuiet(now); // the other gates are taken one at a time, never nested
string? command;
bool missed;
lock (_xpBonus.Gate)
{
missed = _xpBonus.Tick(now);
command = _xpBonus.Due(now, canSend, quiet);
}
if (missed && _xpBonusAnnounce)
{
_xpBonusAnnounce = false;
Reply.Fail($"No reply to {DreamWeaveXpBonus.Command}.");
}
if (command != null)
{
if (Send(command)) NoteServerSend();
else lock (_xpBonus.Gate) _xpBonus.NotSent();
}
if (now >= _xpBonusSaveDueMs) XpBonusSave();
}
/// <summary>No /b or /top went in the last few seconds, none is due in the next few, and no board reply is awaited.</summary>
private bool XpBonusQuiet(long now)
{
const long gap = DreamWeaveXpBonus.GapMs;
if (now - _lastServerSendMs < gap) return false;
long bankNext;
lock (_bank.Gate) bankNext = _bank.NextCheckMs;
if (bankNext - now < gap && bankNext - now > -gap) return false;
lock (_boards.Gate)
{
if (_boards.Pending || _boards.SweepLeft > 0) return false;
long boardsNext = _boards.NextAutoMs;
if (boardsNext - now < gap && boardsNext - now > -gap) return false;
}
return true;
}
/// <summary>The reading saved for this character (it doesn't replace one read since login).</summary>
private void XpBonusLoadFor(uint player)
{
_xpBonusCharacter = player;
string? json = null;
try
{
string path = DreamWeaveXpBonus.SavePath(Settings.FilePath, player);
if (File.Exists(path)) json = File.ReadAllText(path);
}
catch (Exception ex)
{
LogTagged("The saved offline bonus wasn't read: " + ex.GetType().Name);
}
lock (_xpBonus.Gate) _xpBonus.LoadSaved(json);
}
/// <summary>Writes the reading when it changed (looked at every 30 s, and at logout and shutdown). Pump thread.</summary>
private void XpBonusSave()
{
_xpBonusSaveDueMs = Environment.TickCount64 + XpBonusSaveEveryMs;
uint player = _xpBonusCharacter;
if (player == 0) return;
string json;
lock (_xpBonus.Gate)
{
if (!_xpBonus.Dirty || !_xpBonus.HasReading) return;
json = _xpBonus.SaveJson();
}
try
{
string path = DreamWeaveXpBonus.SavePath(Settings.FilePath, player);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + ".tmp";
File.WriteAllText(tmp, json);
File.Move(tmp, path, overwrite: true);
_xpBonusSaveFailed = false;
}
catch (Exception ex)
{
if (!_xpBonusSaveFailed) LogTagged("The offline bonus wasn't saved: " + ex.GetType().Name + ": " + ex.Message);
_xpBonusSaveFailed = true;
}
}
// ── What the row's buttons and "/rserver xpbonus" do (pump thread) ──
private const string XpBonusNotDreamWeave = "The offline bonus is DreamWeave's; RynthCore doesn't see this world as DreamWeave.";
private void XpBonusCheck(bool typed)
{
if (!Active) { Reply.Fail(XpBonusNotDreamWeave); return; }
if (!Host.HasInvokeChatParser) { Reply.Fail($"This RynthCore can't send {DreamWeaveXpBonus.Command} for a plugin."); return; }
long now = Environment.TickCount64;
lock (_xpBonus.Gate)
{
if (_xpBonus.Waiting(now))
{
if (typed) Reply.Fail("Still waiting for the last offline bonus reply; try again in a few seconds.");
return;
}
_xpBonus.CheckSoon(now);
}
if (!typed) return;
_xpBonusAnnounce = true;
Reply.Ok($"Asking DreamWeave ({DreamWeaveXpBonus.Command}, at the next quiet moment); the answer follows here, not the server's line.");
}
private void XpBonusSetAuto(bool on, bool typed)
{
lock (_xpBonus.Gate) _xpBonus.SetAutoRead(on, Environment.TickCount64);
if (Settings.SetBool(DreamWeaveXpBonus.SettingAutoRead, on)) Settings.Save();
if (typed)
Reply.Ok(on ? $"The offline bonus is read automatically: {DreamWeaveXpBonus.Command} after login and every ten minutes, its reply kept out of chat."
: "The offline bonus is no longer read automatically (the server's own lines and every /b still update it).");
}
private void XpBonusCommandVerbs(List<string> verbs) => verbs.Add("xpbonus");
private const string XpBonusUsage = "/rserver xpbonus [check | auto on|off]: DreamWeave's offline bonus (double XP) time, also on the window's Character tab";
private void XpBonusChatCommand(string[] parts, ref bool handled)
{
if (parts.Length < 2 || !parts[1].Equals("xpbonus", StringComparison.OrdinalIgnoreCase)) return;
handled = true;
string verb = parts.Length > 2 ? parts[2].ToLowerInvariant() : "";
string arg = parts.Length > 3 ? parts[3].ToLowerInvariant() : "";
switch (verb)
{
case "":
case "status":
{
if (!Active) { Reply.Fail(XpBonusNotDreamWeave); return; }
string line, detail;
bool auto;
lock (_xpBonus.Gate)
{
long now = Environment.TickCount64;
line = _xpBonus.Line(now);
detail = _xpBonus.Detail(now, DateTime.UtcNow);
auto = _xpBonus.AutoRead;
}
Reply.Ok($"{line}. {detail}. Automatic read {(auto ? "on" : "off")}.");
return;
}
case "check":
case "refresh":
XpBonusCheck(typed: true);
return;
case "auto":
if (arg == "on") XpBonusSetAuto(true, typed: true);
else if (arg == "off") XpBonusSetAuto(false, typed: true);
else Reply.Fail("Usage: /rserver xpbonus auto on|off");
return;
}
Reply.Fail("Usage: " + XpBonusUsage);
}
private void XpBonusInfoLines(Action<string> line)
{
lock (_xpBonus.Gate)
{
long now = Environment.TickCount64;
line($"{_xpBonus.Line(now)} ({_xpBonus.Detail(now, DateTime.UtcNow)}); automatic read {(_xpBonus.AutoRead ? "on" : "off")} (/rserver xpbonus).");
}
}
}

View file

@ -10,7 +10,7 @@
<RynthPluginServerName>DreamWeave</RynthPluginServerName>
<RynthPluginServerHosts>play.acdreamweave.com</RynthPluginServerHosts>
<RynthPluginServerWorldNames>DreamWeave|Dream Weave</RynthPluginServerWorldNames>
<RynthPluginDescription>DreamWeave only: the server card (rules, server features, player commands, links, account setup) in its own window on the RynthCore bar, the retail Character panel whose XP for next level keeps reading past level 275, and the bank check every minute that gives Lum/hr its luminance. Class Abilities, Market and Suit Builder open the website logged in as this account: from buttons on the card, or from the bar icon's dropdown.</RynthPluginDescription>
<RynthPluginDescription>DreamWeave only: the server card (rules, server features, player commands, links, account setup) in its own window on the RynthCore bar, the retail Character panel whose XP for next level keeps reading past level 275, the bank check every minute that gives Lum/hr its luminance, a Leaderboards tab with your rank on every /top board, and your offline bonus (double XP) time on the Character tab. Class Abilities, Market and Suit Builder open the website logged in as this account: from buttons on the card, or from the bar icon's dropdown.</RynthPluginDescription>
<!-- Declared 90, not the 66 default: a release build raises anything under 88 to the SDK's API, so the plugin would load on no current engine.
90 is the highest API among the SDK members called outside an isolated NoInlining method: RynthAcPanel (a static field's type),
IsAcPanelOpen, AcPanel, PanelScale, PanelDragWithLastItem, GetIconTexture and HasFramelessWindows (v90). Anything newer must stay

View file

@ -30,9 +30,12 @@ internal static class ServerData
"Drift Network: a hall of linked drift-doors, recalled to with /dn (/tn for the retail Town Network).",
"Threads dungeons (/dd) and treasure-map dig sites (/digsite, /rrtm).",
"PvP arenas (1v1, 2v2, Tugak Brawl free-for-all) and battlegrounds on templates, with ratings (/arena).",
"Leaderboards for DPS, defense, waves, speed, level, bank, stamps, threads and PvP (/top).",
"Leaderboards (/top): level, banked pyreals, class ability points, quest stamps, Thread-Guide rung, Knot clears, titles, deaths, the Proving Grounds' DPS, defense, wave and speed trials (and past season winners), and the PvP arena ladders.",
"The Leaderboards tab of this window shows every board with your rank on each, and can refresh them automatically (/rserver boards).",
"XP, luminance and custom augmentations (/aug).",
"Experience bonuses: gear, augmentations, alt-character catch-up and offline (/bonus).",
"Offline bonus (double XP): time banks 1:1 while a character is logged out or idle, up to 24 hours, and gives extra combat XP and luminance (+100%, double, by the server's default) while you spend it fighting (/offlinebonus).",
"The Character tab of this window shows your offline bonus time, counting down while you fight and up while you bank, with a Check now button (/rserver xpbonus).",
"Fast tick opt-in: faster spell release, fast-chug and melee stick-to-target (/fasttick).",
"Web character sheet you can publish (/charsheet).",
"Class Abilities, Market and Suit Builder open logged in from the buttons on this card or the bar icon's menu (/rserver abilities | market | suit).",
@ -55,10 +58,11 @@ internal static class ServerData
new ServerCommand("/digsite", "status of the dig site you are at; /digsite bail ends one you dug"),
new ServerCommand("/rrtm", "reroll a treasure map's dig site to the one nearest you"),
new ServerCommand("/arena", "PvP arena: /arena join 1v1|2v2|tugak|bg, templates, status, rating, top"),
new ServerCommand("/top", "leaderboards: dps, defense, wave, speed, level, bank, stamp, thread, 1v1, 2v2, tugak, bg"),
new ServerCommand("/top", "leaderboards (alone: the list): level, bank, cap, stamp, thread, knot, title, deaths, dps, defense, wave, speed, speed winners, 1v1, 2v2, tugak, bg"),
new ServerCommand("/xp", "your experience progress"),
new ServerCommand("/quests", "your quest stamp progress"),
new ServerCommand("/bonus", "every experience bonus you have and the total (/altbonus, /offlinebonus)"),
new ServerCommand("/offlinebonus", "your offline bonus (double XP) time left, and whether it is being spent or banking"),
new ServerCommand("/lph", "luminance per hour since login, or since /lph start"),
new ServerCommand("/pickupspeed", "your pick-up speed bonus, including permanent quest bonuses"),
new ServerCommand("/fasttick", "fast tick on, off, default or status"),
@ -72,6 +76,6 @@ internal static class ServerData
Discord = "https://discord.gg/p2h3yca4BD",
Wiki = "https://wiki.acdreamweave.com",
Source = "public AC server list (acresources/serverslist), checked 2026-10-13; features and commands from " +
"github.com/Awful-Waffle-Rofl/ACE-DreamWeave (4aa7de6), checked 2026-10-14",
"github.com/Awful-Waffle-Rofl/ACE-DreamWeave (4aa7de6), checked 2026-10-14; /top boards checked in game 2026-11-15",
};
}