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

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthInventory.Data;
/// <summary>One character on the Banking tab: its saved balances (null = never read) and account.</summary>
internal sealed record BankRosterEntry(string Name, string Account, bool Current, IltBankRow? Bank);
/// <summary>
/// The Banking tab's character list (2026-10-13; the Mini Remote's Banking tab moved here). Every
/// character RynthILT has bank balances for on this server (its saved per-character state, so every
/// account played on this PC), plus every character Global Inventory has recorded on the same
/// server without a balance yet, so the list covers the same characters as the inventory does.
/// Pure: the tests feed it a parsed bank view and an index.
/// </summary>
internal static class BankRoster
{
/// <summary>
/// The merged list: the logged-in character first, then by name. A name in both lists keeps
/// RynthILT's balances and the inventory's account.
/// </summary>
public static List<BankRosterEntry> Build(IltBankView bank, InventoryIndex? index)
{
var byName = new Dictionary<string, BankRosterEntry>(StringComparer.OrdinalIgnoreCase);
foreach (IltBankRow r in bank.Characters)
byName[r.Name] = new BankRosterEntry(r.Name, string.Empty, r.Current, r);
if (index != null)
{
foreach (CharacterInfo ci in index.Characters)
{
// Same server only: a bank belongs to one world.
if (!SameServer(ci, bank)) continue;
string account = !string.IsNullOrEmpty(ci.Account) && ci.Account != "unknown" ? ci.Account : string.Empty;
if (byName.TryGetValue(ci.Name, out BankRosterEntry? have))
byName[ci.Name] = have with { Account = account, Current = have.Current || ci.IsCurrentCharacter };
else
byName[ci.Name] = new BankRosterEntry(ci.Name, account, ci.IsCurrentCharacter, null);
}
}
var list = new List<BankRosterEntry>(byName.Values);
list.Sort((a, b) => a.Current != b.Current ? (a.Current ? -1 : 1) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
return list;
}
/// <summary>
/// A recorded character is on the bank's server: the world RynthILT names when it gave one,
/// otherwise the server Global Inventory says you are on now.
/// </summary>
private static bool SameServer(CharacterInfo ci, IltBankView bank) =>
bank.World.Length > 0 ? InventoryIndex.SameName(ci.Server, bank.World) : ci.IsCurrentServer;
/// <summary>The sums over every character with a balance (one row of the same shape).</summary>
public static IltBankRow Totals(IReadOnlyList<BankRosterEntry> roster)
{
long py = 0, lum = 0, lk = 0, mk = 0, ec = 0, wec = 0, pc = 0;
foreach (BankRosterEntry e in roster)
{
if (e.Bank is not { } b) continue;
py += b.Pyreals; lum += b.Luminance; lk += b.LegendaryKeys; mk += b.MythicalKeys;
ec += b.EnlightenedCoins; wec += b.WeaklyEnlightenedCoins; pc += b.PrestigeCoins;
}
return new IltBankRow("Total", false, py, lum, lk, mk, ec, wec, pc, DateTime.MinValue);
}
/// <summary>
/// The withdraw / transfer amount typed in the form: a positive whole number (commas and spaces
/// allowed), or 0 when it isn't one.
/// </summary>
public static long ParseAmount(string? text)
{
if (string.IsNullOrWhiteSpace(text)) return 0;
string digits = text.Replace(",", string.Empty).Replace(" ", string.Empty).Trim();
return long.TryParse(digits, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out long n) && n > 0 ? n : 0;
}
}

View file

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthInventory.Data;
/// <summary>
/// Storage another plugin read for us (Plugins/Shared/StorageFeed.cs): a server-side store the client
/// is never shown, e.g. Aelrynth's account vault from RynthAelrynth. Filed with the character's storage
/// like a container that was opened; RynthInventory itself knows nothing about any server's store.
/// Pure: RynthInventory.Tests covers it.
/// </summary>
internal static class ExternalStorage
{
/// <summary>The feed's record as a storage record, seen now (<paramref name="seenUtc"/>).</summary>
public static StorageRecord ToRecord(StorageFeedRecord feed, DateTime seenUtc)
{
var items = new List<ItemRecord>(feed.Items.Count);
foreach (StorageFeedItem f in feed.Items)
{
var it = new ItemRecord
{
Id = f.Id,
Wcid = f.Wcid,
Name = f.Name,
Icon = f.Icon,
Underlay = f.Underlay,
Overlay = f.Overlay,
Stack = Math.Max(1, f.Stack),
MaxStack = f.MaxStack,
ItemType = f.ItemType,
Place = ItemPlace.Storage,
};
it.Category = ItemCategory.FromItemType(it.ItemType);
items.Add(it);
}
return new StorageRecord { Id = feed.Id, Name = feed.Name, Label = feed.Label, Cell = 0, SeenUtc = seenUtc, Items = items };
}
/// <summary>A copy of <paramref name="storage"/> with <paramref name="record"/> in it (replacing the one with its id).</summary>
public static List<StorageRecord> FileInto(IReadOnlyList<StorageRecord> storage, StorageRecord record)
{
var list = new List<StorageRecord>(storage);
int i = list.FindIndex(s => s.Id == record.Id);
if (i >= 0) list[i] = record; else list.Add(record);
return list;
}
}

View file

@ -35,6 +35,13 @@ internal sealed class InventoryContext
public bool IconsAvailable;
public DateTime UtcNow;
/// <summary>RynthILT's "RynthILT.Data" (the Banking tab's balances and bank commands).</summary>
public readonly RynthCore.Plugin.Shared.RynthIltDataClient IltData = new();
/// <summary>The bank RynthILT last reported (None without RynthILT); read while the window shows.</summary>
public RynthCore.Plugin.Shared.IltBankView Bank = RynthCore.Plugin.Shared.IltBankView.None;
/// <summary>Set by the plugin: queues a bank verb with RynthILT (IltBankView.*Verb); false when refused.</summary>
public Func<string, bool> BankCommand = _ => false;
public Action RequestRescan = () => { };
public Action RequestReload = () => { };
/// <summary>Forgets a character (moves its file aside). Returns a message for the player.</summary>

View file

@ -37,7 +37,7 @@ public static unsafe class PluginExports
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion()
{
try { return LiteralPointer("0.1.0"u8); }
try { return LiteralPointer("0.1.1"u8); }
catch { return IntPtr.Zero; }
}
@ -59,8 +59,23 @@ public static unsafe class PluginExports
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
/// <summary>
/// The engine's plugin-command broker: "storage" from another plugin (StorageFeed.cs, e.g. Aelrynth's
/// account vault from RynthAelrynth). The ANSI strings are copied before returning; the payload is
/// only queued, so any thread is fine.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginApplyRemoteCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void ApplyRemoteCommand(IntPtr actionAnsi, IntPtr valueAnsi)
{
try
{
string action = actionAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(actionAnsi) ?? string.Empty) : string.Empty;
if (action.Length == 0 || action.Length > 32) return;
string value = valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty;
Runtime.Plugin?.ApplyRemoteCommand(action, value);
}
catch { /* never let a managed exception cross the native boundary */ }
}
// Inventory change triggers (the scan's poll catches the rest, e.g. moves from a corpse).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })]

