Snapshot for release 2026.10.20.1 (internal 7116fab)

This commit is contained in:
Tom Bohar 2026-10-20 21:28:18 -04:00
commit bfcd48950d
215 changed files with 16200 additions and 2838 deletions

View file

@ -187,6 +187,31 @@ internal sealed record ServerProfileView(string Id, string Name, string Plugin,
}
}
/// <summary>
/// A live number from the profile's "values" (a server plugin's ServerPackPlugin.SetProfileValue,
/// e.g. "voidDotDurationScale"), or <paramref name="fallback"/> when the profile, the value or a
/// finite number isn't there (an older plugin, another server, a server without the rule).
/// </summary>
public static double Value(string? json, string key, double fallback)
{
if (string.IsNullOrWhiteSpace(json) || string.IsNullOrEmpty(key)) return fallback;
try
{
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object
|| !root.TryGetProperty("values", out JsonElement values) || values.ValueKind != JsonValueKind.Object
|| !values.TryGetProperty(key, out JsonElement v) || v.ValueKind != JsonValueKind.Number
|| !v.TryGetDouble(out double d) || !double.IsFinite(d))
return fallback;
return d;
}
catch (JsonException)
{
return fallback;
}
}
/// <summary>One plain-ASCII line for a status report ("PvE, ACE; botting forbidden - ...").</summary>
public string Summary()
{
@ -211,6 +236,55 @@ internal sealed record ServerProfileView(string Id, string Name, string Plugin,
/// <param name="AfterCap">"afterCap": applied last, only once the item's tink slots are full.</param>
/// <param name="StackGroup">"stackGroup": rows in one group share <paramref name="StackCap"/> per item ("" = none).</param>
/// <param name="StackCap">"stackCap": the group's combined cap per item.</param>
/// <summary>
/// Which jewelry is a trinket on the active server (the profile's "trinkets": name words and words
/// that rule a name out again). <see cref="None"/> (no server, or one without trinkets): nothing is.
/// </summary>
internal sealed record ServerTrinketRule(IReadOnlyList<string> Names, IReadOnlyList<string> Except)
{
public static readonly ServerTrinketRule None = new(Array.Empty<string>(), Array.Empty<string>());
/// <summary>True when <paramref name="name"/> holds one of the words and none of the exceptions.</summary>
public bool IsTrinket(string? name)
{
string n = name ?? string.Empty;
if (n.Length == 0 || Names.Count == 0) return false;
foreach (string x in Except)
if (x.Length > 0 && n.Contains(x, StringComparison.OrdinalIgnoreCase)) return false;
foreach (string w in Names)
if (w.Length > 0 && n.Contains(w, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
/// <summary>The profile's rule, read leniently: <see cref="None"/> without one (or for unusable text).</summary>
public static ServerTrinketRule Parse(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return None;
try
{
using JsonDocument doc = JsonDocument.Parse(json);
if (doc.RootElement.ValueKind != JsonValueKind.Object
|| !doc.RootElement.TryGetProperty("trinkets", out JsonElement t) || t.ValueKind != JsonValueKind.Object)
return None;
var names = Words(t, "names");
return names.Count == 0 ? None : new ServerTrinketRule(names, Words(t, "except"));
}
catch (JsonException)
{
return None;
}
}
private static List<string> Words(JsonElement e, string name)
{
var list = new List<string>();
if (!e.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) return list;
foreach (JsonElement w in a.EnumerateArray())
if (w.ValueKind == JsonValueKind.String && w.GetString() is { Length: > 0 and <= 64 } s) list.Add(s.Trim());
return list;
}
}
internal sealed record ServerSalvageView(string Bench, int Material, string Kind, string Effect, bool UsesTinkSlot, string NameMatch,
int AppliedInt = 0, bool Prepared = false, int Order = 0, bool AfterCap = false,
string StackGroup = "", int StackCap = 0)

View file

@ -1,9 +1,9 @@
// PetCaptureLines.cs - The chat lines that mean an ACECustom siphon-lens capture worked.
//
// One list for both plugins (linked source): RynthAi's Pets tab reads them to time its auto-capture
// (success -> short cooldown), and RynthILT's Vaulted Dungeons keeper counts a capture as a kill for
// its "Kill Client" timer (a hunter who captures instead of killing is not idle). They are the
// MonsterCapture success replies the Pets tab already matched; nothing new is guessed here.
// RynthILT's (linked source): its siphon auto-capture (IltPetAutomation, RynthAi's Pets tab's until
// 2026-10-20) reads them to time the next lens (success -> short cooldown), and its Vaulted Dungeons
// keeper counts a capture as a kill for its "Kill Client" timer (a hunter who captures instead of
// killing is not idle). They are the MonsterCapture success replies; nothing new is guessed here.
using System;
namespace RynthCore.Plugin.Shared;

View file

@ -4,8 +4,10 @@
// borrows from RynthAi. The Mini Remote that hosts the ILT tabs, the /myquests
// tracker (the Temple attribute tracker reads its flags), spell names (the dispel
// keeper), VTank loot-profile matching (equipment suits) and the VTank .usd
// importer (which edits RynthAi's own rules; drawn in RynthILT's Gear tab), and the
// Mini Remote's session stats (the Character tab's rates count the same session).
// importer (which edits RynthAi's own rules; drawn in RynthILT's Gear tab), the
// Mini Remote's session stats (the ILT rates count the same session), and since
// 2026-10-20 combat's generic back-away (the Empyrean Handler's ring) and the loot
// rules' wield counters (the T11 counters RynthILT reads from /aug).
// Compiled into both plugins (linked source), so the layout can't drift.
//
// Rules: as RynthILT.Hub (Shared/RynthIltHubApi.cs): append-only, UTF-8 strings,
@ -26,6 +28,18 @@ public static class RynthAiHub
/// <summary>RenderSection: the VTank .usd settings importer (RynthAi's monster / weapon / consumable rules).</summary>
public const string SectionVTankImport = "vtank-import";
// BackAwayFrom results.
/// <summary>The back-jump started; attacks wait until it settles.</summary>
public const int BackAwayStarted = 1;
/// <summary>Not now: RynthAi's macro isn't running with combat on, it is backing away already, or it isn't logged in.</summary>
public const int BackAwayNotNow = 0;
/// <summary>The character is outside the radius: nothing done.</summary>
public const int BackAwayOutside = 2;
/// <summary>The object (or the player) has no position.</summary>
public const int BackAwayUnknownObject = 3;
/// <summary>In range, but the jump didn't start.</summary>
public const int BackAwayJumpRefused = -1;
}
/// <summary>One /myquests flag as RynthAi's quest tracker has it. Blittable.</summary>
@ -176,9 +190,37 @@ public unsafe struct RynthAiHubApiV1
public static int VaultedDungeonsEnabledOffset => (int)BaseStructSize + sizeof(nint);
/// <summary>
/// VaultedDungeonsEnabled(): 1 when RynthAi's "Vaulted Dungeons" setting (Settings > Navigation) is
/// on. That setting is the master switch of RynthILT's Vaulted Dungeons keeper and lives only in
/// RynthAi; 0 (off) is also the answer before login and after shutdown. Any thread.
/// VaultedDungeonsEnabled(): obsolete since 2026-10-20, kept because the table is append-only. The
/// Vaulted Dungeons master switch is RynthILT's own setting now (RynthILT 0.4+ reads its state, and
/// RynthAi mirrors it for the engine through RynthILT.Hub GetSetting / SetSetting). RynthAi answers
/// the value its profile still carries (what RynthILT copied once), so an older RynthILT keeps
/// working; 0 before login and after shutdown. Any thread.
/// </summary>
public delegate* unmanaged[Cdecl]<int> VaultedDungeonsEnabled;
// ── Appended 2026-10-20 (check with Has before calling) ─────────────────
/// <summary>The byte offset of <see cref="BackAwayFrom"/> (for <see cref="Has"/>): right after VaultedDungeonsEnabled.</summary>
public static int BackAwayFromOffset => (int)BaseStructSize + 2 * sizeof(nint);
/// <summary>
/// BackAwayFrom(objectId, radiusYards, holdMs): a server plugin's "get out of this radius now" (RynthILT:
/// the Empyrean Handler's lethal ring). RynthAi faces the object, run-back jumps away from it (holdMs =
/// the jump's charge, 100-3000) and holds its attacks until the jump settles, then re-engages the same
/// target; the radius is at least the player's Ring Range. Only while RynthAi's macro runs with combat
/// on. Returns <see cref="RynthAiHub.BackAwayStarted"/> and the other BackAway* results. Pump thread.
/// </summary>
public delegate* unmanaged[Cdecl]<uint, float, int, int> BackAwayFrom;
/// <summary>The byte offset of <see cref="SetPlayerCounter"/> (for <see cref="Has"/>): right after BackAwayFrom.</summary>
public static int SetPlayerCounterOffset => (int)BaseStructSize + 3 * sizeof(nint);
/// <summary>
/// SetPlayerCounter(propertyId, value): a player counter the server doesn't send at login and the
/// loot rules' wield gates compare against (the T11 "Can Wield" key: Item Augmentations 9008, Triune
/// Weave 50000, the school charms 50001-50004). The server plugin reads them (RynthILT: ACECustom's
/// "/aug" reply, with its item-aug override applied) and reports each; value &lt; 0 = unknown again.
/// 1 = taken, 0 = not such a counter. Any thread.
/// </summary>
public delegate* unmanaged[Cdecl]<uint, long, int> SetPlayerCounter;
}

View file

@ -28,6 +28,9 @@ public sealed unsafe class RynthAiSessionClient
/// <summary>RynthAi answered with its hub table (last lookup).</summary>
public bool Connected => _table != null && _table->Version >= 1;
/// <summary>RynthAi is loaded and answers on its hub interface now (looked up again every few seconds while it is missing).</summary>
public bool IsLoaded(RynthCoreHost host, long now) => Table(host, now) != null;
/// <summary>Forget the table; the next call looks it up again (login, logout).</summary>
public void Reset()
{

View file

@ -1,8 +1,9 @@
// ============================================================================
// RynthSuite - Plugins/Shared/RynthIltDataApi.cs
// The "RynthILT.Data" interface: the Infinite Leaftide data RynthILT's Mini Remote Charms
// and Banking tabs show, for other plugins to draw (SilentKelpie's RynthOracle Character
// tab and RynthInventory Global Inventory "Banking" tab read it; neither is in this tree yet):
// and Banking tabs show, for other plugins to draw (RynthOracle's Character tab charms,
// Pet Breeding tab and Quests tab guardians, and RynthInventory's Global Inventory "Banking" tab
// read it; the Mini Remote's own tabs keep working beside them):
// - the registry charms and Guardian Hands (GetCharmsJson, ToggleCharm);
// - the bank balances of every character RynthILT has seen on this server, and
// deposits, withdrawals, transfers and balance reads (GetBankJson, BankCommand);
@ -48,8 +49,8 @@
// The reader confirms a transfer with the player before sending it (RynthILT doesn't ask again).
//
// Version 2 (RynthILT 0.3.1) appends GetPetBreedingJson and PetBreedingCommand: the data of the
// pet breeding tracker RynthILT draws in the Mini Remote's Pets > Breeding sub-tab (no plugin in
// this tree reads it yet). Readers still query version 1 and accept a version-1 table, so charms
// pet breeding tracker RynthILT draws in the Mini Remote's Pets > Breeding sub-tab (RynthOracle's
// Pet Breeding tab reads it too). Readers still query version 1 and accept a version-1 table, so charms
// and the bank keep working with an older RynthILT; they use the breeding functions only when
// the table says Version >= 2 and is that big (HasPetBreeding).
//
@ -69,6 +70,19 @@
// "sex": "...", "partners": 1 } }
// PetBreedingCommand verbs (ASCII): refresh | debug | dance | apply <supplyKey> <essenceId>
// The reader confirms "apply" and "dance" with the player first (RynthILT doesn't ask again).
//
// Version 3 (RynthILT 0.2.20) appends GetGuardianJson and GuardianCommand (the Temple guardians
// on RynthOracle's Quests tab). Readers use them only when Version >= 3 and the table is that big
// (HasGuardian); a version-2 table still answers charms, the bank and breeding (V2Size).
//
// GetGuardianJson payload (IltGuardian.BuildJson; read leniently):
// { "available": true, "world": "...", "chat": true, "auto": false, "buy": true, "cooldownHours": 20,
// "answer": "Pyreal", "npc": "Guardian of ...", "answerAgeSec": 42 (-1 none yet), "heard": "...",
// "running": false, "status": "idle", "synced": "2026-10-18T19:05:00Z" ("" /qb not read),
// "rows": [ { "attribute": "Strength", "npc": "...", "count": 3, "status": "Ready", "eta": "",
// "ready": true, "exact": true } ] } exact = from /myquests (else /qb estimates)
// GuardianCommand verbs (ASCII): handin | stop | refresh | chat on|off | auto on|off | buy on|off
// Auto hand-in and buying a missing Temple item run inside RynthILT whatever the reader shows.
// ============================================================================
using System;
@ -85,7 +99,7 @@ namespace RynthCore.Plugin.Shared;
public unsafe struct RynthIltDataApiV1
{
public const string InterfaceName = "RynthILT.Data";
public const uint InterfaceVersion = 2;
public const uint InterfaceVersion = 3;
/// <summary>The size of a version-1 table (everything before GetPetBreedingJson) on this platform.</summary>
public static uint V1Size
@ -97,6 +111,16 @@ public unsafe struct RynthIltDataApiV1
}
}
/// <summary>The size of a version-2 table (everything before GetGuardianJson) on this platform.</summary>
public static uint V2Size
{
get
{
RynthIltDataApiV1 t = default;
return (uint)((byte*)&t.GetGuardianJson - (byte*)&t);
}
}
public uint Version; // InterfaceVersion of the table RynthILT filled; 0 once it has shut down
public uint StructSize; // sizeof(RynthIltDataApiV1) as RynthILT built it
@ -125,6 +149,14 @@ public unsafe struct RynthIltDataApiV1
/// <summary>PetBreedingCommand(utf8 verb line): queues a breeding verb (header above). 1 = queued, 0 = refused.</summary>
public delegate* unmanaged[Cdecl]<byte*, int> PetBreedingCommand;
// ── Version 3 ───────────────────────────────────────────────────────────
/// <summary>GetGuardianJson(buffer, capacity): the Temple guardian JSON, same contract as GetCharmsJson.</summary>
public delegate* unmanaged[Cdecl]<byte*, int, int> GetGuardianJson;
/// <summary>GuardianCommand(utf8 verb line): queues a guardian verb (header above). 1 = queued, 0 = refused.</summary>
public delegate* unmanaged[Cdecl]<byte*, int> GuardianCommand;
}
/// <summary>
@ -183,7 +215,33 @@ public sealed unsafe class RynthIltDataClient
}
private static bool HasPetBreeding(RynthIltDataApiV1* t)
=> t != null && t->Version >= 2 && t->StructSize >= (uint)sizeof(RynthIltDataApiV1);
=> t != null && t->Version >= 2 && t->StructSize >= RynthIltDataApiV1.V2Size;
/// <summary>The Temple guardian JSON now ("" without a RynthILT that has it, version 3).</summary>
public string ReadGuardian(RynthCoreHost host, long now)
{
RynthIltDataApiV1* t = Table(host, now);
return !HasGuardian(t) || t->GetGuardianJson == null ? "" : Read(t->GetGuardianJson);
}
/// <summary>The loaded RynthILT has the guardian functions (table version 3 or later).</summary>
public bool GuardianSupported => HasGuardian(_table);
/// <summary>Queues a guardian verb line (see the header). False without RynthILT or when it refused.</summary>
public bool GuardianCommand(RynthCoreHost host, long now, string verbLine)
{
RynthIltDataApiV1* t = Table(host, now);
if (!HasGuardian(t) || t->GuardianCommand == null || string.IsNullOrWhiteSpace(verbLine)) return false;
byte[] bytes = Encoding.UTF8.GetBytes(verbLine + "\0");
try
{
fixed (byte* p = bytes) return t->GuardianCommand(p) == 1;
}
catch { return false; }
}
private static bool HasGuardian(RynthIltDataApiV1* t)
=> t != null && t->Version >= 3 && t->StructSize >= (uint)sizeof(RynthIltDataApiV1);
/// <summary>Asks RynthILT to use a carried charm. False without RynthILT or when it refused.</summary>
public bool ToggleCharm(RynthCoreHost host, long now, uint objectId)
@ -548,6 +606,88 @@ public sealed class IltBreedingView
=> string.Join(' ', "apply", (supplyKey ?? "").Trim(), essenceId.ToString(CultureInfo.InvariantCulture));
}
/// <summary>One Temple attribute turn-in from the guardian JSON.</summary>
public sealed record IltGuardianRow(string Attribute, string Npc, int Count, string Status, string Eta, bool Ready, bool Exact);
/// <summary>The Temple guardian JSON parsed. <see cref="None"/> without RynthILT; every field read leniently.</summary>
public sealed class IltGuardianView
{
public static readonly IltGuardianView None = new();
/// <summary>RynthILT answered.</summary>
public bool Loaded { get; private init; }
public bool Available { get; private init; }
public string World { get; private init; } = "";
/// <summary>Translate the guardians' tells as they arrive.</summary>
public bool Chat { get; private init; }
/// <summary>Give the answer item to the guardian automatically after a chat answer.</summary>
public bool Auto { get; private init; }
/// <summary>Buy a missing Temple item from the nearest vendor first.</summary>
public bool Buy { get; private init; }
public int CooldownHours { get; private init; }
public string Answer { get; private init; } = "";
public string Npc { get; private init; } = "";
/// <summary>Seconds since the last answer (-1 none yet).</summary>
public long AnswerAgeSec { get; private init; } = -1;
public string Heard { get; private init; } = "";
/// <summary>A hand-in is running.</summary>
public bool Running { get; private init; }
public string Status { get; private init; } = "";
/// <summary>When /qb was last read (MinValue never).</summary>
public DateTime SyncedUtc { get; private init; } = DateTime.MinValue;
public IReadOnlyList<IltGuardianRow> Rows { get; private init; } = Array.Empty<IltGuardianRow>();
public static IltGuardianView Parse(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return None;
try
{
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) return None;
var rows = new List<IltGuardianRow>();
foreach (JsonElement r in IltJson.Array(root, "rows"))
{
string attr = IltJson.Str(r, "attribute");
if (attr.Length == 0) continue;
rows.Add(new IltGuardianRow(attr, IltJson.Str(r, "npc"), (int)IltJson.Long(r, "count"), IltJson.Str(r, "status"),
IltJson.Str(r, "eta"), IltJson.Bool(r, "ready"), IltJson.Bool(r, "exact")));
}
DateTime synced = DateTime.MinValue;
string when = IltJson.Str(root, "synced");
if (when.Length > 0
&& DateTime.TryParse(when, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t))
synced = t;
return new IltGuardianView
{
Loaded = true,
Available = IltJson.Bool(root, "available"),
World = IltJson.Str(root, "world"),
Chat = IltJson.Bool(root, "chat"),
Auto = IltJson.Bool(root, "auto"),
Buy = IltJson.Bool(root, "buy"),
CooldownHours = (int)IltJson.Long(root, "cooldownHours"),
Answer = IltJson.Str(root, "answer"),
Npc = IltJson.Str(root, "npc"),
AnswerAgeSec = IltJson.Long(root, "answerAgeSec", -1),
Heard = IltJson.Str(root, "heard"),
Running = IltJson.Bool(root, "running"),
Status = IltJson.Str(root, "status"),
SyncedUtc = synced,
Rows = rows,
};
}
catch (JsonException) { return None; }
}
/// <summary>The guardian verb lines (header of this file); pure so the tests check them.</summary>
public static string HandInVerb() => "handin";
public static string StopVerb() => "stop";
public static string RefreshVerb() => "refresh";
/// <summary>"chat on", "auto off", "buy on": <paramref name="name"/> is chat, auto or buy.</summary>
public static string SwitchVerb(string name, bool on) => (name ?? "").Trim().ToLowerInvariant() + (on ? " on" : " off");
}
/// <summary>Lenient JSON field reads shared by the views above.</summary>
internal static class IltJson
{

View file

@ -1,10 +1,14 @@
// ============================================================================
// RynthSuite - Plugins/Shared/RynthIltHubApi.cs
// The "RynthILT.Hub" interface: RynthILT's Infinite Leaftide features as RynthAi's
// Mini Remote shows them. The Mini Remote stays RynthAi's (its window, tab bar,
// Remote tab, Quests and Pets tabs); RynthILT supplies the ILT tabs (Character,
// Banking, Gear, Charms, Games), a few ILT sections drawn inside RynthAi's
// surfaces, the server's ILT feature bits and the "/ra hub ..." ILT verbs.
// The "RynthILT.Hub" interface: a server plugin's features as RynthAi's Mini
// Remote shows them (RynthILT's Infinite Leaftide ones; any server plugin may serve
// the same layout as "RynthServer.Hub", which RynthAi asks the active server's owner
// for first). The Mini Remote stays RynthAi's (its window, tab bar, Remote, Pets and
// Crafting tabs) and knows no server's content: the plugin supplies its tabs and the
// Pets tab's sub-tabs, its sections drawn inside RynthAi's surfaces (Remote, Pets,
// Options, menu), its feature bits, texts and mirrored settings, its "/ra" verbs and
// the pet summon-from-empty gate. Field names say ILT for history; the meaning is
// "the plugin's server" (IsIltWorld, GetForceIlt).
// Compiled into both plugins (linked source), so the layout can't drift.
//
// Rules (as the RynthAi.* interfaces, Shared/RynthAiScriptApi.cs):
@ -48,13 +52,48 @@ public static class RynthIltHub
public const string SectionPetLogs = "pets-logs";
/// <summary>
/// Pets tab, Breeding sub-tab: the pet breeding tracker, the sub-tab's whole body (RynthILT 0.3.1+;
/// older copies draw nothing). RynthAi shows the sub-tab on an ILT world unless FeaturePetBreeding is off.
/// older copies draw nothing). Since 2026-10-20 RynthAi shows it because GetSubTabs(TabParentPets)
/// lists it (RynthILT: an ILT world unless FeaturePetBreeding is off); older RynthAi decided itself.
/// </summary>
public const string SectionPetBreeding = "pets-breeding";
/// <summary>
/// Pets tab, under the roster: the ACECustom pet charms (Summon Essence Refill and its "summon from
/// empty" opt-in, Universal Summoning Mastery, the casting supplies warning). RynthILT 2026-10-20+;
/// it was RynthAi's. Draws its own leading separator; nothing off ILT.
/// </summary>
public const string SectionPetCharms = "pets-charms";
/// <summary>Pets tab, under the charms: ACECustom siphon-lens auto-capture (switch, lens, status). As SectionPetCharms.</summary>
public const string SectionPetCapture = "pets-capture";
/// <summary>GetSubTabs parent: RynthAi's Pets tab (its first sub-tab, the roster, is RynthAi's own).</summary>
public const string TabParentPets = "pets";
/// <summary>
/// GetSetting / SetSetting key: the Vaulted Dungeons keeper's master switch (0 off, 1 on; RynthILT's
/// per-character setting since 2026-10-20, RynthAi's profile's before). RynthAi mirrors it into the
/// engine's Settings > Navigation row; -1 (no row) off ILT.
/// </summary>
public const string SettingVaultedDungeons = "vaulted-dungeons";
/// <summary>Mini Remote menu, under Infinite Leaftide: why no ILT feature is on, the Force-ILT override, Refresh.</summary>
public const string SectionIltStatus = "ilt-status";
/// <summary>Mini Remote menu without RynthCore's server list: RynthILT's own Infinite Leaftide items.</summary>
public const string SectionServerMenu = "server-menu";
/// <summary>
/// Remote tab, Stats section, under RynthAi's per-hour lines: the server's own session rates (RynthILT:
/// Enlightened Coins and pyreals per hour). RynthILT 2026-10-20+; RynthAi drew them from GetRates before.
/// </summary>
public const string SectionRemoteStats = "remote-stats";
/// <summary>
/// The Remote tab's Options popup, under RynthAi's own section switches: the server's Remote sections'
/// switches (RynthILT: Bank, Guardian answer; saved by RynthILT, which then draws or skips SectionRemoteBank /
/// SectionRemoteGuardian). RynthILT 2026-10-20+; they were RynthAi's huds.json flags.
/// </summary>
public const string SectionRemoteOptions = "remote-options";
/// <summary>GetText id: the tail RynthAi adds to its one-line session report ("" or ", Coins 1.2k/h, Pyr 4.5m/h").</summary>
public const string TextSessionReport = "session-report";
/// <summary>GetText id: the RynthCore server id this plugin's tabs and menu entries belong to ("ilt").</summary>
public const string TextServerId = "server-id";
/// <summary>Feature keys RynthAi reads (GetFeature).</summary>
public const string FeatureQuests = "quests";
@ -88,6 +127,37 @@ public unsafe struct RynthIltHubApiV1
public const string InterfaceName = "RynthILT.Hub";
public const uint InterfaceVersion = 1;
/// <summary>
/// The same table under a server-neutral name (2026-10-20): RynthAi asks the engine's active server's
/// owner plugin for it first, so any server plugin can offer the Mini Remote tabs, sections and verbs
/// in this layout. RynthILT serves both names.
/// </summary>
public const string NeutralInterfaceName = "RynthServer.Hub";
/// <summary>
/// The table's size up to and including Command, as every RynthILT since the interface's first
/// release fills it. Readers check StructSize against this (not sizeof, which grows as functions
/// are appended) and check for the appended functions with <see cref="Has"/>.
/// </summary>
public static uint BaseStructSize => (uint)(2 * sizeof(uint) + 9 * sizeof(nint));
/// <summary>Whether a table RynthILT built is big enough to hold the function at <paramref name="offset"/>.</summary>
public static bool Has(RynthIltHubApiV1* t, int offset) => t != null && t->StructSize >= (uint)(offset + sizeof(nint));
/// <summary>Byte offset of the n-th function appended after the base table (0 = AllowSummonOnEmpty).</summary>
private static int Appended(int n) => (int)BaseStructSize + n * sizeof(nint);
/// <summary>Offset of <see cref="AllowSummonOnEmpty"/> (for <see cref="Has"/>).</summary>
public static int AllowSummonOnEmptyOffset => Appended(0);
/// <summary>Offset of <see cref="GetSubTabs"/>.</summary>
public static int GetSubTabsOffset => Appended(1);
/// <summary>Offset of <see cref="GetSetting"/>.</summary>
public static int GetSettingOffset => Appended(2);
/// <summary>Offset of <see cref="SetSetting"/>.</summary>
public static int SetSettingOffset => Appended(3);
/// <summary>Offset of <see cref="GetText"/>.</summary>
public static int GetTextOffset => Appended(4);
public uint Version; // InterfaceVersion of the table RynthILT filled; 0 once it has shut down
public uint StructSize; // sizeof(RynthIltHubApiV1) as RynthILT built it
@ -124,4 +194,38 @@ public unsafe struct RynthIltHubApiV1
/// 1 = handled, 0 = not an ILT verb. Pump thread.
/// </summary>
public delegate* unmanaged[Cdecl]<byte*, int> Command;
// ── Appended 2026-10-20 (check with Has before calling) ─────────────────
/// <summary>
/// AllowSummonOnEmpty(): 1 when a pet may be summoned from an EMPTY essence because the server
/// refills it (ACECustom's Summon Essence Refill charm is on, the player opted in, and the server
/// confirmed the feature). RynthAi's PetManager hook asks this; 0 off ILT and whenever unsure (an
/// unknown state never spends pyreals). Cached by RynthILT's tick. Any thread.
/// </summary>
public delegate* unmanaged[Cdecl]<int> AllowSummonOnEmpty;
/// <summary>
/// GetSubTabs(parent, tabs, capacity): the sub-tabs RynthILT adds to one of RynthAi's tabs
/// (parent RynthIltHub.TabParentPets: the Pets tab's Breeding). Each tab's Id is a section id
/// drawn with RenderSection; Width / Height are 0 (the parent's size). Writes up to capacity,
/// returns how many (tabs null: the count); 0 off ILT or for an unknown parent. Render thread.
/// </summary>
public delegate* unmanaged[Cdecl]<byte*, IltTabV1*, int, int> GetSubTabs;
/// <summary>
/// GetSetting(key): one of the server plugin's settings that another plugin shows (RynthIltHub.Setting*;
/// RynthAi mirrors them into the engine's Settings window). The value, or -1 when the plugin has no
/// such setting to offer now (unknown key, before login, off ILT). Any thread.
/// </summary>
public delegate* unmanaged[Cdecl]<byte*, int> GetSetting;
/// <summary>SetSetting(key, value): changes that setting (saved by RynthILT); 1 = taken, 0 = not ours / not now. Any thread.</summary>
public delegate* unmanaged[Cdecl]<byte*, int, int> SetSetting;
/// <summary>
/// GetText(id, buffer, capacity): a short text RynthAi shows (RynthIltHub.Text*), UTF-8, truncated to
/// capacity. Returns its length; 0 for nothing (unknown id, off ILT). Any thread.
/// </summary>
public delegate* unmanaged[Cdecl]<byte*, byte*, int, int> GetText;
}

