merge: bring main (engine 2026.10.5.16) into QOL-items for PR #10

Resolves the 15 conflicting files between QOL-items and main's upstream
snapshot line. Plugin API is now 80: main's v77-v79 numbering stays and
GetMergeStackResultFn (v77 on QOL-items) moves to the end of the table as v80
in the engine and the SDK.

Details in Changelog/2026-10-07-merge-main-into-QOL-items.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
BlankenshipG 2026-10-07 09:01:16 -04:00
commit 50056c1d6f
123 changed files with 13415 additions and 1182 deletions

View file

@ -0,0 +1,39 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Checks a change to the dat code against the code it replaces, on the real dat files, read
only. Covers the StatusAgent's reader and icon decoder (src\RynthCore.StatusAgent\Dat) and
the engine's portal reader and icon decoder (src\RynthCore.Engine\UI\ScriptWindows\
AcIconDecoder.cs), all compiled in. It uses only their API, so the same source builds
against the old code (check out the base commit) and the new; each build writes a manifest
and "diff" compares two:
manifest <AC folder> <out> every file in client_portal.dat and client_cell_1.dat through
both readers (id, flags, offset, size, SHA-256 of the bytes),
FindFile misses, landblock cell ids, EntriesInRange per type.
icons <AC folder> <out> every 0x06 texture through IconDecoder.Decode and
AcIconDecoder.Decode (icon and UI limits): size and a SHA-256
of the RGBA pixels; 3,000 composed underlay/icon/overlay stacks.
diff <a> <b> compares two outputs. Timing lines ("#t") and the order of the
list calls ("#o") are reported, not compared: the lists are
compared as sets.
Run: dotnet run -c Release (after the usual separator) icons "C:\Turbine\Asheron's Call" old.txt
The RynthSuite twin, Tools\RynthCore.DatReaderCheck, covers RynthAi's reader and geometry.
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>DatReaderCheck</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.StatusAgent\Dat\*.cs" Link="StatusAgent\%(Filename)%(Extension)" />
<Compile Include="..\..\src\RynthCore.Engine\UI\ScriptWindows\AcIconDecoder.cs" Link="Engine\AcIconDecoder.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,253 @@
// DatReaderCheck - proves a change to RynthCore's dat code on the real dat files (read only).
// Written for RynthCore (MIT). The modes are described in DatReaderCheck.csproj.
//
// Only the API of the code under test is used (StatusAgent: DatDatabase, IconDecoder; engine:
// AcDatFile, AcIconDecoder), so the same source builds against the old code and the new, and
// two builds' outputs can be compared line by line.
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using RynthCore.Engine.UI.ScriptWindows;
using RynthCore.StatusAgent;
using RynthCore2.TerrainData;
namespace DatReaderCheck;
internal static class Program
{
private static int Main(string[] args)
{
if (args.Length >= 3 && args[0] == "manifest") return Manifest(args[1], args[2]);
if (args.Length >= 3 && args[0] == "icons") return Icons(args[1], args[2]);
if (args.Length >= 3 && args[0] == "diff") return Diff(args[1], args[2]);
Console.WriteLine("usage: manifest <AC folder> <out> | icons <AC folder> <out> | diff <a> <b>");
return 2;
}
private static StreamWriter Out(string path) => new(path, false, new UTF8Encoding(false)) { NewLine = "\n" };
// ------------------------------------------------------------------ manifest
private static int Manifest(string acDir, string outPath)
{
using var w = Out(outPath);
int rc = DumpDat(w, Path.Combine(acDir, "client_portal.dat"));
rc |= DumpDat(w, Path.Combine(acDir, "client_cell_1.dat"));
var p = Process.GetCurrentProcess();
p.Refresh();
w.WriteLine($"#t process peak working set {p.PeakWorkingSet64 / 1048576.0:F1} MB");
return rc;
}
private static int DumpDat(StreamWriter w, string path)
{
Console.WriteLine("== " + Path.GetFileName(path));
w.WriteLine("== " + Path.GetFileName(path));
var sw = Stopwatch.StartNew();
using var db = new DatDatabase();
bool ok = db.Open(path);
w.WriteLine($"open {ok}");
w.WriteLine($"#t open {sw.Elapsed.TotalMilliseconds:F0} ms");
if (!ok) { Console.WriteLine("open failed: " + string.Join(" | ", db.DiagLog)); return 1; }
w.WriteLine($"header FileType={db.FileType:X8} BlockSize={db.BlockSize} FileSize={db.FileSize} DataSet={db.DataSet:X8} BTreeRoot={db.BTreeRoot:X8} IsLoaded={db.IsLoaded} records={db.RecordCount}");
using var engine = AcDatFile.Open(path, out string why);
w.WriteLine($"engine-open {(engine != null ? "ok" : why)}");
var all = db.EntriesInRange(0, uint.MaxValue);
w.WriteLine($"entries-in-range-all {all.Count} {Hashes(all)}");
var ids = all.Select(e => e.id).OrderBy(i => i).ToList();
var idSet = new HashSet<uint>(ids);
sw.Restart();
int nulls = 0, mismatch = 0, engineDiff = 0, engineNull = 0;
long bytes = 0;
foreach (uint id in ids)
{
var f = db.FindFile(id);
if (f == null || f.ObjectId != id) mismatch++;
byte[]? data = db.GetFileData(id);
string digest;
if (data == null) { nulls++; digest = "NULL"; }
else { bytes += data.Length; digest = data.Length + " " + Convert.ToHexString(SHA256.HashData(data)); }
w.WriteLine($"f {id:X8} {f?.BitFlags:X8} {f?.FileOffset:X8} {f?.FileSize} = {digest}");
if (engine != null)
{
byte[]? e = engine.Read(id, int.MaxValue);
if (e == null) engineNull++;
else if (data == null || !e.AsSpan().SequenceEqual(data)) engineDiff++;
}
}
w.WriteLine($"files {ids.Count} read-null {nulls} find-mismatch {mismatch} bytes {bytes} engine-null {engineNull} engine-differs {engineDiff}");
w.WriteLine($"#t all files {sw.Elapsed.TotalMilliseconds:F0} ms");
Console.WriteLine($" {ids.Count} files, {nulls} null, {mismatch} find mismatches; engine reader: {engineNull} null, {engineDiff} differ");
// The engine reader's size cap and a few caps around real sizes.
if (engine != null)
{
int capped = 0;
foreach (var e in all.Take(2000)) if (engine.Read(e.id, (int)e.size - 1) == null) capped++;
int fits = 0;
foreach (var e in all.Take(2000)) if (engine.Read(e.id, (int)e.size) != null) fits++;
w.WriteLine($"engine-cap below-size-null {capped} at-size-ok {fits}");
}
sw.Restart();
int probes = 0, misses = 0, wrong = 0, engineWrong = 0;
void Probe(uint id)
{
probes++;
var f = db.FindFile(id);
bool expect = idSet.Contains(id);
if (f == null) { misses++; if (expect) wrong++; }
else if (!expect || f.ObjectId != id) wrong++;
if (engine != null && probes % 8 == 0 && (engine.Read(id, int.MaxValue) != null) != expect) engineWrong++;
if (db.GetFileData(id) == null == expect) wrong++;
}
foreach (uint id in ids)
{
if (id != uint.MaxValue) Probe(id + 1);
if (id != 0) Probe(id - 1);
}
var rng = new Random(20261005);
for (int i = 0; i < 1_000_000; i++) Probe((uint)rng.NextInt64(0, 1L << 32));
for (uint t = 0; t <= 0x40; t++) for (uint lo = 0; lo < 0x400; lo++) Probe((t << 24) | lo);
Probe(0); Probe(uint.MaxValue);
w.WriteLine($"probes {probes} misses {misses} wrong {wrong} engine-wrong {engineWrong}");
w.WriteLine($"#t probes {sw.Elapsed.TotalMilliseconds:F0} ms");
for (uint t = 0; t <= 0xFF; t++)
{
var r = db.EntriesInRange(t << 24, (t << 24) | 0xFFFFFF);
if (r.Count > 0) w.WriteLine($"range {t:X2} {r.Count} {Hashes(r)}");
}
int withCells = 0, cellIds = 0;
for (uint lb = 0; lb <= 0xFFFF; lb++)
{
var c = db.GetLandblockCellIds(lb);
if (c.Count == 0) continue;
withCells++; cellIds += c.Count;
w.WriteLine($"lb {lb:X4} {c.Count} {Hashes(c.Select(i => (i, 0u)).ToList())}");
}
w.WriteLine($"landblocks with-cells {withCells} cell-ids {cellIds}");
db.Close();
w.WriteLine($"closed IsLoaded={db.IsLoaded} find-after-close={(db.FindFile(ids[0]) == null ? "null" : "hit")}");
return 0;
}
// Which entries a list holds, whatever their order, then (on a "#o" line, which diff reports
// but doesn't count) the order itself: the old reader returned ties and cell ids in its
// dictionary's order; the new one sorts them (size then id, cell ids ascending).
private static string Hashes(List<(uint id, uint size)> list) =>
Hash(list.OrderBy(e => e.id).ThenBy(e => e.size).ToList()) + "\n#o order " + Hash(list);
private static string Hash(List<(uint id, uint size)> list)
{
var b = new byte[list.Count * 8];
for (int i = 0; i < list.Count; i++)
{
BitConverter.TryWriteBytes(b.AsSpan(i * 8), list[i].id);
BitConverter.TryWriteBytes(b.AsSpan(i * 8 + 4), list[i].size);
}
return Convert.ToHexString(SHA256.HashData(b), 0, 12);
}
// ------------------------------------------------------------------ icons
private static int Icons(string acDir, string outPath)
{
using var w = Out(outPath);
string path = Path.Combine(acDir, "client_portal.dat");
using var db = new DatDatabase();
if (!db.Open(path)) { Console.WriteLine("open failed"); return 1; }
using var engine = AcDatFile.Open(path, out string why);
if (engine == null) { Console.WriteLine("engine open failed: " + why); return 1; }
var decoder = new IconDecoder(db);
var ids = db.EntriesInRange(0x06000000, 0x06FFFFFF).Select(e => e.id).OrderBy(i => i).ToList();
w.WriteLine($"textures {ids.Count}");
var byFormat = new SortedDictionary<string, int[]>(); // format -> [count, status ok, engine ok, engine-ui ok]
double agentMs = 0, engineMs = 0;
var sw = new Stopwatch();
var decodable = new List<uint>();
foreach (uint id in ids)
{
byte[]? raw = db.GetFileData(id);
string fmt = "?";
int fw = 0, fh = 0;
if (raw != null && raw.Length >= 24)
{
fw = BitConverter.ToInt32(raw, 8); fh = BitConverter.ToInt32(raw, 12);
fmt = BitConverter.ToUInt32(raw, 16).ToString("X8");
}
sw.Restart();
var a = decoder.Decode(id);
agentMs += sw.Elapsed.TotalMilliseconds;
sw.Restart();
var e1 = AcIconDecoder.Decode(engine, id);
var e2 = AcIconDecoder.Decode(engine, id, AcIconDecoder.MaxUiSide);
engineMs += sw.Elapsed.TotalMilliseconds;
w.WriteLine($"t {id:X8} {fmt} {fw}x{fh} agent={D(a?.Width, a?.Height, a?.Pixels)} icon={D(e1?.Width, e1?.Height, e1?.Pixels)} ui={D(e2?.Width, e2?.Height, e2?.Pixels)}");
if (!byFormat.TryGetValue(fmt, out var c)) byFormat[fmt] = c = new int[4];
c[0]++;
if (a != null) c[1]++;
if (e1 != null) { c[2]++; if (fw == 32 && fh == 32) decodable.Add(id); }
if (e2 != null) c[3]++;
}
foreach (var kv in byFormat)
w.WriteLine($"format {kv.Key}: {kv.Value[0]} textures, agent decodes {kv.Value[1]}, engine icon {kv.Value[2]}, engine ui {kv.Value[3]}");
w.WriteLine($"#t agent decode {agentMs:F0} ms, engine decode (icon + ui) {engineMs:F0} ms");
Console.WriteLine($"{ids.Count} textures");
foreach (var kv in byFormat) Console.WriteLine($" {kv.Key}: {kv.Value[0]} agent {kv.Value[1]} icon {kv.Value[2]} ui {kv.Value[3]}");
// Composed item pictures: underlay + icon + overlay (0 = none).
var rng = new Random(424242);
for (int i = 0; i < 3000 && decodable.Count > 0; i++)
{
uint icon = decodable[rng.Next(decodable.Count)];
uint under = rng.Next(3) == 0 ? 0 : decodable[rng.Next(decodable.Count)];
uint over = rng.Next(3) == 0 ? 0 : decodable[rng.Next(decodable.Count)];
var c = AcIconDecoder.Compose(engine, icon, under, over);
w.WriteLine($"c {icon:X8} {under:X8} {over:X8} {D(c?.Width, c?.Height, c?.Pixels)}");
}
// Ids that aren't textures, or aren't there.
foreach (uint id in new uint[] { 0, 0x05000001, 0x06FFFFFF, 0x07000001, 0x0E00000E })
w.WriteLine($"x {id:X8} agent={D(decoder.Decode(id)?.Width, 0, decoder.Decode(id)?.Pixels)} icon={D(AcIconDecoder.Decode(engine, id)?.Width, 0, AcIconDecoder.Decode(engine, id)?.Pixels)}");
return 0;
}
private static string D(int? w, int? h, byte[]? px) =>
px == null ? "null" : $"{w}x{h}:{Convert.ToHexString(SHA256.HashData(px), 0, 12)}";
// ------------------------------------------------------------------ diff
private static int Diff(string a, string b)
{
var oa = File.ReadLines(a).Where(l => l.StartsWith("#o")).ToList();
var ob = File.ReadLines(b).Where(l => l.StartsWith("#o")).ToList();
int orderDiffs = oa.Count == ob.Count ? oa.Where((l, i) => l != ob[i]).Count() : -1;
Console.WriteLine($"order lines: {oa.Count} vs {ob.Count}, {(orderDiffs < 0 ? "counts differ" : orderDiffs + " differ")} (reported, not counted)");
using var la = File.ReadLines(a).Where(l => !l.StartsWith('#')).GetEnumerator();
using var lb = File.ReadLines(b).Where(l => !l.StartsWith('#')).GetEnumerator();
long n = 0, diffs = 0;
while (true)
{
bool ha = la.MoveNext(), hb = lb.MoveNext();
if (!ha && !hb) break;
n++;
string sa = ha ? la.Current : "<end>", sb = hb ? lb.Current : "<end>";
if (sa == sb) continue;
if (diffs < 40) Console.WriteLine($"line {n}:\n a: {sa}\n b: {sb}");
diffs++;
}
Console.WriteLine($"{n} lines compared, {diffs} differ");
foreach (var (name, file) in new[] { ("a", a), ("b", b) })
{
Console.WriteLine($"timings {name}:");
foreach (var l in File.ReadLines(file).Where(l => l.StartsWith("#t"))) Console.WriteLine(" " + l);
}
return diffs == 0 ? 0 : 1;
}
}

View file

@ -3,7 +3,9 @@
<!--
Offline tests for the launcher's Available plugins list, plugin installs with download
progress and Cancel (RynthUpdater.Available.cs, DownloadProgress.cs), and the front page's
update card (UpdateCardModel.cs). A throwaway key signs a feed served by a local
update card (UpdateCardModel.cs), and plugin manifests' minEngineApi (a plugin build the
installed engine would refuse is neither installed nor updated; "needs RynthCore X"
instead). A throwaway key signs a feed served by a local
HttpListener; plugins install into temp folders. Never opens the launcher window, never
reads or writes outside %TEMP%.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
@ -23,6 +25,7 @@
<Compile Include="..\..\src\RynthCore.App.Avalonia\DownloadProgress.cs" Link="Linked\DownloadProgress.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\UpdateCardModel.cs" Link="Linked\UpdateCardModel.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\UpdateTrust.cs" Link="Linked\UpdateTrust.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Linked\PluginContractVersion.cs" />
</ItemGroup>
</Project>

View file

@ -55,6 +55,11 @@ internal static class Program
await Run(nameof(UpdateCardStates), UpdateCardStates);
await Run(nameof(UpdateCardDownloading), UpdateCardDownloading);
await Run(nameof(UpdateCardWhatsNew), UpdateCardWhatsNew);
await Run(nameof(TooNewPluginIsNotInstalled), TooNewPluginIsNotInstalled);
await Run(nameof(TooNewPluginWithoutCoreApiSaysTheApi), TooNewPluginWithoutCoreApiSaysTheApi);
await Run(nameof(TooNewUpdateIsHeldBack), TooNewUpdateIsHeldBack);
await Run(nameof(TooNewCompanionWaits), TooNewCompanionWaits);
await Run(nameof(MinEngineApiAtOrBelowInstalledIsFine), MinEngineApiAtOrBelowInstalledIsFine);
}
finally
{
@ -148,8 +153,10 @@ internal static class Program
/// </summary>
private static Feed Setup(string tag, bool descriptions = true, IEnumerable<string>? extraPlugins = null,
Dictionary<string, string>? descriptionOverride = null, bool signDescriptions = true, string? badUrlFor = null,
string[]? changes = null)
string[]? changes = null, Dictionary<string, uint>? minEngineApi = null, uint coreEngineApi = 0)
{
_minEngineApi = minEngineApi;
_coreEngineApi = coreEngineApi;
string dir = Path.Combine(_root, tag);
string state = Path.Combine(dir, "state"), app = Path.Combine(dir, "app"), suite = Path.Combine(dir, "Games", "RynthSuite");
Directory.CreateDirectory(state); Directory.CreateDirectory(app);
@ -180,13 +187,16 @@ internal static class Program
["size"] = body.Length, ["sha256"] = Sha(body),
};
if (descriptions) p["description"] = descriptionOverride != null && descriptionOverride.TryGetValue(name, out string? d) ? d : $"Feed line for {name}.";
if (_minEngineApi != null && _minEngineApi.TryGetValue(name, out uint min)) p["minEngineApi"] = min;
plugins.Add(p);
}
var core = new Dictionary<string, object> { ["release"] = 2026100501, ["version"] = "2026.10.5.1", ["url"] = _base + $"{tag}/releases/1/RynthCore-Setup.exe", ["size"] = 1, ["sha256"] = "00" };
if (_coreEngineApi != 0) core["engineApi"] = _coreEngineApi;
var manifest = new Dictionary<string, object?>
{
["schema"] = 1, ["release"] = 2026100501, ["version"] = "2026.10.5.1",
["published"] = Published.ToString("yyyy-MM-ddTHH:mm:ssZ"), ["notes"] = "Release notes for players.",
["core"] = new Dictionary<string, object> { ["release"] = 2026100501, ["version"] = "2026.10.5.1", ["url"] = _base + $"{tag}/releases/1/RynthCore-Setup.exe", ["size"] = 1, ["sha256"] = "00" },
["core"] = core,
["plugins"] = plugins,
};
if (changes != null) manifest["changes"] = changes;
@ -349,6 +359,106 @@ internal static class Program
Check(c2.Plugins.Any(p => p.Entry.Name == "RynthOracle" && p.State == RynthUpdater.PluginState.UpToDate), "the next check sees it up to date");
}
// ── Plugin manifests: minEngineApi ───────────────────────────────────────
// The feed fixture's optional fields (set by Setup, read by WriteFeed).
private static Dictionary<string, uint>? _minEngineApi;
private static uint _coreEngineApi;
private const uint Installed = 76; // the engine API the test launcher "installed"
private static async Task TooNewPluginIsNotInstalled()
{
// RynthOracle's build needs API 77; this feed's core release brings it.
var f = Setup("api-new", minEngineApi: new() { ["RynthOracle"] = Installed + 1, ["RynthChat"] = 66 }, coreEngineApi: Installed + 1);
f.Upd.InstalledEngineApi = Installed;
var paths = new List<string> { f.RynthAiPath };
var c = await f.Upd.CheckAsync(paths);
var oracle = c.Available.Single(a => a.Entry.Name == "RynthOracle");
Check(oracle.Entry.MinEngineApi == Installed + 1, "minEngineApi read from the feed");
Check(!oracle.CanInstall, "a too-new plugin can't be installed");
Check(oracle.Blocker == "needs RynthCore 2026.10.5.1", "it says which RynthCore it needs: " + oracle.Blocker);
Check(c.Available.Single(a => a.Entry.Name == "RynthChat").CanInstall, "a plugin within the engine's API still can");
Check(c.Available.Single(a => a.Entry.Name == "RynthNav").CanInstall, "a plugin without minEngineApi still can");
try
{
await f.Upd.InstallPluginAsync(c, "RynthOracle", paths);
Check(false, "InstallPluginAsync should refuse a too-new plugin");
}
catch (InvalidOperationException ex)
{
Check(ex.Message.Contains("needs RynthCore"), "refused with the reason: " + ex.Message);
}
Check(!File.Exists(oracle.Path), "nothing written");
Check(!Directory.Exists(Path.GetDirectoryName(oracle.Path)!), "no folder created");
}
private static async Task TooNewPluginWithoutCoreApiSaysTheApi()
{
// The feed's core doesn't say its API (or brings an older one): name the API instead.
var f = Setup("api-nocore", minEngineApi: new() { ["RynthOracle"] = Installed + 2 }, coreEngineApi: Installed + 1);
f.Upd.InstalledEngineApi = Installed;
var c = await f.Upd.CheckAsync(new[] { f.RynthAiPath });
var oracle = c.Available.Single(a => a.Entry.Name == "RynthOracle");
Check(oracle.Blocker == $"needs a newer RynthCore (API {Installed + 2})", "names the API: " + oracle.Blocker);
var g = Setup("api-nocore2", minEngineApi: new() { ["RynthOracle"] = Installed + 1 });
g.Upd.InstalledEngineApi = Installed;
var c2 = await g.Upd.CheckAsync(new[] { g.RynthAiPath });
Check(c2.Available.Single(a => a.Entry.Name == "RynthOracle").Blocker == $"needs a newer RynthCore (API {Installed + 1})",
"a core without engineApi: the API too");
}
private static async Task TooNewUpdateIsHeldBack()
{
var f = Setup("api-update", minEngineApi: new() { ["RynthChat"] = Installed + 1, ["RynthNav"] = Installed }, coreEngineApi: Installed + 1);
f.Upd.InstalledEngineApi = Installed;
string chat = Place(f, "RynthChat"), nav = Place(f, "RynthNav");
byte[] oldChat = Encoding.UTF8.GetBytes("dll RynthChat v1"), oldNav = Encoding.UTF8.GetBytes("dll RynthNav v1");
File.WriteAllBytes(chat, oldChat); File.SetLastWriteTimeUtc(chat, Published.AddDays(-3));
File.WriteAllBytes(nav, oldNav); File.SetLastWriteTimeUtc(nav, Published.AddDays(-3));
var c = await f.Upd.CheckAsync(new[] { f.RynthAiPath, chat, nav });
var chatStatus = c.Plugins.Single(p => p.Entry.Name == "RynthChat");
Check(chatStatus.State == RynthUpdater.PluginState.NeedsNewerEngine, "too-new update held back: " + chatStatus.State);
Check(chatStatus.Blocker == "needs RynthCore 2026.10.5.1", "with the reason: " + chatStatus.Blocker);
Check(c.PluginsWaitingForCore.Any(p => p.Entry.Name == "RynthChat"), "listed as waiting for RynthCore");
Check(c.Plugins.Single(p => p.Entry.Name == "RynthNav").State == RynthUpdater.PluginState.NeedsUpdate, "an update at the installed API goes ahead");
Check(c.PluginsToUpdate.Select(p => p.Entry.Name).SequenceEqual(new[] { "RynthNav" }), "only RynthNav is updated");
await f.Upd.UpdatePluginsAsync(c);
Check(File.ReadAllBytes(chat).SequenceEqual(oldChat), "RynthChat kept as it was (the engine would refuse the new build)");
Check(!File.Exists(chat + ".previous"), "no .previous for RynthChat");
Check(File.ReadAllBytes(nav).SequenceEqual(Body("RynthNav")), "RynthNav updated");
// After RynthCore is updated (the new launcher knows the new API), the update goes through.
f.Upd.InstalledEngineApi = Installed + 1;
var after = await f.Upd.CheckAsync(new[] { f.RynthAiPath, chat, nav });
Check(after.Plugins.Single(p => p.Entry.Name == "RynthChat").State == RynthUpdater.PluginState.NeedsUpdate, "updated once RynthCore catches up");
}
private static async Task TooNewCompanionWaits()
{
var f = Setup("api-companion", minEngineApi: new() { ["RynthLua"] = Installed + 1 }, coreEngineApi: Installed + 1);
f.Upd.InstalledEngineApi = Installed;
var c = await f.Upd.CheckAsync(new[] { f.RynthAiPath });
Check(c.Companions.Count == 0, "a too-new companion isn't installed beside RynthAi");
Check(c.Available.Single(a => a.Entry.Name == "RynthLua").Blocker.Length > 0, "and shows what it needs under Available");
f.Upd.InstalledEngineApi = Installed + 1;
var later = await f.Upd.CheckAsync(new[] { f.RynthAiPath });
Check(later.Companions.Count == 1 && later.Companions[0].Entry.Name == "RynthLua", "offered once RynthCore catches up (not marked as offered before)");
}
private static async Task MinEngineApiAtOrBelowInstalledIsFine()
{
var f = Setup("api-ok", minEngineApi: new() { ["RynthOracle"] = Installed, ["RynthInventory"] = 71 });
f.Upd.InstalledEngineApi = Installed;
var paths = new List<string> { f.RynthAiPath };
var c = await f.Upd.CheckAsync(paths);
Check(c.Available.All(a => a.CanInstall), "everything installable: " + string.Join(",", c.Available.Where(a => !a.CanInstall).Select(a => a.Entry.Name)));
var done = await f.Upd.InstallPluginAsync(c, "RynthOracle", paths);
Check(done.Downloaded && File.Exists(done.Path), "installed at the exact minimum");
Check(f.Upd.InstalledEngineApi == Installed && new RynthUpdater().InstalledEngineApi == RynthCore.Engine.Plugins.PluginContractVersion.Current,
"the launcher's default is the engine's own API constant");
}
private static async Task InstallRefusesTamperedFile()
{
var f = Setup("tamper");

View file

@ -20,6 +20,7 @@
<Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.Available.cs" Link="Linked\RynthUpdater.Available.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\DownloadProgress.cs" Link="Linked\DownloadProgress.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\UpdateTrust.cs" Link="Linked\UpdateTrust.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Linked\PluginContractVersion.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,102 @@
// NetProbe - a test plugin for the v78 server-message stream (see the csproj). It asks for
// every message the SDK parses, parses what arrives and logs the first few of each kind,
// plus a count every 30 s, through the host log ("NetProbe:" lines in the RynthCore log).
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.PluginCore;
using RynthCore.PluginSdk.Net;
namespace RynthCore.Plugin.NetProbe;
public sealed class NetProbePlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("NetProbe");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.1.0");
internal static NetProbePlugin? Instance;
private const int FirstN = 5;
private readonly Dictionary<string, (int Ok, int Failed, int Leftover)> _kinds = new();
private long _messages, _lastSummary;
private static readonly uint[] Opcodes =
{
ServerOpcode.HearSpeech, ServerOpcode.HearRangedSpeech, ServerOpcode.HearEmote, ServerOpcode.HearSoulEmote,
};
private static readonly uint[] GameEvents =
{
GameEventType.PopUpString, GameEventType.FriendsUpdate, GameEventType.FellowshipQuit, GameEventType.FellowshipDismiss,
GameEventType.ChannelBroadcast, GameEventType.ConfirmationRequest, GameEventType.AllegianceLoginNotification,
GameEventType.HearDirectSpeech, GameEventType.FellowshipFullUpdate, GameEventType.FellowshipDisband,
GameEventType.FellowshipUpdateFellow, GameEventType.TransientString,
};
public override int Initialize()
{
Instance = this;
if (!Host.HasServerMessages)
{
Log($"NetProbe: engine API v{Host.Version} has no server messages (needs v78).");
return 0;
}
int r = Host.SetServerMessageInterest(Opcodes, GameEvents);
Log($"NetProbe: SetServerMessageInterest -> {r} (1 streaming, 2 stream off, 0 no export, -1 unknown caller).");
return 0;
}
public override void Shutdown() => Instance = null;
internal unsafe void OnServerMessage(uint opcode, byte* data, int length)
{
_messages++;
NetMessageInfo info = NetMessages.Inspect(ServerMessage.FromCallback(opcode, data, length));
string kind = info.Known ? info.Kind : $"unasked {info.Kind}";
var k = _kinds.TryGetValue(kind, out var v) ? v : default;
int seen = k.Ok + k.Failed;
_kinds[kind] = (k.Ok + (info.Parsed ? 1 : 0), k.Failed + (info.Parsed ? 0 : 1), k.Leftover + (info.Parsed && info.Leftover != 0 ? 1 : 0));
if (seen < FirstN || !info.Parsed || info.Leftover != 0)
Log($"NetProbe: {kind} len={length} {(info.Parsed ? "ok" : "FAILED")}{(info.Leftover != 0 ? $" leftover={info.Leftover}" : "")} {info.Summary}");
}
public override void OnTick()
{
long now = Environment.TickCount64;
if (now - _lastSummary < 30000) return;
_lastSummary = now;
if (_messages == 0) return;
var parts = new List<string>();
foreach (var (kind, c) in _kinds)
parts.Add($"{kind} {c.Ok}" + (c.Failed > 0 ? $"/{c.Failed} failed" : "") + (c.Leftover > 0 ? $"/{c.Leftover} leftover" : ""));
Log($"NetProbe: {_messages} messages: {string.Join(", ", parts)}");
}
}
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<NetProbePlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCore.PluginSdk.RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => NetProbePlugin.NamePointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => NetProbePlugin.VersionPointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
/// <summary>v78: data = the message after its opcode, valid only during the call.</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnServerMessage", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnServerMessage(uint opcode, byte* data, int length)
{
try { NetProbePlugin.Instance?.OnServerMessage(opcode, data, length); }
catch { } // never let an exception cross the native boundary
}
}