View file

@ -39,8 +39,10 @@
</ItemGroup>
<ItemGroup>
<!-- Server signal vs a player's copy of it (VaultFeed). Also linked by RynthInventory.Tests. -->
<Compile Include="..\Shared\ChatSource.cs" Link="Shared\ChatSource.cs" />
<!-- Storage another plugin reads for us ("storage" commands: Aelrynth's vault from RynthAelrynth). Also linked by RynthInventory.Tests. -->
<Compile Include="..\Shared\StorageFeed.cs" Link="Shared\StorageFeed.cs" />
<!-- RynthILT's "RynthILT.Data" interface: the Banking tab's balances for every character on the server. -->
<Compile Include="..\Shared\RynthIltDataApi.cs" Link="Shared\RynthIltDataApi.cs" />
</ItemGroup>
</Project>

View file

@ -7,6 +7,7 @@ using RynthCore.Plugin.RynthInventory.Data;
using RynthCore.Plugin.RynthInventory.Scanning;
using RynthCore.Plugin.RynthInventory.Ui;
using RynthCore.Plugin.RynthInventory.Views;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
@ -17,7 +18,9 @@ namespace RynthCore.Plugin.RynthInventory;
/// (like Virindi Global Inventory). Each client scans the character it is logged into (a full
/// scan after login, then whenever the inventory changes, debounced) and writes one file per
/// character per server; storage the character opens (house storage, banks, vaults) is
/// recorded when it is opened. /ginv opens a window that merges every file.
/// recorded when it is opened, and storage another plugin reads for it (a server plugin's
/// server-side store, through Plugins/Shared/StorageFeed.cs) when that arrives. /ginv opens a
/// window that merges every file.
///
/// Everything runs on the plugin pump (OnTick and the events the engine drains into it)
/// except OnChatBarEnter, which the engine may call on AC's thread: it only queues the
@ -26,7 +29,14 @@ namespace RynthCore.Plugin.RynthInventory;
/// </summary>
public sealed class RynthInventoryPlugin : RynthPluginBase
{
public const string Version = "0.1.0";
// Previous release: 0.1.0. Keep in step with PluginExports.GetVersion.
public const string Version = "0.1.1";
// RynthILT's bank JSON: every BankTabReadMs on the Banking tab, every BankIdleReadMs with the
// window on another tab (so the Banking button appears on ILT worlds), never with it closed.
private const long BankTabReadMs = 2000, BankIdleReadMs = 10_000;
private long _nextBankReadMs;
private string _bankJson = string.Empty;
private const long IdentityRetryMs = 1000;
private const long AccountWaitMs = 15_000;
@ -47,10 +57,12 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
private InventoryView? _view;
private readonly ConcurrentQueue<string> _commands = new();
// The Aelrynth account vault (/mule-data), read a few seconds after login and every VaultRefreshMs.
private const long VaultFirstAskMs = 8_000, VaultRefreshMs = 10 * 60_000;
private VaultFeed? _vault;
private long _nextVaultAskMs;
// Storage other plugins read for us ("storage" plugin commands, StorageFeed.cs): queued by
// ApplyRemoteCommand (any thread), filed on the tick once the character is known. Aelrynth's
// account vault comes this way from RynthAelrynth (it was read here until 2026-10-20).
private readonly ConcurrentQueue<string> _storagePushes = new();
private const int MaxQueuedPushes = 8;
private string _lastPush = string.Empty;
private bool _identityKnown;
private long _loginMs;
@ -86,8 +98,8 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
_c.RequestRescan = () => { _scheduler.RequestFullScan(); _forceWrite = true; };
_c.RequestReload = () => { _reloadWanted = true; _files.Clear(); };
_c.Forget = ForgetCharacter;
_c.BankCommand = SendBankVerb;
_ui.Log = msg => Host.Log(msg);
_vault = new VaultFeed(text => Host.InvokeChatParser(text));
_view = new InventoryView(_c);
// No bar button of its own: opened from the engine Inventory window's GInv button, the
@ -115,17 +127,50 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
_c.LastSavedUtc = default;
_c.LastSaveError = string.Empty;
_scanner.Reset();
_vault?.Reset();
_nextVaultAskMs = 0;
CloseStorage();
_lastViewed = 0;
_lastWriteMs = 0;
_carriedIds.Clear();
_carriedPacks.Clear();
RefreshIconSupport();
ClearBank();
if (_window != null) { _window.Visible = _c.Settings.MainWindowOpen; _window.NeedsPass = true; }
}
/// <summary>Forgets the last bank read (login, logout): the next character's comes fresh.</summary>
private void ClearBank()
{
_c.Bank = Shared.IltBankView.None;
_bankJson = string.Empty;
_nextBankReadMs = 0;
}
/// <summary>The Banking tab's actions: a verb line for RynthILT, then a quick re-read for its reply.</summary>
private bool SendBankVerb(string verb)
{
long now = Environment.TickCount64;
bool ok = _c.InWorld && _c.IltData.BankCommand(Host, now, verb);
_nextBankReadMs = now + 500;
if (_window != null) _window.NeedsPass = true;
return ok;
}
/// <summary>
/// Reads RynthILT's bank JSON while the window is open (more often on the Banking tab) and
/// redraws when it changed. Reading is what tells RynthILT someone is looking.
/// </summary>
private void TickBank(long now)
{
if (!_c.InWorld || _window == null || _view == null || !_window.Visible) return;
if (now < _nextBankReadMs) return;
_nextBankReadMs = now + (_view.Tab == InventoryView.TabBanking ? BankTabReadMs : BankIdleReadMs);
string json = _c.IltData.ReadBank(Host, now);
if (string.Equals(json, _bankJson, StringComparison.Ordinal)) return;
_bankJson = json;
_c.Bank = Shared.IltBankView.Parse(json);
_window.NeedsPass = true;
}
public override void OnLogout()
{
// Last word for this character: write what it has now (also refreshes its "scanned" time).
@ -138,6 +183,9 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
_ui.SubmitEmpty(Host);
_c.Live = null;
_indexDirty = true;
ClearBank();
while (_storagePushes.TryDequeue(out _)) { } // the next character's come fresh
_lastPush = string.Empty;
}
public override void Shutdown()
@ -226,11 +274,6 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
case "keep":
KeepOpenContainer();
break;
case "vault":
if (_vault == null || !Host.HasInvokeChatParser) { _c.Print("This engine can't send commands for the plugin, so the vault can't be read."); break; }
_nextVaultAskMs = Environment.TickCount64 + VaultRefreshMs;
_c.Print(_vault.Ask(Environment.TickCount64, force: true) ? "Reading the vault (/mule-data)..." : "The vault is already being read: " + _vault.Describe());
break;
case "reload":
_reloadWanted = true;
_files.Clear();
@ -239,9 +282,16 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
case "status":
PrintStatus();
break;
case "bank":
case "banking":
// The Banking tab: every character's Infinite Leaftide bank (RynthILT's data). Shows, never toggles off.
_view?.ShowBanking();
_nextBankReadMs = 0;
if (_window != null) { _window.Visible = true; _window.NeedsPass = true; }
break;
case "help":
case "?":
_c.Print("/ginv (window), /ginv <text> (search), /ginv scan (rescan and save now), /ginv keep (record the open container as storage), /ginv vault (read the Aelrynth account vault now), /ginv reload, /ginv status");
_c.Print("/ginv (window), /ginv <text> (search), /ginv bank (every character's Infinite Leaftide bank), /ginv scan (rescan and save now), /ginv keep (record the open container as storage), /ginv reload, /ginv status");
break;
default:
_view?.SetSearch(arg);
@ -261,7 +311,7 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
int items = _c.Live?.Items.Count ?? 0, storage = _c.Live?.Storage.Count ?? 0;
string saved = _c.LastSavedUtc == default ? "not saved yet" : "saved " + InventoryIndex.Age(_c.LastSavedUtc, DateTime.UtcNow);
_c.Print($"{who}: {items} items carried, {storage} storage container(s), {saved}. {_c.Index?.Characters.Count ?? 0} characters in {_c.Store.Root}.");
if (_vault != null) _c.Print("Aelrynth vault: " + _vault.Describe() + ".");
if (_lastPush.Length > 0) _c.Print("From other plugins: " + _lastPush + ".");
if (_c.LastSaveError.Length > 0) _c.Print("Last save failed: " + _c.LastSaveError);
}
@ -309,6 +359,7 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
}
TickWrite(now);
TickIndex(now);
TickBank(now);
if (!Host.HasUi || _window == null || _view == null) return;
Record(_window, now, 2000, _view.Draw);
@ -345,48 +396,42 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
if (_openStorage != 0 && now >= _nextStorageScanMs)
ScanStorage(now, final: false);
TickVault(now);
TickStoragePushes(now);
}
// ── The account vault ───────────────────────────────────────────────────
// ── Storage from other plugins ──────────────────────────────────────────
/// <summary>
/// Asks the server for the vault after login and now and then, and files what comes back with the
/// character's storage (one record, the same id on every character of the account).
/// RynthPluginApplyRemoteCommand: "storage" (StorageFeed.Action) carries a whole store another
/// plugin read. Any thread: the payload is only queued (the newest few).
/// </summary>
private void TickVault(long now)
internal void ApplyRemoteCommand(string action, string value)
{
VaultFeed? v = _vault;
if (v == null || _c.Live == null || !Host.HasInvokeChatParser) return;
if (_nextVaultAskMs == 0) _nextVaultAskMs = now + VaultFirstAskMs;
else if (now >= _nextVaultAskMs && v.Status != VaultFeed.State.Unsupported)
{
_nextVaultAskMs = now + VaultRefreshMs;
v.Ask(now);
}
v.Tick(now, _c.Account);
if (v.TakeChanged() && v.Record != null) FileVault(v.Record, now);
if (!action.Equals(StorageFeed.Action, StringComparison.OrdinalIgnoreCase) || value.Length == 0 || value.Length > StorageFeed.MaxJsonLength) return;
_storagePushes.Enqueue(value);
while (_storagePushes.Count > MaxQueuedPushes && _storagePushes.TryDequeue(out _)) { }
}
private void FileVault(StorageRecord vault, long now)
/// <summary>Files what other plugins sent, once the character (and so its storage) is known. Plugin tick.</summary>
private void TickStoragePushes(long now)
{
if (_c.Live == null) return;
var storage = new List<StorageRecord>(_c.Live.Storage);
int i = storage.FindIndex(s => s.Id == vault.Id);
if (i >= 0) storage[i] = vault; else storage.Add(vault);
CharacterSnapshot snap = NewSnapshot(_c.Live.Items, storage);
snap.ScannedUtc = _c.Live.ScannedUtc;
_c.Live = snap;
_indexDirty = true;
_scheduler.ContentChanged(now, snap.ContentHash());
}
// May run on AC's thread: the feed only queues.
public override void OnChatWindowText(string? text, int chatType, ref int eat)
{
if (eat == 0 && _vault != null && _vault.ShouldEat(text, chatType)) eat = 1;
while (_storagePushes.TryDequeue(out string? json))
{
StorageFeedRecord? feed = StorageFeed.Parse(json, out string error);
if (feed == null)
{
Host.Log("[RynthInventory] storage from another plugin refused: " + error);
continue;
}
StorageRecord record = ExternalStorage.ToRecord(feed, DateTime.UtcNow);
CharacterSnapshot snap = NewSnapshot(_c.Live.Items, ExternalStorage.FileInto(_c.Live.Storage, record));
snap.ScannedUtc = _c.Live.ScannedUtc;
_c.Live = snap;
_indexDirty = true;
_scheduler.ContentChanged(now, snap.ContentHash());
_lastPush = $"{record.Label} ({record.Items.Count} item(s)) at {DateTime.Now:HH:mm}";
}
}
private void StartCharacter(long now, uint player, string server, string account, string character)