View file

@ -0,0 +1,74 @@
// ============================================================================
// RynthSuite - Plugins/Shared/RynthIltServerApi.cs
// The "RynthILT.Server" interface: what RynthILT knows about the Infinite Leaftide
// server, for any plugin that wants it without drawing RynthILT's UI (RynthOracle's
// Fellowship tab, for one). One call hands out a JSON snapshot: whether this is an
// ILT world, every Leaftide feature RynthILT supports with the server's state for it,
// and the server's fellowship rules.
// Separate from "RynthILT.Hub" (RynthIltHubApi.cs) so that interface, which RynthAi asks
// for at an exact version, never has to change for this.
// Compiled into RynthILT and its readers (linked source), so the layout can't drift.
//
// Rules (as the other shared interfaces):
// - Append-only: new functions go at the end, and Version goes up.
// - Strings are UTF-8, NUL-terminated. The JSON itself is plain ASCII.
// - Every function returns safely (no exception crosses the boundary).
// - The table is allocated once per loaded copy of RynthILT and never freed; shutdown
// sets Version to 0, and a reader re-queries (host GetPluginInterface) when it sees that.
//
// GetProfileJson payload (every field may be missing on an older RynthILT; read leniently):
// {
// "ilt": true, // ILT world (its world list, or the character's override)
// "world": "InfiniteLeaftide", // the world name the server announced ("" before login)
// "forced": false, // "Treat this world as ILT" is on
// "source": "probe", // where the feature bits came from ("ilt-features", "probe", "")
// "checked": "2026-10-13T21:25:37Z", // last server-options check (UTC), "" = never
// "features": [ { "key": "bank", "label": "Banking", "group": "Character",
// "state": 1, "where": "Mini Remote > Banking tab" }, ... ],
// // state: 1 on, 0 off, -1 not known yet
// "fellowship": { "maxMembers": 29, "zoneShare": 1, "blackjack": 0, "luminanceShare": 1 },
// "questBonus": { "disabled": false, "generation": 2, "count": 41, "status": "12 completed, 3 incomplete",
// "completed": [ "flag", ... ], "incomplete": [ "flag", ... ] }
// // the /qb list; ILT worlds only (generation 0 = not loaded yet)
// }
// ============================================================================
using System.Runtime.InteropServices;
namespace RynthCore.Plugin.Shared;
/// <summary>Constants of the "RynthILT.Server" interface.</summary>
public static class RynthIltServer
{
/// <summary>The providing plugin's display name.</summary>
public const string PluginName = "RynthILT";
/// <summary>Feature state in the profile JSON: the server reports it on.</summary>
public const int StateOn = 1;
/// <summary>Feature state: the server reports it off.</summary>
public const int StateOff = 0;
/// <summary>Feature state: not known yet (not checked, not an ILT world, or no RynthILT).</summary>
public const int StateUnknown = -1;
/// <summary>A retail fellowship's member limit (what a reader assumes without RynthILT).</summary>
public const int RetailFellowshipMax = 9;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct RynthIltServerApiV1
{
public const string InterfaceName = "RynthILT.Server";
public const uint InterfaceVersion = 1;
public uint Version; // InterfaceVersion of the table RynthILT filled; 0 once it has shut down
public uint StructSize; // sizeof(RynthIltServerApiV1) as RynthILT built it
/// <summary>
/// GetProfileJson(buffer, capacity): writes the profile JSON (UTF-8, NUL-terminated) into
/// buffer when it fits, and returns its length in bytes without the NUL. A return value of
/// capacity or more means nothing was written: call again with a bigger buffer. 0 = nothing
/// to report (RynthILT shutting down). Any thread (it hands out a snapshot RynthILT's pump
/// rebuilds about once a second).
/// </summary>
public delegate* unmanaged[Cdecl]<byte*, int, int> GetProfileJson;
}

View file

@ -40,7 +40,10 @@
// "afterCap": true, // last, only once the item's tink slots are full
// "stackGroup": "x", "stackCap": 10 // rows of one group share this cap per item
// } ],
// "discord": "", "website": "", "wiki": "", "source": ""
// "discord": "", "website": "", "wiki": "", "source": "",
// "values": { // live numbers for this character on this server ({} when none;
// "voidDotDurationScale": 1.35 // ServerProfileView.Value reads one): RynthConquest's Void DoT
// } // duration rule, which RynthOracle's Void timers apply
// }
// ============================================================================

View file

@ -0,0 +1,23 @@
// ServerChatRequest.cs - "the server plugin just sent this command": a short time window in which the
// command's reply counts as the plugin's own, so the server's code (ServerPackPlugin.ServerChatText)
// can hide replies to its own requests and still show the same command typed by hand. A time window,
// as RynthOracle has always done it (ported from Oracle of Dereth by Advis Eveldan, MIT): these replies
// carry nothing tying them to the request. Each reply line extends it, so a long reply stays ours to its end.
// Pure: RynthServerPack.Tests covers it.
namespace RynthCore.Plugin.ServerPack;
internal sealed class ServerChatRequest
{
public const long WindowMs = 5000;
private long _untilMs;
public void Sent(long nowMs) => _untilMs = nowMs + WindowMs;
public void Clear() => _untilMs = 0;
public bool Awaiting(long nowMs) => nowMs < _untilMs;
/// <summary>A reply line arrived: keep the window open a little longer.</summary>
public void Extend(long nowMs)
{
if (Awaiting(nowMs)) _untilMs = nowMs + 2000 > _untilMs ? nowMs + 2000 : _untilMs;
}
}

View file

@ -67,6 +67,10 @@ public static unsafe class ServerPackExports
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
// Incoming chat, for the server's own code (ServerPackPlugin.ServerChatText). Pump thread.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
/// <summary>The standalone server card ("/rserver"). Render thread.</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Render()
@ -95,8 +99,8 @@ public static unsafe class ServerPackExports
/// <summary>
/// RynthCore's Mini Remote sections: "section:server-&lt;id&gt;" (":popout" added in a popped-out
/// window) draws the server card into the engine's current window. 1 = drawn, 0 = not ready or
/// not ours.
/// window) draws the server card into the engine's current window, "section:server-&lt;id&gt;.&lt;page&gt;"
/// one of the server's own pages (ServerPackPages). 1 = drawn, 0 = not ready or not ours.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })]
public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight)
@ -106,9 +110,18 @@ public static unsafe class ServerPackExports
if (surface == null) return 0;
string name = Marshal.PtrToStringUTF8((IntPtr)surface) ?? string.Empty;
if (name.EndsWith(":popout", StringComparison.Ordinal)) name = name[..^":popout".Length];
if (!name.Equals(ServerPackPlugin.SettingsSurface, StringComparison.Ordinal)) return 0;
var plugin = Runtime.Plugin;
if (plugin == null || !plugin.RenderEmbeddedCard(out float wantH)) return 0;
if (plugin == null) return 0;
float wantH;
if (name.Equals(ServerPackPlugin.SettingsSurface, StringComparison.Ordinal))
{
if (!plugin.RenderEmbeddedCard(out wantH)) return 0;
}
else
{
string? page = ServerPackPages.PageIdOf(name, RynthPluginInfo.ServerId);
if (page == null || !plugin.RenderEmbeddedPage(page, out wantH)) return 0;
}
if (wantWidth != null) *wantWidth = width;
if (wantHeight != null) *wantHeight = wantH;
return 1;