View file

@ -0,0 +1,35 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
NetProbe: a test plugin for the v78 server-message stream. It asks for every message the
SDK parses (RynthCore.PluginSdk.Net), parses what arrives on RynthPluginOnServerMessage
and writes the first few of each kind, and a count every 30 s, to the RynthCore log
("NetProbe:"). For the in-game check only; not shipped.
dotnet publish -c Release -o <a test folder>, then add the DLL in the launcher's Plugins tab.
-->
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<RootNamespace>RynthCore.Plugin.NetProbe</RootNamespace>
<AssemblyName>RynthCore.Plugin.NetProbe</AssemblyName>
<Platforms>x86</Platforms>
</PropertyGroup>
<ItemGroup>
<IlcArg Include="--runtimeopt:GCSegmentSize=800000" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,39 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline replay tests for the server-message stream (plugin API v78):
- the engine's datagram walk, packet ring, fragment reassembler and interest sets
(src\RynthCore.Engine\Net\*, compiled in; pure code, no engine state);
- the SDK's typed parsers (src\RynthCore.PluginSdk\Net, by project reference);
- fragment edge cases: out of order, duplicate, retransmitted, missing (stale),
oversized, slot exhaustion, session reset, malformed datagrams;
- throughput and allocation numbers for the receive-side copy and the reassembly.
Fixtures are built by hand (WireBuilder.cs, plus one hex datagram written out byte by byte).
Extra arguments are .rnc captures from "/rc netmsg capture" to replay and summarise.
Nothing native: no AC, no engine.
Run: dotnet run -c Release [(double dash) capture.rnc ...] (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>NetMessageTests</RootNamespace>
<ServerGarbageCollection>false</ServerGarbageCollection>
<TieredPGO>true</TieredPGO>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\Net\AcPacketWire.cs" Link="Engine\AcPacketWire.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Net\PacketRing.cs" Link="Engine\PacketRing.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Net\FragmentReassembler.cs" Link="Engine\FragmentReassembler.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Net\ServerMessageInterest.cs" Link="Engine\ServerMessageInterest.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,969 @@
using System.Buffers.Binary;
using System.Diagnostics;
using RynthCore.Engine.Net;
using RynthCore.PluginSdk.Net;
namespace NetMessageTests;
/// <summary>Collects what the reassembler hands over (copied: the pointer is only valid during the call).</summary>
internal sealed unsafe class Collect : IServerMessageSink
{
public readonly List<(uint Seq, byte[] Bytes)> Messages = new();
public void OnServerMessage(uint fragmentSequence, byte* message, int length)
=> Messages.Add((fragmentSequence, new ReadOnlySpan<byte>(message, length).ToArray()));
}
/// <summary>Counts only (the perf runs: no copies).</summary>
internal sealed unsafe class CountOnly : IServerMessageSink
{
public long Count, Bytes;
public uint OpcodeXor;
public void OnServerMessage(uint fragmentSequence, byte* message, int length)
{
Count++;
Bytes += length;
OpcodeXor ^= *(uint*)message;
}
}
internal static unsafe class Program
{
private static int _checks, _failed;
private static string _case = "";
private static long _now = 1_000_000;
private static int Main(string[] args)
{
// Datagram walk
WalkPlain();
WalkOptionalHeaders();
WalkBadDatagrams();
GoldenHexDatagram();
// Reassembly
SingleFragment();
MultiFragmentInOrder();
MultiFragmentOutOfOrder();
DuplicateFragmentsAndRetransmits();
MissingFragmentGoesStale();
Oversized();
InconsistentAndBadFragments();
SlotExhaustion();
SeveralMessagesPerDatagram();
SessionReset();
DoneWindowSlides();
// Ring, interest
RingBasics();
RingWrapAndFull();
RingCounterWrap();
RingThreaded();
Interest();
// Parsers
Strings();
ChatParsers();
FellowshipParsers();
FriendsAndAllegiance();
SystemTextAndConfirmation();
TruncationNeverThrows();
EndToEndGameEvents();
// Captures given on the command line
foreach (string path in args)
Replay(path);
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
Console.WriteLine(_failed == 0 ? "ALL NET MESSAGE TESTS PASSED." : $"{_failed} FAILED.");
Performance();
return _failed == 0 ? 0 : 1;
}
// ── helpers ─────────────────────────────────────────────────────────────
private static void Feed(FragmentReassembler r, byte[] datagram, IServerMessageSink sink)
{
fixed (byte* p = datagram)
r.ProcessDatagram(p, datagram.Length, _now, sink);
}
private static PacketWalk Walk(byte[] d, out int start, out int end)
{
fixed (byte* p = d)
return AcPacketWire.LocateFragments(p, d.Length, out start, out end);
}
private static byte[] Msg(int length, uint opcode = 0xF745, byte seed = 1)
{
var b = new byte[length];
if (length >= 4) BinaryPrimitives.WriteUInt32LittleEndian(b, opcode);
for (int i = 4; i < length; i++) b[i] = (byte)(seed + i * 7);
return b;
}
private static void Case(string name)
{
_case = name;
Console.WriteLine($"- {name}");
}
private static void Eq<T>(T actual, T expected, string what) =>
Check(EqualityComparer<T>.Default.Equals(actual, expected), $"{what}: expected {expected}, got {actual}");
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine($" FAIL [{_case}] {what}");
}
// ── datagram walk ───────────────────────────────────────────────────────
private static void WalkPlain()
{
Case("walk: one fragment, no optional headers");
byte[] d = Datagram.Frags(new Frag(1, 1, 0, Msg(40)));
Eq(Walk(d, out int s, out int e), PacketWalk.Ok, "status");
Eq(s, 20, "fragments start after the 20-byte header");
Eq(e, d.Length, "fragments end at the datagram end");
Case("walk: no BlobFragments flag (ack only)");
byte[] ack = Datagram.Build(Datagram.AckSequence);
Eq(Walk(ack, out _, out _), PacketWalk.NoFragments, "status");
}
private static void WalkOptionalHeaders()
{
Case("walk: ack + time sync + echo response + flow before the fragments");
uint flags = Datagram.AckSequence | Datagram.TimeSync | Datagram.EchoResponse | Datagram.Flow;
byte[] d = Datagram.Build(flags, 0, null, new Frag(1, 1, 0, Msg(30)));
Eq(Walk(d, out int s, out _), PacketWalk.Ok, "status");
Eq(s, 20 + 4 + 8 + 8 + 6, "fragment start skips 26 bytes of optional headers");
Case("walk: reject-retransmit list (u32 count + ids)");
byte[] r = Datagram.Build(Datagram.RejectRetransmit | Datagram.AckSequence, 3, null, new Frag(1, 1, 0, Msg(12)));
Eq(Walk(r, out s, out _), PacketWalk.Ok, "status");
Eq(s, 20 + 4 + 12 + 4, "start after the list and the ack");
Case("walk: a header this reader can't size (referral) is skipped, not guessed");
byte[] referral = Datagram.Build(Datagram.Referral, 0, null, new Frag(1, 1, 0, Msg(12)));
Eq(Walk(referral, out _, out _), PacketWalk.UnknownOptional, "status");
}
private static void WalkBadDatagrams()
{
Case("walk: malformed datagrams are rejected whole");
Eq(Walk(new byte[10], out _, out _), PacketWalk.Malformed, "shorter than a header");
byte[] good = Datagram.Frags(new Frag(1, 1, 0, Msg(40)));
Eq(Walk(good[..^1], out _, out _), PacketWalk.Malformed, "header size runs past the bytes received");
byte[] longer = Datagram.Build(0, 0, 40 + 16 + 4, new Frag(1, 1, 0, Msg(40)));
Eq(Walk(longer, out _, out _), PacketWalk.Malformed, "header size larger than the datagram");
byte[] fragTooBig = Datagram.Frags(new Frag(1, 1, 0, Msg(40), SizeOverride: 16 + 41));
Eq(Walk(fragTooBig, out _, out _), PacketWalk.Malformed, "fragment size past the end");
byte[] fragTooSmall = Datagram.Frags(new Frag(1, 1, 0, Msg(40), SizeOverride: 15));
Eq(Walk(fragTooSmall, out _, out _), PacketWalk.Malformed, "fragment size under its header");
byte[] gap = Datagram.Build(0, 0, 40 + 16 + 3, new Frag(1, 1, 0, Msg(40)));
Array.Resize(ref gap, gap.Length + 3);
Eq(Walk(gap, out _, out _), PacketWalk.Malformed, "fragments don't tile the declared size");
byte[] none = Datagram.Build(Datagram.BlobFragments);
Eq(Walk(none, out _, out _), PacketWalk.Malformed, "fragment flag with no fragment");
var r = new FragmentReassembler();
var c = new Collect();
Feed(r, good[..^1], c);
Feed(r, longer, c);
Eq(c.Messages.Count, 0, "nothing delivered from malformed datagrams");
Eq(r.PacketsMalformed, 2L, "malformed counter");
}
/// <summary>
/// One datagram written out byte by byte: packet seq 5, flags 0x4004 (ack + fragments),
/// size 44, ack 4; fragment seq 0x10, id 0x80000001, count 1, size 40, index 0, queue 10;
/// message HearEmote 0x01E0 from 0x50000002 "Bob": "waves."
/// </summary>
private static void GoldenHexDatagram()
{
Case("golden datagram: HearEmote, hand-written bytes");
byte[] d = Convert.FromHexString(
"05000000" + "04400000" + "00000000" + "0100" + "0000" + "2C00" + "0000" + // header
"04000000" + // ack
"10000000" + "01000080" + "0100" + "2800" + "0000" + "0A00" + // fragment header
"E0010000" + "02000050" + "0300" + "426F62" + "000000" + "0600" + "77617665732E"); // message
Eq(d.Length, 64, "64 bytes");
var r = new FragmentReassembler();
var c = new Collect();
Feed(r, d, c);
Eq(c.Messages.Count, 1, "one message");
if (c.Messages.Count != 1) return;
Eq(c.Messages[0].Seq, 0x10u, "fragment sequence");
Check(ServerMessage.TryFromWire(c.Messages[0].Bytes, out ServerMessage m), "wraps");
Eq(m.Opcode, ServerOpcode.HearEmote, "opcode");
NetMessageInfo info = NetMessages.Inspect(m);
Check(info.Parsed && info.Leftover == 0, $"parsed with nothing left ({info.Kind} parsed={info.Parsed} leftover={info.Leftover})");
var e = info.Value as HearEmote;
Eq(e?.SenderId, 0x50000002u, "sender");
Eq(e?.SenderName, "Bob", "name");
Eq(e?.Text, "waves.", "text");
}
// ── reassembly ──────────────────────────────────────────────────────────
private static void SingleFragment()
{
Case("one-fragment message is delivered as is");
var r = new FragmentReassembler();
var c = new Collect();
byte[] m = Msg(100, 0xF7B0);
Feed(r, Datagram.Frags(new Frag(5, 1, 0, m)), c);
Eq(c.Messages.Count, 1, "delivered");
Check(c.Messages.Count == 1 && c.Messages[0].Bytes.AsSpan().SequenceEqual(m), "bytes intact");
Eq(r.MultiFragmentMessages, 0L, "not counted as multi-fragment");
}
private static void MultiFragmentInOrder()
{
Case("multi-fragment message, fragments in order, one per datagram");
var r = new FragmentReassembler();
var c = new Collect();
byte[] m = Msg(448 * 3 + 17, 0xF7B0);
foreach (Frag f in Datagram.Split(9, m))
{
Eq(c.Messages.Count, 0, $"nothing before the last fragment (index {f.Index})");
Feed(r, Datagram.Frags(f), c);
}
Eq(c.Messages.Count, 1, "delivered once complete");
Check(c.Messages.Count == 1 && c.Messages[0].Bytes.AsSpan().SequenceEqual(m), "bytes reassembled exactly");
Eq(r.PartialCount, 0, "slot freed");
}
private static void MultiFragmentOutOfOrder()
{
Case("multi-fragment message, fragments reversed and shuffled");
var rng = new Random(1234);
for (int trial = 0; trial < 50; trial++)
{
var r = new FragmentReassembler();
var c = new Collect();
byte[] m = Msg(rng.Next(449, 448 * 20), 0xF7B0, (byte)trial);
Frag[] frags = Datagram.Split((uint)(100 + trial), m);
if (trial == 0) Array.Reverse(frags); else rng.Shuffle(frags);
foreach (Frag f in frags) Feed(r, Datagram.Frags(f), c);
if (c.Messages.Count != 1 || !c.Messages[0].Bytes.AsSpan().SequenceEqual(m))
{
Check(false, $"trial {trial}: {frags.Length} fragments not reassembled exactly ({c.Messages.Count} delivered)");
return;
}
}
Check(true, "50 random orders reassembled exactly");
Case("uneven fragment sizes still pack together");
var r2 = new FragmentReassembler();
var c2 = new Collect();
byte[] whole = Msg(300, 0xF7B0);
Feed(r2, Datagram.Frags(new Frag(77, 3, 2, whole[250..])), c2);
Feed(r2, Datagram.Frags(new Frag(77, 3, 0, whole[..100])), c2);
Feed(r2, Datagram.Frags(new Frag(77, 3, 1, whole[100..250])), c2);
Check(c2.Messages.Count == 1 && c2.Messages[0].Bytes.AsSpan().SequenceEqual(whole), "100 + 150 + 50 bytes");
}
private static void DuplicateFragmentsAndRetransmits()
{
Case("duplicate fragments and retransmitted datagrams");
var r = new FragmentReassembler();
var c = new Collect();
byte[] m = Msg(1000, 0xF7B0);
Frag[] f = Datagram.Split(20, m);
Feed(r, Datagram.Frags(f[0]), c);
Feed(r, Datagram.Frags(f[0]), c); // duplicate while partial
Feed(r, Datagram.Build(Datagram.Retransmission, 0, null, f[1]), c);
Feed(r, Datagram.Frags(f[2]), c);
Eq(c.Messages.Count, 1, "delivered once");
Eq(r.DuplicateFragments, 1L, "one duplicate while partial");
foreach (Frag x in f) Feed(r, Datagram.Build(Datagram.Retransmission, 0, null, x), c); // whole message again
Eq(c.Messages.Count, 1, "a retransmitted complete message isn't delivered twice");
Feed(r, Datagram.Frags(new Frag(21, 1, 0, Msg(20))), c);
Feed(r, Datagram.Frags(new Frag(21, 1, 0, Msg(20))), c);
Eq(c.Messages.Count, 2, "one-fragment message delivered once");
Eq(r.DuplicateMessages, 1L, "duplicate one-fragment message counted");
Check(c.Messages.Count == 2 && c.Messages[0].Bytes.AsSpan().SequenceEqual(m), "bytes intact");
}
private static void MissingFragmentGoesStale()
{
Case("a message missing a fragment is dropped after StaleMs, then a late fragment can't revive it");
var r = new FragmentReassembler();
var c = new Collect();
Frag[] f = Datagram.Split(30, Msg(1500, 0xF7B0));
Feed(r, Datagram.Frags(f[0]), c);
Feed(r, Datagram.Frags(f[1]), c);
Eq(r.PartialCount, 1, "one partial");
_now += FragmentReassembler.StaleMs + 1;
Feed(r, Datagram.Frags(new Frag(31, 1, 0, Msg(10))), c); // any traffic runs the eviction
Eq(r.PartialCount, 0, "evicted");
Eq(r.EvictedStale, 1L, "stale counter");
Feed(r, Datagram.Frags(f[2]), c);
Feed(r, Datagram.Frags(f[3]), c);
Eq(c.Messages.Count(m => m.Seq == 30), 0, "never delivered incomplete");
Eq(r.PartialCount, 0, "late fragments don't start a new partial");
Eq(r.DuplicateFragments, 2L, "they count as fragments of a finished sequence");
}
private static void Oversized()
{
Case("oversized messages are dropped and remembered");
var r = new FragmentReassembler();
var c = new Collect();
Feed(r, Datagram.Frags(new Frag(40, FragmentReassembler.MaxFragments + 1, 0, Msg(448))), c);
Eq(r.Oversized, 1L, "too many fragments");
Eq(r.PartialCount, 0, "no slot taken");
Feed(r, Datagram.Frags(new Frag(40, FragmentReassembler.MaxFragments + 1, 1, Msg(448))), c);
Eq(r.DuplicateFragments, 1L, "its other fragments are ignored as done");
byte[] big = Msg(FragmentReassembler.FragmentStride + 1, 0xF7B0);
Feed(r, Datagram.Frags(new Frag(41, 2, 0, Msg(448))), c);
Feed(r, Datagram.Frags(new Frag(41, 2, 1, big)), c);
Eq(r.Oversized, 2L, "fragment body over the stride");
Eq(r.PartialCount, 0, "its partial dropped");
Eq(c.Messages.Count, 0, "nothing delivered");
Case("largest allowed message still reassembles");
byte[] max = Msg(448 * FragmentReassembler.MaxFragments, 0xF7B0);
foreach (Frag f in Datagram.Split(42, max)) Feed(r, Datagram.Frags(f), c);
Check(c.Messages.Count == 1 && c.Messages[0].Bytes.AsSpan().SequenceEqual(max), $"{max.Length} bytes in {FragmentReassembler.MaxFragments} fragments");
}
private static void InconsistentAndBadFragments()
{
Case("bad fragments: index >= count, count 0, count changes mid-message, body under 4 bytes");
var r = new FragmentReassembler();
var c = new Collect();
Feed(r, Datagram.Frags(new Frag(50, 2, 2, Msg(10))), c);
Feed(r, Datagram.Frags(new Frag(51, 0, 0, Msg(10))), c);
Feed(r, Datagram.Frags(new Frag(52, 3, 0, Msg(448))), c);
Feed(r, Datagram.Frags(new Frag(52, 4, 1, Msg(448))), c);
Feed(r, Datagram.Frags(new Frag(53, 1, 0, new byte[] { 1, 2, 3 })), c);
Eq(r.BadFragments, 4L, "four bad fragments counted");
Eq(c.Messages.Count, 0, "nothing delivered");
}
private static void SlotExhaustion()
{
Case("more partial messages than slots: the least recently touched is dropped");
var r = new FragmentReassembler();
var c = new Collect();
for (uint s = 0; s <= FragmentReassembler.MaxPartials; s++)
{
_now += 1;
Feed(r, Datagram.Frags(new Frag(60 + s, 2, 0, Msg(448, 0xF7B0, (byte)s))), c);
}
Eq(r.PartialCount, FragmentReassembler.MaxPartials, "slots full");
Eq(r.EvictedFull, 1L, "one evicted");
Feed(r, Datagram.Frags(new Frag(60, 2, 1, Msg(100))), c);
Eq(c.Messages.Count(m => m.Seq == 60), 0, "the evicted (oldest) message doesn't complete");
Eq(r.EvictedFull, 1L, "and its straggler evicts nothing else");
Feed(r, Datagram.Frags(new Frag(61, 2, 1, Msg(100))), c);
Eq(c.Messages.Count(m => m.Seq == 61), 1, "the next one does");
}
private static void SeveralMessagesPerDatagram()
{
Case("several fragments of different messages in one datagram, interleaved");
var r = new FragmentReassembler();
var c = new Collect();
byte[] a = Msg(700, 0xF7B0, 3), b = Msg(30, 0x02BB, 4), d = Msg(900, 0xF745, 5);
Frag[] fa = Datagram.Split(70, a, 400), fd = Datagram.Split(72, d, 400);
Feed(r, Datagram.Frags(fa[0], new Frag(71, 1, 0, b), fd[2]), c);
Feed(r, Datagram.Frags(fd[0], fa[1]), c);
Feed(r, Datagram.Frags(fd[1]), c);
Eq(c.Messages.Count, 3, "three messages");
Eq(string.Join(",", c.Messages.Select(m => m.Seq)), "71,70,72", "completion order");
Check(c.Messages.Count == 3 && c.Messages[1].Bytes.AsSpan().SequenceEqual(a) && c.Messages[2].Bytes.AsSpan().SequenceEqual(d), "bytes intact");
}
private static void SessionReset()
{
Case("a ConnectRequest (new session) restarts the sequence window");
var r = new FragmentReassembler();
var c = new Collect();
for (uint s = 1; s <= 50; s++) Feed(r, Datagram.Frags(new Frag(s, 1, 0, Msg(8))), c);
Feed(r, Datagram.Frags(new Frag(2, 1, 0, Msg(8))), c);
Eq(c.Messages.Count, 50, "an old sequence is a duplicate within a session");
Feed(r, Datagram.Build(Datagram.ConnectRequest), c);
Eq(r.SessionResets, 1L, "reset seen");
Feed(r, Datagram.Frags(new Frag(2, 1, 0, Msg(8))), c);
Eq(c.Messages.Count, 51, "the same sequence is new after the reset");
}
private static void DoneWindowSlides()
{
Case("the done window slides: a long-finished sequence is still rejected, recent ones tracked by bit");
var r = new FragmentReassembler();
var c = new Collect();
Feed(r, Datagram.Frags(new Frag(10, 1, 0, Msg(8))), c);
Feed(r, Datagram.Frags(new Frag(10 + FragmentReassembler.DoneWindow + 5, 1, 0, Msg(8))), c);
Feed(r, Datagram.Frags(new Frag(10, 1, 0, Msg(8))), c);
Eq(c.Messages.Count, 2, "far-behind sequence rejected");
Feed(r, Datagram.Frags(new Frag(20 + FragmentReassembler.DoneWindow, 1, 0, Msg(8))), c);
Eq(c.Messages.Count, 3, "a sequence inside the window that never completed is accepted");
// A partial that started before many later one-fragment messages still completes.
Frag[] f = Datagram.Split(30000, Msg(900, 0xF7B0));
Feed(r, Datagram.Frags(f[0]), c);
for (uint s = 30001; s < 30001 + 1000; s++) Feed(r, Datagram.Frags(new Frag(s, 1, 0, Msg(8))), c);
Feed(r, Datagram.Frags(f[1]), c);
Feed(r, Datagram.Frags(f[2]), c);
Eq(c.Messages.Count(m => m.Seq == 30000), 1, "slow multi-fragment message completes behind 1000 newer ones");
}
// ── ring ────────────────────────────────────────────────────────────────
private static bool Read(PacketRing ring, out byte[] data, out uint stamp)
{
data = Array.Empty<byte>();
if (!ring.TryPeek(out byte* p, out int len, out stamp, out int rel)) return false;
data = new ReadOnlySpan<byte>(p, len).ToArray();
ring.Release(rel);
return true;
}
private static bool Write(PacketRing ring, byte[] d, uint stamp = 0)
{
fixed (byte* p = d) return ring.TryWrite(p, d.Length, stamp);
}
private static void RingBasics()
{
Case("ring: FIFO, stamps, too-long rejected");
var ring = new PacketRing(4096);
Check(Write(ring, Msg(100, 1), 11) && Write(ring, Msg(3, 2), 22), "two writes");
Check(Read(ring, out byte[] a, out uint sa) && a.Length == 100 && sa == 11, "first back");
Check(Read(ring, out byte[] b, out uint sb) && b.Length == 3 && sb == 22, "second back");
Check(!Read(ring, out _, out _), "empty");
Check(!Write(ring, new byte[PacketRing.MaxDatagram + 1]), "too long refused");
Eq(ring.DroppedTooLong, 1L, "counted");
}
private static void RingWrapAndFull()
{
Case("ring: wraps at the end, drops (never waits) when full");
var ring = new PacketRing(4096);
int wrote = 0, read = 0;
var rng = new Random(7);
var pending = new Queue<byte[]>();
for (int i = 0; i < 5000; i++)
{
byte[] d = Msg(rng.Next(20, 500), (uint)i, (byte)i);
if (Write(ring, d)) { pending.Enqueue(d); wrote++; }
if (rng.Next(3) == 0)
while (Read(ring, out byte[] got, out _))
{
read++;
if (!got.AsSpan().SequenceEqual(pending.Dequeue())) { Check(false, $"datagram {read} corrupted across a wrap"); return; }
}
}
while (Read(ring, out byte[] got, out _)) { read++; if (!got.AsSpan().SequenceEqual(pending.Dequeue())) { Check(false, "tail corrupted"); return; } }
Eq(read, wrote, "everything written was read back intact, in order");
Check(ring.DroppedFull > 0, $"some writes were refused while full ({ring.DroppedFull})");
Eq(ring.Written, (long)wrote, "written counter");
}
private static void RingCounterWrap()
{
Case("ring: the byte counters wrap past int.MaxValue");
var ring = new PacketRing(4096, int.MaxValue - 3000);
int ok = 0;
for (int i = 0; i < 200; i++)
{
byte[] d = Msg(100 + i, (uint)i, (byte)i);
if (!Write(ring, d) || !Read(ring, out byte[] got, out _) || !got.AsSpan().SequenceEqual(d)) break;
ok++;
}
Eq(ok, 200, "200 round trips across the wrap");
Eq(ring.Used, 0, "empty after");
}
private static void RingThreaded()
{
Case("ring: one producer thread, one consumer thread, 200k datagrams");
var ring = new PacketRing(64 * 1024);
const int N = 200_000;
int produced = 0;
var t = new Thread(() =>
{
byte[] d = new byte[400];
for (int i = 0; i < N; i++)
{
int len = 20 + (i % 380);
BinaryPrimitives.WriteInt32LittleEndian(d, i);
d[len - 1] = (byte)i;
while (!Write(ring, d[..len], (uint)i)) Thread.SpinWait(20); // the test retries; the hook drops
produced++;
}
});
t.Start();
int expect = 0;
bool ok = true;
var sw = Stopwatch.StartNew();
while (expect < N && sw.Elapsed.TotalSeconds < 30)
{
if (!Read(ring, out byte[] got, out uint stamp)) { Thread.SpinWait(10); continue; }
int len = 20 + (expect % 380);
if (got.Length != len || BinaryPrimitives.ReadInt32LittleEndian(got) != expect || got[len - 1] != (byte)expect || stamp != (uint)expect)
{
ok = false;
break;
}
expect++;
}
t.Join();
Check(ok && expect == N, $"all {N} datagrams in order and intact (got {expect})");
}
private static void Interest()
{
Case("interest sets");
var s = new ServerMessageInterest();
Check(s.IsEmpty, "starts empty");
uint[] ops = { 0x02BB, 0x01E0 };
uint[] evs = { 0x02BE, 0x0021 };
fixed (uint* o = ops) fixed (uint* e = evs) Check(s.Set(o, 2, e, 2), "set");
Check(s.Wants(0x02BB, 0) && s.Wants(0x01E0, 0), "listed opcodes");
Check(!s.Wants(0xF745, 0), "unlisted opcode");
Check(s.Wants(0xF7B0, 0x02BE) && s.Wants(0xF7B0, 0x0021), "listed game events");
Check(!s.Wants(0xF7B0, 0x02C2), "unlisted game event");
Check(!s.Wants(0x1_0000, 0), "out-of-range opcode never wanted");
uint[] allEv = { 0xF7B0 };
fixed (uint* o = allEv) Check(s.Set(o, 1, null, 0), "0xF7B0 alone");
Check(s.Wants(0xF7B0, 0x1234) && !s.Wants(0x02BB, 0), "every game event, nothing else");
uint[] all = { 0xFFFFFFFF };
fixed (uint* o = all) Check(s.Set(o, 1, null, 0), "all");
Check(s.Wants(0xF745, 0) && s.Wants(0xF7B0, 5), "everything");
uint[] bad = { 0x02BB, 0x10000 };
fixed (uint* o = bad) Check(!s.Set(o, 2, null, 0), "an out-of-range opcode refuses the whole set");
Check(s.IsEmpty, "and leaves it empty");
Check(!s.Set(null, 3, null, 0), "null with a count refused");
Check(s.Set(null, 0, null, 0) && s.IsEmpty, "empty set = off");
}
// ── parsers ─────────────────────────────────────────────────────────────
private static void Strings()
{
Case("String16L: lengths 0-6 pad to 4, Latin-1, long form refused");
for (int len = 0; len <= 6; len++)
{
string text = new string('x', len);
byte[] b = new Body().Str(text).U32(0xDEADBEEF).ToArray();
Eq(b.Length % 4, 0, $"length {len} padded");
var r = new NetReader(b);
Check(r.String16L(out string got) && got == text && r.U32(out uint tail) && tail == 0xDEADBEEF, $"length {len} round trip");
}
var lat = new NetReader(new Body().Str("Café Æthel").ToArray());
Check(lat.String16L(out string l) && l == "Café Æthel", "Latin-1 characters");
var lng = new NetReader(new byte[] { 0xFF, 0xFF, 4, 0, 0, 0, 1, 2, 3, 4 });
Check(!lng.String16L(out _), "0xFFFF long form refused");
var shortStr = new NetReader(new byte[] { 10, 0, 1, 2 });
Check(!shortStr.String16L(out _), "length past the end refused");
}
private static NetMessageInfo InspectTop(uint opcode, Body body)
{
ServerMessage.TryFromWire(body.Message(opcode), out ServerMessage m);
return NetMessages.Inspect(m);
}
private static NetMessageInfo InspectEvent(uint type, Body body)
{
ServerMessage.TryFromWire(body.GameEvent(type), out ServerMessage m);
return NetMessages.Inspect(m);
}
private static void Clean(NetMessageInfo i, string kind)
{
Eq(i.Kind, kind, "kind");
Check(i.Known && i.Parsed, $"{kind} parsed");
Eq(i.Leftover, 0, $"{kind} leftover");
}
private static void ChatParsers()
{
Case("HearSpeech 0x02BB");
var i = InspectTop(0x02BB, new Body().Str("Hello there").Str("Aria").U32(0x50000010).U32(2));
Clean(i, "HearSpeech");
var s = (HearSpeech)i.Value!;
Check(s.Text == "Hello there" && s.SenderName == "Aria" && s.SenderId == 0x50000010 && s.ChatType == 2, "fields");
Case("HearRangedSpeech 0x02BC");
i = InspectTop(0x02BC, new Body().Str("Help!").Str("Town Crier").U32(0x7A000001).F32(37.5f).U32(12));
Clean(i, "HearRangedSpeech");
var rs = (HearRangedSpeech)i.Value!;
Check(rs.Text == "Help!" && rs.SenderName == "Town Crier" && rs.SenderId == 0x7A000001 && rs.Range == 37.5f && rs.ChatType == 12, "fields");
Case("HearEmote 0x01E0 / HearSoulEmote 0x01E2");
i = InspectTop(0x01E0, new Body().U32(0x50000011).Str("Bren").Str("bows deeply."));
Clean(i, "HearEmote");
var e = (HearEmote)i.Value!;
Check(e.SenderId == 0x50000011 && e.SenderName == "Bren" && e.Text == "bows deeply." && !e.Soul, "emote fields");
i = InspectTop(0x01E2, new Body().U32(0x50000012).Str("Cy").Str("*laughs*"));
Clean(i, "HearSoulEmote");
Check(((HearEmote)i.Value!).Soul, "soul flag");
Case("HearDirectSpeech (tell) game event 0x02BD");
i = InspectEvent(0x02BD, new Body().Str("psst").Str("Dax").U32(0x50000013).U32(0x50000001).U32(3).U32(0));
Clean(i, "HearDirectSpeech");
var t = (HearDirectSpeech)i.Value!;
Check(t.Text == "psst" && t.SenderName == "Dax" && t.SenderId == 0x50000013 && t.TargetId == 0x50000001 && t.ChatType == 3 && t.Flags == 0, "fields");
Case("ChannelBroadcast game event 0x0147");
i = InspectEvent(0x0147, new Body().U32(0x800).Str("").Str("pulling now"));
Clean(i, "ChannelBroadcast");
var cb = (ChannelBroadcast)i.Value!;
Check(cb.Channel == 0x800 && cb.SenderName == "" && cb.Text == "pulling now", "own line: empty sender");
}
private static Body FellowBody(Body b, uint id, string name, uint level, bool shareLoot)
=> b.U32(id).U32(1000).U32(10).U32(level).U32(300).U32(250).U32(200).U32(280).U32(240).U32(190).Bool(shareLoot).Str(name);
private static void FellowshipParsers()
{
Case("FellowshipFullUpdate 0x02BE: members, flags, departed, locks");
var b = new Body().TableHeader(2);
FellowBody(b, 0x50000001, "Leader Lee", 126, true);
FellowBody(b, 0x50000002, "Bo", 80, false);
b.Str("Hunters").U32(0x50000001).Bool(true).Bool(false).Bool(true).Bool(false);
b.TableHeader(1).U32(0x50000003).I32(1234);
b.TableHeader(1).Str("Lugian Citadel").U32(1).U32(2).U32(3).U32(4).U32(5);
var i = InspectEvent(0x02BE, b);
Clean(i, "FellowshipFullUpdate");
var f = (FellowshipFullUpdate)i.Value!;
Check(f.Name == "Hunters" && f.LeaderId == 0x50000001 && f.ShareXp && !f.EvenXpSplit && f.Open && !f.Locked, "header fields");
Eq(f.Fellows.Count, 2, "members");
var lee = f.Fellows[0];
Check(lee.Id == 0x50000001 && lee.Name == "Leader Lee" && lee.Level == 126 && lee.XpCached == 1000 && lee.LumCached == 10 &&
lee.MaxHealth == 300 && lee.MaxStamina == 250 && lee.MaxMana == 200 && lee.Health == 280 && lee.Stamina == 240 && lee.Mana == 190 && lee.ShareLoot, "fellow fields");
Check(!f.Fellows[1].ShareLoot && f.Fellows[1].Name == "Bo", "second fellow");
Check(f.TailParsed && f.RecentlyDeparted.TryGetValue(0x50000003, out int when) && when == 1234 && f.LockNames.SequenceEqual(new[] { "Lugian Citadel" }), "tail");
Case("FellowshipFullUpdate whose tail doesn't fit: members still returned, leftover reported");
var b2 = new Body().TableHeader(1);
FellowBody(b2, 0x50000001, "Solo", 50, true);
b2.Str("One").U32(0x50000001).Bool(false).Bool(true).Bool(false).Bool(true);
b2.Bytes(0x01, 0x02); // a tail this layout doesn't know
i = InspectEvent(0x02BE, b2);
Check(i.Parsed && i.Leftover == 2, $"parsed with 2 leftover (parsed={i.Parsed} leftover={i.Leftover})");
var f2 = (FellowshipFullUpdate)i.Value!;
Check(!f2.TailParsed && f2.Fellows.Count == 1 && f2.Locked, "main fields kept, tail flagged unread");
Case("FellowshipUpdateFellow 0x02C0");
// fellow id, xp, lum, level, max h/s/m, current h/s/m, share loot, name, update type
var u = new Body().U32(0x50000002).U32(1000).U32(10).U32(81).U32(300).U32(250).U32(200).U32(100).U32(50).U32(25).Bool(false).Str("Bo").U32(3);
i = InspectEvent(0x02C0, u);
Clean(i, "FellowshipUpdateFellow");
var uf = (FellowshipUpdateFellow)i.Value!;
Check(uf.Fellow.Id == 0x50000002 && uf.Fellow.Level == 81 && uf.Fellow.Health == 100 && uf.UpdateType == 3, "fields");
Case("FellowshipQuit 0x00A3, FellowshipDismiss 0x00A4, FellowshipDisband 0x02BF");
i = InspectEvent(0x00A3, new Body().U32(0x50000004));
Clean(i, "FellowshipQuit");
Check(((FellowshipMemberLeft)i.Value!).FellowId == 0x50000004 && !((FellowshipMemberLeft)i.Value!).Dismissed, "quit");
i = InspectEvent(0x00A4, new Body().U32(0x50000005));
Clean(i, "FellowshipDismiss");
Check(((FellowshipMemberLeft)i.Value!).Dismissed, "dismiss");
i = InspectEvent(0x02BF, new Body());
Clean(i, "FellowshipDisband");
}
private static void FriendsAndAllegiance()
{
Case("FriendsUpdate 0x0021: full list");
var b = new Body().U32(2)
.U32(0x50000020).Bool(true).Bool(false).Str("Ana").U32List(0x50000001).U32List()
.U32(0x50000021).Bool(false).Bool(true).Str("Bertram").U32List().U32List(0x50000001, 0x50000002)
.U32(FriendsUpdate.Full);
var i = InspectEvent(0x0021, b);
Clean(i, "FriendsUpdate");
var fu = (FriendsUpdate)i.Value!;
Eq(fu.Friends.Count, 2, "two friends");
Check(fu.Friends[0].Id == 0x50000020 && fu.Friends[0].Online && !fu.Friends[0].AppearOffline && fu.Friends[0].Name == "Ana" &&
fu.Friends[0].OutFriends.SequenceEqual(new uint[] { 0x50000001 }) && fu.Friends[0].InFriends.Length == 0, "first");
Check(!fu.Friends[1].Online && fu.Friends[1].AppearOffline && fu.Friends[1].InFriends.Length == 2, "second");
Eq(fu.UpdateType, FriendsUpdate.Full, "update type");
Case("FriendsUpdate: login change for one friend");
i = InspectEvent(0x0021, new Body().U32(1).U32(0x50000020).Bool(false).Bool(false).Str("Ana").U32List().U32List().U32(FriendsUpdate.LoginChange));
Clean(i, "FriendsUpdate");
Check(((FriendsUpdate)i.Value!).UpdateType == FriendsUpdate.LoginChange, "type 4");
Case("FriendsUpdate: absurd count refused without allocating it");
i = InspectEvent(0x0021, new Body().U32(0x7FFFFFFF).U32(0));
Check(i.Known && !i.Parsed, "refused");
Case("AllegianceLoginNotification 0x027A");
i = InspectEvent(0x027A, new Body().U32(0x50000030).Bool(true));
Clean(i, "AllegianceLoginNotification");
var a = (AllegianceLoginNotification)i.Value!;
Check(a.CharacterId == 0x50000030 && a.LoggedIn, "fields");
}
private static void SystemTextAndConfirmation()
{
Case("PopUpString 0x0004, TransientString 0x02EB");
var i = InspectEvent(0x0004, new Body().Str("You have been booted."));
Clean(i, "PopUpString");
Check(((SystemText)i.Value!).Text == "You have been booted." && !((SystemText)i.Value!).Transient, "popup");
i = InspectEvent(0x02EB, new Body().Str("You're too busy!"));
Clean(i, "TransientString");
Check(((SystemText)i.Value!).Transient, "transient");
Case("ConfirmationRequest 0x0274");
i = InspectEvent(0x0274, new Body().U32(4).U32(0x1234).Str("Ana has invited you to join a fellowship."));
Clean(i, "ConfirmationRequest");
var c = (ConfirmationRequest)i.Value!;
Check(c.ConfirmationType == 4 && c.ContextId == 0x1234 && c.Text.StartsWith("Ana has invited"), "fields");
Case("unknown messages are reported as unknown");
i = InspectTop(0xF745, new Body().U32(1));
Check(!i.Known, "top-level");
i = InspectEvent(0x02C2, new Body().U32(1));
Check(!i.Known, "game event");
}
private static void TruncationNeverThrows()
{
Case("every parser, every truncation of its fixture: false, no exception");
var fixtures = new List<(string, byte[])>
{
("speech", new Body().Str("Hello there").Str("Aria").U32(1).U32(2).Message(0x02BB)),
("ranged", new Body().Str("Help!").Str("Crier").U32(1).F32(1).U32(2).Message(0x02BC)),
("emote", new Body().U32(1).Str("Bren").Str("bows.").Message(0x01E0)),
("tell", new Body().Str("psst").Str("Dax").U32(1).U32(2).U32(3).U32(0).GameEvent(0x02BD)),
("channel", new Body().U32(1).Str("A").Str("B").GameEvent(0x0147)),
("friends", new Body().U32(1).U32(1).Bool(true).Bool(false).Str("Ana").U32List(5).U32List(6).U32(0).GameEvent(0x0021)),
("allegiance", new Body().U32(1).Bool(true).GameEvent(0x027A)),
("confirm", new Body().U32(4).U32(5).Str("ok?").GameEvent(0x0274)),
("popup", new Body().Str("hi").GameEvent(0x0004)),
("update fellow", new Body().U32(1).U32(1).U32(1).U32(1).U32(1).U32(1).U32(1).U32(1).U32(1).U32(1).Bool(true).Str("Bo").U32(1).GameEvent(0x02C0)),
("quit", new Body().U32(1).GameEvent(0x00A3)),
};
var full = new Body().TableHeader(1);
FellowBody(full, 1, "Lee", 5, true);
full.Str("F").U32(1).Bool(true).Bool(true).Bool(true).Bool(true).TableHeader(0).TableHeader(0);
fixtures.Add(("fellowship", full.GameEvent(0x02BE)));
int cuts = 0;
foreach ((string name, byte[] wire) in fixtures)
{
ServerMessage.TryFromWire(wire, out ServerMessage whole);
NetMessageInfo w = NetMessages.Inspect(whole);
if (!w.Parsed || w.Leftover != 0) { Check(false, $"{name}: full fixture should parse cleanly"); continue; }
int headerLen = whole.IsGameEvent ? 16 : 4;
for (int len = headerLen; len < wire.Length; len++)
{
try
{
ServerMessage.TryFromWire(wire.AsSpan(0, len), out ServerMessage m);
NetMessageInfo i = NetMessages.Inspect(m);
// A cut on a string's padding or the fellowship tail can still parse; it must then report what it used.
if (i.Parsed && name != "fellowship" && i.Leftover != 0) Check(false, $"{name} cut at {len}: parsed but leftover {i.Leftover}");
cuts++;
}
catch (Exception ex)
{
Check(false, $"{name} cut at {len} threw {ex.GetType().Name}");
}
}
}
Check(cuts > 300, $"{cuts} truncations tried");
}
private static void EndToEndGameEvents()
{
Case("end to end: a 3-datagram fellowship update, out of order, through ring and reassembler to the parser");
var b = new Body().TableHeader(9);
for (uint n = 0; n < 9; n++) FellowBody(b, 0x50000100 + n, $"Member number {n} with a long name", 100 + n, n % 2 == 0);
b.Str("A fellowship with a long name").U32(0x50000100).Bool(true).Bool(true).Bool(false).Bool(false).TableHeader(0).TableHeader(0);
byte[] wire = b.GameEvent(0x02BE, 0x50000100, 42);
Frag[] frags = Datagram.Split(500, wire);
Check(frags.Length >= 2, $"{wire.Length} bytes needs {frags.Length} fragments");
var ring = new PacketRing(4096);
var order = frags.Reverse().ToArray();
foreach (Frag f in order) Write(ring, Datagram.Build(Datagram.AckSequence | Datagram.TimeSync, 0, null, f));
var r = new FragmentReassembler();
var c = new Collect();
while (ring.TryPeek(out byte* p, out int len, out _, out int rel))
{
r.ProcessDatagram(p, len, _now, c);
ring.Release(rel);
}
Eq(c.Messages.Count, 1, "one message");
if (c.Messages.Count != 1) return;
ServerMessage.TryFromWire(c.Messages[0].Bytes, out ServerMessage m);
Check(m.IsGameEvent && m.EventObjectId == 0x50000100 && m.EventSequence == 42 && m.EventType == 0x02BE, "game event header");
Check(FellowshipFullUpdate.TryParse(m.EventBody, out var fs, out int used) && used == m.EventBody.Length, "parsed whole");
Check(fs != null && fs.Fellows.Count == 9 && fs.Fellows[8].Name == "Member number 8 with a long name" && fs.TailParsed, "all members");
}
// ── replay of captures ──────────────────────────────────────────────────
private static void Replay(string path)
{
Case($"replay {Path.GetFileName(path)}");
byte[] file;
try { file = File.ReadAllBytes(path); }
catch (Exception ex) { Check(false, $"read failed: {ex.Message}"); return; }
if (file.Length < 4 || file[0] != 'R' || file[1] != 'N' || file[2] != 'C' || file[3] != '1')
{
Check(false, "not an RNC1 capture");
return;
}
var r = new FragmentReassembler();
var c = new Collect();
int pos = 4, datagrams = 0;
while (pos + 6 <= file.Length)
{
uint stamp = BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(pos));
int len = BinaryPrimitives.ReadUInt16LittleEndian(file.AsSpan(pos + 4));
pos += 6;
if (pos + len > file.Length) { Check(false, $"truncated record at {pos}"); break; }
fixed (byte* p = &file[pos])
r.ProcessDatagram(p, len, stamp, c);
pos += len;
datagrams++;
}
var byKind = new SortedDictionary<string, (int Ok, int Failed, int Leftover)>();
var opcodes = new Dictionary<string, int>();
foreach (var (_, bytes) in c.Messages)
{
ServerMessage.TryFromWire(bytes, out ServerMessage m);
string key = m.IsGameEvent ? $"F7B0/{m.EventType:X4}" : $"{m.Opcode:X4}";
opcodes[key] = opcodes.GetValueOrDefault(key) + 1;
NetMessageInfo i = NetMessages.Inspect(m);
if (!i.Known) continue;
var k = byKind.GetValueOrDefault(i.Kind);
byKind[i.Kind] = (k.Ok + (i.Parsed ? 1 : 0), k.Failed + (i.Parsed ? 0 : 1), k.Leftover + (i.Parsed && i.Leftover != 0 ? 1 : 0));
if (!i.Parsed || i.Leftover != 0)
Console.WriteLine($" {i.Kind} parsed={i.Parsed} leftover={i.Leftover} bytes={Convert.ToHexString(bytes.AsSpan(0, Math.Min(bytes.Length, 64)))}");
}
Console.WriteLine($" {datagrams} datagrams -> {r.Messages} messages ({r.MultiFragmentMessages} multi-fragment); malformed {r.PacketsMalformed}, " +
$"unknown header {r.PacketsUnknownOptional}, dup {r.DuplicateFragments}, bad {r.BadFragments}, stale {r.EvictedStale}, {r.PartialCount} left partial");
Console.WriteLine($" top opcodes: {string.Join(" ", opcodes.OrderByDescending(o => o.Value).Take(15).Select(o => $"{o.Key}x{o.Value}"))}");
foreach (var (kind, v) in byKind)
Console.WriteLine($" {kind}: {v.Ok} ok, {v.Failed} failed, {v.Leftover} with leftover");
Check(r.PacketsMalformed == 0, "no malformed datagrams in a real capture");
Check(byKind.Values.All(v => v.Failed == 0), "every known message parsed");
}
// ── performance ─────────────────────────────────────────────────────────
private static void Performance()
{
Console.WriteLine();
Console.WriteLine("Performance (synthetic server traffic; Release build, this machine):");
// A mix shaped like play: mostly one-fragment messages of 20-300 bytes, packed 1-3 per
// datagram, plus a 2-8 fragment message every ~25 datagrams; acks and time sync on many.
var rng = new Random(99);
var datagrams = new List<byte[]>();
uint seq = 1;
int msgCount = 0;
while (datagrams.Count < 50_000)
{
if (rng.Next(25) == 0)
{
byte[] big = Msg(rng.Next(900, 448 * 8), 0xF7B0, (byte)seq);
foreach (Frag f in Datagram.Split(seq++, big)) datagrams.Add(Datagram.Build(Datagram.AckSequence, 0, null, f));
msgCount++;
continue;
}
int n = rng.Next(1, 4);
var frags = new Frag[n];
int room = 448;
for (int k = 0; k < n; k++)
{
int len = Math.Min(rng.Next(20, 300), room - 16 * (n - k));
if (len < 8) len = 8;
room -= len + 16;
frags[k] = new Frag(seq++, 1, 0, Msg(len, 0xF749, (byte)k));
msgCount++;
}
uint flags = rng.Next(4) == 0 ? Datagram.AckSequence | Datagram.TimeSync : Datagram.AckSequence;
datagrams.Add(Datagram.Build(flags, 0, null, frags));
}
long totalBytes = datagrams.Sum(d => (long)d.Length);
var pinned = datagrams.Select(d => GC.AllocateArray<byte>(d.Length, pinned: true)).ToArray();
for (int i = 0; i < pinned.Length; i++) datagrams[i].CopyTo(pinned[i], 0);
// 1) Receive side: what the detour does while capturing (flags check + ring write),
// timed in batches of 1024 datagrams (the ring is emptied between batches, untimed).
var ring = new PacketRing(512 * 1024);
const int Rounds = 20, Batch = 1024;
long copies = 0, hookTicks = 0;
for (int round = 0; round < Rounds + 2; round++)
{
bool timed = round >= 2;
for (int i0 = 0; i0 < pinned.Length; i0 += Batch)
{
int i1 = Math.Min(pinned.Length, i0 + Batch);
long t0 = Stopwatch.GetTimestamp();
for (int i = i0; i < i1; i++)
{
byte[] d = pinned[i];
fixed (byte* p = d)
{
uint flags = AcPacketWire.ReadU32(p + 4);
if ((flags & (PacketFlags.BlobFragments | PacketFlags.ConnectRequest)) != 0)
ring.TryWrite(p, d.Length, 0);
}
}
long t1 = Stopwatch.GetTimestamp();
if (timed) { hookTicks += t1 - t0; copies += i1 - i0; }
ring.Clear();
}
}
double tickNs = 1e9 / Stopwatch.Frequency;
double hookNs = hookTicks * tickNs / copies;
Console.WriteLine($" receive hook copy: {hookNs:0} ns per datagram (avg {totalBytes / datagrams.Count} bytes), {copies:N0} datagrams; ring drops {ring.DroppedFull}");
// 2) Pump side: ring read + reassembly into a counting sink, timed per drained batch.
var r = new FragmentReassembler();
var sink = new CountOnly();
long allocBefore = 0, processed = 0, pumpTicks = 0, msgsTimed = 0, multiTimed = 0;
for (int round = 0; round < Rounds + 2; round++)
{
bool timed = round >= 2;
r.Reset();
if (round == 2) allocBefore = GC.GetAllocatedBytesForCurrentThread();
long m0 = r.Messages, mm0 = r.MultiFragmentMessages;
for (int i0 = 0; i0 < pinned.Length; i0 += Batch)
{
int i1 = Math.Min(pinned.Length, i0 + Batch);
for (int i = i0; i < i1; i++)
fixed (byte* p = pinned[i])
ring.TryWrite(p, pinned[i].Length, 0);
long t0 = Stopwatch.GetTimestamp();
while (ring.TryPeek(out byte* rp, out int len, out _, out int rel))
{
r.ProcessDatagram(rp, len, 1000, sink);
ring.Release(rel);
}
long t1 = Stopwatch.GetTimestamp();
if (timed) { pumpTicks += t1 - t0; processed += i1 - i0; }
}
if (timed) { msgsTimed += r.Messages - m0; multiTimed += r.MultiFragmentMessages - mm0; }
}
long allocAfter = GC.GetAllocatedBytesForCurrentThread();
double pumpNs = pumpTicks * tickNs / processed;
Console.WriteLine($" pump (ring read + reassembly): {pumpNs:0} ns per datagram, {pumpTicks * tickNs / msgsTimed:0} ns per message; " +
$"{msgsTimed / Rounds:N0} messages per round of {pinned.Length:N0} datagrams ({multiTimed / Rounds:N0} multi-fragment)");
Console.WriteLine($" steady-state allocation: {(allocAfter - allocBefore) / (double)processed:0.00} bytes per datagram over {processed:N0} datagrams");
// 3) What a busy minute costs: ~100 datagrams/s is heavy play, 400/s a portal into a town.
Console.WriteLine($" at 400 datagrams/s: hook {hookNs * 400 / 1000:0.0} us/s on the receive thread, pump {pumpNs * 400 / 1000:0.0} us/s");
Console.WriteLine(" stream off: the detour adds one volatile bool read (ServerMessageStream.OnDatagram returns at once).");
}
}