View file

@ -1,252 +0,0 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Text.Json;
using RynthCore.Plugin.RynthInventory.Data;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthInventory.Scanning;
/// <summary>
/// The Aelrynth account vault (the Aeshnidae.Mule mod): item storage the retail client is never
/// shown, so the only way to see inside is to ask. The plugin types /mule-data, exactly as a
/// player could, and the server answers one chat line a page:
///
/// ~ael1 {"t":"mule","ready":true,"page":1,"pages":3,"count":57,"max":1000,"items":[{...}]}
///
/// (the same "~ael1" lines the Aelrynth Companion reads; only lines whose "t" is "mule" are ours).
/// The pages are collected into one StorageRecord and kept with the character's storage, so the
/// vault is searched, shown with icons and merged across characters like any other storage; the
/// newest copy wins, and a vault belongs to the account, so every character sees the same one.
///
/// A server without the command is asked once after login; its "Unknown command" reply is eaten
/// and the plugin stays quiet. A vault the server says is not ready yet is asked again a few
/// times, and is never recorded as empty.
///
/// Threads: <see cref="ShouldEat"/> may run on AC's thread (it only queues); everything else runs
/// on the plugin tick.
/// </summary>
internal sealed class VaultFeed
{
public const string Command = "/mule-data";
public const string Prefix = "~ael1 ";
public const string Label = "Account vault";
public const string VaultName = "Aelrynth vault";
public enum State { Idle, Asking, Unsupported, Waiting }
private const long AnswerWindowMs = 15_000, RetryReadyMs = 3_000;
private const int MaxReadyRetries = 6, MaxPages = 80;
private const string UnknownMarker = "\u0001unknown";
private readonly Func<string, bool> _send;
private readonly ConcurrentQueue<string> _lines = new();
private long _sentAtMs;
private volatile bool _expecting;
private int _readyTries;
private long _retryAtMs;
private readonly List<ItemRecord> _pages = new();
private bool _changed;
public VaultFeed(Func<string, bool> send) => _send = send;
public State Status { get; private set; } = State.Idle;
/// <summary>The vault once a full read finished (null until then).</summary>
public StorageRecord? Record { get; private set; }
public int Max { get; private set; }
/// <summary>For /ginv status.</summary>
public string Describe() => Status switch
{
State.Unsupported => "no vault on this server",
State.Asking => "reading the vault...",
State.Waiting => "the vault is still loading on the server",
_ => Record == null ? "vault not read yet" : $"vault: {Record.Items.Count} item(s)" + (Max > 0 ? $" of {Max}" : ""),
};
/// <summary>True once after <see cref="Record"/> was replaced.</summary>
public bool TakeChanged() { bool c = _changed; _changed = false; return c; }
public void Reset()
{
Status = State.Idle;
_expecting = false;
_pages.Clear();
_readyTries = 0;
while (_lines.TryDequeue(out _)) { }
}
/// <summary>Starts a read from page 1, unless one is under way or the server has no vault (<paramref name="force"/> asks anyway).</summary>
public bool Ask(long nowMs, bool force = false)
{
if (Status == State.Asking || Status == State.Waiting) return false;
if (Status == State.Unsupported && !force) return false;
_readyTries = 0;
_pages.Clear();
return SendPage(nowMs, 1);
}
private bool SendPage(long nowMs, int page)
{
_sentAtMs = nowMs;
Status = State.Asking;
_expecting = true;
if (_send(page <= 1 ? Command : Command + " " + page.ToString(CultureInfo.InvariantCulture))) return true;
_expecting = false;
Status = State.Idle;
return false;
}
/// <summary>
/// True for a line this feed answers, so the caller keeps it out of the chat window. Cheap; any thread.
/// <paramref name="chatType"/> is the line's eChatTypes (-1 = not known). Server lines only: a line
/// in a player's chat type, or one that doesn't start with the marker (a player's copy has their
/// name in front), is left alone, so nobody can feed the vault view or hide chat by typing "~ael1".
/// </summary>
public bool ShouldEat(string? text, int chatType = -1)
{
if (string.IsNullOrEmpty(text) || ChatSource.IsPlayerAuthored(chatType)) return false;
int at = ChatSource.ContentStart(text);
if (ChatSource.StartsWithMarker(text, Prefix))
{
// Only our own kind: another plugin's ~ael1 line (the Companion's) stays visible to it.
if (text.IndexOf("\"t\":\"mule\"", at, StringComparison.Ordinal) < 0) return false;
_lines.Enqueue(text.Substring(at + Prefix.Length));
return true;
}
// The reply of a server that has no such command: swallowed only while we wait for one.
if (_expecting && IsUnknownCommandReply(text))
{
_lines.Enqueue(UnknownMarker);
return true;
}
return false;
}
/// <summary>ACE's "Unknown command: mule-data" (GameActionTalk names the bare command; a leading / or @ is allowed).</summary>
private static bool IsUnknownCommandReply(string text)
{
const string marker = "Unknown command:";
if (!ChatSource.StartsWithMarker(text, marker, StringComparison.OrdinalIgnoreCase)) return false;
string named = text.Substring(ChatSource.ContentStart(text) + marker.Length).Trim().TrimStart('/', '@');
return string.Equals(named, "mule-data", StringComparison.OrdinalIgnoreCase);
}
/// <summary>Applies what arrived and decides what to send next. Plugin tick.</summary>
public void Tick(long nowMs, string account)
{
while (_lines.TryDequeue(out string? line)) Apply(line, nowMs, account);
if (Status == State.Waiting && nowMs >= _retryAtMs) SendPage(nowMs, 1);
else if (Status == State.Asking && nowMs - _sentAtMs > AnswerWindowMs)
{
// Nothing came back: a server without the mod, or a lost line. The next /ginv vault retries.
_expecting = false;
Status = State.Idle;
_pages.Clear();
}
}
private void Apply(string line, long nowMs, string account)
{
if (line == UnknownMarker)
{
if (Status == State.Asking) { _expecting = false; Status = State.Unsupported; _pages.Clear(); }
return;
}
if (Status != State.Asking) return; // a line we did not ask for (typed by hand, say)
_expecting = false;
try
{
using JsonDocument doc = JsonDocument.Parse(line);
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) { Status = State.Idle; return; }
if (!(root.TryGetProperty("ready", out JsonElement ready) && ready.ValueKind == JsonValueKind.True))
{
string why = Str(root, "why");
if (why == "loading" && ++_readyTries <= MaxReadyRetries) { Status = State.Waiting; _retryAtMs = nowMs + RetryReadyMs; }
else Status = State.Idle; // closed / fault / error: try again at the next refresh
_pages.Clear();
return;
}
int page = Int(root, "page", 1), pages = Math.Min(Math.Max(Int(root, "pages", 1), 1), MaxPages);
Max = Int(root, "max", Max);
int count = Int(root, "count", 0);
if (page == 1) _pages.Clear();
if (root.TryGetProperty("items", out JsonElement items) && items.ValueKind == JsonValueKind.Array)
foreach (JsonElement e in items.EnumerateArray())
if (e.ValueKind == JsonValueKind.Object) _pages.Add(Item(e));
if (page < pages) { SendPage(nowMs, page + 1); return; }
// Last page. A total that disagrees with what was read means the vault changed under
// the read (a deposit between pages): keep the old copy and read again shortly.
if (count != _pages.Count && _readyTries++ < MaxReadyRetries)
{
Status = State.Waiting; _retryAtMs = nowMs + RetryReadyMs; _pages.Clear(); return;
}
Record = new StorageRecord
{
Id = VaultId(account),
Name = VaultName,
Label = Label,
Cell = 0,
SeenUtc = DateTime.UtcNow,
Items = new List<ItemRecord>(_pages),
};
_pages.Clear();
_changed = true;
Status = State.Idle;
}
catch (JsonException)
{
Status = State.Idle;
_pages.Clear();
}
}
private static ItemRecord Item(JsonElement e)
{
var it = new ItemRecord
{
Id = UInt(e, "o"),
Wcid = UInt(e, "w"),
Name = Str(e, "n"),
Icon = UInt(e, "i"),
Underlay = UInt(e, "u"),
Overlay = UInt(e, "v"),
Stack = Math.Max(1, Int(e, "s", 1)),
MaxStack = Int(e, "m", 0),
ItemType = UInt(e, "y"),
Place = ItemPlace.Storage,
};
it.Category = ItemCategory.FromItemType(it.ItemType);
return it;
}
/// <summary>
/// A stand-in container id for the account's vault. Storage is merged by (server, id) with the
/// newest copy winning, so the same id on every character of the account shows ONE vault. It is
/// in the top of the id space, where no object the client has seen lives.
/// </summary>
public static uint VaultId(string account)
{
uint h = 2166136261u;
foreach (char c in (account ?? "").Trim().ToLowerInvariant()) { h ^= c; h *= 16777619u; }
return 0xFF000000u | (h & 0x00FFFFFFu);
}
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;
}