View file

@ -78,6 +78,13 @@ internal sealed class ServerPackInfo
public ServerCommand[] Commands { get; init; } = Array.Empty<ServerCommand>();
/// <summary>The server's own tinkering salvage (only recipes known to exist); empty = none defined.</summary>
public ServerSalvage[] Salvage { get; init; } = Array.Empty<ServerSalvage>();
/// <summary>
/// Jewelry that is a trinket on this server (the Crafting tab's Trinkets bench, not Jewelry): name
/// words, case-insensitive, and words that rule a name out again ("top" but not "topaz"). Empty:
/// the server has no trinkets (retail: every jewelry piece is Jewelry).
/// </summary>
public string[] TrinketNames { get; init; } = Array.Empty<string>();
public string[] TrinketExcept { get; init; } = Array.Empty<string>();
/// <summary>"3 accounts", "3 active characters", ...; empty when not published.</summary>
public string AccountLimit { get; init; } = string.Empty;
public BottingPolicy Botting { get; init; } = BottingPolicy.Unknown;

View file

@ -6,6 +6,7 @@
// unloaded); after Release() it reports Version 0 and GetProfileJson answers 0. Before the plugin is
// up, or between characters, the profile still describes the server (active false, no world).
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
@ -20,7 +21,7 @@ internal static unsafe class ServerPackInterface
private static volatile bool _released;
/// <summary>The last JSON handed out, and what it was built for (rebuilt only when that changes).</summary>
private sealed record Snapshot(bool Active, string World, string Json);
private sealed record Snapshot(bool Active, string World, int ValuesRevision, string Json);
private static Snapshot? _last;
/// <summary>The table for (<paramref name="iface"/>, <paramref name="version"/>), or 0 when it isn't ours.</summary>
@ -52,10 +53,14 @@ internal static unsafe class ServerPackInterface
ServerPackInfo info = plugin?.Info ?? ServerPackPlugin.StaticInfo;
bool active = plugin?.Active ?? false;
string world = plugin?.World ?? string.Empty;
int valuesRevision = plugin?.ProfileValues.Revision ?? -1;
Snapshot? last = Volatile.Read(ref _last);
if (last != null && last.Active == active && last.World == world) return last.Json;
string json = ServerPackProfile.BuildJson(info, RynthPluginInfo.Name, RynthPluginInfo.Version, active, world);
Volatile.Write(ref _last, new Snapshot(active, world, json));
if (last != null && last.Active == active && last.World == world && last.ValuesRevision == valuesRevision) return last.Json;
KeyValuePair<string, double>[] values = plugin != null
? plugin.ProfileValues.Snapshot(out valuesRevision)
: Array.Empty<KeyValuePair<string, double>>();
string json = ServerPackProfile.BuildJson(info, RynthPluginInfo.Name, RynthPluginInfo.Version, active, world, values);
Volatile.Write(ref _last, new Snapshot(active, world, valuesRevision, json));
return json;
}