View file

@ -0,0 +1,91 @@
using System.Buffers.Binary;
using System.Text;
namespace NetMessageTests;
/// <summary>Little-endian writer for message bodies, in the AC wire types the parsers read.</summary>
internal sealed class Body
{
private readonly List<byte> _b = new();
public byte[] ToArray() => _b.ToArray();
public int Length => _b.Count;
public Body U16(ushort v) { Span<byte> t = stackalloc byte[2]; BinaryPrimitives.WriteUInt16LittleEndian(t, v); _b.AddRange(t.ToArray()); return this; }
public Body U32(uint v) { Span<byte> t = stackalloc byte[4]; BinaryPrimitives.WriteUInt32LittleEndian(t, v); _b.AddRange(t.ToArray()); return this; }
public Body I32(int v) => U32(unchecked((uint)v));
public Body F32(float v) => U32(BitConverter.SingleToUInt32Bits(v));
public Body Bool(bool v) => U32(v ? 1u : 0u);
public Body Bytes(params byte[] v) { _b.AddRange(v); return this; }
/// <summary>u16 length, Latin-1 bytes, zero padding so 2 + length is a multiple of 4.</summary>
public Body Str(string s)
{
byte[] raw = Encoding.Latin1.GetBytes(s);
U16((ushort)raw.Length);
_b.AddRange(raw);
for (int pad = (4 - ((2 + raw.Length) & 3)) & 3; pad > 0; pad--) _b.Add(0);
return this;
}
public Body U32List(params uint[] v) { U32((uint)v.Length); foreach (uint x in v) U32(x); return this; }
public Body TableHeader(int count, int buckets = 32) => U16((ushort)count).U16((ushort)buckets);
/// <summary>A whole top-level message: u32 opcode then this body.</summary>
public byte[] Message(uint opcode) => new Body().U32(opcode).Bytes(ToArray()).ToArray();
/// <summary>A whole game event message: 0xF7B0, object id, sequence, event type, this body.</summary>
public byte[] GameEvent(uint eventType, uint objectId = 0x50000001, uint sequence = 7)
=> new Body().U32(0xF7B0).U32(objectId).U32(sequence).U32(eventType).Bytes(ToArray()).ToArray();
}
/// <summary>One fragment for <see cref="Datagram"/>.</summary>
internal readonly record struct Frag(uint Sequence, ushort Count, ushort Index, byte[] Data, uint Id = 0x80000001, ushort Queue = 10, int? SizeOverride = null);
/// <summary>Builds server-to-client datagrams: 20-byte header, optional headers, fragments.</summary>
internal static class Datagram
{
public const uint BlobFragments = 0x4, AckSequence = 0x4000, TimeSync = 0x01000000, EchoResponse = 0x04000000,
Flow = 0x08000000, RejectRetransmit = 0x2000, Referral = 0x800, ConnectRequest = 0x40000, Retransmission = 0x1;
private static uint _packetSeq = 100;
/// <summary>
/// Optional headers are written for the flags given (fixed sizes, zero contents; a reject
/// list gets <paramref name="rejectCount"/> entries). BlobFragments is added when frags are given.
/// </summary>
public static byte[] Build(uint flags, int rejectCount = 0, int? sizeOverride = null, params Frag[] frags)
{
if (frags.Length > 0) flags |= BlobFragments;
var after = new Body();
if ((flags & RejectRetransmit) != 0) { after.U32((uint)rejectCount); for (int i = 0; i < rejectCount; i++) after.U32((uint)(i + 1)); }
if ((flags & AckSequence) != 0) after.U32(99);
if ((flags & ConnectRequest) != 0) after.Bytes(new byte[32]);
if ((flags & TimeSync) != 0) after.Bytes(new byte[8]);
if ((flags & EchoResponse) != 0) after.Bytes(new byte[8]);
if ((flags & Flow) != 0) after.Bytes(new byte[6]);
foreach (Frag f in frags)
{
after.U32(f.Sequence).U32(f.Id).U16(f.Count).U16((ushort)(f.SizeOverride ?? (16 + f.Data.Length))).U16(f.Index).U16(f.Queue);
after.Bytes(f.Data);
}
byte[] tail = after.ToArray();
var d = new Body().U32(_packetSeq++).U32(flags).U32(0).U16(1).U16(0).U16((ushort)(sizeOverride ?? tail.Length)).U16(0);
return d.Bytes(tail).ToArray();
}
public static byte[] Frags(params Frag[] frags) => Build(0, 0, null, frags);
/// <summary>Splits a message into fragments of at most <paramref name="chunk"/> bytes (448 like the server).</summary>
public static Frag[] Split(uint sequence, byte[] message, int chunk = 448)
{
int count = Math.Max(1, (message.Length + chunk - 1) / chunk);
var list = new Frag[count];
for (int i = 0; i < count; i++)
{
int off = i * chunk;
list[i] = new Frag(sequence, (ushort)count, (ushort)i, message.AsSpan(off, Math.Min(chunk, message.Length - off)).ToArray());
}
return list;
}
}