View file

@ -0,0 +1,237 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using RynthCore.Plugin.RynthInventory.Data;
using RynthCore.Plugin.RynthInventory.Ui;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthInventory.Views;
/// <summary>
/// Banking: the Infinite Leaftide bank of every character on this server (the Mini Remote's Banking
/// tab moved here 2026-10-13). Balances, form choices and the last reply come from RynthILT's
/// "RynthILT.Data" bank JSON; the character list adds the inventory's characters on the same server
/// (BankRoster). Deposits, withdrawals, transfers and balance reads go back to RynthILT as verb lines;
/// a transfer is confirmed here first (RynthILT doesn't ask again).
/// </summary>
internal sealed partial class InventoryView
{
private const int MaxTransactionsShown = 20;
private const float ColPyreals = 150f, ColLum = 270f, ColKeys = 380f, ColCoins = 450f, ColUpdated = 560f;
private int _depositIndex, _withdrawIndex, _withdrawNote, _transferIndex, _transferNote;
private string _withdrawAmount = string.Empty, _transferAmount = string.Empty, _transferTo = string.Empty;
/// <summary>The transfer waiting for "Yes, send": its verb line and the sentence shown.</summary>
private (string Verb, string Text)? _confirmTransfer;
private string _bankMessage = string.Empty;
/// <summary>
/// The Banking tab button shows when RynthILT answered on an ILT world, or when the tab was asked
/// for (/ginv bank) so it can say what is missing.
/// </summary>
private bool BankingShown => Tab == TabBanking || (_c.Bank.Loaded && _c.Bank.Available);
/// <summary>Opens on the Banking tab ("/ginv bank", RynthAi's and RynthILT's bank links).</summary>
public void ShowBanking()
{
Tab = TabBanking;
_confirmTransfer = null;
}
private void DrawBanking(UiWindow w)
{
IltBankView b = _c.Bank;
if (!b.Loaded)
{
w.TextDisabled("The bank comes from RynthILT (Infinite Leaftide). Load RynthILT to see every character's bank here.");
return;
}
if (!b.Available)
{
w.TextDisabled("This isn't an Infinite Leaftide world, so there is no bank to show.");
return;
}
w.Text($"Bank on {(b.World.Length > 0 ? b.World : "this server")}");
w.SameLine();
w.SmallButton("Refresh", "b.refresh", () => SendBank(IltBankView.RefreshVerb(), "Reading the balance..."));
w.Tooltip("A quiet /bank balance read for the character you're on (other characters update when they log in).");
if (b.Enabled == 0) w.TextColored(UiColors.Red, "This server has no /bank command.");
else if (b.Enabled < 0) w.TextDisabled("Whether this server has /bank isn't known yet.");
if (b.Result.Length > 0) w.TextColored(UiColors.Gold, b.Result);
if (_bankMessage.Length > 0) w.TextColored(UiColors.Yellow, _bankMessage);
List<BankRosterEntry> roster = BankRoster.Build(b, _c.Index);
DrawBankTable(w, roster);
if (b.Enabled != 0)
{
DrawDeposit(w, b);
DrawWithdraw(w, b);
DrawTransfer(w, b, roster);
}
DrawTransactions(w, b);
}
private void DrawBankTable(UiWindow w, List<BankRosterEntry> roster)
{
w.SeparatorText($"Characters ({roster.Count})");
w.TextDisabled("Character");
w.SameLine(ColPyreals); w.TextDisabled("Pyreals");
w.SameLine(ColLum); w.TextDisabled("Luminance");
w.SameLine(ColKeys); w.TextDisabled("Keys L/M");
w.SameLine(ColCoins); w.TextDisabled("Coins E/W/P");
w.SameLine(ColUpdated); w.TextDisabled("Updated");
foreach (BankRosterEntry e in roster)
{
string name = e.Current ? e.Name + " (you)" : e.Name;
if (e.Bank is { } r)
{
w.Text(name);
if (e.Account.Length > 0) w.Tooltip("Account: " + e.Account);
BankCells(w, r);
w.SameLine(ColUpdated);
w.TextDisabled(r.UpdatedUtc == DateTime.MinValue ? "-" : InventoryIndex.Age(r.UpdatedUtc, _c.UtcNow));
}
else
{
w.TextDisabled(name);
if (e.Account.Length > 0) w.Tooltip("Account: " + e.Account);
w.SameLine(ColPyreals);
w.TextDisabled("not read yet: log in with RynthILT loaded");
}
}
if (roster.Count == 0) w.TextDisabled("No characters on this server yet.");
else
{
w.TextColored(UiColors.Gold, "Total");
BankCells(w, BankRoster.Totals(roster));
}
}
/// <summary>The balance columns of one row (Pyreals .. Coins).</summary>
private static void BankCells(UiWindow w, IltBankRow r)
{
w.SameLine(ColPyreals); w.Text(N(r.Pyreals));
w.SameLine(ColLum); w.Text(N(r.Luminance));
w.SameLine(ColKeys); w.Text($"{N(r.LegendaryKeys)}/{N(r.MythicalKeys)}");
w.SameLine(ColCoins); w.Text($"{N(r.EnlightenedCoins)}/{N(r.WeaklyEnlightenedCoins)}/{N(r.PrestigeCoins)}");
}
private void DrawDeposit(UiWindow w, IltBankView b)
{
if (b.Deposits.Count == 0) return;
w.SeparatorText("Deposit");
_depositIndex = Math.Clamp(_depositIndex, 0, b.Deposits.Count - 1);
w.Combo("What", "b.dep.what", _depositIndex, b.Deposits, i => _depositIndex = i);
w.SameLine();
int di = _depositIndex;
string label = b.Deposits[di];
w.SmallButton("Deposit", "b.dep.go", () => SendBank(IltBankView.DepositVerb(di), "Depositing " + label + "..."));
}
private void DrawWithdraw(UiWindow w, IltBankView b)
{
if (b.Withdrawals.Count == 0) return;
w.SeparatorText("Withdraw");
_withdrawIndex = Math.Clamp(_withdrawIndex, 0, b.Withdrawals.Count - 1);
w.Combo("Currency", "b.wd.what", _withdrawIndex, Labels(b.Withdrawals), i => _withdrawIndex = i);
IltBankChoice choice = b.Withdrawals[_withdrawIndex];
w.InputText(choice.Notes ? "Notes" : "Amount", "b.wd.amt", _withdrawAmount, 20, v => _withdrawAmount = v);
int note = NoteCombo(w, b, choice, "b.wd.note", _withdrawNote, i => _withdrawNote = i);
w.SameLine();
int wi = _withdrawIndex;
w.SmallButton("Withdraw", "b.wd.go", () =>
{
long amount = BankRoster.ParseAmount(_withdrawAmount);
if (amount <= 0) { _bankMessage = "Type a whole number to withdraw."; return; }
SendBank(IltBankView.WithdrawVerb(wi, amount, note), $"Withdrawing {N(amount)} {choice.Label}...");
});
}
private void DrawTransfer(UiWindow w, IltBankView b, List<BankRosterEntry> roster)
{
if (b.Transfers.Count == 0) return;
w.SeparatorText("Transfer");
_transferIndex = Math.Clamp(_transferIndex, 0, b.Transfers.Count - 1);
w.Combo("Currency", "b.tx.what", _transferIndex, Labels(b.Transfers), i => { _transferIndex = i; _confirmTransfer = null; });
IltBankChoice choice = b.Transfers[_transferIndex];
w.InputText(choice.Notes ? "Notes" : "Amount", "b.tx.amt", _transferAmount, 20, v => { _transferAmount = v; _confirmTransfer = null; });
int note = NoteCombo(w, b, choice, "b.tx.note", _transferNote, i => { _transferNote = i; _confirmTransfer = null; });
w.InputText("To", "b.tx.to", _transferTo, 40, v => { _transferTo = v; _confirmTransfer = null; });
// The other characters on this server, to fill "To" with one click.
var others = new List<string> { "Pick a character..." };
foreach (BankRosterEntry e in roster) if (!e.Current) others.Add(e.Name);
if (others.Count > 1)
{
w.SameLine();
w.Combo("##pick", "b.tx.pick", 0, others, i => { if (i > 0 && i < others.Count) { _transferTo = others[i]; _confirmTransfer = null; } });
}
if (_confirmTransfer is { } pending)
{
w.TextColored(UiColors.Red, pending.Text);
w.SmallButton("Yes, send", "b.tx.yes", () =>
{
_confirmTransfer = null;
SendBank(pending.Verb, "Transfer sent...");
});
w.SameLine();
w.SmallButton("Cancel", "b.tx.no", () => _confirmTransfer = null);
return;
}
int ti = _transferIndex;
w.SmallButton("Transfer...", "b.tx.go", () =>
{
long amount = BankRoster.ParseAmount(_transferAmount);
string to = (_transferTo ?? string.Empty).Trim();
if (amount <= 0) { _bankMessage = "Type a whole number to transfer."; return; }
if (to.Length == 0) { _bankMessage = "Type (or pick) who gets the transfer."; return; }
string what = choice.Notes && note < b.Notes.Count ? $"{N(amount)} x {b.Notes[note].Label}" : $"{N(amount)} {choice.Label}";
_confirmTransfer = (IltBankView.TransferVerb(ti, amount, note, to), $"Send {what} to {to}? This can't be undone.");
_bankMessage = string.Empty;
});
}
/// <summary>
/// The trade-note combo for a choice that counts notes; returns the note index in use (0 when
/// the choice isn't notes). A pick arrives as an event and lands in <paramref name="set"/>.
/// </summary>
private static int NoteCombo(UiWindow w, IltBankView b, IltBankChoice choice, string id, int index, Action<int> set)
{
if (!choice.Notes || b.Notes.Count == 0) return 0;
var labels = new List<string>(b.Notes.Count);
foreach (IltBankNote n in b.Notes) labels.Add($"{n.Label} ({N(n.Value)} pyreals)");
index = Math.Clamp(index, 0, b.Notes.Count - 1);
w.Combo("Note", id, index, labels, set);
return index;
}
private void DrawTransactions(UiWindow w, IltBankView b)
{
if (b.Transactions.Count == 0) return;
if (!w.CollapsingHeader($"Recent transfers ({b.Transactions.Count})", "b.txlog")) return;
int shown = 0;
foreach (IltBankTx t in b.Transactions)
{
if (shown++ >= MaxTransactionsShown) { w.TextDisabled($"...and {b.Transactions.Count - MaxTransactionsShown} more."); break; }
string dir = t.Type.Length > 0 ? t.Type : "?";
w.Text($"{t.When} {dir} {N(t.Amount)} {t.Currency}{(t.Player.Length > 0 ? " - " + t.Player : "")}");
}
}
/// <summary>Hands a verb to RynthILT; says so when it was refused.</summary>
private void SendBank(string verb, string sending)
{
_bankMessage = _c.BankCommand(verb) ? sending : "RynthILT didn't take that (is it loaded, and are you logged in?).";
}
private static List<string> Labels(IReadOnlyList<IltBankChoice> choices)
{
var list = new List<string>(choices.Count);
foreach (IltBankChoice c in choices) list.Add(c.Label);
return list;
}
private static string N(long n) => n.ToString("N0", CultureInfo.InvariantCulture);
}