View file

@ -12,6 +12,7 @@
// with a single reference write, so the render thread always reads a whole one.
// Pure (no host calls): RynthServerPack.Tests covers it.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
@ -163,8 +164,10 @@ internal sealed class ServerPackModel
/// card in the shared "Server" section, shown only while that server is active (detected or
/// forced in RynthCore Options > Diagnostics). The card left the Char section on 2026-10-13: that
/// section is Session Stats now, session stats only.
/// <paramref name="pages"/> (ServerPackPages, already validated) are the server's own views:
/// primary views of the same section, so each gets a sub-tab there, also only on that server.
/// </summary>
public static string BuildSectionsJson(ServerPackInfo info, string pluginName)
public static string BuildSectionsJson(ServerPackInfo info, string pluginName, IReadOnlyList<ServerPage>? pages = null)
{
var sb = new StringBuilder(512);
sb.Append("{\"version\":1,\"servers\":[{\"id\":").Append(Q(info.Id)).Append(",\"name\":").Append(Q(info.Name));
@ -180,7 +183,22 @@ internal sealed class ServerPackModel
sb.Append(",\"primary\":false,\"height\":320,\"enabled\":true,\"tooltip\":");
sb.Append(Q("What is known about " + info.Name + ": rules, account limits, botting policy, links and setup ("
+ pluginName + "; also /rserver)."));
sb.Append(",\"order\":130}]}");
sb.Append(",\"order\":130}");
if (pages != null)
{
for (int i = 0; i < pages.Count; i++)
{
ServerPage p = pages[i];
sb.Append(",{\"section\":").Append(Q(SectionId));
sb.Append(",\"server\":").Append(Q(info.Id));
sb.Append(",\"label\":").Append(Q(p.Label));
sb.Append(",\"surface\":").Append(Q(ServerPackPages.SurfaceFor(info.Id, p.Id)));
sb.Append(",\"primary\":true,\"width\":").Append(ServerPackPages.Width).Append(",\"height\":").Append(ServerPackPages.Height);
sb.Append(",\"enabled\":true,\"tooltip\":").Append(Q(p.Tooltip.Length > 0 ? p.Tooltip : p.Label + " (" + pluginName + ")"));
sb.Append(",\"order\":").Append(100 + i).Append('}');
}
}
sb.Append("]}");
return sb.ToString();
}