View file

@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the nameplate sizing settings and the Vision overlay opacity sliders
(2026-10-05): src\RynthCore.Engine\ImGui\MonsterHud\MonsterHudSettings.cs and
src\RynthCore.Engine\UI\Data\ArgbOpacity.cs, compiled in. Defaults equal today's look,
the nameplate_settings.txt lines round-trip (old files without the new keys still load),
out-of-range values clamp, and an untouched opacity never changes a colour.
No file I/O: the settings file is written to and read from memory, and the background
writer is a stub that never runs its work (so %LocalAppData%\RynthCore is never touched).
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>PlateSizingTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\MonsterHudSettings.cs" Link="Engine\MonsterHudSettings.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ArgbOpacity.cs" Link="Engine\ArgbOpacity.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,231 @@
using System.Globalization;
using RynthCore.Engine.ImGuiBackend.Hud;
using RynthCore.Engine.UI.Data;
namespace RynthCore.Engine.UI
{
/// <summary>Stub: counts saves, never runs them (no file I/O in the tests).</summary>
internal static class UiBackgroundWriter
{
public static int Enqueued;
public static void Enqueue(string label, Action work) => Enqueued++;
}
}
namespace PlateSizingTests
{
using S = MonsterHudSettings;
/// <summary>
/// The nameplate sizing settings (per plate type: bar width, bar height, text size) and the
/// ArgbOpacity helper behind the Vision overlay opacity sliders.
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static string _case = "";
private static int Main()
{
DefaultsAreTodaysLook();
RoundTrip();
OldFileLoads();
Clamping();
ResetSizesOnlyTouchesSizes();
ResetAllResetsSizes();
RefactorKeepsEveryKey();
OpacityDefaults();
OpacityRoundTripsEveryAlpha();
OpacitySetKeepsRgb();
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
Console.WriteLine(_failed == 0 ? "ALL PLATE SIZING TESTS PASSED." : $"{_failed} FAILED.");
return _failed == 0 ? 0 : 1;
}
private static (string Key, Func<float> Get, Action<float> Set, float Min, float Max)[] Sizes => new (string, Func<float>, Action<float>, float, float)[]
{
("monsterBarWidth", () => S.MonsterBarWidth, v => S.MonsterBarWidth = v, S.MinBarWidth, S.MaxBarWidth),
("monsterBarHeight", () => S.MonsterBarHeight, v => S.MonsterBarHeight = v, S.MinBarHeight, S.MaxBarHeight),
("monsterTextSize", () => S.MonsterTextSize, v => S.MonsterTextSize = v, S.MinTextSize, S.MaxTextSize),
("npcTextSize", () => S.NpcTextSize, v => S.NpcTextSize = v, S.MinTextSize, S.MaxTextSize),
("playerTextSize", () => S.PlayerTextSize, v => S.PlayerTextSize = v, S.MinTextSize, S.MaxTextSize),
("selfBarWidth", () => S.SelfBarWidth, v => S.SelfBarWidth = v, S.MinBarWidth, S.MaxBarWidth),
("selfBarHeight", () => S.SelfBarHeight, v => S.SelfBarHeight = v, S.MinBarHeight, S.MaxBarHeight),
("selfTextSize", () => S.SelfTextSize, v => S.SelfTextSize = v, S.MinTextSize, S.MaxTextSize),
};
private static string[] Written()
{
var sw = new StringWriter(CultureInfo.InvariantCulture);
S.WriteAll(sw);
return sw.ToString().Split('\n', StringSplitOptions.RemoveEmptyEntries).Select(l => l.TrimEnd('\r')).ToArray();
}
// ── nameplate sizes ─────────────────────────────────────────────────
private static void DefaultsAreTodaysLook()
{
Case("defaults: every size multiplier is 1 (today's look), inside its range");
foreach (var s in Sizes)
{
Check(s.Get() == 1.0f, $"{s.Key} defaults to 1");
Check(s.Min <= 1.0f && 1.0f <= s.Max, $"{s.Key} range [{s.Min}, {s.Max}] holds 1");
}
string[] lines = Written();
foreach (var s in Sizes)
Check(lines.Contains(s.Key + "=1"), $"{s.Key}=1 written");
}
private static void RoundTrip()
{
Case("save/load: non-default sizes come back");
float[] values = { 1.75f, 0.5f, 1.25f, 0.8f, 2f, 2.5f, 3f, 0.65f };
var sizes = Sizes;
for (int i = 0; i < sizes.Length; i++) sizes[i].Set(values[i]);
S.Scale = 1.3f; S.SelfNumbers = true;
string[] lines = Written();
S.ResetToDefaults();
Check(S.MonsterBarWidth == 1f && S.SelfTextSize == 1f, "reset before reload");
S.ApplyLines(lines);
for (int i = 0; i < sizes.Length; i++)
Check(MathF.Abs(sizes[i].Get() - values[i]) < 0.001f, $"{sizes[i].Key} = {values[i]} after reload (got {sizes[i].Get()})");
Check(MathF.Abs(S.Scale - 1.3f) < 0.001f && S.SelfNumbers, "other settings in the same file still load");
S.ResetToDefaults();
}
private static void OldFileLoads()
{
Case("a file from before 2026-10-05 (no size keys) loads with sizes at 1");
S.MonsterBarWidth = 2f; S.NpcTextSize = 1.5f;
S.ResetToDefaults();
S.ApplyLines(new[]
{
"# RynthCore monster nameplates - auto-generated, hand-edits OK. /rc plates in game.",
"enabled=1", "scale=1.2", "opacity=0.8", "selfNumbers=1", "npcNames=1",
});
foreach (var s in Sizes) Check(s.Get() == 1f, $"{s.Key} stays 1");
Check(MathF.Abs(S.Scale - 1.2f) < 0.001f, "scale from the old file");
}
private static void Clamping()
{
Case("load: out-of-range values clamp, junk is ignored");
S.ResetToDefaults();
S.ApplyLines(new[]
{
"monsterBarWidth=9", "monsterBarHeight=0.01", "monsterTextSize=-3",
"npcTextSize=abc", "playerTextSize=", "selfBarWidth=0.1", "selfBarHeight=99", "selfTextSize=1e9",
});
Check(S.MonsterBarWidth == S.MaxBarWidth, "bar width capped");
Check(S.MonsterBarHeight == S.MinBarHeight, "bar height floored");
Check(S.MonsterTextSize == S.MinTextSize, "negative text size floored");
Check(S.NpcTextSize == 1f, "junk ignored (NPC)");
Check(S.PlayerTextSize == 1f, "empty ignored (player)");
Check(S.SelfBarWidth == S.MinBarWidth, "self width floored");
Check(S.SelfBarHeight == S.MaxBarHeight, "self height capped");
Check(S.SelfTextSize == S.MaxTextSize, "self text capped");
S.ResetToDefaults();
}
private static void ResetSizesOnlyTouchesSizes()
{
Case("Reset bar and text sizes: sizes back to 1, nothing else, saved");
S.ResetToDefaults();
foreach (var s in Sizes) s.Set(1.5f);
S.Scale = 1.4f; S.MaxPlates = 7; S.SelfName = true;
int saves = RynthCore.Engine.UI.UiBackgroundWriter.Enqueued;
S.ResetSizes();
foreach (var s in Sizes) Check(s.Get() == 1f, $"{s.Key} back to 1");
Check(MathF.Abs(S.Scale - 1.4f) < 0.001f && S.MaxPlates == 7 && S.SelfName, "other settings kept");
Check(RynthCore.Engine.UI.UiBackgroundWriter.Enqueued == saves + 1, "one save queued");
S.ResetToDefaults();
}
private static void ResetAllResetsSizes()
{
Case("Reset all to defaults also resets the sizes");
foreach (var s in Sizes) s.Set(0.7f);
S.ResetToDefaults();
foreach (var s in Sizes) Check(s.Get() == 1f, $"{s.Key} back to 1");
}
private static void RefactorKeepsEveryKey()
{
Case("write -> apply -> write is stable (the load/save split kept every key)");
S.ResetToDefaults();
S.Enabled = false; S.MaxDistance = 50f; S.Filter = PlateFilter.Engaged; S.SelfPlacement = SelfPlacement.Follow;
S.SelfPosition = SelfPlatePosition.Left; S.GainTime = 2.25f; S.NumSize = 1.5f; S.SelfFixedX = 0.25f;
S.MonsterBarHeight = 2f; S.PlayerTextSize = 0.75f;
string[] first = Written();
S.ResetToDefaults();
S.ApplyLines(first);
string[] second = Written();
Check(first.SequenceEqual(second), "identical text after a reload");
Check(first.Length == second.Length && first.Length > 50, $"{first.Length} lines written");
S.ResetToDefaults();
}
// ── overlay opacity (colour alpha) ───────────────────────────────────
private static readonly (string Name, uint Argb, int Pct)[] TodaysColours =
{
("slopes (impassable terrain)", 0x60FF2020u, 38),
("water", 0x600060FFu, 38),
("radar ring", 0x80FFD000u, 50),
};
private static void OpacityDefaults()
{
Case("opacity: today's colours show today's opacity, untouched they never change");
foreach (var c in TodaysColours)
{
float p = ArgbOpacity.Percent(c.Argb);
Check((int)MathF.Round(p) == c.Pct, $"{c.Name} shows {c.Pct}% (got {p:0.##})");
Check(ArgbOpacity.WithPercent(c.Argb, p) == c.Argb, $"{c.Name} unchanged when re-applied");
}
Check(ArgbOpacity.Percent(0x00123456) == 0f && ArgbOpacity.Percent(0xFF123456) == 100f, "0 and 100 at the ends");
}
private static void OpacityRoundTripsEveryAlpha()
{
Case("opacity: every alpha byte survives percent and back");
int bad = 0;
for (uint a = 0; a <= 255; a++)
{
uint c = (a << 24) | 0x00ABCDEF;
if (ArgbOpacity.WithPercent(c, ArgbOpacity.Percent(c)) != c) bad++;
}
Check(bad == 0, $"{bad} of 256 alpha values changed");
}
private static void OpacitySetKeepsRgb()
{
Case("opacity: setting it changes only the alpha, clamped to 0..100");
Check(ArgbOpacity.WithPercent(0x60FF2020, 100f) == 0xFFFF2020, "100% = solid, RGB kept");
Check(ArgbOpacity.WithPercent(0x60FF2020, 0f) == 0x00FF2020, "0% = invisible, RGB kept");
Check(ArgbOpacity.WithPercent(0x80FFD000, 25f) == 0x40FFD000, "25% = 0x40");
Check(ArgbOpacity.WithPercent(0x80FFD000, 150f) == 0xFFFFD000, "above 100 clamps");
Check(ArgbOpacity.WithPercent(0x80FFD000, -5f) == 0x00FFD000, "below 0 clamps");
Check(ArgbOpacity.WithPercent(0x80FFD000, float.NaN) == 0x00FFD000, "NaN is 0");
}
// ── harness ─────────────────────────────────────────────────────────
private static void Case(string name)
{
_case = name;
Console.WriteLine("- " + name);
}
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine($" FAIL [{_case}] {what}");
}
}
}

View file