View file

@ -8,12 +8,12 @@ namespace RynthCore.Plugin.RynthInventory.Views;
/// <summary>
/// The Global Inventory window: a search page (every character on every server, filters,
/// totals, results, details) and a characters page (snapshot ages, forget). Recorded on the
/// pump thread, replayed by the engine.
/// totals, results, details), a characters page (snapshot ages, forget) and, with RynthILT, a
/// Banking page (Views\BankingTab.cs). Recorded on the pump thread, replayed by the engine.
/// </summary>
internal sealed class InventoryView
internal sealed partial class InventoryView
{
public const int TabSearch = 0, TabCharacters = 1;
public const int TabSearch = 0, TabCharacters = 1, TabBanking = 2;
private const int PageSize = 100;
private const float RowIcon = 18f, DetailIcon = 32f, DetailsHeight = 190f;
@ -58,10 +58,21 @@ internal sealed class InventoryView
w.SameLine();
int chars = _c.Index?.Characters.Count ?? 0;
w.ToggleButton($"Characters ({chars})", "tab.chars", Tab == TabCharacters, () => Tab = TabCharacters, small: true);
if (BankingShown)
{
w.SameLine();
w.ToggleButton("Banking", "tab.bank", Tab == TabBanking, () => Tab = TabBanking, small: true);
}
w.SameLine();
w.TextDisabled(StatusLine());
w.Separator();
// The bank comes from RynthILT, not the inventory files: it draws before they are read.
if (Tab == TabBanking)
{
DrawBanking(w);
return;
}
if (_c.Index == null)
{
w.TextDisabled(_c.Loading ? "Reading the inventory files..." : "No inventory read yet.");
@ -222,6 +233,17 @@ internal sealed class InventoryView
private void Select(string key) => _selectedKey = _selectedKey == key ? null : key;
/// <summary>
/// Clicking one of the logged-in character's own items also selects it in the game (the bag and
/// the selection panel), as clicking it in the pack would. Another character's item can't be.
/// A problem report asked for this (R-20261016-213300-1737).
/// </summary>
private void SelectInGame(InventoryRow? r)
{
if (r == null || !r.Owner.IsCurrentCharacter || r.Item.Id == 0 || !_c.Host.HasSelectItem) return;
_c.Host.SelectItem(r.Item.Id);
}
private void DrawRow(UiWindow w, InventoryRow r)
{
ItemRecord it = r.Item;
@ -234,7 +256,7 @@ internal sealed class InventoryView
string key = RowKey(r);
uint? color = !r.Owner.IsCurrentServer ? UiColors.OtherServer : IsStale(r.SeenUtc) ? UiColors.Stale : null;
if (color != null) w.PushStyleColor(UiFormat.ColText, color.Value);
w.Selectable(label, "r." + key, _selectedKey == key, () => Select(key), 0f, icons ? RowIcon : 0f);
w.Selectable(label, "r." + key, _selectedKey == key, () => { Select(key); SelectInGame(r); }, 0f, icons ? RowIcon : 0f);
if (color != null) w.PopStyleColor();
}
@ -245,7 +267,9 @@ internal sealed class InventoryView
string label = $"{t.Name} x{t.Count.ToString("N0", CultureInfo.InvariantCulture)} - {t.Characters} character{(t.Characters == 1 ? "" : "s")}";
if (t.Servers > 1) label += $", {t.Servers} servers";
string key = GroupKey(t);
w.Selectable(label, "g." + key, _selectedKey == key, () => Select(key), 0f, icons ? RowIcon : 0f);
// A total across characters: select the logged-in character's own stack, if it has one.
w.Selectable(label, "g." + key, _selectedKey == key,
() => { Select(key); SelectInGame(t.Holders.Find(h => h.Owner.IsCurrentCharacter)); }, 0f, icons ? RowIcon : 0f);
}
/// <summary>