View file

@ -0,0 +1,86 @@
// ServerPackPages.cs - Pages a server plugin adds beside its server card (RynthConquest's Conquest and
// Leaderboards pages, RynthAelrynth's Leaderboards, ...).
//
// A server's own features need somewhere to show. The ServerPackPlugin.ServerPages hook lists them
// once, at construction; the shared code then
// * declares each one in the sections manifest as a primary view of the shared "Server" section,
// shown only while this plugin's server is active (contribution "server": <id>), so RynthCore's
// Mini Remote gives it a sub-tab next to the server card;
// * draws it through RynthPluginRenderEmbed under the surface "section:server-<id>.<page>"
// (":popout" added in a popped-out window), into the engine's current window and context;
// * shows the same pages as tabs of the standalone "/rserver" window, after the card.
// Draw runs on the render thread: a page reads its state under its own lock and queues anything it
// sends for the plugin tick (ServerPackPlugin.RunOnTick).
// Pure (no ImGui, no host calls): RynthServerPack.Tests covers it.
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.ServerPack;
/// <summary>
/// One page a server plugin adds. <paramref name="Id"/> is 1-16 of a-z, 0-9 and '-' (part of the
/// surface name); <paramref name="Draw"/> draws the body into the current ImGui window (render thread).
/// </summary>
internal sealed record ServerPage(string Id, string Label, string Tooltip, Action Draw);
internal static class ServerPackPages
{
/// <summary>At most this many pages per plugin (the Mini Remote shows them as one row of tabs).</summary>
public const int MaxPages = 6;
/// <summary>The longest page id (keeps "section:server-&lt;32-char id&gt;.&lt;page&gt;" under the engine's 64).</summary>
public const int MaxIdLength = 16;
/// <summary>The engine caps contribution labels at 48 characters.</summary>
public const int MaxLabelLength = 48;
/// <summary>Page views open at this size in the Mini Remote (it fits the window to the view).</summary>
public const int Width = 540, Height = 520;
/// <summary>True for a page id: 1-16 of a-z, 0-9 and '-'.</summary>
public static bool IsValidId(string? id)
{
if (string.IsNullOrEmpty(id) || id.Length > MaxIdLength) return false;
foreach (char c in id)
if (!(c is >= 'a' and <= 'z' || c is >= '0' and <= '9' || c == '-')) return false;
return true;
}
/// <summary>"section:server-conquest.bank": the page's surface.</summary>
public static string SurfaceFor(string serverId, string pageId) => ServerPackModel.SurfaceFor(serverId) + "." + pageId;
/// <summary>
/// The page id a surface names for this server ("section:server-conquest.bank" -> "bank"), or
/// null for the card, another server's surface or anything else. ":popout" is ignored.
/// </summary>
public static string? PageIdOf(string? surface, string serverId)
{
if (string.IsNullOrEmpty(surface)) return null;
string name = surface.EndsWith(":popout", StringComparison.Ordinal) ? surface[..^":popout".Length] : surface;
string prefix = ServerPackModel.SurfaceFor(serverId) + ".";
if (!name.StartsWith(prefix, StringComparison.Ordinal)) return null;
string id = name[prefix.Length..];
return IsValidId(id) ? id : null;
}
/// <summary>
/// The pages kept from what a plugin listed: valid, unique ids, a label, at most
/// <see cref="MaxPages"/>; each one dropped is reported to <paramref name="log"/>.
/// </summary>
public static List<ServerPage> Validate(IEnumerable<ServerPage>? pages, Action<string>? log = null)
{
var kept = new List<ServerPage>();
if (pages == null) return kept;
foreach (ServerPage p in pages)
{
if (p == null) continue;
string why = !IsValidId(p.Id) ? "its id isn't 1-16 of a-z, 0-9 and '-'"
: string.IsNullOrWhiteSpace(p.Label) ? "it has no label"
: p.Draw == null ? "it has nothing to draw"
: kept.Exists(k => k.Id == p.Id) ? "another page has its id"
: kept.Count >= MaxPages ? $"a plugin has at most {MaxPages} pages"
: string.Empty;
if (why.Length > 0) { log?.Invoke($"Page '{p.Id}' left out: {why}."); continue; }
string label = p.Label.Trim();
kept.Add(p with { Label = label.Length <= MaxLabelLength ? label : label[..MaxLabelLength], Tooltip = p.Tooltip ?? string.Empty });
}
return kept;
}
}

View file