@ -0,0 +1,40 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline tests for plugin manifests:
- parsing and checks (src\RynthCore.PluginSdk\Manifest, from the SDK);
- the engine's gate (src\RynthCore.Engine\Plugins\PluginManifestGate.cs, compiled in):
engine API refusals, required/optional dependencies, load order, plugins without one;
- reading the embedded resource from real PE files (a manifest embedded into a copy of
this test's own DLL with UpdateResource, as the build does);
- the SDK's API version can't drift: RynthCoreHost.CurrentApiVersion, the SDK's table size
(RynthCoreApiNative vs the engine's RynthCoreAPI, compiled in) and the build targets'
RynthCoreSdkApiVersion all match PluginContractVersion.Current.
Extra arguments are plugin DLLs to read and check (e.g. a RynthSuite publish folder's).
Never loads a plugin, never touches %APPDATA% or C:\Games.
Run: dotnet run -c Release [plugin.dll ...] (arguments after a double dash) (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>PluginManifestTests</RootNamespace>
<NoWarn>$(NoWarn);CS0649;CS0169</NoWarn>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
<ProjectReference Include="..\..\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
</ItemGroup>
<ItemGroup>
<!-- The engine's side: its table, its version and its manifest gate. -->
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginContract.cs" Link="Engine\PluginContract.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Engine\PluginContractVersion.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginManifestGate.cs" Link="Engine\PluginManifestGate.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,516 @@
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using RynthCore.Engine.Plugins;
using RynthCore.PluginSdk;
using RynthCore.PluginSdk.Manifest;
// What the SDK targets add to a plugin built with RynthPluginMinEngineApi=71 (see ManifestAttributeDrivesRuntimeMinimum).
[assembly: RynthPluginManifest(71)]
// Offline tests for plugin manifests: parsing, the engine's gate (API + dependencies + order),
// reading the embedded resource from PE files, and the SDK's API version. See the csproj.
internal static class Program
{
private static int _fails, _asserts;
private static void Check(bool cond, string msg)
{
_asserts++;
if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); }
}
private static void Eq<T>(T actual, T expected, string msg) =>
Check(EqualityComparer<T>.Default.Equals(actual, expected), $"{msg}: expected '{expected}', got '{actual}'");
private static string _root = "";
private const uint Api = PluginContractVersion.Current;
private static int Main(string[] args)
{
_root = Path.Combine(Path.GetTempPath(), "rynth-manifest-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_root);
try
{
Run(nameof(ParsesFullManifest), ParsesFullManifest);
Run(nameof(ParsesShorthandAndIgnoresUnknown), ParsesShorthandAndIgnoresUnknown);
Run(nameof(RejectsBrokenManifests), RejectsBrokenManifests);
Run(nameof(RoundTripsThroughJson), RoundTripsThroughJson);
Run(nameof(EngineApiCheck), EngineApiCheck);
Run(nameof(VersionComparisons), VersionComparisons);
Run(nameof(NoManifestsLoadExactlyAsListed), NoManifestsLoadExactlyAsListed);
Run(nameof(TooNewPluginIsRefusedOthersKeepOrder), TooNewPluginIsRefusedOthersKeepOrder);
Run(nameof(RequiredDependencyMissingRefuses), RequiredDependencyMissingRefuses);
Run(nameof(OptionalDependencyNeverRefusesOrReorders), OptionalDependencyNeverRefusesOrReorders);
Run(nameof(RefusalCascadesDownTheChain), RefusalCascadesDownTheChain);
Run(nameof(RequiredDependenciesStartFirst), RequiredDependenciesStartFirst);
Run(nameof(DependencyVersions), DependencyVersions);
Run(nameof(DependencyOnPluginWithoutManifest), DependencyOnPluginWithoutManifest);
Run(nameof(RequiredCycleRefusesNothing), RequiredCycleRefusesNothing);
Run(nameof(CheckRequiredStartedAtInit), CheckRequiredStartedAtInit);
Run(nameof(ReadsResourceFromPe32AndPe32Plus), ReadsResourceFromPe32AndPe32Plus);
Run(nameof(NoResourceAndNotAPe), NoResourceAndNotAPe);
Run(nameof(GatePlanFromFiles), GatePlanFromFiles);
Run(nameof(SdkApiVersionCannotDrift), SdkApiVersionCannotDrift);
Run(nameof(TrainingStructsMirror), TrainingStructsMirror);
Run(nameof(ManifestAttributeDrivesRuntimeMinimum), ManifestAttributeDrivesRuntimeMinimum);
foreach (string dll in args)
Run("Plugin " + Path.GetFileName(dll), () => CheckBuiltPlugin(dll));
}
finally
{
try { Directory.Delete(_root, true); } catch { }
}
Console.WriteLine();
Console.WriteLine(_fails == 0 && _asserts > 0 ? $"PASS ({_asserts} assertions)" : $"FAIL ({_fails} of {_asserts} assertions failed)");
return _fails == 0 && _asserts > 0 ? 0 : 1;
}
private static void Run(string name, Action test)
{
int before = _fails;
try { test(); }
catch (Exception ex) { _fails++; _asserts++; Console.WriteLine($" [FAIL] {name} threw {ex.GetType().Name}: {ex.Message}"); }
Console.WriteLine($"{(_fails == before ? "ok " : "FAIL")} {name}");
}
// ── Fixtures ─────────────────────────────────────────────────────────────
private static RynthPluginManifest M(string name, uint min = 66, string version = "2026.10.5.1", uint max = 0,
params (string Name, string Min, bool Optional)[] deps)
{
var m = new RynthPluginManifest { Name = name, Version = version, MinEngineApi = min, MaxEngineApi = max };
foreach (var d in deps) m.Dependencies.Add(new RynthPluginDependency { Name = d.Name, MinVersion = d.Min, Optional = d.Optional });
return m;
}
private static PluginCandidate C(string name, RynthPluginManifest? m = null, string fileVersion = "") =>
new($@"C:\Games\RynthSuite\{name}\RynthCore.Plugin.{name}.dll", m, fileVersion);
private static string Names(IEnumerable<PluginCandidate> list) => string.Join(",", list.Select(c => c.Name));
// ── Parsing ──────────────────────────────────────────────────────────────
private static void ParsesFullManifest()
{
var m = RynthPluginManifest.Parse("""
{
"schema": 1,
"name": "RynthOracle",
"version": "2026.10.5.1",
"minEngineApi": 71,
"maxEngineApi": 90,
"dependencies": [
{ "name": "RynthAi", "optional": true },
{ "name": "RynthNav", "minVersion": "2026.10.1.1" }
],
"author": "RynthSuite",
"description": "Quests, character, titles and leaderboards.",
"homepage": "https://aelrynth.com/rynth.html",
"license": "MIT"
}
""");
Eq(m.Name, "RynthOracle", "name");
Eq(m.Version, "2026.10.5.1", "version");
Eq(m.MinEngineApi, 71u, "minEngineApi");
Eq(m.MaxEngineApi, 90u, "maxEngineApi");
Eq(m.Dependencies.Count, 2, "dependency count");
Check(m.Dependencies[0].Optional && m.Dependencies[0].Name == "RynthAi", "first dependency optional RynthAi");
Check(!m.Dependencies[1].Optional && m.Dependencies[1].MinVersion == "2026.10.1.1", "second dependency required with min version");
Eq(m.Author, "RynthSuite", "author");
Eq(m.License, "MIT", "license");
Eq(m.Homepage, "https://aelrynth.com/rynth.html", "homepage");
}
private static void ParsesShorthandAndIgnoresUnknown()
{
var m = RynthPluginManifest.Parse("""{ "schema": 2, "name": "X", "minEngineApi": "70", "dependencies": ["RynthNav@2026.10.1.1", "RynthAi"], "futureField": { "a": 1 } }""");
Eq(m.Schema, 2, "a later schema is read");
Eq(m.MinEngineApi, 70u, "minEngineApi as a string");
Eq(m.Dependencies[0].Name, "RynthNav", "shorthand name");
Eq(m.Dependencies[0].MinVersion, "2026.10.1.1", "shorthand version");
Check(!m.Dependencies[1].Optional, "shorthand is required");
var bare = RynthPluginManifest.Parse("""{ "name": "Bare" }""");
Eq(bare.MinEngineApi, 0u, "no minEngineApi means no limit");
Eq(bare.Dependencies.Count, 0, "no dependencies");
}
private static void RejectsBrokenManifests()
{
string[] bad =
{
"not json",
"[]",
"""{ "version": "1.0" }""",
"""{ "name": "" }""",
"""{ "name": "X", "minEngineApi": 76, "maxEngineApi": 70 }""",
"""{ "name": "X", "minEngineApi": -1 }""",
"""{ "name": "X", "minEngineApi": "abc" }""",
"""{ "name": "X", "dependencies": ["X"] }""",
"""{ "name": "X", "dependencies": [{ "name": "Y", "minVersion": "soon" }] }""",
"""{ "name": "X", "dependencies": [42] }""",
"""{ "name": "X", "dependencies": {} }""",
"""{ "name": "X", "schema": 0 }""",
};
foreach (string json in bad)
{
Check(RynthPluginManifest.TryParse(json, out string err) == null && err.Length > 0, $"refused: {json}");
}
}
private static void RoundTripsThroughJson()
{
var m = M("RynthAi", 66, "2026.10.5.1", 0, ("RynthNav", "", true), ("RynthLua", "2026.9.1.1", false));
m.Description = "The bot: \"combat\", buffs\nand more";
m.License = "MIT";
var back = RynthPluginManifest.Parse(m.ToJson());
Eq(back.Name, m.Name, "name");
Eq(back.Description, m.Description, "description with quotes and newline");
Eq(back.Dependencies.Count, 2, "dependencies");
Check(back.Dependencies[0].Optional && !back.Dependencies[1].Optional, "optional flags");
Eq(back.Dependencies[1].MinVersion, "2026.9.1.1", "min version");
Check(!m.ToJson().Contains("maxEngineApi"), "no maxEngineApi written when unset");
}
private static void EngineApiCheck()
{
Eq(M("RynthOracle", 77).CheckEngine(76), "RynthOracle needs a newer RynthCore (API 77)", "too new");
Check(M("RynthOracle", 76).CheckEngine(76) == null, "exact minimum runs");
Check(M("RynthOracle", 66).CheckEngine(76) == null, "older minimum runs");
Check(M("Old", 60, max: 70).CheckEngine(76)?.Contains("too old") == true, "past maxEngineApi refused");
Check(M("Old", 60, max: 76).CheckEngine(76) == null, "at maxEngineApi runs");
Eq(RynthPluginManifest.NameFromFile(@"C:\x\RynthCore.Plugin.RynthNav.dll"), "RynthNav", "name from file");
Eq(RynthPluginManifest.NameFromFile(@"C:\x\Other.dll"), "Other", "name from other file");
}
private static void VersionComparisons()
{
Check(PluginVersion.Satisfies("2026.10.5.1", "2026.10.1.1"), "newer satisfies");
Check(PluginVersion.Satisfies("2026.10.1.1", "2026.10.1.1"), "equal satisfies");
Check(!PluginVersion.Satisfies("2026.9.30.4", "2026.10.1.1"), "older doesn't");
Check(PluginVersion.Satisfies("2026.10.5.1+8ca322f", "2026.10.5"), "build metadata ignored, 3 vs 4 parts");
Check(PluginVersion.Satisfies("1.0.0", "2026.10.1.1"), "dev build satisfies anything");
Check(PluginVersion.Satisfies("1.0.0+abc", "2026.10.1.1"), "dev build with commit satisfies");
Check(PluginVersion.IsDevBuild("1.0.0.0") && !PluginVersion.IsDevBuild("1.0.1"), "dev build detection");
Check(!PluginVersion.Satisfies("", "2026.10.1.1"), "no version doesn't satisfy a minimum");
Check(PluginVersion.Satisfies("", ""), "no minimum, anything goes");
Check(PluginVersion.TryParse("v2.0.0-beta", out var v) && v.Major == 2, "v prefix and prerelease");
}
// ── Resolution (the engine's load plan) ──────────────────────────────────
private static void NoManifestsLoadExactlyAsListed()
{
var list = new[] { C("RynthChat"), C("RynthAi"), C("RynthNav"), C("Zed") };
PluginResolution r = PluginManifestResolver.Resolve(list, Api);
Eq(Names(r.Order), "RynthChat,RynthAi,RynthNav,Zed", "order unchanged");
Eq(r.Refused.Count, 0, "nothing refused");
Eq(r.Notes.Count, 0, "nothing to say");
}
private static void TooNewPluginIsRefusedOthersKeepOrder()
{
var list = new[] { C("RynthChat"), C("RynthOracle", M("RynthOracle", Api + 1)), C("RynthAi", M("RynthAi", 66)) };
PluginResolution r = PluginManifestResolver.Resolve(list, Api);
Eq(Names(r.Order), "RynthChat,RynthAi", "the rest load in order");
Eq(r.Refused.Count, 1, "one refused");
Eq(r.Refused[0].Reason, $"RynthOracle needs a newer RynthCore (API {Api + 1})", "reason fit for chat");
Check(r.Refused[0].IsEngineMismatch, "engine mismatch flagged");
}
private static void RequiredDependencyMissingRefuses()
{
var list = new[] { C("RynthLua", M("RynthLua", 66, deps: ("RynthAi", "", false))), C("RynthChat") };
PluginResolution r = PluginManifestResolver.Resolve(list, Api);
Eq(Names(r.Order), "RynthChat", "dependent not loaded");
Eq(r.Refused.Single().Reason, "RynthLua needs the RynthAi plugin, which is not in the plugin list", "reason");
Check(!r.Refused[0].IsEngineMismatch, "dependency refusal flagged");
}
private static void OptionalDependencyNeverRefusesOrReorders()
{
// RynthAi and RynthLua can each use the other: optional both ways is no cycle and no reorder.
var list = new[]
{
C("RynthAi", M("RynthAi", 66, deps: new[] { ("RynthNav", "", true), ("RynthLua", "", true), ("RynthNet", "", true) })),
C("RynthLua", M("RynthLua", 66, deps: ("RynthAi", "", true))),
C("RynthNet", M("RynthNet", 66, deps: ("RynthAi", "", true))),
};
PluginResolution r = PluginManifestResolver.Resolve(list, Api);
Eq(Names(r.Order), "RynthAi,RynthLua,RynthNet", "order unchanged");
Eq(r.Refused.Count, 0, "nothing refused");
Check(r.Notes.Any(n => n.Contains("optional plugin RynthNav is not loaded")), "missing optional noted");
}
private static void RefusalCascadesDownTheChain()
{
var list = new[]
{
C("C", M("C", 66, deps: ("B", "", false))),
C("B", M("B", 66, deps: ("A", "", false))),
C("A", M("A", Api + 5)),
C("D"),
};
PluginResolution r = PluginManifestResolver.Resolve(list, Api);
Eq(Names(r.Order), "D", "only the independent plugin loads");
Eq(r.Refused.Count, 3, "three refused");
Check(r.Refused.Any(x => x.Plugin.Name == "B" && x.Reason == "B needs A, which was not loaded"), "B refused for A");
Check(r.Refused.Any(x => x.Plugin.Name == "C" && x.Reason == "C needs B, which was not loaded"), "C refused for B");
}
private static void RequiredDependenciesStartFirst()
{
var list = new[]
{
C("RynthChat"),
C("Addon", M("Addon", 66, deps: ("RynthNav", "", false))),
C("RynthTracker"),
C("RynthNav", M("RynthNav", 66)),
C("RynthVision"),
};
PluginResolution r = PluginManifestResolver.Resolve(list, Api);
Eq(Names(r.Order), "RynthChat,RynthNav,Addon,RynthTracker,RynthVision", "RynthNav moved before Addon, the rest as listed");
}
private static void DependencyVersions()
{
var tooOld = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "2026.10.1.1", false))), C("RynthNav", M("RynthNav", 66, "2026.9.30.2")) };
PluginResolution r = PluginManifestResolver.Resolve(tooOld, Api);
Eq(Names(r.Order), "RynthNav", "too-old dependency refuses the dependent");
Eq(r.Refused.Single().Reason, "Addon needs RynthNav 2026.10.1.1 or newer (this one is 2026.9.30.2)", "reason");
var dev = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "2026.10.1.1", false))), C("RynthNav", M("RynthNav", 66, "1.0.0")) };
r = PluginManifestResolver.Resolve(dev, Api);
Eq(Names(r.Order), "RynthNav,Addon", "a dev build satisfies");
Check(r.Notes.Any(n => n.Contains("dev build")), "dev build noted");
var optOld = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "2026.10.1.1", true))), C("RynthNav", M("RynthNav", 66, "2026.9.1.1")) };
r = PluginManifestResolver.Resolve(optOld, Api);
Eq(r.Refused.Count, 0, "an old optional dependency refuses nothing");
Check(r.Notes.Any(n => n.Contains("older")), "old optional noted");
}
private static void DependencyOnPluginWithoutManifest()
{
// RynthNav from before manifests: found by its file name, versioned by its version resource.
var list = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "2026.10.1.1", false))), C("RynthNav", null, "2026.10.4.3+abcdef") };
PluginResolution r = PluginManifestResolver.Resolve(list, Api);
Eq(Names(r.Order), "RynthNav,Addon", "satisfied by file name and version resource");
var noVersion = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "2026.10.1.1", false))), C("RynthNav") };
r = PluginManifestResolver.Resolve(noVersion, Api);
Check(r.Refused.Single().Reason.Contains("has no version"), "an unversioned plugin can't meet a minimum");
var anyVersion = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "", false))), C("RynthNav") };
r = PluginManifestResolver.Resolve(anyVersion, Api);
Eq(r.Refused.Count, 0, "no minimum: any copy will do");
}
private static void RequiredCycleRefusesNothing()
{
var list = new[] { C("A", M("A", 66, deps: ("B", "", false))), C("B", M("B", 66, deps: ("A", "", false))), C("Z") };
PluginResolution r = PluginManifestResolver.Resolve(list, Api);
Eq(r.Refused.Count, 0, "a cycle isn't a reason to refuse");
Eq(r.Order.Count, 3, "all load");
Check(r.Notes.Any(n => n.Contains("cycle")), "cycle noted");
}
private static void CheckRequiredStartedAtInit()
{
var m = M("Addon", 66, deps: new[] { ("RynthNav", "", false), ("RynthAi", "", true) });
Check(PluginManifestGate.CheckRequiredStarted(null, _ => null) == null, "no manifest, no check");
Check(PluginManifestGate.CheckRequiredStarted(m, n => n == "RynthNav" ? true : null) == null, "required started, optional absent: fine");
Eq(PluginManifestGate.CheckRequiredStarted(m, n => n == "RynthNav" ? false : true), "Addon needs RynthNav, which failed to start", "required failed");
Eq(PluginManifestGate.CheckRequiredStarted(m, _ => null), "Addon needs RynthNav, which is not loaded", "required missing");
}
// ── PE files ─────────────────────────────────────────────────────────────
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr BeginUpdateResourceW(string file, bool deleteExisting);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool UpdateResourceW(IntPtr h, IntPtr type, string name, ushort lang, byte[] data, uint cb);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool EndUpdateResourceW(IntPtr h, bool discard);
/// <summary>What the build's RynthEmbedPluginManifest task does.</summary>
private static void Embed(string path, string json, string name = RynthPluginManifest.ResourceName)
{
IntPtr h = BeginUpdateResourceW(path, false);
if (h == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error());
byte[] data = Encoding.UTF8.GetBytes(json);
if (!UpdateResourceW(h, (IntPtr)RynthPluginManifest.ResourceType, name, 0, data, (uint)data.Length))
{
int err = Marshal.GetLastWin32Error();
EndUpdateResourceW(h, true);
throw new Win32Exception(err);
}
if (!EndUpdateResourceW(h, false)) throw new Win32Exception(Marshal.GetLastWin32Error());
}
private static string CopyOf(string source, string name)
{
string dest = Path.Combine(_root, Guid.NewGuid().ToString("N")[..8], name);
Directory.CreateDirectory(Path.GetDirectoryName(dest)!);
File.Copy(source, dest);
return dest;
}
private static string ThisDll => typeof(Program).Assembly.Location;
private static string ThisExe => Path.ChangeExtension(ThisDll, ".exe");
private static void ReadsResourceFromPe32AndPe32Plus()
{
// The test's own IL DLL is PE32 (AnyCPU); its apphost .exe is a native PE32+ image.
foreach (string source in new[] { ThisDll, ThisExe })
{
string copy = CopyOf(source, "RynthCore.Plugin.Probe" + Path.GetExtension(source));
Check(PluginManifestReader.Read(copy) == null, $"{Path.GetFileName(source)}: no manifest before embedding");
string json = M("Probe", 71, deps: ("RynthAi", "", true)).ToJson();
Embed(copy, json);
RynthPluginManifest? m = PluginManifestReader.Read(copy);
Check(m != null, $"{Path.GetFileName(source)}: manifest read back");
Eq(m?.MinEngineApi ?? 0, 71u, $"{Path.GetFileName(source)}: minEngineApi");
Eq(PluginManifestReader.ReadJson(copy), json, $"{Path.GetFileName(source)}: exact JSON");
Check(!string.IsNullOrEmpty(System.Diagnostics.FileVersionInfo.GetVersionInfo(copy).ProductVersion),
$"{Path.GetFileName(source)}: version resource survives");
// Replace in place (a rebuild): the new one wins.
Embed(copy, M("Probe", 72).ToJson());
Eq(PluginManifestReader.Read(copy)?.MinEngineApi ?? 0, 72u, $"{Path.GetFileName(source)}: re-embedded");
// Readable while another process has it open for execution-style sharing (the engine's shadow copy case).
using (new FileStream(copy, FileMode.Open, FileAccess.Read, FileShare.Read))
Check(PluginManifestReader.Read(copy) != null, $"{Path.GetFileName(source)}: readable while open");
}
// Lower-case name in the file still matches (resource names are case-insensitive).
string lower = CopyOf(ThisDll, "lower.dll");
Embed(lower, M("Lower", 66).ToJson(), "rynth_plugin_manifest");
Eq(PluginManifestReader.Read(lower)?.Name, "Lower", "case-insensitive resource name");
}
private static void NoResourceAndNotAPe()
{
string text = Path.Combine(_root, "notes.dll");
File.WriteAllText(text, "this is not a DLL, just text long enough to have a header-sized body .................................");
try { PluginManifestReader.Read(text); Check(false, "a text file should throw"); }
catch (InvalidDataException) { Check(true, "text file refused as not a PE"); }
string tiny = Path.Combine(_root, "tiny.dll");
File.WriteAllBytes(tiny, new byte[] { 0x4D, 0x5A });
try { PluginManifestReader.Read(tiny); Check(false, "a 2-byte file should throw"); }
catch (InvalidDataException) { Check(true, "truncated file refused"); }
// Another RCDATA resource, not ours: still "no manifest".
string other = CopyOf(ThisDll, "other.dll");
Embed(other, "{}", "SOMETHING_ELSE");
Check(PluginManifestReader.Read(other) == null, "other resources are not a manifest");
}
private static void GatePlanFromFiles()
{
string dir = Path.Combine(_root, "suite");
Directory.CreateDirectory(dir);
string P(string name) => Path.Combine(dir, $"RynthCore.Plugin.{name}.dll");
File.Copy(ThisDll, P("RynthChat")); // no manifest: loads as before
File.Copy(ThisDll, P("RynthOracle"));
Embed(P("RynthOracle"), M("RynthOracle", Api + 1).ToJson());
File.Copy(ThisDll, P("RynthAi"));
Embed(P("RynthAi"), M("RynthAi", 66, deps: ("RynthLua", "", true)).ToJson());
File.Copy(ThisDll, P("Broken"));
Embed(P("Broken"), "{ \"name\": "); // broken JSON: loads as without one
File.Copy(ThisDll, P("Needy"));
Embed(P("Needy"), M("Needy", 66, deps: ("RynthNav", "", false)).ToJson());
var paths = new[] { P("RynthChat"), P("RynthOracle"), P("RynthAi"), P("Broken"), P("Needy") };
PluginManifestGate.LoadPlan plan = PluginManifestGate.Plan(paths, Api, _ => "2026.10.4.3");
Eq(string.Join(",", plan.Load.Select(l => RynthPluginManifest.NameFromFile(l.Path))), "RynthChat,RynthAi,Broken", "load list");
Check(plan.Load.Single(l => l.Path == P("RynthChat")).Manifest == null, "RynthChat has no manifest");
Check(plan.Load.Single(l => l.Path == P("RynthAi")).Manifest?.Name == "RynthAi", "RynthAi carries its manifest");
Eq(plan.Refused.Count, 2, "two refused");
Check(plan.Refused.Any(r => r.Reason == $"RynthOracle needs a newer RynthCore (API {Api + 1})"), "Oracle refused for API");
Check(plan.Refused.Any(r => r.Reason.StartsWith("Needy needs the RynthNav plugin")), "Needy refused for RynthNav");
Check(plan.Log.Any(l => l.Contains("Broken") && l.Contains("manifest unreadable")), "broken manifest logged");
Check(plan.Log.Any(l => l.Contains("optional plugin RynthLua")), "optional note logged");
PluginManifestGate.LoadPlan none = PluginManifestGate.Plan(new[] { P("RynthChat"), P("Broken") }, Api);
Eq(none.Load.Count, 2, "no manifests: everything loads");
Check(none.Log.Any(l => l.Contains("no plugin has a manifest")), "said once");
}
// ── The SDK's version ────────────────────────────────────────────────────
private static void SdkApiVersionCannotDrift()
{
Eq(RynthCoreHost.CurrentApiVersion, PluginContractVersion.Current, "RynthCoreHost.CurrentApiVersion");
Check(RynthCoreHost.BaselineApiVersion <= RynthCoreHost.CurrentApiVersion, "baseline at or below current");
// The SDK's copy of the table must reach as far as the engine's (same field count, same size).
int sdkFields = typeof(RynthCoreApiNative).GetFields().Length;
int engineFields = typeof(RynthCoreAPI).GetFields().Length;
Eq(sdkFields, engineFields, "RynthCoreApiNative fields vs the engine's RynthCoreAPI (add the new fields to the SDK)");
Eq(Marshal.SizeOf<RynthCoreApiNative>(), Marshal.SizeOf<RynthCoreAPI>(), "table size");
// The build targets' copy, used to refuse a RynthPluginMinEngineApi the SDK doesn't know.
string targets = FindUp(Path.Combine("src", "RynthCore.PluginSdk", "build", "RynthCore.PluginSdk.targets"));
Match match = Regex.Match(File.ReadAllText(targets), @"<RynthCoreSdkApiVersion>(\d+)</RynthCoreSdkApiVersion>");
Check(match.Success, "targets declare RynthCoreSdkApiVersion");
Eq(match.Success ? uint.Parse(match.Groups[1].Value) : 0u, PluginContractVersion.Current, "RynthCoreSdkApiVersion in RynthCore.PluginSdk.targets");
}
// v79: the SDK's copies of the training structs must be the engine's, byte for byte.
private static void TrainingStructsMirror()
{
Eq(Marshal.SizeOf<RynthCore.PluginSdk.TrainingInfoNative>(), 64, "SDK TrainingInfoNative size");
Eq(Marshal.SizeOf<RynthCore.Engine.Plugins.TrainingInfoNative>(), 64, "engine TrainingInfoNative size");
Eq(Marshal.SizeOf<RynthCore.PluginSdk.TrainingEntryNative>(), 64, "SDK TrainingEntryNative size");
Eq(Marshal.SizeOf<RynthCore.Engine.Plugins.TrainingEntryNative>(), 64, "engine TrainingEntryNative size");
foreach (var f in typeof(RynthCore.Engine.Plugins.TrainingInfoNative).GetFields())
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.TrainingInfoNative>(f.Name), (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.TrainingInfoNative>(f.Name), "TrainingInfoNative." + f.Name + " offset");
foreach (var f in typeof(RynthCore.Engine.Plugins.TrainingEntryNative).GetFields())
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.TrainingEntryNative>(f.Name), (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.TrainingEntryNative>(f.Name), "TrainingEntryNative." + f.Name + " offset");
Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits");
Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits");
// The three v79 slots, then v80's GetMergeStackResultFn, end the table in this order.
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).TakeLast(4).ToArray();
Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn", "GetMergeStackResultFn" }), "v79 then v80 slots last: " + string.Join(",", names));
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).TakeLast(4).ToArray();
Check(sdkNames.SequenceEqual(names), "SDK v79 and v80 slots in the same order");
}
private sealed class ProbePlugin : RynthCore.PluginCore.RynthPluginBase { }
private sealed class OverridingPlugin : RynthCore.PluginCore.RynthPluginBase { public override uint MinimumApiVersion => 70; }
private static void ManifestAttributeDrivesRuntimeMinimum()
{
// RynthPluginBase.MinimumApiVersion defaults to the assembly's [RynthPluginManifest(min)] ...
Eq(new ProbePlugin().MinimumApiVersion, 71u, "default follows the manifest attribute");
// ... an explicit override still wins ...
Eq(new OverridingPlugin().MinimumApiVersion, 70u, "an override wins");
// ... and an assembly without one (RynthCore.PluginSdk itself has none) gets the baseline.
Check(typeof(RynthCoreHost).Assembly.GetCustomAttributes(typeof(RynthPluginManifestAttribute), false).Length == 0,
"the SDK assembly carries no manifest attribute");
}
private static string FindUp(string relative)
{
for (DirectoryInfo? d = new(AppContext.BaseDirectory); d != null; d = d.Parent)
{
string p = Path.Combine(d.FullName, relative);
if (File.Exists(p)) return p;
}
throw new FileNotFoundException(relative);
}
// ── Real plugin DLLs (arguments) ─────────────────────────────────────────
private static void CheckBuiltPlugin(string dll)
{
RynthPluginManifest? m = PluginManifestReader.Read(dll);
Check(m != null, $"{dll}: has a manifest");
if (m == null) return;
Console.WriteLine($" {PluginManifestGate.Describe(m)}");
Eq(m.Name, RynthPluginManifest.NameFromFile(dll), $"{Path.GetFileName(dll)}: manifest name matches the file");
Check(m.MinEngineApi >= RynthCoreHost.BaselineApiVersion, $"{m.Name}: minEngineApi {m.MinEngineApi} at or above the SDK baseline");
Check(m.CheckEngine(PluginContractVersion.Current) == null, $"{m.Name}: runs on this engine (API {PluginContractVersion.Current})");
Check(m.Description.Length > 0, $"{m.Name}: has a description");
Check(!string.IsNullOrEmpty(System.Diagnostics.FileVersionInfo.GetVersionInfo(dll).ProductVersion), $"{m.Name}: version resource intact");
}
}

View file

@ -0,0 +1,37 @@
#Requires -Version 7
<#
.SYNOPSIS
Checks installer\PluginManifest.ps1 (what Publish-Update.ps1 uses to put minEngineApi in the feed)
against plugin DLLs: it must read the same manifest the engine and launcher read.
.EXAMPLE
.\Test-PluginManifestPs.ps1 -Dll C:\Projects\manifest\_pub\RynthChat\RynthCore.Plugin.RynthChat.dll
Exit 0 = pass. Read-only: maps the DLLs as data files, runs nothing from them.
#>
param([string[]]$Dll = @(), [string[]]$NoManifestDll = @())
$ErrorActionPreference = "Stop"
$repo = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path
. (Join-Path $repo "installer\PluginManifest.ps1")
$fails = 0
function Check($cond, $msg) { if ($cond) { Write-Host "ok $msg" } else { Write-Host "FAIL $msg"; $script:fails++ } }
$api = Get-RynthEngineApi $repo
$src = Get-Content (Join-Path $repo "src\RynthCore.Engine\Plugins\PluginContractVersion.cs") -Raw
Check ($api -gt 0 -and $src -match "Current = $api;") "Get-RynthEngineApi reads PluginContractVersion.Current ($api)"
foreach ($d in $Dll) {
$m = Get-RynthPluginManifest $d
Check ($null -ne $m) "$(Split-Path $d -Leaf): manifest found"
if (-not $m) { continue }
$expected = [IO.Path]::GetFileNameWithoutExtension($d) -replace '^RynthCore\.Plugin\.', ''
Check ($m.name -eq $expected) "$(Split-Path $d -Leaf): name '$($m.name)'"
Check ([int]$m.minEngineApi -ge 66 -and [int]$m.minEngineApi -le $api) "$(Split-Path $d -Leaf): minEngineApi $($m.minEngineApi) within 66..$api"
}
foreach ($d in $NoManifestDll) {
Check ($null -eq (Get-RynthPluginManifest $d)) "$(Split-Path $d -Leaf): no manifest -> `$null"
}
if ($fails -gt 0) { Write-Host "FAIL ($fails)"; exit 1 }
Write-Host "PASS"
exit 0

View file