@ -14,11 +14,33 @@
// Server-specific features: add files to the server's project implementing the partial hooks below
// (ServerLoginComplete, ServerTick, ServerChatCommand, ...). Unimplemented hooks compile away.
//
// Threads: OnTick, login/logout and the engine's export calls run on the plugin pump. OnChatBarEnter
// runs on AC's main thread, so it only queues. The card draws on the render thread (OnRender,
// RynthPluginRenderEmbed) and queues its commands for the tick.
// What the shared code gives a server's own features (added 2026-10-20, when RynthOracle's and
// RynthInventory's Conquest and Aelrynth features moved into RynthConquest and RynthAelrynth, so a
// shared plugin carries nothing for one server):
// ServerPages(list) pages of its own (ServerPackPages.cs): sub-tabs of the Mini Remote's
// Server section, only while its server is active, and tabs of the
// /rserver window. Draw runs on the render thread.
// ServerChatText(...) every incoming chat line (pump thread), to read the server's replies
// and hide the ones answering the plugin's own requests (eat).
// ServerChatBar(text) every line sent through the chat bar (AC's thread: note it only),
// to tell the player's typed command from the plugin's own.
// Settings the plugin's own settings file (ServerPackSettings.cs), loaded before
// ServerInitialize; MigrateOnce imports a setting from its old home.
// SetProfileValue(key, n) a live number in its "RynthServer.Profile" ("values"), for other
// plugins that apply a server rule without knowing the server.
// ServerCommandVerbs(list) its own "/rserver <verb>" words, handled in ServerChatCommand.
// RunOnTick(action) work for the next tick (a page's button, on the render thread).
// Send(command) a chat command as if typed (pump thread, logged in only);
// LogTagged(text) the engine log, "[RynthConquest] ..."; ChatLine(text) the chat window.
// The tick, chat and command hooks only run while a character is logged in; each
// should check Active itself, since the plugin can be loaded for a world that isn't its server.
//
// Threads: OnTick, login/logout, chat lines and the engine's export calls run on the plugin pump.
// OnChatBarEnter runs on AC's main thread, so it only queues. The card and the pages draw on the
// render thread (OnRender, RynthPluginRenderEmbed) and queue their commands for the tick.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using ImGuiNET;
using RynthCore.PluginCore;
@ -40,10 +62,19 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
private readonly ServerPackModel _model;
private readonly ServerPackUi _ui;
private readonly string _sectionsJson;
// The server's own pages (ServerPages), validated; what was left out is logged at Initialize.
private readonly List<ServerPage> _pages;
private readonly List<string> _pageNotes = new();
private readonly ServerPackSettings _settings = new(ServerPackSettings.DefaultPath(RynthPluginInfo.Name));
private readonly ServerProfileValues _profileValues = new();
// RynthCore commands from the card (render thread), run on the next tick.
private readonly ConcurrentQueue<string> _engineCommands = new();
// "/rserver ..." lines from OnChatBarEnter, run on the next tick.
private readonly ConcurrentQueue<string[]> _commands = new();
// The server code's work for the tick (RunOnTick: its pages' buttons).
private readonly ConcurrentQueue<Action> _tickActions = new();
// The server's own "/rserver" verbs (ServerCommandVerbs).
private readonly HashSet<string> _serverVerbs = new(StringComparer.OrdinalIgnoreCase);
private volatile bool _loginComplete;
private volatile string? _world;
private bool _wasActive;
@ -52,8 +83,14 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
{
ServerPackInfo info = ServerData.Create();
_model = new ServerPackModel(info);
_ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world);
_sectionsJson = ServerPackModel.BuildSectionsJson(info, RynthPluginInfo.Name);
var pages = new List<ServerPage>();
ServerPages(pages);
_pages = ServerPackPages.Validate(pages, _pageNotes.Add);
var verbs = new List<string>();
ServerCommandVerbs(verbs);
foreach (string v in verbs) if (!string.IsNullOrWhiteSpace(v)) _serverVerbs.Add(v.Trim());
_ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world, _pages);
_sectionsJson = ServerPackModel.BuildSectionsJson(info, RynthPluginInfo.Name, _pages);
}
internal ServerPackInfo Info => _model.Info;
@ -79,8 +116,52 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
partial void ServerTick(bool active);
/// <summary>"/rserver &lt;verb&gt; ..." verbs the shared code doesn't know; set handled to stop the help text.</summary>
partial void ServerChatCommand(string[] parts, ref bool handled);
/// <summary>
/// The server's own "/rserver" verbs (lower case), so "/rserver vault" reaches ServerChatCommand
/// instead of being read as another server's id. Called once, from the constructor.
/// </summary>
partial void ServerCommandVerbs(List<string> verbs);
/// <summary>Extra lines for "/rserver info".</summary>
partial void ServerInfoLines(Action<string> line);
/// <summary>The server's own pages (ServerPackPages.cs). Called once, from the constructor (no Host yet).</summary>
partial void ServerPages(List<ServerPage> pages);
/// <summary>
/// An incoming chat line (pump thread, logged in only): set <paramref name="eat"/> to keep it out of
/// the chat window (it comes in true when an earlier plugin already ate it).
/// </summary>
partial void ServerChatText(string text, int chatType, ref bool eat);
/// <summary>
/// A line sent through the chat bar, typed or another plugin's command (trimmed), before
/// "/rserver" is looked at. AC's main thread: only note it (interlocked state or a queue).
/// </summary>
partial void ServerChatBar(string text);
// ── What the server's own code uses ──────────────────────────────────
/// <summary>The plugin's settings file (loaded before ServerInitialize). Pump thread.</summary>
internal ServerPackSettings Settings => _settings;
/// <summary>The live numbers of the profile ("values"). Any thread.</summary>
internal ServerProfileValues ProfileValues => _profileValues;
/// <summary>The pages this plugin draws.</summary>
internal IReadOnlyList<ServerPage> Pages => _pages;
/// <summary>Publishes a live number in the "RynthServer.Profile" JSON ("values"). Any thread.</summary>
internal void SetProfileValue(string key, double value) => _profileValues.Set(key, value);
/// <summary>Runs <paramref name="action"/> on the next tick while logged in (dropped at logout). Any thread.</summary>
internal void RunOnTick(Action action)
{
if (action != null) _tickActions.Enqueue(action);
}
/// <summary>Sends a chat command as if typed; false when nothing went out. Pump thread.</summary>
internal bool Send(string command)
=> _loginComplete && !string.IsNullOrWhiteSpace(command) && Host.HasInvokeChatParser && Host.InvokeChatParser(command);
/// <summary>The plugin's log, tagged with its name.</summary>
internal void LogTagged(string message) => Host.Log($"[{RynthPluginInfo.Name}] {message}");
public override int Initialize()
{
@ -89,6 +170,9 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
// Mini Remote's included), never a second copy of ImGui (ImGuiNativeBinding.cs). Found and fixed
// by SilentKelpie (rynth PR #12); re-implemented here.
RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log($"[{RynthPluginInfo.Name}] {msg}"));
foreach (string note in _pageNotes) LogTagged(note);
_settings.Load();
if (_settings.LastError.Length > 0) LogTagged($"Settings ({_settings.FilePath}) not read: {_settings.LastError}; using defaults.");
ServerInitialize();
return 0;
}
@ -108,7 +192,9 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
_world = null;
while (_commands.TryDequeue(out _)) { }
while (_engineCommands.TryDequeue(out _)) { }
while (_tickActions.TryDequeue(out _)) { }
_model.Clear();
_profileValues.Clear();
ServerLogout();
}
@ -124,6 +210,11 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command))
ChatLine($"[{RynthPluginInfo.Name}] RynthCore didn't take: " + command);
}
while (_tickActions.TryDequeue(out Action? action))
{
try { action(); }
catch (Exception ex) { LogTagged($"A queued action failed: {ex.GetType().Name}: {ex.Message}"); }
}
bool active = Active;
if (active && !_wasActive && Info.Botting == BottingPolicy.Forbidden)
@ -173,7 +264,20 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
/// into the engine's current window and context (popped-out windows have their own).
/// <paramref name="wantHeight"/> is the height it used. False until login. Render thread.
/// </summary>
internal bool RenderEmbeddedCard(out float wantHeight)
internal bool RenderEmbeddedCard(out float wantHeight) => RenderEmbedded(_ui.RenderBody, "Server card", out wantHeight);
/// <summary>
/// RynthPluginRenderEmbed "section:server-&lt;id&gt;.&lt;page&gt;": one of the server's pages
/// (ServerPages) in RynthCore's Mini Remote. False for a page this plugin doesn't have, or before login.
/// </summary>
internal bool RenderEmbeddedPage(string pageId, out float wantHeight)
{
wantHeight = 0;
ServerPage? page = _pages.Find(p => p.Id == pageId);
return page != null && RenderEmbedded(page.Draw, "Page " + page.Label, out wantHeight);
}
private bool RenderEmbedded(Action draw, string what, out float wantHeight)
{
wantHeight = 0;
if (!_loginComplete) return false;
@ -184,24 +288,36 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
try
{
float startY = ImGui.GetCursorPosY();
_ui.RenderBody();
draw();
wantHeight = MathF.Max(40f, ImGui.GetCursorPosY() - startY + 4f);
return true;
}
catch (Exception ex)
{
Host.Log($"[{RynthPluginInfo.Name}] Server card failed: {ex.Message}");
Host.Log($"[{RynthPluginInfo.Name}] {what} failed: {ex.Message}");
return false;
}
finally { ImGui.SetCurrentContext(previous); }
}
// ── Chat ─────────────────────────────────────────────────────────────
/// <summary>Incoming chat (pump thread): the server's own code reads it (ServerChatText).</summary>
public override void OnChatWindowText(string? text, int chatType, ref int eat)
{
if (!_loginComplete || string.IsNullOrEmpty(text)) return;
bool eaten = eat != 0;
ServerChatText(text, chatType, ref eaten);
if (eaten) eat = 1;
}
// ── Commands ─────────────────────────────────────────────────────────
public override void OnChatBarEnter(string? text, ref int eat)
{
if (!_loginComplete || string.IsNullOrEmpty(text)) return;
string trimmed = text.Trim();
ServerChatBar(trimmed);
if (!trimmed.Equals(ChatCommand, StringComparison.OrdinalIgnoreCase)
&& !trimmed.StartsWith(ChatCommand + " ", StringComparison.OrdinalIgnoreCase))
return;
@ -216,8 +332,9 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
_commands.Enqueue(parts);
}
private static bool IsVerb(string word) =>
word.ToLowerInvariant() is "show" or "hide" or "toggle" or "info" or "help" or "on" or "off" or "auto";
private bool IsVerb(string word) =>
word.ToLowerInvariant() is "show" or "hide" or "toggle" or "info" or "help" or "on" or "off" or "auto"
|| _serverVerbs.Contains(word);
/// <summary>Drops the server id: "/rserver coldeve info" -> "/rserver info".</summary>
private static string[] Shift(string[] parts)

View file

@ -9,10 +9,90 @@
// The JSON is plain ASCII (anything else is \u-escaped), so a reader can show it in the AC client.
// Pure (no host calls): RynthServerPack.Tests covers it.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace RynthCore.Plugin.ServerPack;
/// <summary>
/// Live numbers a server plugin publishes in its profile ("values"), for other plugins that apply a
/// server rule without knowing the server: e.g. RynthConquest's "voidDotDurationScale" (how much
/// longer this character's Void damage-over-time lasts there), which RynthOracle's Void timers use.
/// Set from the server's own code (ServerPackPlugin.SetProfileValue), read by the profile interface
/// on any thread; <see cref="Revision"/> goes up on every change, so the JSON is rebuilt only then.
/// </summary>
internal sealed class ServerProfileValues
{
private readonly object _gate = new();
private readonly List<KeyValuePair<string, double>> _values = new();
private volatile int _revision;
/// <summary>Goes up whenever a value changes.</summary>
public int Revision => _revision;
/// <summary>1-48 of letters, digits, '.', '_' and '-'.</summary>
public static bool IsValidKey(string? key)
{
if (string.IsNullOrEmpty(key) || key.Length > 48) return false;
foreach (char c in key)
if (!(char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or '-')) return false;
return true;
}
/// <summary>Sets (or adds) a value; false for a bad key or a number that isn't finite. Any thread.</summary>
public bool Set(string key, double value)
{
if (!IsValidKey(key) || !double.IsFinite(value)) return false;
lock (_gate)
{
int i = _values.FindIndex(v => v.Key == key);
if (i >= 0)
{
if (_values[i].Value.Equals(value)) return true;
_values[i] = new KeyValuePair<string, double>(key, value);
}
else _values.Add(new KeyValuePair<string, double>(key, value));
_revision++;
}
return true;
}
/// <summary>Drops one value (true when it was there). Any thread.</summary>
public bool Remove(string key)
{
lock (_gate)
{
int i = _values.FindIndex(v => v.Key == key);
if (i < 0) return false;
_values.RemoveAt(i);
_revision++;
return true;
}
}
/// <summary>Drops every value (logout: the next character publishes its own). Any thread.</summary>
public void Clear()
{
lock (_gate)
{
if (_values.Count == 0) return;
_values.Clear();
_revision++;
}
}
/// <summary>A copy of the values and the revision it belongs to. Any thread.</summary>
public KeyValuePair<string, double>[] Snapshot(out int revision)
{
lock (_gate)
{
revision = _revision;
return _values.ToArray();
}
}
}
internal static class ServerPackProfile
{
/// <summary>The profile JSON's schema (RynthServerProfile.Schema).</summary>
@ -29,9 +109,11 @@ internal static class ServerPackProfile
/// <summary>
/// The profile for <paramref name="info"/>: <paramref name="active"/> is this plugin's verdict
/// (RynthCore's when it pushed one), <paramref name="world"/> the world name the client reports.
/// (RynthCore's when it pushed one), <paramref name="world"/> the world name the client reports,
/// <paramref name="values"/> the live numbers the server's own code published (ServerProfileValues).
/// </summary>
public static string BuildJson(ServerPackInfo info, string pluginName, string pluginVersion, bool active, string? world)
public static string BuildJson(ServerPackInfo info, string pluginName, string pluginVersion, bool active, string? world,
IReadOnlyList<KeyValuePair<string, double>>? values = null)
{
var sb = new StringBuilder(1024);
sb.Append("{\"schema\":").Append(Schema);
@ -93,10 +175,35 @@ internal static class ServerPackProfile
sb.Append('}');
}
sb.Append(']');
// Added within schema 1 (2026-10-20), only when the server has trinkets.
if (info.TrinketNames.Length > 0)
{
sb.Append(",\"trinkets\":{");
sb.Append("\"names\":[");
for (int i = 0; i < info.TrinketNames.Length; i++) { if (i > 0) sb.Append(','); Str(sb, info.TrinketNames[i]); }
sb.Append("],\"except\":[");
for (int i = 0; i < info.TrinketExcept.Length; i++) { if (i > 0) sb.Append(','); Str(sb, info.TrinketExcept[i]); }
sb.Append("]}");
}
Field(sb, "discord", info.Discord);
Field(sb, "website", info.Website);
Field(sb, "wiki", info.Wiki);
Field(sb, "source", info.Source);
// Added within schema 1: live numbers for this character on this server ({} when none).
sb.Append(",\"values\":{");
if (values != null)
{
bool first = true;
foreach (KeyValuePair<string, double> v in values)
{
if (!ServerProfileValues.IsValidKey(v.Key) || !double.IsFinite(v.Value)) continue;
if (!first) sb.Append(',');
first = false;
Str(sb, v.Key);
sb.Append(':').Append(v.Value.ToString("R", CultureInfo.InvariantCulture));
}
}
sb.Append('}');
sb.Append('}');
return sb.ToString();
}