@ -0,0 +1,119 @@
using RynthCore.Engine;
namespace ReloadDeferralTests;
/// <summary>
/// The engine's hot-reload deferral (ReloadDeferral.cs). Drakkon died on 2026-10-05 after an
/// engine reload took every plugin down for 8 s mid-fight; the engine now waits while a plugin
/// (RynthAi) says a reload would hurt, up to 2 minutes.
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static string _case = "";
private static int Main()
{
NoBlockerReloadsAtOnce();
WaitsWhileInCombatThenReloads();
CapReloadsAnyway();
ThrowingQueryNeverHolds();
SeveralPluginsDescribed();
Console.WriteLine($"{_checks} check(s), {_failed} failed.");
return _failed == 0 ? 0 : 1;
}
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine($"[FAIL] {_case}: {what}");
}
/// <summary>A fake clock that only moves when the deferral sleeps.</summary>
private sealed class Rig
{
public DateTime Now = new(2026, 10, 5, 13, 42, 54, DateTimeKind.Utc);
public readonly List<string> Logs = new();
public readonly List<string> Notes = new();
public int Queries;
public Func<int, IReadOnlyList<(string, string)>> Answer = _ => Array.Empty<(string, string)>();
public ReloadDeferral Make() => new()
{
Query = () => Answer(++Queries),
Log = Logs.Add,
Notify = Notes.Add,
Clock = () => Now,
Sleep = t => Now += t,
};
}
private static readonly (string, string)[] InCombat = { ("RynthAi", "in combat (a monster engaged, health 12% under Emergency Heal At 30%)") };
private static void NoBlockerReloadsAtOnce()
{
_case = "no blocker";
var r = new Rig();
var outcome = r.Make().Run(out TimeSpan waited);
Check(outcome == ReloadDeferral.Outcome.Clear, "nothing objects: Clear");
Check(waited == TimeSpan.Zero, "no wait");
Check(r.Queries == 1, "asked once");
Check(r.Logs.Count == 0 && r.Notes.Count == 0, "nothing logged or said");
}
private static void WaitsWhileInCombatThenReloads()
{
_case = "in combat";
var r = new Rig();
// In combat for the first 80 answers (40 s at 0.5 s), then clear.
r.Answer = n => n <= 80 ? InCombat : Array.Empty<(string, string)>();
var outcome = r.Make().Run(out TimeSpan waited);
Check(outcome == ReloadDeferral.Outcome.ClearedAfterWait, $"cleared after a wait (got {outcome})");
Check(Math.Abs(waited.TotalSeconds - 40) < 0.01, $"waited 40 s (got {waited.TotalSeconds})");
Check(r.Logs.Count > 0 && r.Logs[0].StartsWith("engine reload waiting: RynthAi in combat (a monster engaged", StringComparison.Ordinal),
$"the first line names the plugin and why: {r.Logs.FirstOrDefault()}");
int repeats = r.Logs.Count(l => l.StartsWith("engine reload waiting:", StringComparison.Ordinal));
Check(repeats == 3, $"the waiting line at once, then every 15 s (0, 15, 30 s: 3 lines, got {repeats})");
Check(r.Logs[^1].StartsWith("engine reload: the plugins are clear after 40.0 s", StringComparison.Ordinal), $"the last line says it goes now: {r.Logs[^1]}");
Check(r.Notes.Count == 1 && r.Notes[0].Contains("RynthAi in combat"), "the player is told once");
}
private static void CapReloadsAnyway()
{
_case = "cap";
var r = new Rig();
r.Answer = _ => InCombat; // never clears
var outcome = r.Make().Run(out TimeSpan waited);
Check(outcome == ReloadDeferral.Outcome.TimedOut, $"timed out (got {outcome})");
Check(waited >= ReloadDeferral.DefaultCap && waited < ReloadDeferral.DefaultCap + TimeSpan.FromSeconds(1),
$"at the 2-minute cap (got {waited.TotalSeconds} s)");
Check(r.Logs[^1].Contains("reloading anyway") && r.Logs[^1].Contains("RynthAi in combat"), $"and says so: {r.Logs[^1]}");
Check(r.Queries <= 242, $"asked about every 0.5 s, no busier (got {r.Queries})");
}
private static void ThrowingQueryNeverHolds()
{
_case = "query throws";
var r = new Rig();
r.Answer = _ => throw new InvalidOperationException("plugin list changed");
var outcome = r.Make().Run(out TimeSpan waited);
Check(outcome == ReloadDeferral.Outcome.Clear, "a failed query doesn't hold the reload");
Check(waited == TimeSpan.Zero, "no wait");
Check(r.Logs.Count == 1 && r.Logs[0].Contains("asking the plugins failed"), "and it is logged");
// Throws while waiting: counts as clear too.
var w = new Rig();
w.Answer = n => n == 1 ? InCombat : throw new InvalidOperationException("boom");
Check(w.Make().Run(out _) == ReloadDeferral.Outcome.ClearedAfterWait, "a query that fails mid-wait ends the wait");
}
private static void SeveralPluginsDescribed()
{
_case = "describe";
string d = ReloadDeferral.Describe(new[] { ("RynthAi", "in combat (a monster engaged)"), ("RynthLua", "busy (a script step)") });
Check(d == "RynthAi in combat (a monster engaged); RynthLua busy (a script step)", $"joined: {d}");
}
}

View file

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the engine's hot-reload deferral (2026-10-05):
src\RynthCore.Engine\ReloadDeferral.cs, compiled in. A reload goes at once when no plugin
objects, waits (asking again every 0.5 s) while one does, logs "engine reload waiting:
RynthAi in combat (...)" at once and then every 15 s, goes ahead when the plugins clear,
and goes anyway at the 2-minute cap. A plugin query that throws never holds a reload.
The clock and the sleep are fakes: the tests take milliseconds, nothing touches the game.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>ReloadDeferralTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\ReloadDeferral.cs" Link="Engine\ReloadDeferral.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,558 @@
using System.Text;
using System.Text.Json;
using RynthCore.StatusAgent;
namespace StatusAgentTests;
/// <summary>
/// The StatusAgent's DrakRemote parity pieces, offline. Args (optional, read-only):
/// --portal PATH also read the real spell table from this portal.dat
/// --cell PATH also render the real world map from this cell.dat (prints size and timing)
/// --out FILE with --cell: write the rendered JPEG there to look at
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static int Main(string[] args)
{
string? portal = Arg(args, "--portal"), cell = Arg(args, "--cell"), outFile = Arg(args, "--out");
Landblocks();
AppMatchesWithTheInstalledPhone();
ClickMapping();
Capabilities();
SpellTable();
Enchantments();
PluginStatusAdditions();
PayloadJsonNames();
WorldMap();
NavSearch();
TravelStatus();
RaiseCommand();
StatusFileReads();
MoveProtocol();
if (Arg(args, "--atlas") is { } atlas) RealAtlas(atlas);
if (portal != null) RealSpellTable(portal);
if (cell != null) RealWorldMap(cell, outFile);
Console.WriteLine();
Console.WriteLine(_failed == 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks} checks failed)");
return _failed == 0 ? 0 : 1;
}
// ── landblocks ──────────────────────────────────────────────────────────
private static void Landblocks()
{
Section("landblock ids");
Check(RemoteParity.LandblockFull("00005A48") == "5A480000", "engine short form \"00005A48\" -> \"5A480000\"");
Check(RemoteParity.LandblockFull("5A48") == "5A480000", "four digits -> full");
Check(RemoteParity.LandblockFull("5A480000") == "5A480000", "full stays full");
Check(RemoteParity.LandblockFull("5A48013F") == "5A480000", "a cell id drops its cell part");
Check(RemoteParity.LandblockFull("") == "", "empty stays empty (outdoors at login)");
Check(RemoteParity.LandblockFull("00000000") == "", "zero is no landblock");
Check(RemoteParity.LandblockFull("zz") == "zz", "unparseable passes through");
Check(RemoteParity.TryLandblockShort("5A480000", out uint a) && a == 0x5A48, "/map?lb=5A480000 -> 0x5A48");
Check(RemoteParity.TryLandblockShort("00005A48", out uint b) && b == 0x5A48, "/map?lb=00005A48 -> 0x5A48");
Check(RemoteParity.TryLandblockShort("5A48", out uint c) && c == 0x5A48, "/map?lb=5A48 -> 0x5A48");
Check(!RemoteParity.TryLandblockShort("", out _) && !RemoteParity.TryLandblockShort("0", out _), "empty / zero refused");
}
/// <summary>DrakRemote v1.0.13 (cf0e206, on the phone now): AcMapEntry.LandblockId shifts a short id up,
/// AcClientStatus.LandblockId takes the id as written. The agent's output must match under those rules.</summary>
private static void AppMatchesWithTheInstalledPhone()
{
Section("matching under the installed app's rules");
static uint MapRule(string s) => uint.TryParse(s, System.Globalization.NumberStyles.HexNumber, null, out var v) ? (v > 0xFFFF ? v : v << 16) : 0;
static uint ClientRule(string s) => uint.TryParse(s, System.Globalization.NumberStyles.HexNumber, null, out var v) ? v : 0;
// Before: what the agent wrote (engine form for both) never matched.
Check(MapRule("00005A48") != ClientRule("00005A48"), "negative control: the old output does not match (the bug)");
string map = RemoteParity.LandblockFull("00005A48"), client = RemoteParity.LandblockFull("00005A48");
Check(MapRule(map) == ClientRule(client) && ClientRule(client) == 0x5A480000, "new output: map and client both 0x5A480000");
// The image URL the app builds from the matched map: lb.ToString("X") of the parsed id.
string urlLb = MapRule(map).ToString("X");
Check(RemoteParity.TryLandblockShort(urlLb, out uint file) && $"{file:X8}_1.bin" == "00005A48_1.bin", "the /map request finds the baked file 00005A48_1.bin");
}
// ── click mapping ───────────────────────────────────────────────────────
private static void ClickMapping()
{
Section("tap-to-click mapping");
Check(RemoteParity.ClickPoint(0, 0, 1280, 720) == (0, 0), "top-left -> 0,0");
Check(RemoteParity.ClickPoint(1, 1, 1280, 720) == (1279, 719), "bottom-right -> last pixel");
Check(RemoteParity.ClickPoint(0.5, 0.5, 1280, 720) == (640, 360), "centre (rounded half away)");
Check(RemoteParity.ClickPoint(0.25, 0.75, 1920, 1080) == (480, 809), "a quarter across, three quarters down");
Check(RemoteParity.ClickPoint(-0.2, 1.4, 800, 600) == (0, 599), "out of range clamps to the edge");
Check(RemoteParity.ClickPoint(double.NaN, double.PositiveInfinity, 800, 600) == (0, 0), "NaN / infinity -> origin, never an exception");
// The same tap on a stream scaled down to 720 wide lands on the same game pixel (same aspect).
var native = RemoteParity.ClickPoint(812.0 / 1919, 300.0 / 1079, 1920, 1080);
Check(native == (812, 300), "a pixel picked on the native frame maps back to itself");
long lp = (long)RemoteParity.MouseLParam(640, 360);
Check((lp & 0xFFFF) == 640 && ((lp >> 16) & 0xFFFF) == 360, "lParam: x low word, y high word");
long big = (long)RemoteParity.MouseLParam(3839, 2159);
Check((big & 0xFFFF) == 3839 && ((big >> 16) & 0xFFFF) == 2159, "lParam holds a 4K client area");
}
// ── capabilities ────────────────────────────────────────────────────────
private static void Capabilities()
{
Section("capabilities");
var all = new AgentConfig { EnableRemoteControl = true, EnableScreenStream = true, EnableVideoStream = true };
var c = RemoteParity.Capabilities(all, iconDat: true, dungeonMaps: true, worldMap: true, characterSheets: true);
Check(c.Movement && c.CloseClient && c.Click && c.Video && c.VideoHd && c.Icons && c.Maps && c.WorldMap && c.Character,
"everything on when configured and present");
Check(!c.Act && !c.Nearby && !c.Pick && !c.Dungeon && !c.VideoMinimized, "DrakBot-only routes stay off on RynthCore");
var readOnly = new AgentConfig();
var r = RemoteParity.Capabilities(readOnly, iconDat: false, dungeonMaps: false, worldMap: false, characterSheets: false);
Check(!r.Movement && !r.CloseClient && !r.Click && !r.Video && !r.VideoHd, "a read-only agent offers no control or video");
Check(!r.Icons && !r.Maps && !r.WorldMap && !r.Character, "nothing on disk -> no icons, maps or Skills tab");
Check(r.Inventory && r.Settings && r.Runs, "the file-backed routes are always there");
var streamOnly = new AgentConfig { EnableScreenStream = true };
Check(!RemoteParity.Capabilities(streamOnly, false, false, false, false).Click, "click needs remote control as well as the stream");
Check(RemoteParity.Capabilities(readOnly, false, false, worldMap: true, false).Maps, "a world map alone lights the Map tab");
}
// ── spell table ─────────────────────────────────────────────────────────
private static byte[] SpellTableFile(params (uint Id, string Name, uint School, uint Icon, uint Category, uint Flags, uint Meta)[] spells)
{
var w = new Writer();
w.U32(0x0E00000E);
w.U16((ushort)spells.Length);
w.U16(64);
foreach (var s in spells)
{
w.U32(s.Id);
w.Obfuscated(s.Name);
w.Obfuscated("A description that is not read.");
w.U32(s.School); w.U32(s.Icon); w.U32(s.Category); w.U32(s.Flags);
w.U32(10); // base mana
w.Zero(8); // range constant, range mod
w.U32(150); // power
w.Zero(12); // economy mod, formula version, component loss
w.U32(s.Meta); w.U32(s.Id);
if (s.Meta is 1 or 12) w.Zero(16);
else if (s.Meta == 7) w.Zero(8);
w.Zero(8 * 4 + 12 + 8 + 4 + 12);
}
return w.ToArray();
}
private static void SpellTable()
{
Section("spell table parse");
byte[] raw = SpellTableFile(
(2, "Strength Self I", 4, 0x06001234, 1, 0x4 | 0x8, 1), // creature, beneficial, enchantment
(1237, "Drain Health Other I", 2, 0x06002222, 83, 0x0, 1), // life, harmful
(157, "Summon Primary Portal I", 3, 0x06003333, 200, 0x4, 7), // a portal summon (different tail)
(4305, "Incantation of Strength Self", 4, 0x06004444, 1, 0x4 | 0x8, 1));
var t = SpellTableService.Parse(raw, out int total);
Check(total == 4 && t.Count == 4, "all four spells read, including after a portal summon's shorter tail");
Check(t.TryGetValue(2, out var s) && s.Name == "Strength Self I" && s.Icon == 0x06001234 && s.Category == 1 && s.Beneficial, "name, icon, family, beneficial");
Check(t.TryGetValue(1237, out var d) && !d.Beneficial && d.School == 2, "a harmful spell is not beneficial");
Check(t.TryGetValue(4305, out var inc) && inc.Name == "Incantation of Strength Self", "the spell after the portal summon is still aligned");
Check(SpellTableService.TierFromName("Strength Self VII") == 7 && SpellTableService.TierFromName("Incantation of Strength Self") == 8
&& SpellTableService.TierFromName("Strength Self VIII") == 8 && SpellTableService.TierFromName("Aura of Defender") == 0, "tier from the name");
var cut = SpellTableService.Parse(raw[..(raw.Length - 40)], out _);
Check(cut.Count == 3, "a truncated file keeps the spells before the cut and never throws");
}
private static void Enchantments()
{
Section("enchantments for the Buffs tab");
var table = SpellTableService.Parse(SpellTableFile(
(2, "Strength Self I", 4, 0x06001234, 1, 0x4, 1),
(1237, "Drain Health Other I", 2, 0x06002222, 83, 0x0, 1)), out _);
SpellTableService.SpellInfo? Lookup(uint id) => table.TryGetValue(id, out var i) ? i : null;
var input = new List<EnchantmentIn>
{
new() { SpellId = 2, SecondsRemaining = 1800 },
new() { SpellId = 1237, SecondsRemaining = 42 },
new() { SpellId = 99999, SecondsRemaining = -1 }, // permanent, unknown to the table
new() { SpellId = 0, SecondsRemaining = 10 }, // junk
};
var outList = RemoteParity.Enchantments(input, Lookup)!;
Check(outList.Count == 3, "id 0 dropped");
Check(outList[0].SpellId == 1237 && outList[1].SpellId == 2 && outList[2].SpellId == 99999, "soonest first, permanent last");
Check(outList[1].Name == "Strength Self I" && outList[1].Family == 1 && outList[1].Tier == 1 && outList[1].IconId == 0x06001234 && outList[1].Beneficial, "named, family, tier, icon");
Check(!outList[0].Beneficial, "a debuff reads as not beneficial (the app lists it under debuffs)");
Check(outList[2].Name == "Spell 99999" && outList[2].IconId == 0 && outList[2].Beneficial && outList[2].SecondsRemaining == -1, "unknown spell: id as name, no icon, kept as a buff");
Check(RemoteParity.Enchantments(null, Lookup) == null, "no enchantments from an older plugin -> null (the app shows nothing in force)");
var before = RemoteParity.Enchantments(new() { new() { SpellId = 2, SecondsRemaining = 5 } }, _ => null)!;
Check(before[0].Name == "Spell 2", "before the table loads the countdown still works");
}
// ── what the plugin writes, read back by the agent ──────────────────────
private static void PluginStatusAdditions()
{
Section("plugin status additions read by the agent");
// A status file as the RynthRemote plugin 0.3 writes it: the engine object + bot + the two additions.
const string file = """
{"schema":"rynthcore.client-status/1","pid":8808,"character":"Drakkon","inWorld":true,
"landblock":"0000A9B4","indoor":false,"area":"A9B4","bot":null,
"enchantments":[{"spellId":1237,"secondsRemaining":42},{"spellId":2,"secondsRemaining":1800},{"spellId":4305,"secondsRemaining":-1}],
"opos":{"cell":"A9B40031","indoor":false,"wx":32549.12,"wy":34620.5,"z":42.03,"heading":271.5}}
""";
var m = JsonSerializer.Deserialize(file, AgentJsonContext.Default.StatusFileModel)!;
Check(m.Enchantments is { Count: 3 } && m.Enchantments[0].SpellId == 1237 && m.Enchantments[2].SecondsRemaining == -1, "enchantments parsed");
Check(m.Opos is { Wx: 32549.12, Wy: 34620.5, Heading: 271.5 } && m.Opos.Cell == "A9B40031", "outdoor position parsed");
var old = JsonSerializer.Deserialize("""{"schema":"rynthcore.client-status/1","pid":1,"landblock":"","indoor":false}""", AgentJsonContext.Default.StatusFileModel)!;
Check(old.Enchantments == null && old.Opos == null, "an older plugin's file still reads (fields absent)");
// The world map pixel for that position: 32549.12/24 = 1356.2, 2040 - 34620.5/24 = 597.5.
var (px, py) = WorldMapService.ToPixel(m.Opos!.Wx, m.Opos.Wy);
Check(Math.Abs(px - 1356.21) < 0.01 && Math.Abs(py - 597.48) < 0.01, "world map pixel for the outdoor position");
}
private static void PayloadJsonNames()
{
Section("JSON names the phone reads");
var payload = new AggregatePayload
{
Host = "PC", ClientCount = 1,
Capabilities = RemoteParity.Capabilities(new AgentConfig { EnableRemoteControl = true, EnableScreenStream = true }, true, true, true, true),
Clients =
{
new ClientStatus
{
Pid = 8808, Landblock = RemoteParity.LandblockFull("00005A48"), Indoor = true, Heading = 90,
Enchantments = new() { new EnchantmentOut { SpellId = 2, Name = "Strength Self I", SecondsRemaining = 1800, IconId = 0x06001234 } },
},
},
};
string json = Encoding.UTF8.GetString(JsonSerializer.SerializeToUtf8Bytes(payload, AgentJsonContext.Default.AggregatePayload));
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
Check(root.TryGetProperty("capabilities", out var caps) && caps.GetProperty("click").GetBoolean() && caps.GetProperty("worldMap").GetBoolean()
&& caps.GetProperty("character").GetBoolean() && !caps.GetProperty("act").GetBoolean(), "capabilities: click, worldMap, character, act");
var c = root.GetProperty("clients")[0];
Check(c.GetProperty("landblock").GetString() == "5A480000", "client landblock in full form");
var e = c.GetProperty("enchantments")[0];
Check(e.GetProperty("spellId").GetUInt32() == 2 && e.GetProperty("name").GetString() == "Strength Self I"
&& e.GetProperty("secondsRemaining").GetDouble() == 1800 && e.GetProperty("iconId").GetUInt32() == 0x06001234
&& e.TryGetProperty("family", out _) && e.TryGetProperty("tier", out _) && e.TryGetProperty("beneficial", out _) && e.TryGetProperty("school", out _),
"enchantment entry has DrakBot's field names");
Check(c.GetProperty("heading").GetDouble() == 90, "heading");
}
// ── world map ───────────────────────────────────────────────────────────
private static byte[] Landblock(ushort terrainWord, byte height, Func<int, byte>? heightAt = null)
{
var b = new byte[8 + 81 * 2 + 81];
for (int i = 0; i < 81; i++)
{
BitConverter.GetBytes(terrainWord).CopyTo(b, 8 + i * 2);
b[8 + 162 + i] = heightAt?.Invoke(i) ?? height;
}
return b;
}
private static void WorldMap()
{
Section("world map render");
// Landblock 0x0000 (south-west corner) is snow; 0xFE00 (south-east) grassland with a road word;
// 0x00FE (north-west) is sand; everything else open sea.
ushort snow = 15 << 2, grass = 1 << 2, road = (1 << 2) | 1, sand = 10 << 2;
var blocks = new Dictionary<int, byte[]>
{
[0x0000] = Landblock(snow, 10),
[0xFE00] = Landblock(road, 10),
[0x00FE] = Landblock(sand, 10),
[0x8080] = Landblock(grass, 0, i => (byte)(i / 9 * 4)), // rising to the east: lit from the north-west
};
byte[] rgb = WorldMapService.Render(lb => blocks.TryGetValue(lb, out var r) ? r : null, out int found);
int size = WorldMapService.Size;
Check(size == 2040 && rgb.Length == size * size * 3, "2040 x 2040 RGB");
Check(found == 4, "four landblocks drawn");
(byte R, byte G, byte B) Px(int x, int y) { int o = (y * size + x) * 3; return (rgb[o], rgb[o + 1], rgb[o + 2]); }
Check(Px(0, size - 1) == (0xF0, 0xF4, 0xF7), "south-west corner is snow, at the bottom-left (north up)");
Check(Px(0, 0) == (0xD8, 0xC4, 0x8A), "landblock 0x00FE (north) is at the top: sand");
Check(Px(0xFE * 8, size - 1) == (0xA8, 0x93, 0x6C), "a road word draws as road");
Check(Px(1000, 1000) == (0x1F, 0x4A, 0x78), "no landblock -> sea");
var g = Px(0x80 * 8 + 3, size - 1 - (0x80 * 8 + 3));
Check(g.G > 0x8B, "a slope rising east is lit brighter than flat grass");
var (wx, wy) = (0x80 * 192.0 + 72, 0x80 * 192.0 + 72); // that cell's corner, in world units
var (mx, my) = WorldMapService.ToPixel(wx, wy);
Check((int)mx == 0x80 * 8 + 3 && (int)Math.Ceiling(my) - 1 == size - 1 - (0x80 * 8 + 3), "ToPixel lands on the cell that was painted");
}
// ── travel ──────────────────────────────────────────────────────────────
private const string AtlasJson = """
{"version":1,"generated":"2026-10-01T09:59:37Z","locations":[
{"name":"Holtburg","type":"Town","cell":"A9B40001","place":"outdoor","ns":42.10,"ew":33.60,"id":1},
{"name":"Holtburg Dungeon","type":"Dungeon","cell":"A9B20001","place":"outdoor","ns":43.57,"ew":32.98,"id":2},
{"name":"Holtburg Portal Shrine","type":"Portal","cell":"A9B40010","place":"outdoor","ns":42.20,"ew":33.50,"id":3,"dest":{"name":"Town Network"}},
{"name":"Barkeeper Holtburg","type":"NPC","cell":"A9B4011A","place":"outdoor","ns":42.15,"ew":33.62,"id":4},
{"name":"Secret Room of Holtburg","type":"Landmark","cell":"01E901AD","place":"dungeon","id":5},
{"name":"Shoushi","type":"Town","cell":"DE510001","place":"outdoor","ns":-33.50,"ew":72.80,"id":6},
{"name":"Lifestone","type":"Lifestone","cell":"A9B40020","place":"outdoor","ns":42.05,"ew":33.55,"id":7},
{"name":"Closed Mine","type":"Dungeon","place":"outdoor","ns":40.0,"ew":30.0,"id":8,"closed":true}
]}
""";
private static void NavSearch()
{
Section("travel search (RynthNav's Atlas ranking)");
var (places, generated) = NavAtlasService.Parse(AtlasJson);
Check(places.Count == 8 && generated == "2026-10-01T09:59:37Z", "Atlas read");
var hits = NavAtlasService.Search(places, "holtburg", null, null, null, 40);
Check(hits.Select(h => h.Place.Name).SequenceEqual(new[] { "Holtburg", "Holtburg Dungeon", "Holtburg Portal Shrine", "Secret Room of Holtburg", "Barkeeper Holtburg" }),
"exact name, then starts-with by type (town, dungeon, portal), then whole-word, then inside a name - as in game");
Check(NavAtlasService.Search(places, "holtburg", "Dungeon", null, null, 40).Single().Place.Name == "Holtburg Dungeon", "type filter");
Check(NavAtlasService.Search(places, "h", null, null, null, 40).Count == 0, "one letter is too little to search");
Check(NavAtlasService.Search(places, "holt dung", null, null, null, 40).Single().Place.Name == "Holtburg Dungeon", "every word somewhere in the name");
var near = NavAtlasService.Search(places, "holtburg", null, 42.10, 33.60, 40);
Check(near[0].Distance == 0 && near[1].Distance is > 300 and < 400, "distance from the character, in RynthNav's units (240 a degree)");
Check(near.Single(h => h.Place.Name == "Secret Room of Holtburg").Distance == null, "a place inside a dungeon has no distance");
Check(NavAtlasService.Search(places, "holtburg", null, null, null, 2).Count == 2, "max");
Check(places.Single(p => p.Name == "Lifestone").Area == "near Holtburg" && places.Single(p => p.Name == "Holtburg").Area == "", "area = nearest town (a town is its own)");
using var doc = JsonDocument.Parse(NavAtlasService.SearchJson(NavAtlasService.Search(places, "holtburg", null, 42.10, 33.60, 40), "holtburg", places.Count, generated));
var root = doc.RootElement;
Check(root.GetProperty("schema").GetString() == "rynthcore.nav-search/1" && root.GetProperty("count").GetInt32() == 5, "search JSON");
var r0 = root.GetProperty("results")[0];
Check(r0.GetProperty("name").GetString() == "Holtburg" && r0.GetProperty("type").GetString() == "Town" && r0.GetProperty("coords").GetString() == "42.1N, 33.6E"
&& r0.GetProperty("ns").GetDouble() == 42.1 && r0.GetProperty("canTravel").GetBoolean() && r0.GetProperty("distance").GetDouble() == 0, "a result: name, type, coords, distance, can travel");
var secret = root.GetProperty("results").EnumerateArray().Single(e => e.GetProperty("name").GetString() == "Secret Room of Holtburg");
Check(!secret.GetProperty("canTravel").GetBoolean() && !secret.TryGetProperty("ns", out _) && secret.GetProperty("where").GetString() == "dungeon", "inside a dungeon: listed, can't travel (RynthNav won't guess)");
var closed = NavAtlasService.SearchJson(NavAtlasService.Search(places, "closed", null, null, null, 5), "closed", 8, "");
Check(closed.Contains("\"closed\":true") && closed.Contains("\"canTravel\":false"), "a closed place can't be travelled to");
Check(NavAtlasService.Fmt(-33.5, 72.8) == "33.5S, 72.8E", "coordinates like RynthNav's");
var (wns, wew) = NavAtlasService.FromWorld((33.6 * 10 + 1019.5) * 24, (42.1 * 10 + 1019.5) * 24);
Check(Math.Abs(wns - 42.1) < 1e-9 && Math.Abs(wew - 33.6) < 1e-9, "world units -> coordinates");
var cfg = new AgentConfig { EnableRemoteControl = true };
Check(RemoteParity.Capabilities(cfg, false, false, false, false, navAtlas: true).Travel, "travel on with the Atlas and remote control");
Check(!RemoteParity.Capabilities(new AgentConfig(), false, false, false, false, navAtlas: true).Travel, "no remote control -> no travel (the Go would be refused)");
Check(!RemoteParity.Capabilities(cfg, false, false, false, false, navAtlas: false).Travel, "no Atlas -> no travel");
}
private static void TravelStatus()
{
Section("travel status");
var sent = new TravelIn { Dest = "Holtburg", Ns = 42.1, Ew = 33.6, State = "sent", SentAt = DateTimeOffset.UtcNow };
var chat = new List<ChatLine>
{
new() { Text = "[RynthNav] walking to Holtburg (2.1k yd) — /rnav stop to cancel" },
new() { Text = "Drakkon says, \"hi\"" },
};
// Standing 1 degree south of Holtburg: 240 units left.
var t = RemoteParity.Travel(sent, chat, indoor: false, wx: (33.6 * 10 + 1019.5) * 24, wy: (41.1 * 10 + 1019.5) * 24)!;
Check(t.State == "sent" && t.Note == "walking to Holtburg (2.1k yd) — /rnav stop to cancel", "RynthNav's latest note, tag removed");
Check(t.Distance == 240, "distance left from the character's position");
chat.Add(new ChatLine { Text = "[RynthNav] Arrived at Holtburg." });
Check(RemoteParity.Travel(sent, chat, false, 1, 1)!.State == "arrived", "RynthNav's arrival note -> arrived");
chat.Add(new ChatLine { Text = "[RynthNav] Arrived at Shoushi." });
Check(RemoteParity.Travel(sent, chat, false, 1, 1)!.State == "sent", "arriving somewhere else doesn't count");
Check(RemoteParity.Travel(sent, chat, indoor: true, 1, 1)!.Distance == null, "no distance indoors");
Check(RemoteParity.Travel(null, chat, false, 1, 1) == null && RemoteParity.Travel(new TravelIn(), chat, false, 1, 1) == null, "no travel yet -> null");
var stopped = RemoteParity.Travel(new TravelIn { Dest = "Holtburg", State = "stopped" }, null, false, 0, 0)!;
Check(stopped.State == "stopped" && stopped.Note == "" && stopped.Distance == null, "stopped, no chat, no position");
// The plugin's status.json entry, read back.
var m = JsonSerializer.Deserialize("""{"schema":"rynthcore.client-status/1","pid":1,"travel":{"dest":"Holtburg","ns":42.1,"ew":33.6,"state":"sent","detail":"","sentAt":"2026-10-05T09:00:00Z"}}""",
AgentJsonContext.Default.StatusFileModel)!;
Check(m.Travel is { Dest: "Holtburg", State: "sent", Ns: 42.1 } && m.Travel.SentAt == new DateTimeOffset(2026, 10, 5, 9, 0, 0, TimeSpan.Zero), "plugin travel entry parsed");
}
private static void RealAtlas(string path)
{
Section("real Atlas (read-only) " + path);
var (places, generated) = NavAtlasService.Parse(File.ReadAllText(path));
Console.WriteLine($" {places.Count:N0} places, generated {generated}");
Check(places.Count > 5000, "the Atlas has thousands of places");
var hits = NavAtlasService.Search(places, "holtburg", null, 42.1, 33.6, 10);
Console.WriteLine(" " + string.Join(" | ", hits.Select(h => $"{h.Place.Name} ({h.Place.Type}{(h.Place.Area.Length > 0 ? ", " + h.Place.Area : "")}{(h.Distance is double d ? $", {d:0} yd" : "")})")));
Check(hits.Count > 0 && hits[0].Place.Name == "Holtburg" && hits[0].Place.Type == "Town", "\"holtburg\" finds the town first");
}
private static void RealSpellTable(string portal)
{
Section("real spell table (read-only) " + portal);
using var db = new RynthCore2.TerrainData.DatDatabase();
Check(db.Open(portal), "portal.dat opens");
byte[]? raw = db.GetFileData(0x0E00000E);
Check(raw != null, "spell table present");
if (raw == null) return;
var t = SpellTableService.Parse(raw, out int total);
Console.WriteLine($" {t.Count:N0} of {total:N0} spells");
Check(t.Count == total && total > 5000, "every spell parsed");
Check(t.TryGetValue(2, out var s) && s.Name == "Strength Self I" && s.Beneficial && s.Icon != 0, "spell 2 is Strength Self I, beneficial, with an icon");
}
private static void RealWorldMap(string cell, string? outFile)
{
Section("real world map (read-only) " + cell);
var sw = System.Diagnostics.Stopwatch.StartNew();
using var db = new RynthCore2.TerrainData.DatDatabase();
Check(db.Open(cell), "cell.dat opens");
Console.WriteLine($" indexed in {sw.Elapsed.TotalSeconds:0.0}s");
byte[] rgb = WorldMapService.Render(lb => db.GetFileData(((uint)lb << 16) | 0xFFFF), out int found);
Console.WriteLine($" {found:N0} landblocks in {sw.Elapsed.TotalSeconds:0.0}s");
Check(found > 20000, "most of Dereth's landblocks found");
if (outFile != null)
{
string dir = Path.Combine(Path.GetTempPath(), "rc-worldmap-test-" + Guid.NewGuid().ToString("N"));
var svc = new WorldMapService(cell, dir);
byte[]? jpg = null;
for (int i = 0; i < 600 && (jpg = svc.GetJpeg()) == null; i++) Thread.Sleep(200);
Check(jpg != null, "the service renders and caches a JPEG");
if (jpg != null) { File.WriteAllBytes(outFile, jpg); Console.WriteLine($" {jpg.Length / 1024:N0} KB -> {outFile}"); }
try { Directory.Delete(dir, true); } catch { }
}
}
// ── helpers ─────────────────────────────────────────────────────────────
private sealed class Writer
{
private readonly MemoryStream _ms = new();
public void U32(uint v) => _ms.Write(BitConverter.GetBytes(v));
public void U16(ushort v) => _ms.Write(BitConverter.GetBytes(v));
public void Zero(int n) => _ms.Write(new byte[n]);
public void Obfuscated(string s)
{
byte[] b = Encoding.Latin1.GetBytes(s);
U16((ushort)b.Length);
foreach (byte x in b) _ms.WriteByte((byte)((x >> 4) | (x << 4)));
while (_ms.Length % 4 != 0) _ms.WriteByte(0);
}
public byte[] ToArray() => _ms.ToArray();
}
private static string? Arg(string[] args, string name)
{
int i = Array.IndexOf(args, name);
return i >= 0 && i + 1 < args.Length ? args[i + 1] : null;
}
// ── raise (Skills tab "+") ──────────────────────────────────────────────
private static void RaiseCommand()
{
Section("raise command (POST /command action raise)");
var control = new AgentConfig { EnableRemoteControl = true };
Check(RemoteParity.Capabilities(control, false, false, false, characterSheets: true, raiseXp: true).RaiseXp, "raiseXp on: control + a sheet + a client that can");
Check(!RemoteParity.Capabilities(new AgentConfig(), false, false, false, true, raiseXp: true).RaiseXp, "off without remote control");
Check(!RemoteParity.Capabilities(control, false, false, false, true, raiseXp: false).RaiseXp, "off when no client can (old engine or plugin)");
Check(!RemoteParity.Capabilities(control, false, false, false, characterSheets: false, raiseXp: true).RaiseXp, "off without character sheets (nothing to show costs from)");
var clients = new Dictionary<int, bool> { [8808] = true, [9100] = false };
int code = RemoteParity.CheckRaise(8808, """{"kind":"attribute","id":5,"count":1,"cost":1234567,"nonce":"k3f9","extra":"dropped"}""", clients, out string norm, out string err);
Check(code == 202 && norm == """{"kind":"attribute","id":5,"count":1,"cost":1234567,"nonce":"k3f9"}""", "accepted and rewritten in the fixed shape (extra members dropped)");
code = RemoteParity.CheckRaise(8808, """{"kind":"Vital","id":"Stamina","count":10,"cost":42}""", clients, out norm, out _);
Check(code == 202 && norm == """{"kind":"vital","id":"stamina","count":10,"cost":42,"nonce":""}""", "vital by name, lower-cased");
code = RemoteParity.CheckRaise(8808, """{"kind":"train","id":22,"cost":6,"count":77}""", clients, out norm, out _);
Check(code == 202 && norm.Contains("\"count\":1"), "train: count forced to 1");
Check(RemoteParity.CheckRaise(1234, """{"kind":"attribute","id":5,"cost":1}""", clients, out _, out err) == 404 && err == "unknown client", "a pid the agent doesn't read -> 404");
Check(RemoteParity.CheckRaise(9100, """{"kind":"attribute","id":5,"cost":1}""", clients, out _, out err) == 409 && err.Contains("plugin API 79"), "a client without raising -> 409 with why");
Check(RemoteParity.CheckRaise(8808, """{"kind":"attribute","id":5,"count":1}""", clients, out _, out err) == 400 && err.Contains("confirmed cost"), "no confirmed cost -> 400");
Check(RemoteParity.CheckRaise(8808, """{"kind":"attribute","id":5,"cost":0}""", clients, out _, out _) == 400, "cost 0 -> 400");
Check(RemoteParity.CheckRaise(8808, """{"kind":"attribute","id":5,"cost":4294967296}""", clients, out _, out _) == 400, "cost over 32 bits -> 400");
Check(RemoteParity.CheckRaise(8808, """{"kind":"attribute","id":9,"cost":1}""", clients, out _, out _) == 400
&& RemoteParity.CheckRaise(8808, """{"kind":"vital","id":2,"cost":1}""", clients, out _, out _) == 400
&& RemoteParity.CheckRaise(8808, """{"kind":"skill","id":"34","cost":1}""", clients, out _, out _) == 400, "bad ids -> 400");
Check(RemoteParity.CheckRaise(8808, """{"kind":"skill","id":34,"count":101,"cost":1}""", clients, out _, out _) == 400
&& RemoteParity.CheckRaise(8808, """{"kind":"skill","id":34,"count":0,"cost":1}""", clients, out _, out _) == 400, "count out of 1..100 -> 400");
Check(RemoteParity.CheckRaise(8808, """{"kind":"luminance","id":1,"cost":1}""", clients, out _, out _) == 400
&& RemoteParity.CheckRaise(8808, "not json", clients, out _, out _) == 400
&& RemoteParity.CheckRaise(8808, "", clients, out _, out _) == 400, "unknown kind / junk / empty -> 400");
code = RemoteParity.CheckRaise(8808, "{\"kind\":\"skill\",\"id\":34,\"cost\":5,\"nonce\":\"a\\\"},{\\\"x\"}", clients, out norm, out _);
Check(code == 202 && norm.EndsWith("\"nonce\":\"ax\"}") && JsonDocument.Parse(norm).RootElement.GetProperty("nonce").GetString() == "ax", "a nonce can't break out of its string");
// The plugin's flag reaches the client and the phone's JSON.
var m = JsonSerializer.Deserialize("""{"schema":"rynthcore.client-status/1","pid":1,"raiseXp":true}""", AgentJsonContext.Default.StatusFileModel)!;
Check(m.RaiseXp, "status.json raiseXp read");
var old = JsonSerializer.Deserialize("""{"schema":"rynthcore.client-status/1","pid":1}""", AgentJsonContext.Default.StatusFileModel)!;
Check(!old.RaiseXp, "an older plugin: no raiseXp -> false");
string json = JsonSerializer.Serialize(new AggregatePayload
{
Capabilities = RemoteParity.Capabilities(control, false, false, false, true, raiseXp: true),
Clients = { new ClientStatus { Pid = 1, RaiseXp = true } },
}, AgentJsonContext.Default.AggregatePayload);
using var doc = JsonDocument.Parse(json);
Check(doc.RootElement.GetProperty("capabilities").GetProperty("raiseXp").GetBoolean()
&& doc.RootElement.GetProperty("clients")[0].GetProperty("raiseXp").GetBoolean(), "capabilities.raiseXp and clients[].raiseXp in the payload");
}
// The flicker's back-end half: a status file caught mid-write must not drop its client from a snapshot,
// and a read must not stop the plugin's atomic replace.
private static void StatusFileReads()
{
Section("status files: shared reads and the last good parse");
string dir = Path.Combine(Path.GetTempPath(), "statusagent-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
try
{
string path = Path.Combine(dir, "RynthCore.25580.status.json");
File.WriteAllText(path, """{"schema":"rynthcore.client-status/1","pid":25580,"character":"Lucy McJuicy","moveProto":2}""");
static StatusFileModel? Parse(string t) => JsonSerializer.Deserialize(t, AgentJsonContext.Default.StatusFileModel);
var t0 = new DateTime(2026, 10, 5, 11, 21, 21, DateTimeKind.Utc);
var m = StatusFileCache.Read(path, Parse, t0);
Check(m?.Character == "Lucy McJuicy" && m.MoveProto == 2, "a good file reads (and carries moveProto)");
// What the agent used to see: the plugin's in-place fallback caught half-written.
File.WriteAllText(path, """{"schema":"rynthcore.client-status/1","pid":25580,"charac""");
var torn = StatusFileCache.Read(path, Parse, t0.AddMilliseconds(60));
Check(torn != null && ReferenceEquals(torn, m), "a torn file answers the last good parse - the client stays in the snapshot");
File.WriteAllText(path, "");
Check(StatusFileCache.Read(path, Parse, t0.AddMilliseconds(120)) is { Character: "Lucy McJuicy" }, "an empty file too");
Check(StatusFileCache.Read(path, Parse, t0.AddSeconds(3.5)) == null, "but not for longer than 3 s (a file that stays broken is a real problem)");
Check(StatusFileCache.Read(Path.Combine(dir, "missing.json"), Parse, t0) == null, "a missing file with no history is just missing");
// While the agent has the file open, the plugin's replace (File.Move over it) fails on Windows
// whatever the read's sharing (MoveFileEx won't replace an open file). RynthRemote 0.3 then
// overwrote the file in place, which is what tore it; 0.4 skips that one write instead. The two
// halves the agent relies on: the replace really fails mid-read (so skipping is needed), and the
// shared read doesn't block an old plugin's in-place rewrite (its torn result is covered above).
File.WriteAllText(path, """{"pid":1,"character":"old"}""");
using (var reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
{
string tmp = path + ".tmp";
File.WriteAllText(tmp, """{"pid":1,"character":"new"}""");
bool moved;
try { File.Move(tmp, path, overwrite: true); moved = true; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { moved = false; }
Check(!moved, "a replace fails while the agent reads - why RynthRemote 0.4 skips that write instead of overwriting in place");
try { File.Delete(tmp); } catch { }
bool rewrote;
try { File.WriteAllText(path, """{"pid":1,"character":"inplace"}"""); rewrote = true; } catch (IOException) { rewrote = false; }
Check(rewrote, "an old plugin's in-place rewrite isn't blocked by the agent's read (no more 'status write failed')");
}
Check(StatusFileCache.ReadAllTextShared(path).Contains("inplace"), "and the next read sees it");
StatusFileCache.Read(path, Parse, t0);
StatusFileCache.ForgetAllBut(Array.Empty<string>());
Check(StatusFileCache.CountForTests == 0, "files that are gone are forgotten");
}
finally { try { Directory.Delete(dir, true); } catch { } }
}
private static void MoveProtocol()
{
Section("hold-to-move protocol passes through");
var payload = new AggregatePayload { Host = "PC", ClientCount = 2, Clients = { new ClientStatus { Pid = 1, MoveProto = 2 }, new ClientStatus { Pid = 2 } } };
using var doc = JsonDocument.Parse(JsonSerializer.SerializeToUtf8Bytes(payload, AgentJsonContext.Default.AggregatePayload));
var cs = doc.RootElement.GetProperty("clients");
Check(cs[0].GetProperty("moveProto").GetInt32() == 2, "a RynthRemote 0.4 client says moveProto 2");
Check(!cs[1].TryGetProperty("moveProto", out var mp) || mp.GetInt32() == 0, "an older plugin's client: 0 or absent, the phone uses the old protocol");
var old = JsonSerializer.Deserialize("""{"pid":1}""", AgentJsonContext.Default.StatusFileModel)!;
Check(old.MoveProto == 0, "a status file without the field reads as 0");
}
private static void Section(string title) => Console.WriteLine("\n== " + title);
private static void Check(bool ok, string what)
{
_checks++;
if (!ok) _failed++;
Console.WriteLine((ok ? " ok " : " FAIL ") + what);
}
}

View file

@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the StatusAgent's DrakRemote parity pieces (src\RynthCore.StatusAgent, compiled in):
landblock ids in the form DrakRemote matches, tap-to-click coordinate mapping, the capabilities block,
enchantments named from the spell table (a hand-made SpellTable file), the world map renderer (made-up
landblocks), the RynthRemote plugin's status additions read back, and the JSON names the phone expects.
No game, no network, no token. Optional: pass a portal.dat / cell.dat path to also read the real ones
(read-only).
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>StatusAgentTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Drawing.Common" Version="9.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.StatusAgent\AgentConfig.cs" Link="Agent\AgentConfig.cs" />
<Compile Include="..\..\src\RynthCore.StatusAgent\AgentLog.cs" Link="Agent\AgentLog.cs" />
<Compile Include="..\..\src\RynthCore.StatusAgent\Models.cs" Link="Agent\Models.cs" />
<Compile Include="..\..\src\RynthCore.StatusAgent\RemoteParity.cs" Link="Agent\RemoteParity.cs" />
<Compile Include="..\..\src\RynthCore.StatusAgent\SpellTableService.cs" Link="Agent\SpellTableService.cs" />
<Compile Include="..\..\src\RynthCore.StatusAgent\WorldMapService.cs" Link="Agent\WorldMapService.cs" />
<Compile Include="..\..\src\RynthCore.StatusAgent\NavAtlasService.cs" Link="Agent\NavAtlasService.cs" />
<Compile Include="..\..\src\RynthCore.StatusAgent\Dat\DatDatabase.cs" Link="Agent\Dat\DatDatabase.cs" />
<Compile Include="..\..\src\RynthCore.StatusAgent\StatusFileCache.cs" Link="Agent\StatusFileCache.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,214 @@
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.UI.ScriptWindows;
using RynthCore.PluginSdk;
namespace TrainingCostTests;
/// <summary>
/// Spending experience, offline: the portal XpTable as the engine reads it, the XP a raise of
/// n ranks costs (what the engine sends and the phone shows), and the checks a raise from the
/// plugin API must pass before anything is sent.
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static int Main(string[] args)
{
string dat = FindDat(args.Length > 0 ? args[0] : @"C:\Turbine\Asheron's Call");
XpTableData? t = RealTable(dat);
if (t != null)
{
TableShape(t);
CostsOnTheRealTable(t);
AffordableMatchesALinearScan(t);
RaiseChecks(t);
}
TrainChecks();
ParserRefusesJunk();
SdkNumbersMatch();
Console.WriteLine();
Console.WriteLine(_failed == 0 && _checks > 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks} checks failed)");
return _failed == 0 && _checks > 0 ? 0 : 1;
}
private static string FindDat(string arg)
{
if (File.Exists(arg)) return arg;
foreach (string name in new[] { "client_portal.dat", "portal.dat" })
{
string p = Path.Combine(arg, name);
if (File.Exists(p)) return p;
}
return Path.Combine(arg, "client_portal.dat");
}
private static XpTableData? RealTable(string path)
{
Section("the XpTable (0x0E000018) from " + path);
using AcDatFile? dat = AcDatFile.Open(path, out string why);
Check(dat != null, "portal dat opens read-only" + (dat == null ? ": " + why : ""));
if (dat == null) return null;
byte[]? raw = dat.Read(0x0E000018, 1024 * 1024);
Check(raw != null && raw.Length > 100, "XpTable present");
if (raw == null) return null;
bool ok = TrainingCosts.TryParseXpTable(raw, out XpTableData t);
Check(ok, "XpTable parses");
Console.WriteLine($" ranks: attributes {t.AttributeXp.Length - 1}, vitals {t.VitalXp.Length - 1}, trained {t.TrainedXp.Length - 1}, specialized {t.SpecializedXp.Length - 1}, levels {t.LevelXp.Length - 1}");
return ok ? t : null;
}
private static void TableShape(XpTableData t)
{
Section("table shape (retail: 190 attribute, 196 vital, 208 trained, 226 specialized ranks, 275 levels)");
Check(t.AttributeXp.Length == 191 && t.VitalXp.Length == 197 && t.TrainedXp.Length == 209 && t.SpecializedXp.Length == 227,
"rank counts");
Check(t.LevelXp.Length == 276, "level count");
foreach (var (name, a) in Tables(t))
{
Check(a[0] == 0, name + ": rank 0 costs nothing");
bool rising = true;
for (int i = 1; i < a.Length; i++) if (a[i] <= a[i - 1]) rising = false;
Check(rising, name + ": strictly rising (every rank costs something)");
}
Check(t.AttributeXp[^1] == 4_019_438_644u, $"attribute top = 4,019,438,644 XP (retail max attribute XP) - got {t.AttributeXp[^1]:N0}");
Check(t.SpecializedXp[^1] == 4_100_490_438u, $"specialized top = 4,100,490,438 XP - got {t.SpecializedXp[^1]:N0}");
}
private static void CostsOnTheRealTable(XpTableData t)
{
Section("costs: table[ranks + n] - spent");
uint[] a = t.AttributeXp;
Check(TrainingCosts.CostOf(a, 0, 0, 1) == a[1], "+1 from rank 0 = table[1]");
Check(TrainingCosts.CostOf(a, 50, a[50], 1) == a[51] - a[50], "+1 from rank 50, nothing extra spent");
Check(TrainingCosts.CostOf(a, 50, a[50] + 1000, 1) == a[51] - a[50] - 1000, "XP already put toward the next rank comes off");
Check(TrainingCosts.CostOf(a, 50, a[50], 10) == a[60] - a[50], "+10 = table[ranks + 10] - spent");
// +10 equals ten +1s in a row (the server raises as far as the XP covers).
foreach (var (name, tab) in Tables(t))
{
bool same = true;
for (uint r = 0; r + 10 < tab.Length; r += 7)
{
uint spent = tab[r] + (r % 3 == 0 ? 0u : Math.Min(5u, tab[r + 1] - tab[r] - 1));
long ten = TrainingCosts.CostOf(tab, r, spent, 10);
long chained = 0; uint rr = r, sp = spent;
for (int k = 0; k < 10; k++) { long c = TrainingCosts.CostOf(tab, rr, sp, 1); chained += c; sp = (uint)(sp + c); rr++; }
if (ten != chained) same = false;
}
Check(same, name + ": +10 = ten +1s");
}
int top = a.Length - 1;
Check(TrainingCosts.CostOf(a, (uint)top, a[top], 1) == -1 && TrainingCosts.IsMax(a, (uint)top), "at the top: -1, IsMax");
Check(TrainingCosts.CostOf(a, (uint)top - 5, a[top - 5], 10) == -1 && TrainingCosts.CostOf(a, (uint)top - 5, a[top - 5], 5) > 0,
"+10 with five ranks left: -1 (+5 still prices)");
Check(TrainingCosts.RanksLeft(a, (uint)top - 5) == 5 && TrainingCosts.RanksLeft(a, (uint)top) == 0, "ranks left");
Check(TrainingCosts.CostOf(a, 0, 0, 0) == 0, "+0 costs 0");
// A few numbers for the report / the phone's first test.
Console.WriteLine($" attribute rank 10 -> 11: {TrainingCosts.CostOf(a, 10, a[10], 1):N0} XP; +10: {TrainingCosts.CostOf(a, 10, a[10], 10):N0} XP");
Console.WriteLine($" vital rank 10 -> 11: {TrainingCosts.CostOf(t.VitalXp, 10, t.VitalXp[10], 1):N0} XP");
Console.WriteLine($" trained rank 10 -> 11: {TrainingCosts.CostOf(t.TrainedXp, 10, t.TrainedXp[10], 1):N0}; specialized: {TrainingCosts.CostOf(t.SpecializedXp, 10, t.SpecializedXp[10], 1):N0}");
Console.WriteLine($" attribute rank 180 -> 181: {TrainingCosts.CostOf(a, 180, a[180], 1):N0} XP");
}
private static void AffordableMatchesALinearScan(XpTableData t)
{
Section("affordable ranks (binary search) = a linear scan");
var rnd = new Random(79);
bool all = true;
foreach (var (_, tab) in Tables(t))
for (int i = 0; i < 400; i++)
{
uint r = (uint)rnd.Next(0, tab.Length);
uint spent = tab[r] + (r + 1 < tab.Length ? (uint)rnd.Next(0, (int)Math.Min(int.MaxValue, tab[r + 1] - tab[r])) : 0u);
long have = rnd.Next(4) switch { 0 => 0, 1 => rnd.Next(), 2 => (long)rnd.Next() * 50, _ => long.MaxValue / 4 };
int lin = 0;
for (int n = 1; ; n++)
{
long c = TrainingCosts.CostOf(tab, r, spent, n);
if (c < 0 || c > have) break;
lin = n;
}
if (TrainingCosts.Affordable(tab, r, spent, have) != lin) all = false;
}
Check(all, "1,600 random ranks / XP amounts on the four tables");
Check(TrainingCosts.Affordable(t.AttributeXp, 0, 0, long.MaxValue) == t.AttributeXp.Length - 1, "unlimited XP buys every rank");
}
private static void RaiseChecks(XpTableData t)
{
Section("the checks before a raise is sent (CheckRaise)");
uint[] a = t.AttributeXp;
long c1 = TrainingCosts.CostOf(a, 100, a[100], 1);
Check(TrainingCosts.CheckRaise(a, 100, a[100], c1, 1, c1, out long sent) == RaiseStatus.Sent && sent == c1, "exactly enough XP, confirmed cost -> Sent with that XP");
Check(TrainingCosts.CheckRaise(a, 100, a[100], c1 - 1, 1, c1, out _) == RaiseStatus.NotEnough, "one XP short -> NotEnough");
Check(TrainingCosts.CheckRaise(a, 100, a[100], long.MaxValue, 1, c1 + 1, out _) == RaiseStatus.CostChanged, "a different confirmed cost -> CostChanged (nothing sent)");
Check(TrainingCosts.CheckRaise(a, 101, a[101], long.MaxValue, 1, c1, out _) == RaiseStatus.CostChanged, "the stat moved on since the user looked -> CostChanged");
Check(TrainingCosts.CheckRaise(a, 100, a[100], long.MaxValue, 1, 0, out sent) == RaiseStatus.Sent && sent == c1, "0 = don't compare");
long c10 = TrainingCosts.CostOf(a, 100, a[100], 10);
Check(TrainingCosts.CheckRaise(a, 100, a[100], long.MaxValue, 10, c10, out sent) == RaiseStatus.Sent && sent == c10, "+10");
int top = a.Length - 1;
Check(TrainingCosts.CheckRaise(a, (uint)top, a[top], long.MaxValue, 1, 0, out _) == RaiseStatus.NotRaisable, "top rank -> NotRaisable");
Check(TrainingCosts.CheckRaise(a, (uint)top - 3, a[top - 3], long.MaxValue, 10, 0, out _) == RaiseStatus.NotRaisable, "+10 past the top -> NotRaisable");
Check(TrainingCosts.CheckRaise(null, 0, 0, long.MaxValue, 1, 0, out _) == RaiseStatus.NotRaisable, "untrained skill (no table) -> NotRaisable");
Check(TrainingCosts.TableFor(t, 3, 1) == null && TrainingCosts.TableFor(t, 3, 0) == null, "untrained / unknown skill: no table");
Check(TrainingCosts.TableFor(t, 3, 2) == t.TrainedXp && TrainingCosts.TableFor(t, 3, 3) == t.SpecializedXp, "trained / specialized tables");
Check(TrainingCosts.TableFor(t, 1, 0) == t.AttributeXp && TrainingCosts.TableFor(t, 2, 0) == t.VitalXp && TrainingCosts.TableFor(t, 9, 0) == null, "attribute / vital / unknown kind");
Check(TrainingCosts.CheckRaise(a, 100, a[100], long.MaxValue, 0, 0, out _) == RaiseStatus.BadArguments
&& TrainingCosts.CheckRaise(a, 100, a[100], long.MaxValue, 101, 0, out _) == RaiseStatus.BadArguments
&& TrainingCosts.CheckRaise(a, 100, a[100], long.MaxValue, 1, -5, out _) == RaiseStatus.BadArguments, "0 ranks, over 100 ranks, a negative cost -> BadArguments");
Check(TrainingCosts.CheckRaise(a, 0, 0, long.MaxValue, 100, 0, out long hundred) == RaiseStatus.Sent && hundred == a[100], "+100 from rank 0 = table[100], within one 32-bit game action");
// A fake table whose step exceeds 32 bits can't be sent in one game action.
uint[] huge = { 0, uint.MaxValue };
Check(TrainingCosts.CheckRaise(huge, 0, 0, long.MaxValue, 1, 0, out long hc) == RaiseStatus.Sent && hc == uint.MaxValue, "uint.MaxValue XP fits");
Check(TrainingCosts.CheckRaise(a, 50, a[51], long.MaxValue, 1, 0, out _) == RaiseStatus.NotRaisable, "spent already covers the next rank (cost 0) -> NotRaisable, nothing sent");
}
private static void TrainChecks()
{
Section("the checks before a train is sent (CheckTrain)");
Check(TrainingCosts.CheckTrain(1, 6, 6, 6) == RaiseStatus.Sent, "untrained, priced 6, 6 credits, confirmed 6 -> Sent");
Check(TrainingCosts.CheckTrain(0, 6, 10, 0) == RaiseStatus.Sent, "not in the skill table yet (class 0) counts as untrained");
Check(TrainingCosts.CheckTrain(1, 6, 5, 6) == RaiseStatus.NotEnough, "5 credits -> NotEnough");
Check(TrainingCosts.CheckTrain(1, 6, 10, 4) == RaiseStatus.CostChanged, "confirmed a different price -> CostChanged");
Check(TrainingCosts.CheckTrain(2, 6, 10, 6) == RaiseStatus.NotRaisable && TrainingCosts.CheckTrain(3, 6, 10, 6) == RaiseStatus.NotRaisable, "already trained / specialized -> NotRaisable");
Check(TrainingCosts.CheckTrain(1, 0, 10, 0) == RaiseStatus.NotRaisable, "no price in the dat -> NotRaisable");
Check(TrainingCosts.CheckTrain(1, 6, 10, -1) == RaiseStatus.BadArguments, "negative confirm -> BadArguments");
}
private static void ParserRefusesJunk()
{
Section("the XpTable parser refuses junk");
Check(!TrainingCosts.TryParseXpTable(Array.Empty<byte>(), out _), "empty");
Check(!TrainingCosts.TryParseXpTable(new byte[23], out _), "short header");
var b = new byte[24];
BitConverter.GetBytes(0x0E000018u).CopyTo(b, 0);
BitConverter.GetBytes(50000u).CopyTo(b, 4);
Check(!TrainingCosts.TryParseXpTable(b, out _), "absurd counts");
var c = new byte[24 + 4 * 2 * 4 + 8 * 2 + 3]; // counts of 1: two of each u32 table, two u64 levels; then cut short
BitConverter.GetBytes(1u).CopyTo(c, 4); BitConverter.GetBytes(1u).CopyTo(c, 8); BitConverter.GetBytes(1u).CopyTo(c, 12);
BitConverter.GetBytes(1u).CopyTo(c, 16); BitConverter.GetBytes(1u).CopyTo(c, 20);
Check(TrainingCosts.TryParseXpTable(c, out XpTableData small) && small.AttributeXp.Length == 2 && small.LevelXp.Length == 2, "the smallest well-formed table");
Check(!TrainingCosts.TryParseXpTable(c.AsSpan(0, c.Length - 4), out _), "the same, a few bytes short");
}
private static void SdkNumbersMatch()
{
Section("the SDK's RaiseResult = the engine's RaiseStatus");
foreach (RaiseStatus s in Enum.GetValues<RaiseStatus>())
Check(Enum.TryParse(s.ToString(), out RaiseResult r) && (int)r == (int)s, $"{s} = {(int)s}");
Check((int)RaiseResult.EngineTooOld == -100 && !Enum.IsDefined(typeof(RaiseStatus), -100), "EngineTooOld is the SDK's own");
Check((uint)TrainingKind.Attribute == 1 && (uint)TrainingKind.Vital == 2 && (uint)TrainingKind.Skill == 3, "kinds 1 / 2 / 3");
}
private static IEnumerable<(string, uint[])> Tables(XpTableData t) =>
new[] { ("attribute", t.AttributeXp), ("vital", t.VitalXp), ("trained", t.TrainedXp), ("specialized", t.SpecializedXp) };
private static void Section(string title) => Console.WriteLine("\n== " + title);
private static void Check(bool ok, string what)
{
_checks++;
if (!ok) _failed++;
Console.WriteLine((ok ? " ok " : " FAIL ") + what);
}
}