View file

@ -0,0 +1,88 @@
// ServerPackRefresh.cs - The Refresh button a server page starts with, and the status line beside it
// (as RynthOracle's pages have it): the page's own command is asked for again, refused for a few
// seconds after it went out (so the button can't spam the server), and the line waits for the reply
// ("Waiting...", then "Updated hh:mm:ss", or "No reply yet" after a while).
// Render thread: Draw runs inside the page's own lock; the page's refresh callback only decides and
// queues what to send (ServerPackPlugin.RunOnTick).
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.ServerPack;
/// <summary>What a Refresh did, and (when it asked the server) how to tell the reply has landed.</summary>
internal sealed record ServerRefreshResult(string What, Func<bool>? Done = null);
internal sealed class ServerRefreshRow
{
public const long CooldownMs = 3000;
public const long ReplyWaitMs = 15_000;
public const string TooSoon = "That was just asked for; wait a few seconds before asking again.";
private static readonly Vector4 Yellow = new(0.95f, 0.85f, 0.35f, 1f);
private static readonly Vector4 Red = new(0.95f, 0.45f, 0.40f, 1f);
private readonly Dictionary<string, long> _sent = new();
private string _scope = string.Empty, _what = string.Empty;
private Func<bool>? _done;
private bool _doneSeen;
private long _atMs;
private DateTime _atLocal, _doneLocal;
/// <summary>The same request (by <paramref name="key"/>) twice within <see cref="CooldownMs"/> is refused.</summary>
public bool CoolingDown(string key, long nowMs)
{
if (_sent.TryGetValue(key, out long t) && nowMs - t < CooldownMs) return true;
_sent[key] = nowMs;
return false;
}
/// <summary>Forgets the status line and the cooldowns (logout).</summary>
public void Reset()
{
_sent.Clear();
_scope = _what = string.Empty;
_done = null;
}
/// <summary>
/// The row: Refresh (tooltip <paramref name="help"/>) and, for the page that last refreshed
/// (<paramref name="scope"/>), what happened.
/// </summary>
public void Draw(string scope, string help, Func<ServerRefreshResult> refresh)
{
long now = Environment.TickCount64;
if (ImGui.SmallButton("Refresh##refresh_" + scope))
{
ServerRefreshResult r;
try { r = refresh(); }
catch (Exception ex) { r = new ServerRefreshResult("Couldn't refresh: " + ex.Message); }
_scope = scope;
_what = r.What;
_done = r.Done;
_doneSeen = false;
_atMs = now;
_atLocal = DateTime.Now;
}
if (help.Length > 0 && ImGui.IsItemHovered()) SafeImGui.SetTooltip(help);
if (_scope != scope || _what.Length == 0) return;
ImGui.SameLine();
if (_done != null && !_doneSeen && _done())
{
_doneSeen = true;
_doneLocal = DateTime.Now;
}
if (_done != null && !_doneSeen)
{
if (now - _atMs > ReplyWaitMs) SafeImGui.TextColored(Red, "No reply yet. Press Refresh to ask again.");
else SafeImGui.TextColored(Yellow, _what + " Waiting for the reply...");
}
else if (_done != null)
SafeImGui.TextDisabled($"Updated {_doneLocal:HH:mm:ss}. {_what}");
else
SafeImGui.TextDisabled($"Refreshed {_atLocal:HH:mm:ss}. {_what}");
}
}

View file

@ -0,0 +1,158 @@
// ServerPackSettings.cs - A server plugin's own settings file, %APPDATA%\RynthCore\<plugin>.json
// (rynthconquest.json, ...), for the server's features (ServerPackPlugin.Settings).
//
// Flat named values (true/false, text), written by hand and read with JsonDocument: plugin types
// never go through System.Text.Json's serializer, which roots them across hot reloads. Values the
// plugin doesn't ask for are kept as they were written, so an older or newer copy of the plugin
// never drops another's. MigrateOnce imports settings that used to live elsewhere (another
// plugin's file) exactly once, and remembers that it did.
// Pure (file I/O only): RynthServerPack.Tests covers it. Pump thread only.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
namespace RynthCore.Plugin.ServerPack;
internal sealed class ServerPackSettings
{
// name -> the value's JSON text, in file order.
private readonly List<KeyValuePair<string, string>> _values = new();
public ServerPackSettings(string path) => FilePath = path;
/// <summary>%APPDATA%\RynthCore\&lt;plugin name, lower case&gt;.json.</summary>
public static string DefaultPath(string pluginName) => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", pluginName.ToLowerInvariant() + ".json");
public string FilePath { get; }
/// <summary>Why the last Load or Save failed ("" when it didn't).</summary>
public string LastError { get; private set; } = string.Empty;
/// <summary>Reads the file; a missing or broken one means defaults (the next save rewrites it).</summary>
public void Load()
{
_values.Clear();
LastError = string.Empty;
try
{
if (!File.Exists(FilePath)) return;
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(FilePath));
if (doc.RootElement.ValueKind != JsonValueKind.Object) { LastError = "not a JSON object"; return; }
foreach (JsonProperty p in doc.RootElement.EnumerateObject())
Put(p.Name, p.Value.GetRawText());
}
catch (Exception ex)
{
_values.Clear();
LastError = ex.Message;
}
}
/// <summary>Writes the file (through a temporary file, so a crash never leaves half of one). False on failure.</summary>
public bool Save()
{
try
{
var sb = new StringBuilder("{\n");
for (int i = 0; i < _values.Count; i++)
{
sb.Append(" ").Append(Quote(_values[i].Key)).Append(": ").Append(_values[i].Value);
sb.Append(i + 1 < _values.Count ? ",\n" : "\n");
}
sb.Append("}\n");
Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
string tmp = FilePath + ".tmp";
File.WriteAllText(tmp, sb.ToString());
File.Move(tmp, FilePath, overwrite: true);
LastError = string.Empty;
return true;
}
catch (Exception ex)
{
LastError = ex.Message;
return false;
}
}
public bool Has(string name) => Find(name) >= 0;
public bool GetBool(string name, bool fallback)
{
int i = Find(name);
return i < 0 ? fallback : _values[i].Value switch { "true" => true, "false" => false, _ => fallback };
}
/// <summary>Sets a value; true when it changed (the caller saves).</summary>
public bool SetBool(string name, bool value) => Put(name, value ? "true" : "false");
public string GetString(string name, string fallback)
{
int i = Find(name);
if (i < 0) return fallback;
try
{
using JsonDocument doc = JsonDocument.Parse(_values[i].Value);
return doc.RootElement.ValueKind == JsonValueKind.String ? doc.RootElement.GetString() ?? fallback : fallback;
}
catch (JsonException) { return fallback; }
}
public bool SetString(string name, string value) => Put(name, Quote(value ?? string.Empty));
/// <summary>
/// Runs <paramref name="migrate"/> once per settings file: unless <paramref name="marker"/> is
/// already set, it runs, the marker is set and the file saved. True when it ran now.
/// </summary>
public bool MigrateOnce(string marker, Action<ServerPackSettings> migrate)
{
if (GetBool(marker, false)) return false;
migrate(this);
SetBool(marker, true);
Save();
return true;
}
/// <summary>
/// A true/false value from another JSON settings file (an old home of a moved setting), or null
/// when the file, the value or its type isn't there. Never throws.
/// </summary>
public static bool? ReadBoolFrom(string path, string name)
{
try
{
if (!File.Exists(path)) return null;
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path));
if (doc.RootElement.ValueKind != JsonValueKind.Object || !doc.RootElement.TryGetProperty(name, out JsonElement v)) return null;
return v.ValueKind switch { JsonValueKind.True => true, JsonValueKind.False => false, _ => null };
}
catch
{
return null;
}
}
private int Find(string name)
{
for (int i = 0; i < _values.Count; i++)
if (string.Equals(_values[i].Key, name, StringComparison.Ordinal)) return i;
return -1;
}
private bool Put(string name, string json)
{
int i = Find(name);
if (i >= 0)
{
if (_values[i].Value == json) return false;
_values[i] = new KeyValuePair<string, string>(name, json);
return true;
}
_values.Add(new KeyValuePair<string, string>(name, json));
return true;
}
private static string Quote(string s) => "\"" + JsonEncodedText.Encode(s).ToString() + "\"";
}

View file