View file

@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for spending experience (plugin API v79): the XpTable parser and the cost
arithmetic and raise / train checks (src\RynthCore.Engine\Compatibility\TrainingCosts.cs,
compiled in), against the XpTable of a real client_portal.dat read with the engine's own dat
reader (AcDatFile in UI\ScriptWindows\AcIconDecoder.cs, read only), plus the SDK's
RaiseResult numbers against the engine's. Nothing native: no AC, no engine state.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail); after the usual separator, an AC folder or a client_portal.dat.
Default dat: C:\Turbine\Asheron's Call\client_portal.dat.
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>TrainingCostTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\TrainingCosts.cs" Link="Engine\TrainingCosts.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\ScriptWindows\AcIconDecoder.cs" Link="Engine\AcIconDecoder.cs" />
<Compile Include="..\..\src\RynthCore.StatusAgent\Dat\DxtUtil.cs" Link="StatusAgent\DxtUtil.cs" />
<ProjectReference Include="..\..\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
</Project>

View file

@ -165,6 +165,14 @@ GROUPS = {
"TimeSyncHooks": [
("ClientNet_HandleTimeSynch", 0x005448F0),
],
"UiFlowHooks": [
("UIFlow_UseNewMode", 0x00479AA0), ("Client_Cleanup", 0x004118D0),
],
"UiElementHooks": [
("UIElementManager_StartTooltip", 0x0045DF70), ("UIElementManager_ResetTooltip", 0x0045C440),
("UIElementManager_CheckTooltip", 0x0045B7C0), ("UIElementManager_StartDragandDrop", 0x0045E120),
("UIElement_CatchDroppedItem", 0x00461860), ("UIElement_ItemList_InqDropIconInfo", 0x004E3380),
],
"PlayerTrade": [
("Event_OpenTradeNegotiations", 0x006AE260), ("Event_AddToTrade", 0x006AE030),
("Event_ResetTrade", 0x006AE330), ("Event_CloseTradeNegotiations", 0x006AE140),

View file

@ -0,0 +1,129 @@
#!/usr/bin/env python3
"""
Offline check of the raise / train senders (Compatibility/PlayerTraining.cs, plugin API v79
Raise / TrainSkill) against an acclient.exe. Read-only: maps the file, runs nothing.
The engine binds the client's own CM_Train game-action senders, the functions the retail
character window calls for "+" (gmAttributeUI / gmSkillUI RaiseSelection and
Raise10Selection) and for the train dialog (gmSkillUI::TrainSkillDialogCallback). This
proves, on the given client build, that:
* each embedded pattern is unique and lands on its VA (as pe_pattern.py CHECK does);
* each target starts a function and is the generated two-argument sender: it reads its
first argument at [esp+1Ch] and its second at [esp+20h] (after sub esp,0Ch and three
pushes), writes the expected game-action opcode (0x45 RaiseAttribute, 0x44 RaiseVital,
0x46 RaiseSkill, 0x47 TrainSkill) and returns with a plain ret (cdecl: the caller pops);
* the retail character window's own raise/train handlers call exactly these functions
(direct E8 calls at the Chorizite-map call sites) with two pushed arguments and pop
8 bytes after: the engine calls them the same way (bool __cdecl (uint, uint)).
Usage: python tools/train_senders_check.py ["<acclient.exe>" ...]
Default: both client copies (C:\\Turbine\\Asheron's Call and C:\\Games\\RynthCore\\AcClient).
Exit 0 = every check passed on every client given.
"""
import os
import struct
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from pe_pattern import read_window, matches, parse_engine_patterns # noqa: E402
DEFAULT_CLIENTS = [r"C:\Turbine\Asheron's Call\acclient.exe", r"C:\Games\RynthCore\AcClient\acclient.exe"]
# name in PlayerTraining.cs -> (opcode, the character window's call sites from the Chorizite
# acclient map: (call address, the function it sits in))
SENDERS = {
"PlayerTraining.Event_TrainAttribute": (0x45, [
(0x0049D361, "gmAttributeUI::RaiseSelection"), (0x0049D491, "gmAttributeUI::Raise10Selection")]),
"PlayerTraining.Event_TrainAttribute2nd": (0x44, [
(0x0049D38A, "gmAttributeUI::RaiseSelection"), (0x0049D4BA, "gmAttributeUI::Raise10Selection")]),
"PlayerTraining.Event_TrainSkill": (0x46, [
(0x0049CBF7, "gmSkillUI::RaiseSelection"), (0x0049BA97, "gmSkillUI::Raise10Selection")]),
"PlayerTraining.Event_TrainSkillAdvancementClass": (0x47, [
(0x0049C5B1, "gmSkillUI::TrainSkillDialogCallback")]),
}
fails = 0
def check(ok, msg):
global fails
print(("ok " if ok else "FAIL ") + msg)
if not ok:
fails += 1
def run(path):
print(f"\n=== {path}")
if not os.path.exists(path):
check(False, "acclient.exe not found")
return
W, BASE = read_window(path)
def at(va, n):
o = va - BASE
return W[o:o + n]
def rel_callers(target):
out, i = [], 0
while True:
i = W.find(b"\xE8", i)
if i < 0 or i + 5 > len(W):
break
if BASE + i + 5 + struct.unpack_from("<i", W, i + 1)[0] == target:
out.append(BASE + i)
i += 1
return out
def pops_8_after(call_va):
after = at(call_va + 5, 16)
if after.find(b"\x83\xC4\x08") >= 0:
return True
if after[0] == 0xEB: # jmp short to a join that pops
dest = call_va + 5 + 2 + struct.unpack_from("<b", after, 1)[0]
return at(dest, 12).find(b"\x83\xC4\x08") >= 0
return False
items = {it["name"]: it for it in parse_engine_patterns() if it["file"] == "PlayerTraining.cs" and it["kind"] == "fn"}
for name, (opcode, sites) in SENDERS.items():
it = items.get(name)
check(it is not None, f"{name}: pattern present in PlayerTraining.cs")
if it is None:
continue
ms = matches(W, it["pattern"], limit=4)
va = BASE + ms[0] if len(ms) == 1 else None
check(va is not None, f"{name}: pattern unique ({len(ms)} match{'es' if len(ms) != 1 else ''}) at 0x{(va or 0):08X}"
+ (" = the map's VA" if va == it["va"] else f" (map VA 0x{it['va']:08X})"))
if va is None:
continue
check(it["pattern"][-1] == opcode and at(va + 90, 7) == bytes([0xC7, 0x02, opcode, 0, 0, 0, 0x8B]),
f"{name}: writes game action 0x{opcode:04X}")
prev = at(va - 4, 4)
check(prev[-1] in (0x90, 0xCC, 0xC3) or (prev[-3] == 0xC2 and prev[-1] == 0x00), f"{name}: starts a function (before: {prev.hex(' ')})")
check(at(va, 6) == bytes([0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57]), f"{name}: sub esp,0Ch / push ebx,esi,edi")
body = at(va, 0x180)
check(body.find(bytes([0x8B, 0x4C, 0x24, 0x1C])) >= 0 and body.find(bytes([0x8B, 0x54, 0x24, 0x20])) >= 0,
f"{name}: reads two stack arguments ([esp+1Ch], [esp+20h])")
end = body.find(bytes([0x83, 0xC4, 0x0C, 0xC3]))
check(end > 0 and body[:end].find(bytes([0xC2, 0x08, 0x00])) < 0 and body[:end].find(bytes([0xC2, 0x04, 0x00])) < 0,
f"{name}: add esp,0Ch / ret at +0x{end:X} (cdecl, no ret N)")
check(body[:end].find(bytes([0x8A, 0xD8])) >= 0, f"{name}: returns the send's bool in al (mov bl,al ... )")
callers = rel_callers(va)
for call, owner in sites:
check(call in callers, f"{name}: called by the character window ({owner}, call at 0x{call:08X})")
if call in callers:
check(pops_8_after(call), f"{name}: {owner} pops 8 bytes after the call (two cdecl arguments)")
print(f" {len(callers)} direct call site(s): " + ", ".join(f"0x{c:08X}" for c in callers))
def main():
paths = sys.argv[1:] or DEFAULT_CLIENTS
for p in paths:
run(p)
print()
print("PASS" if fails == 0 else f"FAIL ({fails})")
return 0 if fails == 0 else 1
if __name__ == "__main__":
sys.exit(main())

175
tools/ui_hooks_check.py Normal file
View file

@ -0,0 +1,175 @@
#!/usr/bin/env python3
"""
Offline check of the UI hooks (Compatibility/UiFlowHooks.cs, Compatibility/UiElementHooks.cs)
against an acclient.exe. Read-only: maps the file, runs nothing.
pe_pattern.py CHECK already proves every embedded pattern is unique and lands on its VA.
This goes further and checks the facts the detours rely on, so a different client build
fails here instead of in game:
* each target starts a function (padding or a ret right before it) and returns the way
its detour's signature says (ret / ret 4 / ret 0Ch / ret 14h, or a tail jump);
* UseNewMode copies UIFlow+0x90 into +0x8C (the offsets the detour reads);
* StartTooltip / ResetTooltip use UIElementManager +0x2F4 / +0x2F8, ResetTooltip
tail-jumps into CheckTooltip;
* StartDragandDrop stores the drag icon at +0x31C and its owner at +0x320;
* StopDragandDrop calls the catcher's vtable +0xD8, and every UIElement vtable in the
client has CatchDroppedItem there (directly, or UIElement_Field's, which calls it);
* every UIElement vtable has GetUIElementType at +0x98 (mov eax,imm32 / ret, or xor/ret),
UIElement_ItemList's returns 0x10000031, GetParent is the vtable +0xA0 call that
GetAncestorByID walks, and the element id is at +0x2E4.
Usage: python tools/ui_hooks_check.py ["<path-to-acclient.exe>"]
Exit 0 = every check passed.
"""
import os
import struct
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from pe_pattern import read_window, matches, parse_engine_patterns # noqa: E402
DEFAULT_CLIENT = r"C:\Turbine\Asheron's Call\acclient.exe"
N = None
fails = 0
def check(ok, msg):
global fails
print(("ok " if ok else "FAIL ") + msg)
if not ok:
fails += 1
def main():
path = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_CLIENT
if not os.path.exists(path):
print(f"acclient.exe not found: {path}")
return 2
W, BASE = read_window(path)
def at(va, n):
o = va - BASE
return W[o:o + n]
def u32(va):
return struct.unpack_from("<I", W, va - BASE)[0]
def find(pat):
ms = matches(W, pat, limit=4)
return BASE + ms[0] if len(ms) == 1 else None
def body_has(va, needle, span=0x200):
return W.find(bytes(needle), va - BASE, va - BASE + span) >= 0
def rel_callers(target, op=0xE8):
out, i = [], 0
while True:
i = W.find(bytes([op]), i)
if i < 0 or i + 5 > len(W):
break
if BASE + i + 5 + struct.unpack_from("<i", W, i + 1)[0] == target:
out.append(BASE + i)
i += 1
return out
def abs_refs(value):
needle, out, i = struct.pack("<I", value), [], 0
while True:
i = W.find(needle, i)
if i < 0:
break
out.append(BASE + i)
i += 1
return out
# 1. the engine's own patterns for these two files, resolved here
want = {"UiFlow.UseNewMode": 0x00479AA0, "UiFlow.ClientCleanup": 0x004118D0,
"UiElement.StartTooltip": 0x0045DF70, "UiElement.ResetTooltip": 0x0045C440,
"UiElement.CheckTooltip": 0x0045B7C0, "UiElement.StartDragandDrop": 0x0045E120,
"UiElement.CatchDroppedItem": 0x00461860, "UiElement.InqDropIconInfo": 0x004E3380}
found = {}
for it in parse_engine_patterns():
if it["file"] in ("UiFlowHooks.cs", "UiElementHooks.cs") and it["kind"] == "fn":
va = find(it["pattern"])
found[it["name"]] = va
check(va == it["va"], f"{it['name']}: pattern unique at 0x{(va or 0):08X} (fallback 0x{it['va']:08X})")
for name in want:
check(name in found, f"{name}: pattern present in the engine source")
va = {k: (found.get(k) or v) for k, v in want.items()}
# 2. function starts and returns
for name, v in va.items():
prev = at(v - 4, 4)
boundary = prev[-1] in (0x90, 0xCC, 0xC3) or (prev[-3] == 0xC2 and prev[-1] == 0x00)
check(boundary, f"{name}: starts a function (bytes before: {prev.hex(' ')})")
check(body_has(va["UiElement.StartTooltip"], [0xC2, 0x14, 0x00], 0x1B0), "StartTooltip: ret 14h (5 stack args: StringInfo*, owner, 3 ids)")
check(body_has(va["UiElement.StartDragandDrop"], [0x32, 0xC0, 0x5B, 0x83, 0xC4, 0x34, 0xC2, 0x0C, 0x00]), "StartDragandDrop: ret 0Ch (element, x, y), returns al")
check(at(va["UiElement.CatchDroppedItem"] + 14, 5) == bytes([0xB0, 0x01, 0xC2, 0x04, 0x00]), "CatchDroppedItem: mov al,1 / ret 4 (one arg: DragDropInfo*)")
check(at(va["UiElement.CatchDroppedItem"] + 7, 2) == bytes([0x6A, 0x15]), "CatchDroppedItem: broadcasts element message 0x15 (drop release)")
check(body_has(va["UiFlow.UseNewMode"], [0x81, 0xC4, 0x90, 0x00, 0x00, 0x00, 0xC3]), "UseNewMode: plain ret (no args)")
check(body_has(va["UiFlow.ClientCleanup"], [0x5E, 0xE9], 0xB0), "Client::Cleanup: ends in a tail jump (no args)")
callers = rel_callers(va["UiElement.InqDropIconInfo"])
check(len(callers) >= 10, f"InqDropIconInfo: {len(callers)} callers in the client (AC uses it itself)")
popping = [c for c in callers if body_has(c + 5, [0x83, 0xC4, 0x10], 0x0C)]
check(len(popping) >= len(callers) - 1,
f"InqDropIconInfo: cdecl with 4 args - {len(popping)}/{len(callers)} callers pop 16 bytes right after (one batches it later)")
check(at(va["UiElement.InqDropIconInfo"], 4) == bytes([0x8B, 0x44, 0x24, 0x10]) and body_has(va["UiElement.InqDropIconInfo"], [0x3B, 0xF3], 0x20),
"InqDropIconInfo: reads its 4th arg first and null-checks the element")
# 3. UseNewMode: +0x90 -> +0x8C
check(body_has(va["UiFlow.UseNewMode"], [0x8B, 0x8E, 0x90, 0x00, 0x00, 0x00, 0x57, 0x89, 0x8E, 0x8C, 0x00, 0x00, 0x00]),
"UseNewMode: mov ecx,[esi+90h] / mov [esi+8Ch],ecx (pending -> current mode)")
check(len(rel_callers(va["UiFlow.UseNewMode"])) == 1, "UseNewMode: one call site")
check(len(rel_callers(va["UiFlow.ClientCleanup"])) == 1 and len(abs_refs(va["UiFlow.ClientCleanup"])) >= 1,
"Client::Cleanup: one direct call (gmClient::Cleanup) and a vtable entry")
# 4. tooltip offsets
check(body_has(va["UiElement.StartTooltip"], [0x89, 0xBE, 0xF4, 0x02, 0x00, 0x00], 0x60), "StartTooltip: owner stored at +0x2F4")
check(body_has(va["UiElement.ResetTooltip"], [0xC7, 0x86, 0xF8, 0x02, 0x00, 0x00, 0, 0, 0, 0], 0x20), "ResetTooltip: clears the tooltip element at +0x2F8")
jmp = W.find(bytes([0x8B, 0xCE, 0x5E, 0xE9]), va["UiElement.ResetTooltip"] - BASE, va["UiElement.ResetTooltip"] - BASE + 0x80)
tail = BASE + jmp + 3 + 5 + struct.unpack_from("<i", W, jmp + 4)[0] if jmp >= 0 else 0
check(tail == va["UiElement.CheckTooltip"], f"ResetTooltip: tail-jumps into CheckTooltip (0x{tail:08X})")
inner = W.find(bytes([0x89, 0xB3, 0xF8, 0x02, 0x00, 0x00]), va["UiElement.StartTooltip"] - BASE - 0x6000, va["UiElement.StartTooltip"] - BASE)
check(inner >= 0, "the inner StartTooltip stores the new tooltip element at +0x2F8")
# 5. drag: icon +0x31C, owner +0x320
check(body_has(va["UiElement.StartDragandDrop"], [0x89, 0x9E, 0x1C, 0x03, 0x00, 0x00], 0x260), "StartDragandDrop: drag icon stored at +0x31C")
check(body_has(va["UiElement.StartDragandDrop"], [0x89, 0x8E, 0x20, 0x03, 0x00, 0x00], 0x260), "StartDragandDrop: drag owner stored at +0x320")
check(len(rel_callers(va["UiElement.StartDragandDrop"])) == 5, "StartDragandDrop: 5 call sites (one is itself: the drag proxy)")
# 6. StopDragandDrop builds DragDropInfo and calls the catcher's +0xD8
stop = find([0x53, 0x57, 0x8B, 0xF9, 0x8B, 0x87, 0x1C, 0x03, 0x00, 0x00, 0x33, 0xDB, 0x3B, 0xC3, 0x0F, 0x84])
check(stop is not None, f"StopDragandDrop found (0x{(stop or 0):08X})")
if stop:
check(body_has(stop, [0x89, 0x46, 0x08], 0x50) and body_has(stop, [0x89, 0x56, 0x0C], 0x60) and body_has(stop, [0x89, 0x4E, 0x10], 0x60),
"StopDragandDrop: DragDropInfo +0x08 icon, +0x0C owner, +0x10 catcher")
check(body_has(stop, [0xFF, 0x90, 0xD8, 0x00, 0x00, 0x00], 0x80), "StopDragandDrop: calls catcher->vtable[+0xD8] (CatchDroppedItem)")
# 7. every UIElement vtable: +0xD8, +0x98, +0xA0
ancestor = find([0x8B, 0x01, 0xFF, 0x90, 0xA0, 0x00, 0x00, 0x00, 0x85, 0xC0, 0x74, 0x1C, 0x56, 0x8B, 0x74, 0x24, 0x08,
0x39, 0xB0, 0xE4, 0x02, 0x00, 0x00])
check(ancestor is not None, f"UIElement::GetAncestorByID found (walks vtable +0xA0, compares +0x2E4) at 0x{(ancestor or 0):08X}")
field = find([0x56, 0x8B, 0xF1, 0x8A, 0x86, 0xF0, 0x05, 0x00, 0x00, 0x84, 0xC0, 0x74, 0x18])
if field:
call = W.find(bytes([0xE8]), field - BASE + 0x2C, field - BASE + 0x2D)
target = BASE + call + 5 + struct.unpack_from("<i", W, call + 1)[0] if call >= 0 else 0
check(target == va["UiElement.CatchDroppedItem"], "UIElement_Field::CatchDroppedItem calls UIElement::CatchDroppedItem")
if ancestor:
tables = [r - 0xA4 for r in abs_refs(ancestor)]
check(len(tables) >= 100, f"{len(tables)} UIElement vtables (GetAncestorByID at +0xA4)")
bad_drop = [t for t in tables if u32(t + 0xD8) not in (va["UiElement.CatchDroppedItem"], field)]
check(not bad_drop, f"every UIElement vtable's +0xD8 reaches CatchDroppedItem ({len(tables) - len(bad_drop)}/{len(tables)})")
bad_type = [t for t in tables if not (at(u32(t + 0x98), 1) == b"\xB8" and at(u32(t + 0x98) + 5, 1) == b"\xC3" or at(u32(t + 0x98), 3) == b"\x33\xC0\xC3")]
check(not bad_type, f"every UIElement vtable's +0x98 is GetUIElementType ({len(tables) - len(bad_type)}/{len(tables)})")
itemlist = [t for t in tables if at(u32(t + 0x98), 6) == bytes([0xB8, 0x31, 0x00, 0x00, 0x10, 0xC3])]
check(len(itemlist) >= 1, f"UIElement_ItemList's GetUIElementType returns 0x10000031 ({len(itemlist)} vtable(s))")
print("=" * 60)
print("PASS - the UI hooks' facts hold on this client." if fails == 0 else f"FAIL - {fails} check(s) failed.")
return 1 if fails else 0
if __name__ == "__main__":
sys.exit(main())