@ -7,6 +7,7 @@
// account limit, botting policy, its features), the commands it adds, its links, and how to set an
// account up for it in the launcher. Render thread only.
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
@ -24,6 +25,7 @@ internal sealed class ServerPackUi
private readonly string _pluginLabel;
private readonly Func<string?> _world;
private readonly string _windowTitle;
private readonly IReadOnlyList<ServerPage> _pages;
private string _status = string.Empty;
/// <summary>The standalone window is open ("/rserver").</summary>
@ -31,21 +33,42 @@ internal sealed class ServerPackUi
/// <param name="pluginLabel">"RynthColdeve 0.1.0", for the title and the card.</param>
/// <param name="world">The world name the client reports now (null when unknown).</param>
public ServerPackUi(ServerPackModel model, string pluginLabel, Func<string?> world)
/// <param name="pages">The server's own pages: tabs of the window after the card.</param>
public ServerPackUi(ServerPackModel model, string pluginLabel, Func<string?> world, IReadOnlyList<ServerPage>? pages = null)
{
_model = model;
_pluginLabel = pluginLabel;
_world = world;
_pages = pages ?? Array.Empty<ServerPage>();
_windowTitle = model.Info.Name + " server (" + pluginLabel + ")##server_" + model.Info.Id;
}
/// <summary>The standalone window, while open.</summary>
/// <summary>The standalone window, while open: the card, and the server's pages as tabs when it has some.</summary>
public void RenderWindow()
{
if (!WindowOpen) return;
ImGui.SetNextWindowSize(new Vector2(460, 520), ImGuiCond.FirstUseEver);
ImGui.SetNextWindowSize(new Vector2(_pages.Count > 0 ? 560 : 460, 520), ImGuiCond.FirstUseEver);
bool open = WindowOpen;
if (ImGui.Begin(_windowTitle, ref open)) RenderBody();
if (ImGui.Begin(_windowTitle, ref open))
{
if (_pages.Count == 0) RenderBody();
else if (ImGui.BeginTabBar("##server_tabs_" + _model.Info.Id))
{
if (ImGui.BeginTabItem("Server##card"))
{
RenderBody();
ImGui.EndTabItem();
}
foreach (ServerPage page in _pages)
{
if (!ImGui.BeginTabItem(page.Label + "##page_" + page.Id)) continue;
if (ImGui.BeginChild("##page_body_" + page.Id)) page.Draw();
ImGui.EndChild();
ImGui.EndTabItem();
}
ImGui.EndTabBar();
}
}
ImGui.End();
WindowOpen = open;
}

View file

@ -17,7 +17,8 @@
engine loads the plugin only for its server) and into RynthPluginInfo (the plugin's own use).
Server-specific features go in the project as more files, through the partial hooks in
ServerPackPlugin.cs (ServerTick, ServerChatCommand, ...), so the shared code stays the same for all.
ServerPackPlugin.cs (ServerTick, ServerChatCommand, ServerChatText, ServerPages, ...), so the
shared code stays the same for all (the hooks and helpers are listed at the top of that file).
-->
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
@ -44,6 +45,11 @@
<Compile Include="$(MSBuildThisFileDirectory)..\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackInfo.cs" Link="ServerPack\ServerPackInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackModel.cs" Link="ServerPack\ServerPackModel.cs" />
<!-- The server's own pages, settings file, reply window and Refresh row (ServerPackPlugin.cs lists the hooks). -->
<Compile Include="$(MSBuildThisFileDirectory)ServerPackPages.cs" Link="ServerPack\ServerPackPages.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackSettings.cs" Link="ServerPack\ServerPackSettings.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerChatRequest.cs" Link="ServerPack\ServerChatRequest.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackRefresh.cs" Link="ServerPack\ServerPackRefresh.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackUi.cs" Link="ServerPack\ServerPackUi.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackPlugin.cs" Link="ServerPack\ServerPackPlugin.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackExports.cs" Link="ServerPack\ServerPackExports.cs" />

View file

@ -0,0 +1,153 @@
// ============================================================================
// RynthSuite - Plugins/Shared/StorageFeed.cs
// Storage the client is never shown, handed to RynthInventory by another plugin: a server plugin
// that can read a server-side store (RynthAelrynth reads Aelrynth's account vault with /mule-data)
// sends RynthInventory the whole record, and RynthInventory files it with the character's storage
// (searched, shown with icons and merged across characters like a container that was opened).
// RynthInventory knows nothing about the server: the sender decides what the store is and when to
// read it; without the sender (its server plugin not installed) nothing is asked and nothing is sent.
//
// Transport: the engine's plugin-command broker, SendPluginCommand("RynthInventory", "storage",
// json) -> RynthInventory's RynthPluginApplyRemoteCommand. The strings travel as ANSI, so the JSON
// is plain ASCII (anything else \u-escaped). Payload (version 1):
// { "v": 1,
// "id": 4278190080, // a stand-in container id, top byte 0xFF (never a real object's);
// // the same id replaces the earlier copy (per character file)
// "name": "Aelrynth vault", "label": "Account vault",
// "items": [ { "o": id, "w": wcid, "n": "name", "i": icon, "u": underlay, "v": overlay,
// "s": stack, "m": max stack, "y": item type }, ... ] }
// Compiled into RynthInventory (receiver) and the senders (linked source), so the format can't drift.
// Pure: RynthInventory.Tests and RynthServerPack.Tests cover it.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
namespace RynthCore.Plugin.Shared;
/// <summary>One stored item, as a sender read it (the vault's "o", "w", "n", ... fields).</summary>
internal sealed record StorageFeedItem(uint Id, uint Wcid, string Name, uint Icon, uint Underlay, uint Overlay,
int Stack, int MaxStack, uint ItemType);
/// <summary>A whole store: its stand-in id, its name and label, and everything in it.</summary>
internal sealed record StorageFeedRecord(uint Id, string Name, string Label, IReadOnlyList<StorageFeedItem> Items);
internal static class StorageFeed
{
/// <summary>The receiver, and the plugin command it answers.</summary>
public const string TargetPlugin = "RynthInventory";
public const string Action = "storage";
public const int Version = 1;
public const int MaxItems = 5000;
public const int MaxJsonLength = 4 * 1024 * 1024;
public const int MaxNameLength = 64;
/// <summary>A stand-in container id: top byte 0xFF, where no object the client has seen lives.</summary>
public static bool IsStandInId(uint id) => id >> 24 == 0xFF;
/// <summary>The payload for <paramref name="record"/> (plain ASCII).</summary>
public static string ToJson(StorageFeedRecord record)
{
var sb = new StringBuilder(64 + record.Items.Count * 120);
sb.Append("{\"v\":").Append(Version).Append(",\"id\":").Append(record.Id.ToString(CultureInfo.InvariantCulture));
sb.Append(",\"name\":"); Str(sb, record.Name);
sb.Append(",\"label\":"); Str(sb, record.Label);
sb.Append(",\"items\":[");
for (int i = 0; i < record.Items.Count; i++)
{
StorageFeedItem it = record.Items[i];
if (i > 0) sb.Append(',');
sb.Append("{\"o\":").Append(it.Id.ToString(CultureInfo.InvariantCulture));
sb.Append(",\"w\":").Append(it.Wcid.ToString(CultureInfo.InvariantCulture));
sb.Append(",\"n\":"); Str(sb, it.Name);
sb.Append(",\"i\":").Append(it.Icon.ToString(CultureInfo.InvariantCulture));
sb.Append(",\"u\":").Append(it.Underlay.ToString(CultureInfo.InvariantCulture));
sb.Append(",\"v\":").Append(it.Overlay.ToString(CultureInfo.InvariantCulture));
sb.Append(",\"s\":").Append(it.Stack.ToString(CultureInfo.InvariantCulture));
sb.Append(",\"m\":").Append(it.MaxStack.ToString(CultureInfo.InvariantCulture));
sb.Append(",\"y\":").Append(it.ItemType.ToString(CultureInfo.InvariantCulture));
sb.Append('}');
}
sb.Append("]}");
return sb.ToString();
}
/// <summary>
/// The record in a payload, or null (with the reason in <paramref name="error"/>) for anything
/// unusable: not JSON, a newer version, an id that isn't a stand-in, no name, too many items.
/// Never throws.
/// </summary>
public static StorageFeedRecord? Parse(string? json, out string error)
{
error = string.Empty;
if (string.IsNullOrWhiteSpace(json)) { error = "empty"; return null; }
if (json.Length > MaxJsonLength) { error = "too large"; return null; }
try
{
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) { error = "not a JSON object"; return null; }
int v = Int(root, "v", 0);
if (v < 1 || v > Version) { error = "version " + v; return null; }
uint id = UInt(root, "id");
if (!IsStandInId(id)) { error = $"id 0x{id:X8} is not a stand-in (top byte 0xFF)"; return null; }
string name = Cap(Str(root, "name"));
if (name.Length == 0) { error = "no name"; return null; }
string label = Cap(Str(root, "label"));
var items = new List<StorageFeedItem>();
if (root.TryGetProperty("items", out JsonElement list) && list.ValueKind == JsonValueKind.Array)
{
foreach (JsonElement e in list.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.Object) continue;
if (items.Count >= MaxItems) { error = $"more than {MaxItems} items"; return null; }
items.Add(new StorageFeedItem(UInt(e, "o"), UInt(e, "w"), Str(e, "n"), UInt(e, "i"), UInt(e, "u"), UInt(e, "v"),
Math.Max(1, Int(e, "s", 1)), Int(e, "m", 0), UInt(e, "y")));
}
}
return new StorageFeedRecord(id, name, label.Length > 0 ? label : name, items);
}
catch (JsonException ex)
{
error = "bad JSON: " + ex.Message;
return null;
}
}
private static string Cap(string s)
{
s = s.Trim();
return s.Length <= MaxNameLength ? s : s[..MaxNameLength];
}
private static int Int(JsonElement e, string name, int fallback) =>
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : fallback;
private static uint UInt(JsonElement e, string name) =>
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetUInt32(out uint u) ? u : 0u;
private static string Str(JsonElement e, string name) =>
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty;
/// <summary>A JSON string literal in plain ASCII (control and non-ASCII characters \u-escaped).</summary>
private static void Str(StringBuilder sb, string? s)
{
sb.Append('"');
foreach (char c in s ?? string.Empty)
{
switch (c)
{
case '"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
default:
if (c < 0x20 || c > 0x7e) sb.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
else sb.Append(c);
break;
}
}
sb.Append('"');
}
}