Snapshot for release 2026.10.19.1 (internal fa7a8f6)

This commit is contained in:
Tom Bohar 2026-10-19 09:11:20 -04:00
commit 44074df011
110 changed files with 8017 additions and 291 deletions

View file

@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the bar declutter work (2026-10-18; Skills-under-Oracle idea from Silentkelpie, rynth PR 6):
- ShownLatch + OracleSkillsEmbed (src\RynthCore.Engine\ImGui\Panels, compiled in): the embedded Skills face is
shown exactly once per visible stretch and hidden exactly once (redraws, tab switches, Clear, window closed,
idle sweep, double Clear, hide without show, two threads), so its Progression subscription never leaks;
and when the Oracle tabs count as reachable (the Skills bar icon / routing rule).
- InventoryTitleLayout (src\RynthCore.Engine\UI): the Classic Inventory title bar at widths 300/360/480,
scales 1 / 1.5 / 2, Vault on and off: no button off the bar or overlapping another, Vault always there,
the title keeps room or is elided; plus the Modern header's icons / menu / none choice.
No ImGui, no files. 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>BarDeclutterTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\ImGui\Panels\ShownLatch.cs" Link="Engine\ShownLatch.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\Panels\OracleSkillsEmbed.cs" Link="Engine\OracleSkillsEmbed.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\InventoryTitleLayout.cs" Link="Engine\InventoryTitleLayout.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,507 @@
using RynthCore.Engine.ImGuiBackend.Panels;
using RynthCore.Engine.UI;
namespace BarDeclutterTests;
// Offline tests for the bar declutter work. 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 int Main()
{
ShownLatchBasics();
EmbedShowRedrawsHide();
EmbedTabSwitches();
EmbedHideWithoutShow();
EmbedDoubleClear();
EmbedWindowClosedAndIdle();
EmbedRaceAndShutdown();
EmbedTwoThreads();
FaceOnShownTwice();
TabsAvailableRule();
TitleLayoutGrid();
TitleLayoutModes();
TitleLayoutNarrow();
TitleLayoutBadInput();
ElideTitle();
HeaderExtras();
HeaderVault();
Console.WriteLine();
Console.WriteLine(_fails == 0 ? $"PASS ({_asserts} checks)" : $"FAIL ({_fails} of {_asserts} checks failed)");
return _fails == 0 ? 0 : 1;
}
// ── The lifecycle ───────────────────────────────────────────────────
/// <summary>
/// Stands in for SkillsFace: the same ShownLatch wiring (OnShown/OnHidden through a latch that runs a
/// "core" once per edge), with the Progression subscribe / unsubscribe counted instead of UiSource.
/// </summary>
private sealed class FakeFace
{
public int Subscribes, Unsubscribes, Outstanding;
private readonly ShownLatch _life;
public FakeFace() => _life = new ShownLatch(() => { Subscribes++; Outstanding++; }, () => { Unsubscribes++; Outstanding--; });
public void OnShown() => _life.Show();
public void OnHidden() => _life.Hide();
}
private static FakeFace Fresh()
{
OracleSkillsEmbed.Shutdown(); // hides anything left by a previous test, forgets the announcement
var face = new FakeFace();
OracleSkillsEmbed.Bind(face.OnShown, face.OnHidden);
return face;
}
/// <summary>One frame of ScriptWindowFace.Draw for the Oracle window: embed drawn only while a tab is active.</summary>
private static void Frame(long nowMs)
{
OracleSkillsEmbed.Sweep(nowMs); // ImGuiPanelHost.DrawAll
if (OracleSkillsEmbed.ActiveTab >= 0) OracleSkillsEmbed.NoteDrawn(nowMs); // SkillsFace.DrawEmbedded
}
private static void ShownLatchBasics()
{
Console.WriteLine("ShownLatch");
int on = 0, off = 0;
var l = new ShownLatch(() => on++, () => off++);
Eq(l.Hide(), false, "hide before any show does nothing");
Eq(off, 0, "no hidden callback without a show");
Eq(l.Show(), true, "first show runs");
Eq(l.Show(), false, "second show is a no-op");
Eq(l.IsShown, true, "shown");
Eq(l.Hide(), true, "hide runs");
Eq(l.Hide(), false, "second hide is a no-op");
Eq(l.IsShown, false, "hidden");
Eq((on, off), (1, 1), "one callback each");
// A shown callback that throws still leaves the latch on, so the matching hide runs.
int h = 0;
var t = new ShownLatch(() => throw new InvalidOperationException("boom"), () => h++);
try { t.Show(); } catch (InvalidOperationException) { }
Eq(t.IsShown, true, "a throwing show leaves the latch on");
t.Hide();
Eq(h, 1, "so the hide still runs once");
}
private static void EmbedShowRedrawsHide()
{
Console.WriteLine("Embed: show, N redraws, hide");
FakeFace f = Fresh();
OracleSkillsEmbed.SetActiveTab(0);
Eq(f.Subscribes, 0, "setting the tab alone shows nothing (the Oracle window may be closed)");
long t = 1000;
for (int i = 0; i < 600; i++, t += 16) Frame(t); // ~10 s of 60 fps
Eq(f.Subscribes, 1, "600 redraws: one subscribe");
Eq(f.Unsubscribes, 0, "600 redraws: no unsubscribe yet");
Eq(OracleSkillsEmbed.IsShown, true, "shown while drawing");
// The old code re-ran OnShown every 2 s: 5 more "2 s gaps" must not add subscribes.
for (int i = 0; i < 5; i++) { t += 900; Frame(t); Frame(t + 16); }
Eq(f.Subscribes, 1, "redraws after long gaps (the old re-run trigger): still one subscribe");
OracleSkillsEmbed.Clear();
Eq(f.Unsubscribes, 1, "Clear: one unsubscribe");
Eq(f.Outstanding, 0, "balanced");
Eq(OracleSkillsEmbed.IsShown, false, "hidden");
for (int i = 0; i < 50; i++, t += 16) Frame(t); // ActiveTab is -1: nothing draws
Eq((f.Subscribes, f.Unsubscribes), (1, 1), "frames after Clear change nothing");
// Shown again later: a second, separate stretch.
OracleSkillsEmbed.SetActiveTab(1);
for (int i = 0; i < 10; i++, t += 16) Frame(t);
OracleSkillsEmbed.Clear();
Eq((f.Subscribes, f.Unsubscribes), (2, 2), "second stretch: two of each in all");
}
private static void EmbedTabSwitches()
{
Console.WriteLine("Embed: skills -> attrs -> progress -> off");
FakeFace f = Fresh();
long t = 5000;
OracleSkillsEmbed.SetActiveTab(0);
for (int i = 0; i < 20; i++, t += 16) Frame(t);
OracleSkillsEmbed.SetActiveTab(1);
for (int i = 0; i < 20; i++, t += 16) Frame(t);
OracleSkillsEmbed.SetActiveTab(2);
for (int i = 0; i < 20; i++, t += 16) Frame(t);
Eq(OracleSkillsEmbed.ActiveTab, 2, "progress selected");
Eq((f.Subscribes, f.Unsubscribes), (1, 0), "switching tabs does not resubscribe or release");
OracleSkillsEmbed.SetActiveTab(0);
Eq((f.Subscribes, f.Unsubscribes), (1, 0), "back to skills: still the same stretch");
OracleSkillsEmbed.Clear(); // /rc oracle-skills off
Eq((f.Subscribes, f.Unsubscribes), (1, 1), "off: released once");
Eq(OracleSkillsEmbed.ActiveTab, -1, "no tab");
OracleSkillsEmbed.SetActiveTab(7);
Eq(OracleSkillsEmbed.ActiveTab, -1, "an out-of-range tab is off");
OracleSkillsEmbed.SetActiveTab(-3);
Eq((f.Subscribes, f.Unsubscribes), (1, 1), "out-of-range tabs change nothing else");
}
private static void EmbedHideWithoutShow()
{
Console.WriteLine("Embed: hide without show");
FakeFace f = Fresh();
OracleSkillsEmbed.Clear();
OracleSkillsEmbed.Sweep(1_000_000);
f.OnHidden();
Eq((f.Subscribes, f.Unsubscribes), (0, 0), "nothing was shown: nothing released (no negative refcount)");
Eq(f.Outstanding, 0, "outstanding is zero");
}
private static void EmbedDoubleClear()
{
Console.WriteLine("Embed: double Clear");
FakeFace f = Fresh();
OracleSkillsEmbed.SetActiveTab(0);
Frame(100);
OracleSkillsEmbed.Clear();
OracleSkillsEmbed.Clear();
OracleSkillsEmbed.Clear();
Eq((f.Subscribes, f.Unsubscribes), (1, 1), "three Clears: one release");
f.OnHidden();
Eq(f.Unsubscribes, 1, "even a stray OnHidden on the face is a no-op");
}
private static void EmbedWindowClosedAndIdle()
{
Console.WriteLine("Embed: Oracle window closed / idle sweep");
FakeFace f = Fresh();
OracleSkillsEmbed.SetActiveTab(2);
Frame(0); Frame(16);
// ScriptWindowFace.OnHidden / ScriptWindowRegistry.RemoveLocked for the Oracle window:
Check(OracleSkillsEmbed.IsOraclePanel("script:RynthOracle/Oracle"), "the Oracle window's panel key matches");
Check(!OracleSkillsEmbed.IsOraclePanel("script:RynthSort/Main"), "another script window's key does not");
if (OracleSkillsEmbed.IsOraclePanel("script:RynthOracle/Oracle")) OracleSkillsEmbed.Clear();
Eq((f.Subscribes, f.Unsubscribes), (1, 1), "window closed: released once");
// Idle: the tab stays set but nothing draws (window collapsed / owner crashed without sending off).
OracleSkillsEmbed.SetActiveTab(0);
Frame(10_000); Frame(10_016);
Eq(f.Subscribes, 2, "shown again");
OracleSkillsEmbed.Sweep(10_016 + OracleSkillsEmbed.IdleMs); // exactly at the limit: still shown
Eq(f.Unsubscribes, 1, "at the idle limit: not yet released");
OracleSkillsEmbed.Sweep(10_016 + OracleSkillsEmbed.IdleMs + 5000);
Eq((f.Subscribes, f.Unsubscribes), (2, 2), "past the idle limit: released once");
OracleSkillsEmbed.Sweep(10_016 + OracleSkillsEmbed.IdleMs + 9000);
Eq(f.Unsubscribes, 2, "sweeping again releases nothing more");
Frame(30_000);
Eq((f.Subscribes, f.Unsubscribes), (3, 2), "the window drawing again shows it again");
OracleSkillsEmbed.Shutdown();
Eq((f.Subscribes, f.Unsubscribes), (3, 3), "engine shutdown releases it");
}
private static void EmbedRaceAndShutdown()
{
Console.WriteLine("Embed: draw after Clear, shutdown");
FakeFace f = Fresh();
OracleSkillsEmbed.SetActiveTab(0);
Frame(1);
OracleSkillsEmbed.Clear();
OracleSkillsEmbed.NoteDrawn(2); // a draw that read the tab just before Clear
Eq((f.Subscribes, f.Unsubscribes), (1, 1), "a draw after Clear does not re-show");
OracleSkillsEmbed.Announce();
Check(OracleSkillsEmbed.TabsAvailable(true), "announced and registered");
OracleSkillsEmbed.Shutdown();
Check(!OracleSkillsEmbed.TabsAvailable(true), "shutdown forgets the announcement");
}
private static void EmbedTwoThreads()
{
Console.WriteLine("Embed: Show and Clear from two threads");
FakeFace f = Fresh();
OracleSkillsEmbed.SetActiveTab(0);
var drawer = Task.Run(() => { for (int i = 0; i < 20000; i++) OracleSkillsEmbed.NoteDrawn(i); });
var clearer = Task.Run(() => { for (int i = 0; i < 20000; i++) OracleSkillsEmbed.Clear(); });
Task.WaitAll(drawer, clearer);
OracleSkillsEmbed.Clear();
Eq(f.Subscribes, f.Unsubscribes, "every subscribe has its unsubscribe");
Check(f.Outstanding == 0, "outstanding is zero");
}
private static void FaceOnShownTwice()
{
Console.WriteLine("Face: host and embed both asking");
// The panel host calls OnShown once per open; the embed's latch may also call it. A face whose OnShown is
// idempotent subscribes once however it is asked.
var f = new FakeFace();
f.OnShown(); f.OnShown(); f.OnShown();
Eq(f.Subscribes, 1, "OnShown x3: one subscribe");
f.OnHidden(); f.OnHidden();
Eq((f.Subscribes, f.Unsubscribes), (1, 1), "OnHidden x2: one unsubscribe");
}
private static void TabsAvailableRule()
{
Console.WriteLine("TabsAvailable (Skills bar icon / routing)");
Fresh();
Eq(OracleSkillsEmbed.TabsAvailable(false), false, "no Oracle window, never announced: Skills icon stays");
Eq(OracleSkillsEmbed.TabsAvailable(true), false, "an Oracle window that never announced (older Oracle): Skills icon stays");
OracleSkillsEmbed.Announce();
Eq(OracleSkillsEmbed.TabsAvailable(false), false, "announced but its window is gone: Skills icon returns");
Eq(OracleSkillsEmbed.TabsAvailable(true), true, "window registered and announced: the tabs are there, icon hidden");
OracleSkillsEmbed.Shutdown();
}
// ── The title bar ───────────────────────────────────────────────────
private static IEnumerable<(string Name, TitleSlot Slot)> Slots(InventoryTitleLayout l)
{
yield return ("Smaller", l.Smaller);
yield return ("Bigger", l.Bigger);
yield return ("Tools", l.Tools);
yield return ("Modern", l.Modern);
yield return ("Vault", l.Vault);
yield return ("Remote", l.Remote);
yield return ("Sort", l.Sort);
yield return ("Count", l.Count);
yield return ("GInv", l.GInv);
yield return ("More", l.More);
}
private static void CheckLayout(InventoryTitleLayout l, float barW, float s, bool vault, float titleWant, string tag)
{
var present = Slots(l).Where(x => x.Slot.Present).OrderBy(x => x.Slot.X).ToList();
foreach (var (name, slot) in present)
{
Check(slot.X >= -0.001f, $"{tag}: {name} starts on the bar (x={slot.X})");
Check(slot.Right <= barW + 0.001f, $"{tag}: {name} ends on the bar (right={slot.Right}, bar={barW})");
}
for (int i = 1; i < present.Count; i++)
Check(present[i - 1].Slot.Right <= present[i].Slot.X + 0.001f,
$"{tag}: {present[i - 1].Name} does not overlap {present[i].Name} ({present[i - 1].Slot.Right} vs {present[i].Slot.X})");
Eq(l.Vault.Present, vault, $"{tag}: Vault present iff the server has it");
bool extrasShown = l.Mode is TitleExtrasMode.Text or TitleExtrasMode.Icons;
Eq(l.Remote.Present && l.Sort.Present && l.Count.Present && l.GInv.Present, extrasShown, $"{tag}: all four related buttons or none");
Eq(l.More.Present, l.Mode == TitleExtrasMode.Menu, $"{tag}: the more button iff Menu mode");
Check(l.TitleLeft >= 0f && l.TitleRight >= l.TitleLeft, $"{tag}: title span is ordered ({l.TitleLeft}..{l.TitleRight})");
Check(l.TitleRight <= l.LeftmostX + 0.001f, $"{tag}: title ends before the first button ({l.TitleRight} vs {l.LeftmostX})");
Check(l.TitleWidth > 0f, $"{tag}: title width > 0 ({l.TitleWidth})");
Check(l.Mode != TitleExtrasMode.None, $"{tag}: the related buttons are reachable from the bar (mode {l.Mode})");
// The title keeps its minimum (or its whole text when shorter) whenever all four buttons are shown.
float owed = Math.Min(titleWant, InventoryTitleLayout.TitleMinUnits * s);
if (extrasShown)
Check(l.TitleWidth >= owed - 0.001f - InventoryTitleLayout.PadUnits * s, $"{tag}: title keeps its room ({l.TitleWidth} >= {owed})");
}
private static void TitleLayoutGrid()
{
Console.WriteLine("Title bar: widths 300/360/480 x scales 1/1.5/2 x Vault on/off");
foreach (float units in new[] { 300f, 360f, 480f })
foreach (float s in new[] { 1f, 1.5f, 2f })
foreach (bool vault in new[] { true, false })
foreach (float want in new[] { 40f, 135f, 190f })
{
float barW = (units - 24f) * s; // the panel less the close button
var l = InventoryTitleLayout.Compute(barW, s, vault, want * s);
CheckLayout(l, barW, s, vault, want * s, $"{units}u s{s} vault={vault} title={want}");
}
// The bar widths a 1.0-2.0 scale gives at the fixed retail panel (300 units x scale), at fractional scales too.
for (float s0 = 1f; s0 <= 2.0001f; s0 += 1f / 32f)
foreach (bool vault in new[] { true, false })
{
float sc = MathF.Round(32f * s0) / 32f;
float barW = 276f * sc;
var l = InventoryTitleLayout.Compute(barW, sc, vault, 130f * sc);
CheckLayout(l, barW, sc, vault, 130f * sc, $"retail s={sc} vault={vault}");
}
}
private static void TitleLayoutModes()
{
Console.WriteLine("Title bar: which style at which width");
Eq(InventoryTitleLayout.Compute(276f, 1f, true, 130f).Mode, TitleExtrasMode.Menu, "retail width + Vault: one more menu");
Eq(InventoryTitleLayout.Compute(276f, 1f, false, 130f).Mode, TitleExtrasMode.Icons, "retail width, no Vault: four icons");
Eq(InventoryTitleLayout.Compute(336f, 1f, true, 130f).Mode, TitleExtrasMode.Icons, "360 wide + Vault: icons");
Eq(InventoryTitleLayout.Compute(456f, 1f, true, 130f).Mode, TitleExtrasMode.Text, "480 wide + Vault: text buttons");
Eq(InventoryTitleLayout.Compute(456f * 1.5f, 1.5f, true, 130f * 1.5f).Mode, TitleExtrasMode.Text, "480 wide at 1.5x: text buttons");
Eq(InventoryTitleLayout.Compute(276f * 1.5f, 1.5f, true, 130f * 1.5f).Mode, TitleExtrasMode.Menu, "retail at 1.5x + Vault: more menu");
// The case from the review: 190 px of text buttons used to push Vault to x=-44 at 300 / scale 1.
var r = InventoryTitleLayout.Compute(276f, 1f, true, 130f);
Check(r.Vault.X > 100f && r.Vault.Right <= r.Smaller.X, $"Vault sits just left of the toggles at retail width (x={r.Vault.X})");
Check(r.TitleWidth >= 100f, $"and the title keeps {r.TitleWidth} px at retail width");
// Everything is relative to the bar: scaling the bar scales the positions (whole-pixel rounding aside).
var a = InventoryTitleLayout.Compute(276f, 1f, true, 130f);
var b = InventoryTitleLayout.Compute(552f, 2f, true, 260f);
Check(MathF.Abs(a.Vault.X * 2f - b.Vault.X) < 0.01f, "Vault at 2x is twice the 1x position");
Check(MathF.Abs(a.More.X * 2f - b.More.X) < 0.01f, "More at 2x is twice the 1x position");
}
private static void TitleLayoutNarrow()
{
Console.WriteLine("Title bar: narrower than any real panel");
for (float barW = 150f; barW <= 700f; barW += 5f)
{
var l = InventoryTitleLayout.Compute(barW, 1f, true, 130f);
var present = Slots(l).Where(x => x.Slot.Present).OrderBy(x => x.Slot.X).ToList();
Check(l.Vault.Present && l.Vault.X >= 0f && l.Vault.Right <= barW, $"w={barW}: Vault present and on the bar");
Check(present.All(x => x.Slot.X >= 0f && x.Slot.Right <= barW + 0.001f), $"w={barW}: every button on the bar");
for (int i = 1; i < present.Count; i++)
Check(present[i - 1].Slot.Right <= present[i].Slot.X + 0.001f, $"w={barW}: {present[i - 1].Name} / {present[i].Name} do not overlap");
Check(l.TitleWidth >= 0f, $"w={barW}: title width never negative");
}
// Far too narrow for the toggles: Vault is clamped at the left edge, never negative; no related buttons.
var tiny = InventoryTitleLayout.Compute(60f, 1f, true, 130f);
Check(tiny.Vault.Present && tiny.Vault.X == 0f, "a 60 px bar: Vault pinned at x=0, not negative");
Eq(tiny.Mode, TitleExtrasMode.None, "a 60 px bar: no related buttons");
Check(tiny.TitleWidth >= 0f, "a 60 px bar: title width not negative");
var noVault = InventoryTitleLayout.Compute(60f, 1f, false, 130f);
Check(!noVault.Vault.Present, "no Vault server: no Vault slot");
}
private static void TitleLayoutBadInput()
{
Console.WriteLine("Title bar: bad input");
var l = InventoryTitleLayout.Compute(float.NaN, 0f, true, float.PositiveInfinity);
Check(float.IsFinite(l.Vault.X) && float.IsFinite(l.TitleRight), "NaN bar width, zero scale: finite positions");
var m = InventoryTitleLayout.Compute(276f, float.NaN, false, -5f);
Check(float.IsFinite(m.Modern.X) && m.Modern.Right <= 276f, "NaN scale reads as 1");
}
private static void ElideTitle()
{
Console.WriteLine("Title: elide");
Func<string, float> m = t => t.Length * 7f;
string full = "Inventory of Drakkon1"; // 21 chars = 147 px
Eq(InventoryTitleLayout.Elide(full, 200f, m), full, "fits: unchanged");
Eq(InventoryTitleLayout.Elide(full, 147f, m), full, "fits exactly: unchanged");
string cut = InventoryTitleLayout.Elide(full, 100f, m);
Check(cut.EndsWith("...") && m(cut) <= 100f && cut.Length > 3, $"cut to fit with an ellipsis: '{cut}'");
Eq(InventoryTitleLayout.Elide(full, 100f, m), cut, "same input, same output");
Eq(InventoryTitleLayout.Elide(full, 21f, m), "...", "room for only the ellipsis");
Eq(InventoryTitleLayout.Elide(full, 20f, m), "", "not even the ellipsis fits: nothing");
Eq(InventoryTitleLayout.Elide(full, 0f, m), "", "no room: nothing");
Eq(InventoryTitleLayout.Elide("", 100f, m), "", "empty stays empty");
for (float w = 21f; w < 147f; w += 7f)
Check(m(InventoryTitleLayout.Elide(full, w, m)) <= w, $"never wider than the room ({w})");
}
private static void HeaderExtras()
{
Console.WriteLine("Modern header: icons / menu / none");
Eq(InventoryTitleLayout.ChooseHeaderExtras(300f, 50f, out bool c1), TitleExtrasMode.Icons, "lots of room: four icons");
Eq(c1, true, "and the count text");
Eq(InventoryTitleLayout.ChooseHeaderExtras(100f, 50f, out bool c2), TitleExtrasMode.Menu, "room for the menu button and the count");
Eq(c2, true, "count kept");
Eq(InventoryTitleLayout.ChooseHeaderExtras(40f, 50f, out bool c3), TitleExtrasMode.Menu, "room for the menu button only");
Eq(c3, false, "count text dropped before the menu button");
Eq(InventoryTitleLayout.ChooseHeaderExtras(10f, 50f, out bool c4), TitleExtrasMode.None, "no room: none");
Eq(c4, false, "nothing fits");
Eq(InventoryTitleLayout.ChooseHeaderExtras(-20f, 50f, out bool c5), TitleExtrasMode.None, "negative room: none");
Eq(c5, false, "no count either");
Eq(InventoryTitleLayout.ChooseHeaderExtras(float.NaN, 50f, out _), TitleExtrasMode.None, "NaN room: none");
}
// ── The Modern header with the Aelrynth Vault button (2026-10-19; idea from Silentkelpie, rynth PR 6) ──
private static IEnumerable<(string Name, TitleSlot Slot)> HeaderSlots(InventoryHeaderLayout h)
{
yield return ("Close", h.Close);
yield return ("Classic", h.Classic);
yield return ("Vault", h.Vault);
yield return ("Remote", h.Remote);
yield return ("Sort", h.Sort);
yield return ("Count", h.Count);
yield return ("GInv", h.GInv);
yield return ("More", h.More);
}
private static void HeaderVault()
{
Console.WriteLine("Modern header: the Vault button");
// Without a vault the plan is exactly the old one, so the header is unchanged off Aelrynth.
foreach (float free in new[] { -30f, 0f, 10f, 24f, 40f, 90f, 100f, 130f, 300f })
foreach (float cw in new[] { 0f, 30f, 50f, 80f })
{
var plan = InventoryTitleLayout.ChooseHeader(free, cw, vault: false);
TitleExtrasMode old = InventoryTitleLayout.ChooseHeaderExtras(free, cw, out bool oldCount);
Check(!plan.Vault && plan.Extras == old && plan.ShowCount == oldCount, $"no vault: same as ChooseHeaderExtras (free {free}, count {cw})");
}
// With a vault the Vault takes its 24 px first; the rest shares what is left.
Eq(InventoryTitleLayout.ChooseHeader(300f, 50f, true).Extras, TitleExtrasMode.Icons, "lots of room + vault: four icons");
Eq(InventoryTitleLayout.ChooseHeader(96f + 60f + 24f - 1f, 50f, true).Extras, TitleExtrasMode.Menu, "one px short of icons + vault: the menu");
Eq(InventoryTitleLayout.ChooseHeader(96f + 60f + 24f, 50f, true).Extras, TitleExtrasMode.Icons, "icons + count + vault just fit");
Eq(InventoryTitleLayout.ChooseHeader(24f + 24f + 60f, 50f, true).Extras, TitleExtrasMode.Menu, "vault + menu + count");
var tight = InventoryTitleLayout.ChooseHeader(24f + 24f, 50f, true);
Check(tight.Vault && tight.Extras == TitleExtrasMode.Menu && !tight.ShowCount, "vault + menu, the count text dropped");
var tiny = InventoryTitleLayout.ChooseHeader(24f, 50f, true);
Check(tiny.Vault && tiny.Extras == TitleExtrasMode.None && !tiny.ShowCount, "room for the vault only: no menu, no count");
foreach (float free in new[] { 20f, 0f, -40f, float.NaN, float.NegativeInfinity })
Check(InventoryTitleLayout.ChooseHeader(free, 50f, true).Vault, $"the Vault is kept whatever the room ({free})");
// Every supported width (the panel's minimum is 140 px) and a range of left-hand text widths:
// the Vault is present, inside the header, clear of the other buttons, and nothing drawn right of the
// pyreals overlaps anything else. Without a vault the geometry is the one the header always had.
int checkedLayouts = 0;
for (float w = 140f; w <= 800f; w += 1f)
foreach (float leftEnd in new[] { 80f, 120f, 150f, 200f })
foreach (float cw in new[] { 0f, 40f, 70f })
foreach (bool vault in new[] { true, false })
{
var h = InventoryHeaderLayout.Compute(w, leftEnd, cw, vault);
string tag = $"w {w} leftEnd {leftEnd} count {cw} vault {vault}";
checkedLayouts++;
var slots = HeaderSlots(h).Where(x => x.Slot.Present).OrderBy(x => x.Slot.X).ToList();
bool ok = true;
foreach (var (name, slot) in slots)
{
if (slot.X < 0f || slot.Right > w + 0.001f) { ok = false; Console.WriteLine($" [FAIL] {tag}: {name} outside the header ({slot.X}..{slot.Right})"); }
}
for (int i = 1; i < slots.Count; i++)
if (slots[i].Slot.X < slots[i - 1].Slot.Right - 0.001f)
{
ok = false;
Console.WriteLine($" [FAIL] {tag}: {slots[i - 1].Name} and {slots[i].Name} overlap");
}
Check(ok, $"{tag}: buttons inside the header and not overlapping");
Check(h.Plan.Vault == vault && h.Vault.Present == vault, $"{tag}: the Vault button exists exactly when asked for");
if (vault)
{
Check(h.Vault.Right <= h.Classic.X + 0.001f && h.Vault.X >= 0f, $"{tag}: Vault sits left of the Classic button, inside the header");
Check(h.Vault.W >= 22f, $"{tag}: Vault keeps its full 22 px size");
foreach (var (name, slot) in slots)
if (name != "Vault" && name != "Close" && name != "Classic")
Check(slot.Right <= h.Vault.X + 0.001f, $"{tag}: {name} stays left of the Vault");
}
else
{
Check(h.Classic.X == w - 46 && h.Close.X == w - 22, $"{tag}: Close / Classic where they always were");
if (h.Plan.Extras == TitleExtrasMode.Icons) Check(h.GInv.X == w - 46 - 24 && h.Remote.X == w - 46 - 96, $"{tag}: the four icons where they always were");
if (h.Plan.Extras == TitleExtrasMode.Menu) Check(h.More.X == w - 46 - 24, $"{tag}: the menu button where it always was");
}
// Related buttons / count never reach back over the pyreals when there was room for them.
TitleSlot? leftmost = h.Plan.Extras == TitleExtrasMode.Icons ? h.Remote : h.Plan.Extras == TitleExtrasMode.Menu ? h.More : null;
if (leftmost is { } lm)
Check(lm.X >= leftEnd + 4f - 0.001f, $"{tag}: related buttons start clear of the pyreals text");
if (h.Plan.ShowCount)
Check(h.CountX + cw <= (leftmost?.X ?? (vault ? h.Vault.X : h.Classic.X)) + 0.001f, $"{tag}: the count text sits left of the buttons");
}
Check(checkedLayouts > 10000, $"swept the layouts ({checkedLayouts})");
// At the retail width (302 px) and the usual left-hand text the Vault is a button, and so are the
// rest that fit: a worked example.
var r = InventoryHeaderLayout.Compute(302f, 150f, 50f, vault: true);
Check(r.Vault.Present && r.Vault.X == 302f - 46 - 24, "302 px: Vault right beside the Classic button");
Eq(r.Plan.Extras, TitleExtrasMode.Menu, "302 px with a vault: related panels fold into the menu");
Check(r.More.Present && r.More.Right <= r.Vault.X, "...left of the Vault");
var wide = InventoryHeaderLayout.Compute(600f, 150f, 50f, vault: true);
Eq(wide.Plan.Extras, TitleExtrasMode.Icons, "600 px with a vault: four icons");
Check(wide.Vault.X == 600f - 46 - 24 && wide.GInv.X == wide.Vault.X - 24, "...the icons start just left of the Vault");
// Garbage in, no crash and the Vault still present.
var bad = InventoryHeaderLayout.Compute(float.NaN, float.NaN, float.NaN, vault: true);
Check(bad.Vault.Present, "NaN sizes: the Vault slot exists (the caller never draws a header this small)");
}
}

View file

@ -2,7 +2,7 @@
<!--
Offline checks for the chat window's coordinate finder (src\RynthCore.Engine\UI\Data\
ChatCoords.cs, compiled in): which chat lines hold map coordinates, in which order and
ChatCoords.cs + a ChatSpan stand-in, compiled in): which chat lines hold map coordinates, in which order and
format, and which ordinary lines must not turn into coordinates.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->

View file

@ -0,0 +1,5 @@
// Stand-in for the engine's ChatSpan (UI/Data/ChatRouting.cs, which drags the whole rule engine in):
// ChatCoords.LinkSpans only reads Start, Length and Argb.
namespace RynthCore.Engine.UI.Data;
internal readonly record struct ChatSpan(int Start, int Length, uint Argb);

View file

@ -22,6 +22,9 @@ internal static class Program
One("Your location is: 0xA9B40019 [84.000 7.100 42.005] 0.0 0.0 0.0 1.0 = 42.1N, 33.6E", 42.1, 33.6, "42.1N, 33.6E");
One("drudges at 42N 33E", 42, 33, "42.0N, 33.0E");
One("0.0N, 101.9W", 0, -101.9, "0.0N, 101.9W");
// Pasted the way players often type them (lowercase, no space): RynthChat makes these links.
One("82.3n,34.2e", 82.3, 34.2, "82.3N, 34.2E");
One("Bob says, \"meet at 82.3n, 34.2e\"", 82.3, 34.2, "82.3N, 34.2E");
// Two in one line, in order.
var two = ChatCoords.Find("from 42.1N, 33.6E to 21.5S, 1.8W");
@ -42,10 +45,103 @@ internal static class Program
None("");
None(null);
PreCheck();
LinkSpans();
Console.WriteLine(_failed == 0 && _checks > 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks})");
return _failed == 0 && _checks > 0 ? 0 : 1;
}
/// <summary>The cheap pre-check ChatFace runs before the regex must never skip a line Find would link.</summary>
private static void PreCheck()
{
foreach (string t in new[] { "42.1N, 33.6E", "42N 33E", "33.6E 42.1N", "at 42.1 N, 33.6 E now", "82.3n,34.2e", "0.5S, 101.2W", "x1 n 2e" })
Check(ChatCoords.MayHaveCoords(t), $"pre-check lets \"{t}\" through");
foreach (string t in new[] { "", "hello world", "no digits here N E", "N5", "12 N (two spaces)", "forty two north" })
Check(!ChatCoords.MayHaveCoords(t), $"pre-check skips \"{t}\"");
// Soundness: over random lines built from coordinate-ish pieces, Find never finds a pair the pre-check skipped.
var rng = new Random(20261019);
string[] pieces = { "42.1", "33.6", "N", "S", "E", "W", "n", "e", " ", ", ", " ", "x", " ", "/", "101.9", "7.5", "5", "120" };
int found = 0;
for (int k = 0; k < 60000; k++)
{
var sb = new System.Text.StringBuilder();
for (int n = rng.Next(1, 9); n > 0; n--) sb.Append(pieces[rng.Next(pieces.Length)]);
string line = sb.ToString();
if (ChatCoords.Find(line).Count > 0)
{
found++;
if (!ChatCoords.MayHaveCoords(line)) Check(false, $"pre-check skipped \"{line}\", which holds a coordinate");
}
}
Check(found > 100, $"the random lines held coordinates to test with ({found})");
Check(true, "pre-check never skipped a line with a coordinate");
}
private const uint LinkCol = 0xFF5ECFE0;
/// <summary>The coordinate links laid over a rule's highlight spans.</summary>
private static void LinkSpans()
{
// No coordinates: the highlights come back as they were.
var plain = new[] { new ChatSpan(2, 3, 0xFF112233), new ChatSpan(8, 2, 0xFF445566) };
Same(ChatCoords.LinkSpans(plain, new List<ChatCoord>(), LinkCol), plain, "no coordinates: highlights unchanged");
Check(ChatCoords.LinkSpans(null, new List<ChatCoord>(), LinkCol).Length == 0, "no spans, no coordinates: nothing");
// A line with only a coordinate (no rule highlight): one link span over it.
string text = "meet at 42.1N, 33.6E soon";
var coords = ChatCoords.Find(text);
var only = ChatCoords.LinkSpans(null, coords, LinkCol);
Check(only.Length == 1 && only[0].Start == coords[0].Start && only[0].Length == coords[0].Length && only[0].Argb == LinkCol,
"a coordinate alone becomes one link span");
// A highlight across the whole line is cut around the coordinate: before, link, after.
var whole = new[] { new ChatSpan(0, text.Length, 0xFFAA0000) };
var cut = ChatCoords.LinkSpans(whole, coords, LinkCol);
Check(cut.Length == 3, $"a highlight over the coordinate is cut in two around it (got {cut.Length})");
if (cut.Length == 3)
{
Check(cut[0].Start == 0 && cut[0].Length == coords[0].Start && cut[0].Argb == 0xFFAA0000, "the part before keeps the highlight");
Check(cut[1].Start == coords[0].Start && cut[1].Length == coords[0].Length && cut[1].Argb == LinkCol, "the coordinate keeps the link colour");
int end = coords[0].Start + coords[0].Length;
Check(cut[2].Start == end && cut[2].Start + cut[2].Length == text.Length && cut[2].Argb == 0xFFAA0000, "the part after keeps the highlight");
}
// A highlight that only covers part of the coordinate loses that part and keeps the rest.
var half = new[] { new ChatSpan(coords[0].Start - 3, 8, 0xFF00AA00) }; // ends inside the coordinate
var halfCut = ChatCoords.LinkSpans(half, coords, LinkCol);
Check(halfCut.Length == 2 && halfCut[0].Argb == 0xFF00AA00 && halfCut[0].Length == 3 && halfCut[1].Argb == LinkCol,
"a highlight ending inside the coordinate is cut at it");
// A highlight beside the coordinate (no overlap) is untouched; the result is sorted and never overlaps.
var beside = new[] { new ChatSpan(0, 4, 0xFF0000AA), new ChatSpan(coords[0].Start + coords[0].Length + 1, 4, 0xFF0000BB) };
var res = ChatCoords.LinkSpans(beside, coords, LinkCol);
Check(res.Length == 3 && res[0].Argb == 0xFF0000AA && res[1].Argb == LinkCol && res[2].Argb == 0xFF0000BB, "highlights beside it stay, in order");
NoOverlap(res, "beside");
// Two coordinates and several highlights: sorted, no overlap, every coordinate present exactly once.
string two = "from 42.1N, 33.6E to 21.5S, 1.8W now";
var cs = ChatCoords.Find(two);
var hl = new[] { new ChatSpan(0, 9, 0xFF010101), new ChatSpan(10, 20, 0xFF020202) };
var r2 = ChatCoords.LinkSpans(hl, cs, LinkCol);
NoOverlap(r2, "two coordinates");
Check(r2.Count(s => s.Argb == LinkCol) == 2, "both coordinates are links");
foreach (ChatCoord c in cs)
Check(r2.Any(s => s.Start == c.Start && s.Length == c.Length && s.Argb == LinkCol), $"link span for {c.Text}");
}
private static void NoOverlap(ChatSpan[] spans, string what)
{
bool ok = true;
for (int i = 1; i < spans.Length; i++)
if (spans[i].Start < spans[i - 1].Start + spans[i - 1].Length) ok = false;
Check(ok, $"{what}: sorted and non-overlapping");
}
private static void Same(ChatSpan[] got, ChatSpan[] want, string what) =>
Check(got.Length == want.Length && got.Zip(want).All(p => p.First == p.Second), what);
private static void One(string text, double ns, double ew, string formatted)
{
var found = ChatCoords.Find(text);

View file

@ -27,6 +27,13 @@
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatFilterPresets.cs" Link="Engine\ChatFilterPresets.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatSettingsDto.cs" Link="Engine\ChatSettingsDto.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatLineColors.cs" Link="Engine\ChatLineColors.cs" />
<!-- 2026-10-19: the retail-chat verdict (a hidden line also stays out of AC's own chat window):
the real router, standard filters and verdict, with EngineStubs.cs standing in for the engine. -->
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatRouting.cs" Link="Engine\ChatRouting.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatRetailVerdict.cs" Link="Engine\ChatRetailVerdict.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Panels\RynthChatPresets.cs" Link="Engine\RynthChatPresets.cs" />
<!-- 2026-10-19: re-reading the shared rynthchat_settings.json when another client saved it. -->
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\SharedFileWatch.cs" Link="Engine\SharedFileWatch.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,24 @@
// The two engine pieces ChatRouting.cs calls, without the engine (same stand-ins as
// tools/ChatHistoryBench/Stubs.cs): RynthLog.UI and ChatModel's MentionEligible / BumpFiltersVersion.
namespace RynthCore.Engine.Compatibility
{
internal static class RynthLog
{
public static int Lines;
public static void UI(string message) { Lines++; }
}
}
namespace RynthCore.Engine.UI.Data
{
internal static class ChatModel
{
public static int FilterBumps;
internal static bool MentionEligible(string channel, int chatType) =>
(channel == "Chat" || channel == "Channels") && chatType is not (4 or 9 or 11);
internal static void BumpFiltersVersion() => FilterBumps++;
}
}

View file

@ -48,6 +48,11 @@ internal static class Program
WhenParsing();
PresetsCatchAndSpare();
PresetsWellFormed();
RetailChannels();
RetailStandardFilters();
RetailRules();
RetailSetting();
SharedFileReload();
LineColorTags();
LineColorKinds();
LineColorDefaultsUnchanged();
@ -431,6 +436,246 @@ internal static class Program
Check(ChatRuleMatching.WhenMatches(null, -1, "Chat", 2), "any");
}
// ── Retail chat verdict (2026-10-19; idea from Silentkelpie, rynth PR 6) ──
// A line the rules or standard filters hide also stays out of AC's own chat window.
// ChatRetailVerdict is the pure part of ChatModel.ShouldHideInRetail.
private static ChatRouter RetailRouter(params ChatFilterRule[] rules) =>
new(rules, mention: null, self: "", countHits: false);
private static ChatFilterRule Rule(string pattern, ChatRuleAction action, string when = "", string tab = "")
{
var r = new ChatFilterRule { Pattern = pattern, Action = action, Tab = tab };
r.When = when;
r.Recompile();
return r;
}
private static void ResetPresets()
{
foreach (var p in RynthCore.Engine.UI.Panels.RynthChatPresets.All)
{
p.Enabled = false;
p.Tab = "";
}
}
private static void RetailChannels()
{
Case("retail verdict: the channel is the one the RynthChat plugin files the line under");
(string Line, int Type, string Channel)[] cases =
{
("Bob says, \"hi\"", 2, "Chat"),
("Bob tells you, \"hi\"", 3, "Chat"),
("[Trade] Bob says, \"WTS\"", 8, "Channels"),
("[Trade] Bob says, \"WTS\"", 0x1C, "Channels"), // ILT / ACECustom deliver channel lines as 0x1C
("[General] Bob says, \"hi\"", 3, "Channels"), // the tag wins over the type
("[Celestial Hand] Bob says, \"hi\"", 3, "Channels"),
("[general] Bob says, \"hi\"", 3, "Channels"), // the tag is case-insensitive
("[Generals] Bob says, \"hi\"", 3, "Chat"), // not a tag
("You have killed 12 Drudges!", 0, "System"),
("You evaded Tusker Guard!", 6, "Combat"),
("Your spell fizzled.", 0x11, "Combat"),
("[RynthAi] Nav loaded", 0, "Rynth"),
("[RynthChat] hello", 3, "Rynth"), // plugin output is Rynth whatever type it was written with
("[rynthai] lower case", 0, "Rynth"),
("[RynthAi Item] Sword of Bob", 3, "Items"), // item info is checked before the Rynth prefix
("[RynthAi Item]no space", 3, "Rynth"), // the Items prefix has its trailing space
("something", 0x7F, "Other"),
};
foreach (var (line, type, chan) in cases)
Check(ChatRetailVerdict.ChannelFor(line, type) == chan, $"'{line}' type {type} -> {chan} (got {ChatRetailVerdict.ChannelFor(line, type)})");
Check(ChatRetailVerdict.ChannelFor("", 2) == "Chat" && ChatRetailVerdict.ChannelFor("", 0x7F) == "Other", "an empty line falls back to the type");
for (int t = 0; t < 40; t++)
Check(ChatRetailVerdict.ChannelForType(t) == ChatRetailVerdict.ChannelFor("plain", t), $"type {t}: no tag, the type decides");
}
private static void RetailStandardFilters()
{
Case("retail verdict: ticked standard filters hide their lines, moves and unticked ones don't");
var presets = RynthCore.Engine.UI.Panels.RynthChatPresets.All;
try
{
ResetPresets();
ChatRouter none = RetailRouter();
foreach (var p in presets)
{
int type = p.Where switch
{
RynthCore.Engine.UI.Panels.RynthChatPresets.Scope.CombatOnly => 0x11,
RynthCore.Engine.UI.Panels.RynthChatPresets.Scope.ChannelsOnly => 0x08,
_ => 0x00,
};
Check(!ChatRetailVerdict.IsHidden(none, p.Example, type), $"{p.Id}: unticked, '{p.Example}' prints");
p.Enabled = true; // hide
Check(ChatRetailVerdict.IsHidden(none, p.Example, type), $"{p.Id}: ticked, '{p.Example}' stays out of the retail chat");
p.Tab = "Spam"; // moved to a tab: RynthChat shows it there, AC still prints it
Check(!ChatRetailVerdict.IsHidden(none, p.Example, type), $"{p.Id}: moved to a tab, '{p.Example}' still prints in AC");
p.Enabled = false;
p.Tab = "";
}
// The reported case: Kill task progress.
var kill = RynthCore.Engine.UI.Panels.RynthChatPresets.Get("social.kill_task_progress");
Check(kill != null, "social.kill_task_progress exists");
if (kill != null)
{
const string killLine = "You have killed 22556 Fanatical Fiuns! You must kill 100000 to complete your task.";
kill.Enabled = true;
Check(ChatRetailVerdict.IsHidden(none, killLine, 0x00), "the kill-task line from the report is hidden");
Check(ChatRetailVerdict.IsHidden(none, killLine, 0x1B), "...whatever system-ish type it arrives with");
Check(!ChatRetailVerdict.IsHidden(none, "You have killed 3 Drudges! Your task is complete!", 0x00), "other kill lines print");
// Player speech is never taken by a filter held to non-chat channels.
Check(!ChatRetailVerdict.IsHidden(none, "Bob says, \"" + killLine + "\"", 0x02), "a player saying it in Local prints");
Check(!ChatRetailVerdict.IsHidden(none, "Bob tells you, \"" + killLine + "\"", 0x03), "a player telling it prints");
}
}
finally { ResetPresets(); }
}
private static void RetailRules()
{
Case("retail verdict: Hide rules hide, Move / Copy / colour rules and off rules don't");
try
{
ResetPresets();
Check(!ChatRetailVerdict.IsHidden(RetailRouter(), "anything", 3), "no rules: nothing hidden");
Check(!ChatRetailVerdict.IsHidden(RetailRouter(Rule("spam", ChatRuleAction.Hide)), "fine line", 3), "a line the rule doesn't match prints");
Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("spam", ChatRuleAction.Hide)), "buy spam now", 3), "a Hide rule hides it");
Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("spam", ChatRuleAction.Hide)), "SPAM", 3), "...case-insensitively");
var off = Rule("spam", ChatRuleAction.Hide);
off.Enabled = false;
Check(!ChatRetailVerdict.IsHidden(RetailRouter(off), "buy spam now", 3), "a rule that is switched off hides nothing");
Check(!ChatRetailVerdict.IsHidden(RetailRouter(Rule("spam", ChatRuleAction.Move, tab: "Mail")), "buy spam now", 3), "a Move rule prints in AC");
Check(!ChatRetailVerdict.IsHidden(RetailRouter(Rule("spam", ChatRuleAction.Copy, tab: "Mail")), "buy spam now", 3), "a Copy rule prints in AC");
var colour = Rule("spam", ChatRuleAction.Color);
colour.ColorMode = ChatColorMode.Line;
Check(!ChatRetailVerdict.IsHidden(RetailRouter(colour), "buy spam now", 3), "a colour rule prints in AC");
// First routing rule decides, as in RynthChat.
Check(!ChatRetailVerdict.IsHidden(RetailRouter(Rule("spam", ChatRuleAction.Move, tab: "Mail"), Rule("spam", ChatRuleAction.Hide)), "spam", 3),
"a Move rule ahead of a Hide rule decides: not hidden");
Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("spam", ChatRuleAction.Hide), Rule("spam", ChatRuleAction.Move, tab: "Mail")), "spam", 3),
"a Hide rule ahead of a Move rule decides: hidden");
// "When" conditions see the channel RynthChat gives the line.
Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("Sword", ChatRuleAction.Hide, "chan:Items")), "[RynthAi Item] Sword of Bob", 3), "chan:Items rule hides item info");
Check(!ChatRetailVerdict.IsHidden(RetailRouter(Rule("Sword", ChatRuleAction.Hide, "chan:Items")), "Bob says, \"Sword\"", 2), "...but not other lines");
Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("loaded", ChatRuleAction.Hide, "chan:Rynth")), "[RynthAi] Nav loaded", 0), "chan:Rynth rule hides plugin output");
Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("WTS", ChatRuleAction.Hide, "chan:Channels")), "[Trade] Bob says, \"WTS\"", 0x1C), "chan:Channels rule hides a tagged 0x1C channel line");
Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("WTS", ChatRuleAction.Hide, "chan:Channels")), "[Trade] Bob says, \"WTS\"", 8), "...and a type 8 one");
Check(!ChatRetailVerdict.IsHidden(RetailRouter(Rule("WTS", ChatRuleAction.Hide, "chan:Channels")), "Bob tells you, \"WTS\"", 3), "...not a tell");
Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("busy", ChatRuleAction.Hide, "type:26")), "You're too busy!", 26), "type:26 rule hides a type 26 line");
Check(!ChatRetailVerdict.IsHidden(RetailRouter(Rule("busy", ChatRuleAction.Hide, "type:26")), "You're too busy!", 0), "...not another type");
// A custom rule decides before the standard filters, as in RynthChat: a Move rule keeps a ticked filter from hiding the line.
var kill = RynthCore.Engine.UI.Panels.RynthChatPresets.Get("social.kill_task_progress")!;
kill.Enabled = true;
const string killLine = "You have killed 12 Drudges! You must kill 50 to complete your task.";
Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("nothing", ChatRuleAction.Hide)), killLine, 0), "a ticked filter hides when no rule decided first");
Check(!ChatRetailVerdict.IsHidden(RetailRouter(Rule("killed", ChatRuleAction.Move, tab: "Kills")), killLine, 0), "a Move rule ahead of the ticked filter keeps the line");
// The retail router must not double count what RynthChat's own pass counts.
var counted = Rule("spam", ChatRuleAction.Hide);
RetailRouter(counted).Evaluate("spam", "Chat", 3, null);
Check(counted.Hits == 0, "a router built with countHits: false leaves Hits alone");
}
finally { ResetPresets(); }
}
private static void RetailSetting()
{
Case("retail verdict: the hideInRetail setting (on unless a file says false)");
var opts = RynthChatJsonContext.Default.RynthChatSettingsDto;
RynthChatSettingsDto old = JsonSerializer.Deserialize(OldFile, opts)!;
Check(old.HideInRetail == null, "a file from before the setting has no value (ChatModel reads that as on)");
string saved = JsonSerializer.Serialize(old, opts);
Check(!saved.Contains("hideInRetail", StringComparison.Ordinal), "saving an old file writes no hideInRetail key");
old.HideInRetail = false;
string off = JsonSerializer.Serialize(old, opts);
Check(off.Contains("\"hideInRetail\":false", StringComparison.Ordinal), "off is saved as hideInRetail:false");
Check(JsonSerializer.Deserialize(off, opts)!.HideInRetail == false, "off loads back");
old.HideInRetail = true;
Check(JsonSerializer.Deserialize(JsonSerializer.Serialize(old, opts), opts)!.HideInRetail == true, "on round-trips");
Check(JsonSerializer.Deserialize("{\"hideInRetail\":null}", opts)!.HideInRetail == null, "null reads as absent");
Check(JsonSerializer.Deserialize(off, opts)!.Filters!.Length == 3, "the other fields are untouched");
}
// ── Shared settings reload (2026-10-19; idea from Silentkelpie, rynth PR 6) ──
// SharedFileWatch: another client rewrote rynthchat_settings.json -> read it; our own saves don't count.
private static void SharedFileReload()
{
Case("shared settings: a client re-reads the file when ANOTHER client saved it");
string dir = Path.Combine(Path.GetTempPath(), "rynth-sharedwatch-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
try
{
string path = Path.Combine(dir, "rynthchat_settings.json");
DateTime t0 = new(2026, 10, 19, 12, 0, 0, DateTimeKind.Utc);
void Write(string text, int secondsAfterT0)
{
File.WriteAllText(path, text);
File.SetLastWriteTimeUtc(path, t0.AddSeconds(secondsAfterT0));
}
// No file yet: nothing to read, no error.
var w = new SharedFileWatch(pollMs: 2000);
Check(w.Changed(10_000, path) == null, "no file: null");
// Loaded at start: that timestamp is not a change.
Write("{\"v\":1}", 0);
w.Seen(File.GetLastWriteTimeUtc(path));
Check(w.Changed(20_000, path) == null, "the file we loaded is not a change");
// Another client saves: read once.
Write("{\"v\":2}", 5);
Check(w.Changed(20_500, path) == null, "...but not before the poll interval (2 s) is up");
Check(w.Changed(22_000, path) == "{\"v\":2}", "another client's save is returned");
Check(w.Changed(24_000, path) == null, "...once");
// Our own save (Saved is called just before the swap) is not a change.
string mine = "{\"v\":3,\"mine\":true}";
w.Saved(mine);
Write(mine, 10);
Check(w.Changed(26_000, path) == null, "this client's own save is not a change");
Check(w.Changed(28_000, path) == null, "...and stays quiet");
// Another client saves after ours: read.
Write("{\"v\":4}", 15);
Check(w.Changed(30_000, path) == "{\"v\":4}", "another client's later save is returned");
// It saves the same text as our last save again (a copy of our settings): still ours by text.
Write(mine, 20);
Check(w.Changed(32_000, path) == null, "text identical to our last save is treated as ours");
// The same timestamp again (nothing written): not read.
Check(w.Changed(34_000, path) == null, "an unchanged timestamp is not read");
// A file that is being swapped (cannot be read): the change is offered again, not lost.
Write("{\"v\":5}", 25);
using (new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None))
{
bool threw = false;
try { w.Changed(36_000, path); }
catch (IOException) { threw = true; }
Check(threw, "an unreadable file throws (the caller logs it)");
}
Check(w.Changed(38_000, path) == "{\"v\":5}", "the change that could not be read is returned at the next poll");
// The file is removed: nothing, no throw.
File.Delete(path);
Check(w.Changed(40_000, path) == null, "a removed file is null");
// A watcher that never saw the file (no file at start) reads the first one it finds.
var late = new SharedFileWatch(pollMs: 2000);
Write("{\"v\":6}", 30);
Check(late.Changed(50_000, path) == "{\"v\":6}", "a file that appears after start is read");
}
finally { try { Directory.Delete(dir, true); } catch { } }
}
// ── Standard filters ─────────────────────────────────────────────────
private static void PresetsCatchAndSpare()

View file

@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the Settings rows of SilentKelpie's RynthAi combat additions (taken 2026-10-19):
Variable Power (monster rules), Hitting the Environment (Missile / Magic) and Pull Away (Kite), and
the Power / Kite fields of a monster rule (UI\Data\SettingsData.cs, DamageData.cs, MonstersPanel.cs).
The new RynthAi settings are mirrored as nullable fields like the Vaulted Dungeons switch: a RynthAi
that predates them omits them, the rows stay hidden, and a save sends null, which RynthAi leaves
alone; one that has them shows the rows with the documented defaults (Off / unchanged).
The engine has no test seam for SettingsData.cs (it pulls in the whole ImGui layer), so this
references the built engine assembly and reaches the internal types by reflection. x86, like
the engine: needs the x86 .NET runtime (C:\Program Files (x86)\dotnet).
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<Platforms>x86</Platforms>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>CombatSettingsTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RynthCore.Engine\RynthCore.Engine.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,182 @@
using System.Collections;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
namespace CombatSettingsTests
{
// Reaches RynthCore.Engine's internal settings mirror, schema and Monsters rule by reflection.
// 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 const string Ns = "RynthCore.Engine.UI.Data.";
private const BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
// RynthAi's SettingsBridgePayload names, with the type each mirror field must have.
private static readonly (string Name, Type Type, string Default)[] Mirrors =
{
("VariablePowerMin", typeof(int?), "50"),
("VariablePowerMax", typeof(int?), "100"),
("MissileEnvironmentResponse", typeof(int?), "0"),
("MagicEnvironmentResponse", typeof(int?), "0"),
("EnvironmentImpactLimit", typeof(int?), "2"),
("EnvironmentImpactWindowSec", typeof(int?), "20"),
("EnvironmentApproachMeters", typeof(int?), "6"),
("EnvironmentMinDistance", typeof(int?), "3"),
("EnvironmentSkipSec", typeof(int?), "30"),
("KitePullMeters", typeof(int?), "20"),
("KiteTagFirst", typeof(bool?), "true"),
};
private static int Main()
{
Assembly engine = Assembly.Load("RynthCore.Engine");
Type settingsType = engine.GetType(Ns + "RynthAiSettings", throwOnError: true)!;
Type ctxType = engine.GetType(Ns + "RynthAiSettingsJsonContext", throwOnError: true)!;
Type schemaType = engine.GetType(Ns + "SettingsSchema", throwOnError: true)!;
object ctx = ctxType.GetProperty("Default", All)!.GetValue(null)!;
var info = (JsonTypeInfo)ctxType.GetProperty("RynthAiSettings", All)!.GetValue(ctx)!;
object Parse(string json) => JsonSerializer.Deserialize(json, info)!;
// ── The mirrors ─────────────────────────────────────────────────────────────
object fresh = Activator.CreateInstance(settingsType, nonPublic: true)!;
string freshJson = JsonSerializer.Serialize(fresh, info);
foreach (var (name, type, _) in Mirrors)
{
PropertyInfo? p = settingsType.GetProperty(name, All);
Check(p != null && p.PropertyType == type, $"{name}: a nullable mirror of RynthAi's setting");
if (p == null) continue;
Check(p.GetValue(fresh) == null, $"{name}: a fresh mirror holds no value (nothing is claimed until RynthAi sends it)");
Check(p.GetValue(Parse("{\"BoostNavPriority\":true}")) == null, $"{name}: an older RynthAi's payload leaves it absent");
Check(freshJson.Contains($"\"{name}\":null"), $"{name}: an unset mirror saves null, never a made-up value (RynthAi leaves its own alone)");
}
string sent = "{\"VariablePowerMin\":40,\"VariablePowerMax\":90,\"MissileEnvironmentResponse\":2,\"MagicEnvironmentResponse\":3," +
"\"EnvironmentImpactLimit\":4,\"EnvironmentImpactWindowSec\":45,\"EnvironmentApproachMeters\":8,\"EnvironmentMinDistance\":5," +
"\"EnvironmentSkipSec\":60,\"KitePullMeters\":33,\"KiteTagFirst\":false}";
object withValues = Parse(sent);
Check((int?)settingsType.GetProperty("VariablePowerMin", All)!.GetValue(withValues) == 40, "RynthAi's value arrives");
Check((bool?)settingsType.GetProperty("KiteTagFirst", All)!.GetValue(withValues) == false, "a false bool arrives as false, not null");
string back = JsonSerializer.Serialize(withValues, info);
foreach (string piece in new[] { "\"VariablePowerMax\":90", "\"MagicEnvironmentResponse\":3", "\"KitePullMeters\":33", "\"KiteTagFirst\":false" })
Check(back.Contains(piece), $"a save sends back what RynthAi sent ({piece})");
// ── The rows ────────────────────────────────────────────────────────────────
var tabs = new Dictionary<string, List<object>>();
foreach (object t in (IEnumerable)schemaType.GetField("Tabs", All)!.GetValue(null)!)
{
string tabName = (string)t.GetType().GetProperty("Name")!.GetValue(t)!;
tabs[tabName] = ((IEnumerable)t.GetType().GetProperty("Rows")!.GetValue(t)!).Cast<object>().ToList();
}
Check(tabs.ContainsKey("Melee Combat") && tabs.ContainsKey("Spell Combat"), "the Melee Combat and Spell Combat tabs exist");
if (!tabs.ContainsKey("Melee Combat") || !tabs.ContainsKey("Spell Combat")) return Finish();
static string Label(object r) => (string?)r.GetType().GetProperty("Label")!.GetValue(r) ?? "";
static string Kind(object r) => r.GetType().GetProperty("Kind")!.GetValue(r)!.ToString()!;
object? Row(string tab, string label, string kind) => tabs[tab].FirstOrDefault(r => Label(r) == label && Kind(r) == kind);
bool Visible(object row, object s) => (bool)row.GetType().GetMethod("IsVisible")!.Invoke(row, new[] { s })!;
double Get(object row, object s) => (double)((Delegate)row.GetType().GetProperty("Get")!.GetValue(row)!).DynamicInvoke(s)!;
void Set(object row, object s, double v) => ((Delegate)row.GetType().GetProperty("Set")!.GetValue(row)!).DynamicInvoke(s, v);
// (tab, label, kind, default shown, min, max)
var rows = new (string Tab, string Label, string Kind, double Default, double Min, double Max)[]
{
("Melee Combat", "Variable Min %", "Int", 50, 0, 100),
("Melee Combat", "Variable Max %", "Int", 100, 0, 100),
("Melee Combat", "Missile Response", "Combo", 0, 0, 3),
("Melee Combat", "Hits to trip", "Int", 2, 1, 10),
("Melee Combat", "Window (s)", "Int", 20, 5, 120),
("Melee Combat", "Move closer by (m)", "Int", 6, 1, 30),
("Melee Combat", "Closest (m)", "Int", 3, 1, 30),
("Melee Combat", "Skip target (s)", "Int", 30, 5, 300),
("Melee Combat", "Pull Distance (m)", "Int", 20, 3, 100),
("Melee Combat", "Tag Before Fleeing", "Bool", 1, 0, 1),
("Spell Combat", "Magic Response", "Combo", 0, 0, 3),
};
object older = Parse("{\"BoostNavPriority\":true}"); // what an older RynthAi sends
object newer = Parse("{\"VariablePowerMin\":50,\"VariablePowerMax\":100,\"MissileEnvironmentResponse\":0,\"MagicEnvironmentResponse\":0," +
"\"EnvironmentImpactLimit\":2,\"EnvironmentImpactWindowSec\":20,\"EnvironmentApproachMeters\":6,\"EnvironmentMinDistance\":3," +
"\"EnvironmentSkipSec\":30,\"KitePullMeters\":20,\"KiteTagFirst\":true}"); // the plugin's own defaults
foreach (var (tab, label, kind, def, min, max) in rows)
{
object? row = Row(tab, label, kind);
Check(row != null, $"{tab} / {label}: a {kind} row");
if (row == null) continue;
Check(!Visible(row, older), $"{label}: hidden for an older RynthAi (it never sent the value)");
Check(!Visible(row, fresh), $"{label}: hidden before RynthAi has sent anything");
Check(Visible(row, newer), $"{label}: shown once RynthAi sends it");
Check(Get(row, newer) == def, $"{label}: shows the plugin's default ({def}) as sent");
Check(Get(row, older) == def, $"{label}: reads the default for an unset mirror, without throwing");
if (kind != "Bool") Check((double)row.GetType().GetProperty("Min")!.GetValue(row)! == min && (double)row.GetType().GetProperty("Max")!.GetValue(row)! == max, $"{label}: range {min}..{max}");
}
// Section headers and spacers of these groups follow the same gate (no empty headers on an older RynthAi).
foreach (string sec in new[] { "Variable Power (monster rules)", "Hitting the Environment", "Pull Away (Kite)" })
foreach (string tab in new[] { "Melee Combat", "Spell Combat" })
{
object? header = Row(tab, sec, "Section");
if (header == null) continue;
Check(!Visible(header, older), $"{tab} / {sec}: the header is hidden for an older RynthAi");
Check(Visible(header, newer), $"{tab} / {sec}: the header shows for a newer one");
}
Check(Row("Melee Combat", "Pull Away (Kite)", "Section") != null && Row("Melee Combat", "Hitting the Environment", "Section") != null
&& Row("Melee Combat", "Variable Power (monster rules)", "Section") != null && Row("Spell Combat", "Hitting the Environment", "Section") != null, "all four section headers exist");
// The combos list RynthAi's EnvironmentResponse in its order.
object missile = Row("Melee Combat", "Missile Response", "Combo")!;
var items = (string[])missile.GetType().GetProperty("Items")!.GetValue(missile)!;
Check(items.SequenceEqual(new[] { "Off", "Move closer", "New target", "Move closer, then new target" }), "Missile Response: Off, Move closer, New target, Move closer then new target (RynthAi's order)");
// A row edits only its own property; the rest rides along.
object edit = Parse("{\"BoostNavPriority\":true," + sent.TrimStart('{'));
Set(Row("Melee Combat", "Pull Distance (m)", "Int")!, edit, 55);
Set(Row("Melee Combat", "Tag Before Fleeing", "Bool")!, edit, 1);
Set(Row("Spell Combat", "Magic Response", "Combo")!, edit, 1);
string after = JsonSerializer.Serialize(edit, info);
Check(after.Contains("\"KitePullMeters\":55") && after.Contains("\"KiteTagFirst\":true") && after.Contains("\"MagicEnvironmentResponse\":1"), "the edits land on their own properties");
Check(after.Contains("\"BoostNavPriority\":true") && after.Contains("\"EnvironmentSkipSec\":60") && after.Contains("\"MissileEnvironmentResponse\":2"), "the other settings ride along unchanged");
// The rows an older RynthAi lacks don't change what a plain save sends.
Set(Row("Melee Combat", "Pull Distance (m)", "Int")!, older, 30); // can't happen in the UI (hidden); must not throw
Check(true, "setting a hidden row doesn't throw");
// ── The monster rule: Power and Kite ────────────────────────────────────────
Type damage = engine.GetType(Ns + "DamageCommands", throwOnError: true)!;
var powers = (string[])damage.GetField("AttackPowerModes", All)!.GetValue(null)!;
var kites = (string[])damage.GetField("KiteModes", All)!.GetValue(null)!;
Check(powers.SequenceEqual(new[] { "Default", "High", "Reckless", "Variable", "Reckless + Variable" }), "Power choices are spelled as RynthAi's AttackPowerModes");
Check(kites.SequenceEqual(new[] { "Default", "Off", "PullAway" }), "Kite choices are spelled as RynthAi's KiteModes");
Type monsters = engine.GetType("RynthCore.Engine.UI.Panels.MonstersPanel", throwOnError: true)!;
Type rule = monsters.GetNestedType("Rule", All)!;
object r1 = Activator.CreateInstance(rule, nonPublic: true)!;
Check((string)rule.GetProperty("AttackPower")!.GetValue(r1)! == "Default", "a new rule's Power is Default (follows the DEFAULT line)");
Check((string)rule.GetProperty("Kite")!.GetValue(r1)! == "Default", "a new rule's Kite is Default (Off on the DEFAULT line)");
MethodInfo equal = monsters.GetMethod("RulesEqual", All)!;
Type listType = typeof(List<>).MakeGenericType(rule);
IList Lst(params object[] xs) { var l = (IList)Activator.CreateInstance(listType)!; foreach (object x in xs) l.Add(x); return l; }
object r2 = Activator.CreateInstance(rule, nonPublic: true)!;
Check((bool)equal.Invoke(null, new object[] { Lst(r1), Lst(r2) })!, "two default rules are equal");
rule.GetProperty("Kite")!.SetValue(r2, "PullAway");
Check(!(bool)equal.Invoke(null, new object[] { Lst(r1), Lst(r2) })!, "a changed Kite is a change (it is saved)");
object r3 = Activator.CreateInstance(rule, nonPublic: true)!;
rule.GetProperty("AttackPower")!.SetValue(r3, "Variable");
Check(!(bool)equal.Invoke(null, new object[] { Lst(r1), Lst(r3) })!, "a changed Power is a change (it is saved)");
return Finish();
}
private static int Finish()
{
Console.WriteLine(_fails == 0 ? $"All {_asserts} checks passed." : $"{_fails} of {_asserts} checks FAILED.");
return _fails == 0 ? 0 : 1;
}
}
}

View file

@ -82,6 +82,41 @@ internal static partial class Program
DrainBounds();
DrainCombatHoldsInventory();
DrainSweepRetriesAfterOverflow();
DrainReachesItemsBehindTheEvaluationBudget();
}
// Review fix 2026-10-18: more than MaxEvaluatedPerTick items waiting (here the pack waits through
// combat) used to leave the newest ones, at the end of the list, unlooked-at for as long as the
// earlier ones kept waiting. The drain now resumes where it stopped.
private static void DrainReachesItemsBehindTheEvaluationBudget()
{
_case = "drain round robin";
const uint Chest = 0x80000B00, Loot = 0x80000B01;
var w = new FakeWorld { Now = 1_000_000, Warm = true };
var d = new AutoIdDrain(w);
int pack = AutoIdDrain.MaxEvaluatedPerTick + 88;
for (uint i = 1; i <= pack; i++) { w.Snapshot[0x8000D000 + i] = (Me, 0); d.Offer(0x8000D000 + i, w.Now - 10_000); }
w.Snapshot[Loot] = (Chest, 0); d.Offer(Loot, w.Now - 10_000); // newest: last in the list
AutoIdDrain.Context Fight() => new()
{
Now = w.Now, Mode = AutoIdMode.Limited, PlayerId = Me, OpenContainer = Chest, OpenedAtMs = w.Now - 5_000,
SettleUntilMs = 0, LoginCompleteAtMs = 1, CombatBusy = true,
};
d.Tick(Fight(), 0);
Check(d.PendingCount == pack + 1, $"first tick: the pack waits, the chest item is behind the budget (pending {d.PendingCount})");
Check(!w.Sent.Any(s => s.Id == Loot), "first tick: the chest item was not reached yet");
for (int k = 0; k < 4; k++) { w.Now += 100; d.Tick(Fight(), 0); }
Check(w.Sent.Any(s => s.Id == Loot), "within a few ticks the chest item is reached and sent although the pack keeps waiting");
Check(!w.Sent.Any(s => (s.Id & 0xFFFFF000) == 0x8000D000), "while the pack, in combat, sent nothing");
Check(d.PendingCount == pack, $"and the waiting pack is all still pending (pending {d.PendingCount})");
// Every pack item is looked at in turn: end the fight and they all go out.
AutoIdDrain.Context Calm() => new()
{
Now = w.Now, Mode = AutoIdMode.Limited, PlayerId = Me, OpenContainer = 0, OpenedAtMs = 0,
SettleUntilMs = 0, LoginCompleteAtMs = 1, CombatBusy = false,
};
for (int k = 0; k < 4000 && d.PendingCount > 0; k++) { w.Now += 100; d.Tick(Calm(), 0); }
Check(d.PendingCount == 0, $"after combat the whole backlog drains (pending {d.PendingCount})");
}
// The pack is created at login, before the snapshot is warm; it must still go out.

View file

@ -20,6 +20,7 @@
AutoIdDrain.cs the AutoId backlog against a fake world: login sweep, cold snapshot,
refused sends kept, bounds
IdRequester.cs the engine-send marker that tags every engine 0xC8
DumpBudget.cs the full OOM dump needs free space and a cap on dumps across clients
PumpGuards.cs TickAll's own steps are caught (logged once, then counted); the hang
report names the plugin call the pump is inside
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
@ -48,6 +49,7 @@
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\CrashExitRule.cs" Link="Engine\CrashExitRule.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AutoIdPolicy.cs" Link="Engine\AutoIdPolicy.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AutoIdDrain.cs" Link="Engine\AutoIdDrain.cs" />
<Compile Include="..\..\src\RynthCore.Engine\DumpBudget.cs" Link="Engine\DumpBudget.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Net\IdRequester.cs" Link="Engine\IdRequester.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PumpGuards.cs" Link="Engine\PumpGuards.cs" />
</ItemGroup>

View file

@ -37,6 +37,10 @@ internal static partial class Program
TransitionDiagonalAndBorderWalksNeverHold();
TransitionTwoLandblockJumpHolds();
TransitionDrainHoldThenStopsSurvive();
TransitionValveOpensAfterMaxHold();
TransitionValveStuckPortalAndReset();
TransitionGateDisabledNeverHolds();
TransitionValveIgnoresShortTransitions();
AddressSpaceFold();
@ -266,6 +270,104 @@ internal static partial class Program
Check(!s.InTransition(9000 + WorldTransitionState.SettleMs), "window ends");
}
// The safety valve (review 2026-10-18): a character that keeps reading dead (Health 0 after a
// revive) must not freeze every queued action for good.
private static void TransitionValveOpensAfterMaxHold()
{
_case = "valve dead forever";
var s = Started();
long t = 2000;
var e = s.Sample(t, true, false, 0x00AE);
Check((e & WorldTransitionState.Edge.Died) != 0 && !s.Overridden, "dead: gate held, valve shut");
Check(s.Decide(t, 1500, false) == WorldTransitionState.Verdict.Hold, "an action queued before is held");
int overrideEdges = 0;
long openedAt = 0;
for (t += 1000; t <= 2000 + WorldTransitionState.MaxHoldMs + 10_000; t += 1000)
{
e = s.Sample(t, true, false, 0x00AE); // still reading dead
if ((e & WorldTransitionState.Edge.GateOverride) != 0) { overrideEdges++; openedAt = t; }
if (t < 2000 + WorldTransitionState.MaxHoldMs)
Check(s.InTransition(t) && !s.Overridden, $"held before the bound (t={t})");
}
Check(overrideEdges == 1, $"exactly one override edge, got {overrideEdges}");
Check(openedAt == 2000 + WorldTransitionState.MaxHoldMs, $"opens at the bound, got {openedAt - 2000} ms");
Check(s.Overridden && s.Overrides == 1, "valve open, counted once");
long now = t;
Check(!s.InTransition(now), "open: nothing is in transition any more");
Check(s.RawInTransition(now), "(the raw state still says dead)");
Check(s.Decide(now, now - 10, false) == WorldTransitionState.Verdict.Run, "new work runs");
Check(s.Decide(now, 1500, false) == WorldTransitionState.Verdict.Drop, "work queued during the hold is dropped as stale, like after any transition");
Check(s.Decide(now, 1500, true) == WorldTransitionState.Verdict.Run, "a stop queued during the hold still runs");
// The character does come back later: the raw transition ends, and the valve re-arms.
s.Sample(now + 1000, false, false, 0x00AE);
Check(s.Overridden, "revived, but the settle window is still running: still open");
s.Sample(now + 1000 + WorldTransitionState.SettleMs, false, false, 0x00AE);
Check(!s.Overridden && !s.RawInTransition(now + 1000 + WorldTransitionState.SettleMs), "settled: valve re-armed");
var d = s.Sample(now + 20_000, true, false, 0x00AE);
Check((d & WorldTransitionState.Edge.Died) != 0 && s.InTransition(now + 20_000), "the next death holds again");
Check(s.HeldForMs(now + 20_000) == 0, "held-for restarts from the new transition");
}
private static void TransitionValveStuckPortalAndReset()
{
_case = "valve stuck portal";
var s = Started();
s.Sample(2000, false, true, 0x00AE);
long t = 2000;
bool opened = false;
for (; t < 2000 + WorldTransitionState.MaxHoldMs + 5000; t += 500)
if ((s.Sample(t, false, true, 0x00AE) & WorldTransitionState.Edge.GateOverride) != 0) opened = true;
Check(opened && !s.InTransition(t) && s.Overrides == 1, "a portal flag that never clears opens the gate once");
// Exiting the portal ends it.
s.Sample(t, false, false, 0x00AE);
s.Sample(t + WorldTransitionState.SettleMs + 1, false, false, 0x00AE);
Check(!s.Overridden, "re-armed after the transition ends");
}
private static void TransitionGateDisabledNeverHolds()
{
_case = "gate disabled";
var s = Started();
s.Enabled = false;
s.Sample(2000, true, false, 0x00AE);
Check(s.RawInTransition(2000) && !s.InTransition(2000), "dead, gate off: not in transition");
Check(!s.CheckHolding(2000) && s.LastBlockedMs == 0, "nothing held, nothing recorded");
Check(s.Decide(2000, 1900, false) == WorldTransitionState.Verdict.Run, "work runs through a death");
Check(s.Decide(2000, 1900, true) == WorldTransitionState.Verdict.Run, "and stops too");
long late = 2000 + WorldTransitionState.MaxHoldMs + 1000;
s.Sample(late, true, false, 0x00AE);
Check(s.Overrides == 1, "the valve counter still counts (only information while the gate is off)");
s.Enabled = true;
s.Sample(late + 1000, true, false, 0x00AE);
Check(!s.InTransition(late + 1000), "turned on again while the valve is open: stays open until the transition ends");
}
private static void TransitionValveIgnoresShortTransitions()
{
_case = "valve short transitions";
var s = Started();
long t = 2000;
// 40 deaths/portals in a row, each well under the bound, each followed by a quiet spell.
for (int i = 0; i < 40; i++)
{
s.Sample(t, true, false, 0x00AE);
t += 20_000;
s.Sample(t, false, true, 0x00AE);
t += 20_000;
s.Sample(t, false, false, 0x00AE);
t += WorldTransitionState.SettleMs + 1000;
s.Sample(t, false, false, 0x00AE);
t += 10_000;
}
Check(s.Overrides == 0, $"transitions that end on their own never trip it, got {s.Overrides}");
// A death straight into a portal without a gap is ONE continuous transition.
var u = Started();
u.Sample(2000, true, false, 0x00AE);
u.Sample(2000 + 60_000, false, true, 0x00AE);
var edges = u.Sample(2000 + 125_000, false, true, 0x00AE);
Check((edges & WorldTransitionState.Edge.GateOverride) != 0, "dead then portaling without a gap: one transition, valve opens at the bound");
}
private static void TransitionLandblockJumpWithoutPortalHolds()
{
_case = "transition jump";

View file

@ -21,6 +21,8 @@ internal static partial class Program
RequestIdNeverMergesIntoAHeldEntry();
ReleasedDataKeptSoRecreateSkips();
ReleasedDataStaleOnLongAbsenceIsDroppedAtRecreate();
DumpBudgetRules();
ReleasedDataExpiresAndServerDeleteEvicts();
TeleportMessageStartsTheWindow();
@ -267,13 +269,84 @@ internal static partial class Program
// Client release (BeingDeleted): AppraisalHooks.OnClientRelease
if (!keep.OnRelease(50, t + 60_000)) cache.Remove(50);
elig.OnClientRelease(50);
// Re-created 5 minutes later: AutoIdService.Enqueue (MarkLive, then the decision)
keep.Forget(50);
var d = elig.OnCreate(50, t + 5 * 60_000, cache.Contains(50));
Check(d == AutoIdEligibility.CreateDecision.SkipRecent, $"re-created within 10 min with the data kept: skipped ({d})");
// Re-created 30 s later (out of view and back): AutoIdService.Enqueue (MarkLive, then the decision)
if (keep.TakeLive(50, t + 90_000)) cache.Remove(50);
var d = elig.OnCreate(50, t + 90_000, cache.Contains(50));
Check(d == AutoIdEligibility.CreateDecision.SkipRecent, $"re-created soon after the release with the data kept: skipped ({d})");
Check(elig.SkippedRecentTotal == 1, $"SkippedRecentCount moves (got {elig.SkippedRecentTotal})");
}
/// <summary>
/// Review fix 2026-10-18: data kept since a release ReleasedObjectRetention.StaleAfterMs ago or
/// more is dropped when the object is re-created (the client sent no updates meanwhile, so a
/// stack count could be minutes old), and the re-create is appraised again.
/// </summary>
private static void ReleasedDataStaleOnLongAbsenceIsDroppedAtRecreate()
{
_case = "release stale";
var cache = new HashSet<uint>();
var keep = new ReleasedObjectRetention();
var elig = new AutoIdEligibility();
long t = 1000;
elig.OnCreate(60, t, cache.Contains(60));
elig.OnSent(60, t + 100);
cache.Add(60);
if (!keep.OnRelease(60, t + 1000)) cache.Remove(60);
elig.OnClientRelease(60);
Check(keep.IsReleased(60), "released: kept");
// 5 minutes later it comes back.
long back = t + 1000 + 5 * 60_000;
bool stale = keep.TakeLive(60, back);
Check(stale, "re-created 5 min after the release: its kept data is stale");
if (stale) cache.Remove(60); // AppraisalHooks.MarkLive evicts it
Check(!keep.IsReleased(60), "and it is current again");
var d = elig.OnCreate(60, back, cache.Contains(60));
Check(d == AutoIdEligibility.CreateDecision.Appraise, $"the re-create is a candidate again ({d})");
// Exactly at the bound, and just under it.
var k2 = new ReleasedObjectRetention();
k2.OnRelease(1, 10_000); k2.OnRelease(2, 10_000);
Check(!k2.TakeLive(1, 10_000 + ReleasedObjectRetention.StaleAfterMs - 1), "just under StaleAfterMs: kept");
Check(k2.TakeLive(2, 10_000 + ReleasedObjectRetention.StaleAfterMs), "at StaleAfterMs: stale");
Check(!k2.TakeLive(3, 99_999), "never released: not stale");
Check(!k2.TakeLive(2, 99_999_999), "and a second create finds nothing to expire");
}
/// <summary>DumpBudget: the full OUT OF MEMORY dump needs room on the volume and a cap across clients.</summary>
private static void DumpBudgetRules()
{
_case = "dump budget";
const long GB = 1024L * 1024 * 1024, MB = 1024L * 1024;
long est = DumpBudget.EstimateFullDumpBytes(3 * GB);
Check(est == 3 * GB + DumpBudget.FullDumpOverheadBytes, "the estimate is the private bytes plus the overhead");
Check(DumpBudget.EstimateFullDumpBytes(0) == DumpBudget.FallbackProcessBytes + DumpBudget.FullDumpOverheadBytes,
"unknown size: the 32-bit maximum");
Check(DumpBudget.Evaluate(100 * GB, est, 0, 0) == DumpVerdict.Full, "plenty of room, no other dumps: full");
Check(DumpBudget.Evaluate(-1, est, 0, 0) == DumpVerdict.LowDisk, "free space unknown: not full");
Check(DumpBudget.Evaluate(est + DumpBudget.MinFreeAfterFullDump - 1, est, 0, 0) == DumpVerdict.LowDisk,
"one byte short of leaving the margin free: low disk");
Check(DumpBudget.Evaluate(est + DumpBudget.MinFreeAfterFullDump, est, 0, 0) == DumpVerdict.Full, "exactly the margin: full");
Check(DumpBudget.Evaluate(2 * GB, est, 0, 0) == DumpVerdict.LowDisk, "a nearly full disk: small dump instead");
// N clients hitting the OOM box together: placeholders count, so only a few get a full dump.
int full = 0;
int count = 0;
long bytes = 0;
for (int client = 0; client < 10; client++)
{
if (DumpBudget.Evaluate(500 * GB, est, count, bytes) == DumpVerdict.Full) { full++; count++; bytes += 0; /* a placeholder is empty */ }
}
Check(full == DumpBudget.MaxFullDumpsAllPids, $"10 clients at once: {DumpBudget.MaxFullDumpsAllPids} full dumps at most, got {full}");
Check(DumpBudget.Evaluate(500 * GB, est, 2, 12 * GB) == DumpVerdict.TooManyBytes, "two dumps already at 12 GB: the bytes cap");
Check(DumpBudget.Evaluate(500 * GB, est, DumpBudget.MaxFullDumpsAllPids, 1 * MB) == DumpVerdict.TooManyDumps, "the count cap");
Check(DumpBudget.Evaluate(1 * GB, est, DumpBudget.MaxFullDumpsAllPids, 0) == DumpVerdict.LowDisk, "low disk is reported first");
Check(DumpBudget.SmallDumpAllowed(DumpBudget.SmallDumpMinFree) && !DumpBudget.SmallDumpAllowed(DumpBudget.SmallDumpMinFree - 1)
&& !DumpBudget.SmallDumpAllowed(-1), "the small dump needs its own margin, and not an unknown disk");
}
private static void ReleasedDataExpiresAndServerDeleteEvicts()
{
_case = "release expiry";

View file

@ -23,10 +23,14 @@
<Compile Include="..\..\src\RynthCore.Engine\Plugins\EngineSettings.cs" Link="Engine\EngineSettings.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\EngineSettingsFile.cs" Link="Engine\EngineSettingsFile.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ReloadCapNotice.cs" Link="Engine\ReloadCapNotice.cs" />
<!-- HoldReloadInWorldMaxMinutes: the default and the 1-240 clamp live with the gate. -->
<Compile Include="..\..\src\RynthCore.Engine\ReloadInWorldGate.cs" Link="Engine\ReloadInWorldGate.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AutoIdPolicy.cs" Link="Engine\AutoIdPolicy.cs" />
<!-- EditIltServerName starts from IltDetect's defaults (IltDetect shares a parser with AelrynthWire). -->
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\IltDetect.cs" Link="Engine\IltDetect.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AelrynthWire.cs" Link="Engine\AelrynthWire.cs" />
<!-- Settings > Display for the AC window: the borderless / window-position decisions (pure functions). -->
<Compile Include="..\..\src\RynthCore.Engine\UI\AcWindowChromePolicy.cs" Link="Engine\AcWindowChromePolicy.cs" />
</ItemGroup>
</Project>

View file

@ -3,6 +3,7 @@ using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using RynthCore.Engine.Plugins;
using static RynthCore.Engine.UI.AcWindowChromePolicy;
namespace RynthCore.Engine
{
@ -47,12 +48,23 @@ namespace EngineSettingsTests
Run(nameof(OwnedKeysMatchEngineSettings), OwnedKeysMatchEngineSettings);
Run(nameof(SaveKeepsLauncherKeys), SaveKeepsLauncherKeys);
Run(nameof(SaveRoundTripsOwnedKeys), SaveRoundTripsOwnedKeys);
Run(nameof(MergeChangedKeysOnly), MergeChangedKeysOnly);
Run(nameof(StaleClientDoesNotOverwriteOtherClientsKeys), StaleClientDoesNotOverwriteOtherClientsKeys);
Run(nameof(EverySetterWritesOnlyItsOwnKey), EverySetterWritesOnlyItsOwnKey);
Run(nameof(NoSaveWithoutAKey), NoSaveWithoutAKey);
Run(nameof(AutoIdModeRoundTrips), AutoIdModeRoundTrips);
Run(nameof(SaveWithoutFileWritesOwnedKeys), SaveWithoutFileWritesOwnedKeys);
Run(nameof(SaveLeavesMalformedFileAlone), SaveLeavesMalformedFileAlone);
Run(nameof(MaxHotReloadsReadAndKept), MaxHotReloadsReadAndKept);
Run(nameof(CloseOnServerDisconnectDefaultOnAndSaved), CloseOnServerDisconnectDefaultOnAndSaved);
Run(nameof(TransitionGateDefaultOnAndSaved), TransitionGateDefaultOnAndSaved);
Run(nameof(HoldReloadInWorldOptInAndSaved), HoldReloadInWorldOptInAndSaved);
Run(nameof(IltServerNamesEdit), IltServerNamesEdit);
Run(nameof(DisplaySettingsDefaultsAndSaved), DisplaySettingsDefaultsAndSaved);
Run(nameof(BorderlessDecisions), BorderlessDecisions);
Run(nameof(PlacementDecisions), PlacementDecisions);
Run(nameof(PlacementFilesArePerClient), PlacementFilesArePerClient);
Run(nameof(PlacementFileRoundTrips), PlacementFileRoundTrips);
}
finally
{
@ -83,8 +95,37 @@ namespace EngineSettingsTests
case "hook-off": EngineSettings.SetUiHookEnabled(args[1], false); break;
case "add-plugin": EngineSettings.AddPluginPath(args[1]); break;
case "imgui-off": EngineSettings.EnableImGuiBackend = false; break;
case "insertrel-on": EngineSettings.InsertReleasesUi = true; break;
case "remove-plugin": EngineSettings.RemovePluginPath(int.Parse(args[1])); break;
case "stale":
// A stale client: it has read the file (EnsureLoaded), another client then edits
// the file (args[1] = a JSON object merged over it), and only then does this client
// change one setting (args[2..] = a child command) and save.
{
_ = EngineSettings.TransitionGate;
string file = Environment.GetEnvironmentVariable("RYNTHCORE_ENGINE_SETTINGS")!;
var theirs = System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(file))!.AsObject();
foreach (var kv in System.Text.Json.Nodes.JsonNode.Parse(args[1])!.AsObject().ToList())
{
theirs.Remove(kv.Key);
theirs[kv.Key] = kv.Value?.DeepClone();
}
File.WriteAllText(file, theirs.ToJsonString());
return Child(args.Skip(2).ToArray());
}
case "dcclose-off": EngineSettings.CloseOnServerDisconnect = false; break;
case "dcclose-on": EngineSettings.CloseOnServerDisconnect = true; break;
case "tgate-off": EngineSettings.TransitionGate = false; break;
case "tgate-on": EngineSettings.TransitionGate = true; break;
case "borderless-on": EngineSettings.BorderlessWindowed = true; break;
case "borderless-off": EngineSettings.BorderlessWindowed = false; break;
case "layout-on": EngineSettings.RememberWindowLayout = true; break;
case "layout-off": EngineSettings.RememberWindowLayout = false; break;
case "acpos-on": EngineSettings.RememberAcWindowPosition = true; break;
case "acpos-off": EngineSettings.RememberAcWindowPosition = false; break;
case "hold-on": EngineSettings.HoldReloadInWorld = true; break;
case "hold-off": EngineSettings.HoldReloadInWorld = false; break;
case "hold-minutes": EngineSettings.HoldReloadInWorldMaxMinutes = int.Parse(args[1]); break;
case "autoid":
if (!RynthCore.Engine.Compatibility.AutoIdPolicy.TryParseMode(args[1], out var aim)) throw new ArgumentException(args[1]);
EngineSettings.AutoIdMode = aim;
@ -100,6 +141,12 @@ namespace EngineSettingsTests
Console.WriteLine("ServerMessageStream=" + EngineSettings.ServerMessageStream);
Console.WriteLine("MaxHotReloads=" + EngineSettings.MaxHotReloads);
Console.WriteLine("CloseOnServerDisconnect=" + EngineSettings.CloseOnServerDisconnect);
Console.WriteLine("TransitionGate=" + EngineSettings.TransitionGate);
Console.WriteLine("BorderlessWindowed=" + EngineSettings.BorderlessWindowed);
Console.WriteLine("RememberWindowLayout=" + EngineSettings.RememberWindowLayout);
Console.WriteLine("RememberAcWindowPosition=" + EngineSettings.RememberAcWindowPosition);
Console.WriteLine("HoldReloadInWorld=" + EngineSettings.HoldReloadInWorld);
Console.WriteLine("HoldReloadInWorldMaxMinutes=" + EngineSettings.HoldReloadInWorldMaxMinutes);
Console.WriteLine("IltServerNames=" + (EngineSettings.IltServerNames is { } n ? string.Join("|", n) : "(none)"));
break;
default: throw new ArgumentException(args[0]);
@ -185,14 +232,17 @@ namespace EngineSettingsTests
Eq(after.GetProperty("SomeNumber").GetRawText(), "1.50", "a number keeps its exact text");
Eq(after.GetProperty("Unicode").GetString(), "Dereth \u00e9 \u2014", "non-ASCII text intact");
// The engine's own keys: written from memory as before.
// The engine's own keys: only the one changed (DisabledUiHooks) is written; every other
// key keeps exactly what the file had (another client's change to those must not be
// overwritten with this client's stale copy).
Eq(string.Join(",", after.GetProperty("DisabledUiHooks").EnumerateArray().Select(e => e.GetString())), "StartTooltip", "DisabledUiHooks written");
Eq(Raw(after.GetProperty("PluginPaths")), Raw(before.GetProperty("PluginPaths")), "PluginPaths kept");
Eq(after.GetProperty("EnableImGuiShell").GetBoolean(), false, "EnableImGuiShell kept (read, written back)");
Eq(after.GetProperty("EnableImGuiShell").GetBoolean(), false, "EnableImGuiShell kept");
Eq(after.GetProperty("DecalBridge").GetString(), "On", "DecalBridge On kept");
Check(!after.TryGetProperty("DecalInGameImGui", out _), "DecalInGameImGui at its default is left out, as before");
foreach (JsonProperty p in before.EnumerateObject())
Check(after.TryGetProperty(p.Name, out JsonElement kept) && JsonElement.DeepEquals(kept, p.Value), $"unchanged key {p.Name} keeps the file's value");
foreach (string key in new[] { "EnablePlugins", "EnableDatShareHook", "EnableAvaloniaOverlay", "EnableD3D9Hook", "EnableEngine", "EngineHookCount", "EnableHangMinidump", "PreventIdleLogoff" })
Check(after.TryGetProperty(key, out _), $"owned key {key} written as before");
Check(after.TryGetProperty(key, out _) == before.TryGetProperty(key, out _), $"owned key {key} not added or dropped by an unrelated save");
// No key twice.
var names = after.EnumerateObject().Select(p => p.Name).ToList();
@ -226,6 +276,175 @@ namespace EngineSettingsTests
Check(ReadJson(path).TryGetProperty("EnableDcompOverlay", out _), "launcher key still there");
}
// EngineSettingsFile.Merge with changedKeys: only the changed keys come from the engine, a changed
// key at its default (left out of ownedJson) is removed, everything else keeps the file's value.
private static void MergeChangedKeysOnly()
{
var keys = new HashSet<string>(StringComparer.Ordinal) { "A", "B", "C", "D" };
string existing = """{ "A": 1, "B": 2, "C": 3, "D": 4, "Launcher": { "x": 1 }, "Mystery": [1, 2] }""";
byte[]? merged = EngineSettingsFile.Merge(existing, Owned("""{ "A": 10, "B": 20, "C": 30 }"""), keys, out string? err, new[] { "B" });
Check(merged != null && err == null, "merged");
JsonElement r = JsonDocument.Parse(merged!).RootElement;
Eq(r.GetProperty("B").GetInt32(), 20, "the changed key B is taken from the engine");
Eq(r.GetProperty("A").GetInt32(), 1, "A (owned, unchanged) keeps the file's value");
Eq(r.GetProperty("C").GetInt32(), 3, "C (owned, unchanged) keeps the file's value");
Eq(r.GetProperty("D").GetInt32(), 4, "D (owned, not written by the engine, unchanged) is kept, not dropped");
Eq(Raw(r.GetProperty("Launcher")), """{"x":1}""", "an unowned key is kept");
Eq(Raw(r.GetProperty("Mystery")), "[1,2]", "an unknown key is kept");
Eq(r.EnumerateObject().Count(), 6, "no key lost or duplicated");
// A changed key the engine left out (back at its default) is removed.
merged = EngineSettingsFile.Merge(existing, Owned("""{ "A": 10 }"""), keys, out _, new[] { "D" });
r = JsonDocument.Parse(merged!).RootElement;
Check(!r.TryGetProperty("D", out _), "a changed key at its default is removed");
Eq(r.GetProperty("A").GetInt32(), 1, "...and A still keeps the file's value");
// A changed key the file doesn't have yet is added.
merged = EngineSettingsFile.Merge("""{ "A": 1 }""", Owned("""{ "A": 10, "B": 20 }"""), keys, out _, new[] { "B" });
r = JsonDocument.Parse(merged!).RootElement;
Eq(r.GetProperty("B").GetInt32(), 20, "a changed key not in the file is added");
Eq(r.GetProperty("A").GetInt32(), 1, "A untouched");
// No file (or an empty one): nothing to keep, everything the engine writes goes in.
foreach (string? none in new[] { null, "", " " })
{
merged = EngineSettingsFile.Merge(none, Owned("""{ "A": 10, "B": 20 }"""), keys, out _, new[] { "B" });
Eq(Raw(JsonDocument.Parse(merged!).RootElement), """{"A":10,"B":20}""", $"'{none}': the whole settings are written when there is no file");
}
// No changedKeys (null): the old behaviour, every owned key rewritten from the engine.
merged = EngineSettingsFile.Merge(existing, Owned("""{ "A": 10, "B": 20 }"""), keys, out _);
r = JsonDocument.Parse(merged!).RootElement;
Eq(r.GetProperty("A").GetInt32(), 10, "without changedKeys A is rewritten");
Check(!r.TryGetProperty("C", out _), "without changedKeys an owned key the engine left out is dropped");
// An unreadable file is still refused with changedKeys.
byte[]? refused = EngineSettingsFile.Merge("{ \"A\": ", Owned("""{ "A": 1 }"""), keys, out string? bad, new[] { "A" });
Check(refused == null && !string.IsNullOrEmpty(bad), "an unreadable file is refused");
}
// The 2026-10-16 bug: a client that never touched a setting wrote its stale copy over another
// client's change. "stale" = the child has loaded the file, another client edits it, then the child
// saves a different setting.
private static void StaleClientDoesNotOverwriteOtherClientsKeys()
{
string dir = NewDir("stale");
string path = Path.Combine(dir, "engine.json");
File.WriteAllText(path, LauncherFile);
// The other client turned several settings away from the default (this client holds the defaults).
const string other = """
{ "TransitionGate": false, "BorderlessWindowed": true, "RememberWindowLayout": false,
"RememberAcWindowPosition": true, "HoldReloadInWorld": true, "HoldReloadInWorldMaxMinutes": 45,
"CloseOnServerDisconnect": false, "EnableImGuiBackend": false, "InsertReleasesUi": true,
"AutoIdMode": "All", "EnableImGuiShell": true, "IltServerNames": [ "Other" ],
"FromNewerBuild": { "k": [ 1, 2 ] } }
""";
var (exit, output) = RunChild(path, "stale", other, "hook-off", "StartTooltip");
Eq(exit, 0, "stale child exit code (" + output.Trim() + ")");
JsonElement after = ReadJson(path);
using JsonDocument theirsDoc = JsonDocument.Parse(other);
foreach (JsonProperty p in theirsDoc.RootElement.EnumerateObject())
Check(after.TryGetProperty(p.Name, out JsonElement v) && JsonElement.DeepEquals(v, p.Value), $"the other client's {p.Name} survives this client's save");
// The key this client changed is written.
Eq(string.Join(",", after.GetProperty("DisabledUiHooks").EnumerateArray().Select(e => e.GetString())), "StartTooltip", "this client's own change is written");
// The launcher's / unknown keys are still there.
Check(after.TryGetProperty("LauncherWindow", out _) && after.TryGetProperty("EnableDcompOverlay", out _), "launcher keys kept");
// A stale client changing a key back to its default removes just that key.
(exit, output) = RunChild(path, "stale", """{ "HoldReloadInWorld": false }""", "tgate-on");
Eq(exit, 0, "second stale child exit code (" + output.Trim() + ")");
after = ReadJson(path);
Check(!after.TryGetProperty("TransitionGate", out _), "TransitionGate changed back to its default is dropped");
Eq(after.GetProperty("HoldReloadInWorld").GetBoolean(), false, "...and the other client's later HoldReloadInWorld=false is not reset");
Eq(after.GetProperty("BorderlessWindowed").GetBoolean(), true, "...nor BorderlessWindowed");
// Both clients change the same key: the later save is the one on disk (nothing to merge).
(exit, output) = RunChild(path, "stale", """{ "HoldReloadInWorldMaxMinutes": 60 }""", "hold-minutes", "90");
Eq(exit, 0, "same-key child exit code (" + output.Trim() + ")");
Eq(ReadJson(path).GetProperty("HoldReloadInWorldMaxMinutes").GetInt32(), 90, "the same key changed in both: the later save wins");
Eq(DumpValue(RunChild(path, "dump").Out, "BorderlessWindowed"), "True", "a later start reads the other client's value");
var keys = ReadJson(path).EnumerateObject().Select(p => p.Name).ToList();
Eq(keys.Count, keys.Distinct(StringComparer.Ordinal).Count(), "no duplicate keys");
NoTempFilesLeft(dir);
}
// Each public setter's Save("Key") must name the key it changed: a wrong or missing name would
// silently not persist. For every setter: a file with a non-default value for the other keys,
// the setter run, and only that one key may differ afterwards.
private static void EverySetterWritesOnlyItsOwnKey()
{
string dir = NewDir("setters");
string path = Path.Combine(dir, "engine.json");
string plugin = Path.Combine(dir, "RynthCore.Plugin.RynthNav.dll");
// Sentinels away from every default, so a key written from memory shows up as a difference.
string seed = LauncherFile.Replace("\"LoggingLevel\"", """
"EnablePlugins": false, "EnableDatShareHook": false, "EnableAvaloniaOverlay": false, "EnableD3D9Hook": false,
"EnableEngine": false, "EngineHookCount": 7, "EnableHangMinidump": false, "PreventIdleLogoff": false,
"DecalStandDown": false, "ServerMessageStream": false, "FlightRecorder": false,
"EnableLargeAddressAlignmentFix": false, "MaxHotReloads": 7, "ReportEndpoint": "http://x.invalid/",
"EnablePluginOverlayWindows": false, "LoadAllServerPlugins": true, "IltHosts": [ "h.invalid" ],
"DisabledUiHooks": [ "Seed" ], "HoldReloadInWorldMaxMinutes": 33, "LoggingLevel"
""");
// (child args, the engine.json key that setter owns, expected raw JSON afterwards or null = just "changed")
var cases = new (string[] Args, string Key, string? Raw)[]
{
(new[] { "imgui-off" }, "EnableImGuiBackend", "false"),
(new[] { "dcclose-off" }, "CloseOnServerDisconnect", "false"),
(new[] { "hook-off", "StartTooltip" }, "DisabledUiHooks", "[\"Seed\",\"StartTooltip\"]"),
(new[] { "insertrel-on" }, "InsertReleasesUi", "true"),
(new[] { "borderless-on" }, "BorderlessWindowed", "true"),
(new[] { "layout-off" }, "RememberWindowLayout", "false"),
(new[] { "acpos-on" }, "RememberAcWindowPosition", "true"),
(new[] { "hold-on" }, "HoldReloadInWorld", "true"),
(new[] { "hold-minutes", "90" }, "HoldReloadInWorldMaxMinutes", "90"),
(new[] { "ilt-add", "Frosthaven" }, "IltServerNames", null),
(new[] { "autoid", "all" }, "AutoIdMode", "\"All\""),
(new[] { "tgate-off" }, "TransitionGate", "false"),
(new[] { "add-plugin", plugin }, "PluginPaths", null),
(new[] { "remove-plugin", "0" }, "PluginPaths", null),
};
foreach (var (args, key, raw) in cases)
{
File.WriteAllText(path, seed);
JsonElement before = ReadJson(path);
var (exit, output) = RunChild(path, args);
Eq(exit, 0, $"{args[0]}: exit code ({output.Trim()})");
JsonElement after = ReadJson(path);
Check(after.TryGetProperty(key, out JsonElement v), $"{args[0]}: {key} written");
if (raw != null && after.TryGetProperty(key, out v))
Eq(Raw(v), raw, $"{args[0]}: {key} value");
if (after.TryGetProperty(key, out v) && before.TryGetProperty(key, out JsonElement was))
Check(!JsonElement.DeepEquals(v, was), $"{args[0]}: {key} actually changed");
foreach (JsonProperty p in before.EnumerateObject())
if (p.Name != key)
Check(after.TryGetProperty(p.Name, out JsonElement kept) && JsonElement.DeepEquals(kept, p.Value), $"{args[0]}: other key {p.Name} keeps the file's value");
foreach (JsonProperty p in after.EnumerateObject())
if (p.Name != key)
Check(before.TryGetProperty(p.Name, out _), $"{args[0]}: no other key ({p.Name}) added");
}
}
// Source guard: the only argument-less Save() call is the one inside Save(string key). A new
// setter written as plain Save() would write nothing under the changed-keys rule.
private static void NoSaveWithoutAKey()
{
string source = File.ReadAllText(FindUp(Path.Combine("src", "RynthCore.Engine", "Plugins", "EngineSettings.cs")));
int bare = Regex.Matches(source, @"^\s*Save\(\);", RegexOptions.Multiline).Count;
Eq(bare, 1, "EngineSettings.cs: Save() with no key is called only from Save(string key)");
int keyed = 0;
foreach (Match m in Regex.Matches(source, @"^\s*Save\(""(\w+)""\);", RegexOptions.Multiline))
{
keyed++;
Check(EngineSettings.OwnedKeys.Contains(m.Groups[1].Value), $"Save(\"{m.Groups[1].Value}\") names an owned key");
}
Check(keyed >= 14, $"found the keyed Save calls ({keyed})");
}
private static void AutoIdModeRoundTrips()
{
string dir = NewDir("autoid");
@ -363,6 +582,257 @@ namespace EngineSettingsTests
}
}
// engine.json TransitionGate (2026-10-18): default on, only a hand-set false is written, other saves keep
// it, a value that is not a boolean is ignored.
private static void TransitionGateDefaultOnAndSaved()
{
string dir = NewDir("tgate");
string path = Path.Combine(dir, "engine.json");
File.WriteAllText(path, LauncherFile);
Eq(DumpValue(RunChild(path, "dump").Out, "TransitionGate"), "True", "missing: on");
Eq(RunChild(path, "hook-off", "StartTooltip").Exit, 0, "save with the default");
Check(!ReadJson(path).TryGetProperty("TransitionGate", out _), "the default isn't written to the file");
var (exit, output) = RunChild(path, "tgate-off");
Eq(exit, 0, "turn off (" + output.Trim() + ")");
Eq(ReadJson(path).GetProperty("TransitionGate").GetRawText(), "false", "off is saved");
Check(ReadJson(path).TryGetProperty("LauncherWindow", out _), "launcher keys kept");
Eq(DumpValue(RunChild(path, "dump").Out, "TransitionGate"), "False", "off read back at the next start");
Eq(RunChild(path, "hook-off", "CheckTooltip").Exit, 0, "another save");
Eq(ReadJson(path).GetProperty("TransitionGate").GetRawText(), "false", "off survives other saves");
Eq(RunChild(path, "tgate-on").Exit, 0, "turn on");
Check(!ReadJson(path).TryGetProperty("TransitionGate", out _), "on again: dropped from the file");
foreach (string bad in new[] { "\"no\"", "0", "null" })
{
File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"TransitionGate\": {bad}, \"LoggingLevel\""));
Eq(DumpValue(RunChild(path, "dump").Out, "TransitionGate"), "True", $"{bad}: ignored, on");
}
}
// Settings > Display (2026-10-18): BorderlessWindowed off and RememberAcWindowPosition off by default,
// RememberWindowLayout on (panels have always been remembered). Only the non-default is written;
// other saves keep it; a value that is not a boolean is ignored.
private static void DisplaySettingsDefaultsAndSaved()
{
string dir = NewDir("display");
string path = Path.Combine(dir, "engine.json");
File.WriteAllText(path, LauncherFile);
string dump = RunChild(path, "dump").Out;
Eq(DumpValue(dump, "BorderlessWindowed"), "False", "borderless defaults off");
Eq(DumpValue(dump, "RememberWindowLayout"), "True", "panel remembering defaults on (unchanged behaviour)");
Eq(DumpValue(dump, "RememberAcWindowPosition"), "False", "game window position is opt-in");
Eq(RunChild(path, "hook-off", "StartTooltip").Exit, 0, "save with the defaults");
foreach (string key in new[] { "BorderlessWindowed", "RememberWindowLayout", "RememberAcWindowPosition" })
Check(!ReadJson(path).TryGetProperty(key, out _), key + ": the default isn't written to the file");
(string cmd, string key, string raw, string value)[] cases =
{
("borderless-on", "BorderlessWindowed", "true", "True"),
("layout-off", "RememberWindowLayout", "false", "False"),
("acpos-on", "RememberAcWindowPosition", "true", "True"),
};
foreach (var (cmd, key, raw, value) in cases)
{
var (exit, output) = RunChild(path, cmd);
Eq(exit, 0, cmd + " (" + output.Trim() + ")");
Eq(ReadJson(path).GetProperty(key).GetRawText(), raw, key + " is saved");
Check(ReadJson(path).TryGetProperty("LauncherWindow", out _), key + ": launcher keys kept");
Eq(DumpValue(RunChild(path, "dump").Out, key), value, key + " read back at the next start");
}
Eq(RunChild(path, "hook-off", "CheckTooltip").Exit, 0, "another save");
foreach (var (_, key, raw, _) in cases)
Eq(ReadJson(path).GetProperty(key).GetRawText(), raw, key + " survives other saves");
Eq(RunChild(path, "borderless-off").Exit, 0, "borderless back off");
Eq(RunChild(path, "layout-on").Exit, 0, "layout back on");
Eq(RunChild(path, "acpos-off").Exit, 0, "position back off");
foreach (var (_, key, _, _) in cases)
Check(!ReadJson(path).TryGetProperty(key, out _), key + ": back at the default, dropped from the file");
foreach (string key in new[] { "BorderlessWindowed", "RememberWindowLayout", "RememberAcWindowPosition" })
foreach (string bad in new[] { "\"no\"", "0", "null" })
{
File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"{key}\": {bad}, \"LoggingLevel\""));
string d = RunChild(path, "dump").Out;
Eq(DumpValue(d, "BorderlessWindowed"), "False", $"{key}={bad}: borderless stays off");
Eq(DumpValue(d, "RememberWindowLayout"), "True", $"{key}={bad}: layout stays on");
Eq(DumpValue(d, "RememberAcWindowPosition"), "False", $"{key}={bad}: position stays off");
}
}
// ── AcWindowChromePolicy: borderless windowed ───────────────────────
private const int Windowed = 0x14CF0000 | WsCaption | WsThickFrame | WsSysMenu | WsMinimizeBox | WsMaximizeBox;
private const int Popup = unchecked((int)0x90000000); // WS_POPUP | WS_VISIBLE: no chrome at all
private static void BorderlessDecisions()
{
// Setting off, a chrome-less window, no marker: it is not ours - no change at all.
foreach (bool fullscreenLooking in new[] { false, true })
{
var d = DecideBorderless(want: false, marker: 0, style: Popup, looksExclusiveFullscreen: fullscreenLooking);
Eq(d.Action, ChromeAction.None, $"off + chrome-less + no marker (fullscreen-looking={fullscreenLooking}): no change");
}
// Setting off, a window with chrome, no marker: nothing either.
Eq(DecideBorderless(false, 0, Windowed, false).Action, ChromeAction.None, "off + chrome + no marker: no change");
// Setting off, our marker, chrome still gone: restore, even when the window fills the monitor.
foreach (bool fullscreenLooking in new[] { false, true })
{
int stripped = Windowed & ~BorderChromeMask;
var d = DecideBorderless(false, marker: Windowed, style: stripped, looksExclusiveFullscreen: fullscreenLooking);
Eq(d.Action, ChromeAction.Restore, $"off + our marker + stripped (fullscreen-looking={fullscreenLooking}): restore");
Eq(d.NewStyle & BorderChromeMask, Windowed & BorderChromeMask, "all the chrome bits come back");
Eq(d.NewStyle & ~BorderChromeMask, stripped & ~BorderChromeMask, "the other style bits stay as they are now");
}
// Our marker, but someone already gave the chrome back (or the marker is junk): only drop it.
Eq(DecideBorderless(false, Windowed, Windowed, false).Action, ChromeAction.ClearMarker, "off + marker + chrome back: marker dropped");
Eq(DecideBorderless(false, Popup, Popup, false).Action, ChromeAction.ClearMarker, "off + marker without a caption: dropped, not restored");
// Setting on: strip once and set the marker.
var strip = DecideBorderless(true, 0, Windowed, false);
Eq(strip.Action, ChromeAction.Strip, "on + chrome + no marker: strip");
Eq(strip.NewStyle & BorderChromeMask, 0, "the chrome bits are gone");
Eq(strip.NewMarker, Windowed, "the marker holds the style from before");
Check(strip.NewMarker != 0, "the marker is never 0 (0 means 'not ours')");
// ...and the next tick, with the marker and no chrome: nothing more to do.
Eq(DecideBorderless(true, strip.NewMarker, strip.NewStyle, false).Action, ChromeAction.None, "on + marker + stripped: nothing more");
// Chrome that is not ours and not there (external tool, fullscreen): leave it, no marker.
Eq(DecideBorderless(true, 0, Popup, false).Action, ChromeAction.None, "on + already chrome-less, no marker: leave it");
Eq(DecideBorderless(true, 0, Popup, true).Action, ChromeAction.None, "on + exclusive fullscreen, no marker: leave it");
// The game put the chrome back after we stripped: strip again.
Eq(DecideBorderless(true, Windowed, Windowed, false).Action, ChromeAction.Strip, "on + marker + chrome came back: strip again");
// Flagged as fullscreen-looking without our marker: left alone.
Eq(DecideBorderless(true, 0, Windowed, true).Action, ChromeAction.None, "on + no marker + flagged fullscreen: left alone");
}
// ── AcWindowChromePolicy: window position ───────────────────────────
private static void PlacementDecisions()
{
var main = new Rect(0, 0, 1920, 1080);
var second = new Rect(1920, 0, 3840, 1080);
var one = new[] { main };
var two = new[] { main, second };
Eq(EvaluatePlacement(true, false, new Rect(100, 100, 1100, 800), one), PlacementVerdict.Ok, "on-screen rect is fine");
Eq(EvaluatePlacement(false, false, new Rect(100, 100, 1100, 800), one), PlacementVerdict.OptedOut, "opted out: never");
Eq(EvaluatePlacement(true, true, new Rect(100, 100, 1100, 800), one), PlacementVerdict.ExclusiveFullscreen, "exclusive fullscreen: skipped");
// Off-screen: a monitor that is gone, or a title bar above the top edge.
Eq(EvaluatePlacement(true, false, new Rect(2000, 100, 3000, 800), one), PlacementVerdict.OffScreen, "saved on the second monitor, which is gone: ignored");
Eq(EvaluatePlacement(true, false, new Rect(2000, 100, 3000, 800), two), PlacementVerdict.Ok, "...but fine while that monitor exists");
Eq(EvaluatePlacement(true, false, new Rect(-5000, -5000, -4000, -4300), two), PlacementVerdict.OffScreen, "far off every monitor: ignored");
Eq(EvaluatePlacement(true, false, new Rect(100, -900, 1100, 200), one), PlacementVerdict.OffScreen, "title bar above the screen: ignored");
Eq(EvaluatePlacement(true, false, new Rect(-32000, -32000, -31840, -31972), two), PlacementVerdict.TooSmall, "a minimised window's rect is refused");
// Sanity limits.
Eq(EvaluatePlacement(true, false, new Rect(0, 0, MinWidth - 1, 600), one), PlacementVerdict.TooSmall, "narrower than the minimum");
Eq(EvaluatePlacement(true, false, new Rect(0, 0, 800, MinHeight - 1), one), PlacementVerdict.TooSmall, "shorter than the minimum");
Eq(EvaluatePlacement(true, false, new Rect(0, 0, MinWidth, MinHeight), one), PlacementVerdict.Ok, "exactly the minimum is fine");
Eq(EvaluatePlacement(true, false, new Rect(0, 0, MaxExtent + 1, 600), one), PlacementVerdict.TooLarge, "absurdly wide");
// Writes only when changed.
var r = new Rect(10, 20, 810, 620);
Check(ShouldWritePlacement(PlacementVerdict.Ok, r, null), "first rect is written");
Check(!ShouldWritePlacement(PlacementVerdict.Ok, r, r), "unchanged rect: no write");
Check(ShouldWritePlacement(PlacementVerdict.Ok, r with { Right = 900 }, r), "changed rect: written");
Check(!ShouldWritePlacement(PlacementVerdict.OffScreen, r, null), "a refused rect is never written");
}
private static void PlacementFilesArePerClient()
{
Eq(ClientKey("DreamWeave", "Drakkon"), "DreamWeave/Drakkon", "key = server/character");
Eq(ClientKey("", "Drakkon"), "Drakkon", "no server: character alone");
Eq(ClientKey("DreamWeave", ""), (string?)null, "no character: no key");
Eq(ClientKey(null, null), (string?)null, "nothing known: no key");
string a = PlacementFileName("DreamWeave/Drakkon");
string b = PlacementFileName("DreamWeave/Drakkon1");
string c = PlacementFileName("Aelrynth/Lucy McJuicy");
Check(a != b && a != c && b != c, "different clients get different files");
Eq(PlacementFileName("dreamweave/drakkon"), a, "stable (and case-insensitive) for one client");
Eq(PlacementFileName(null), SharedFileName, "no key: the shared file");
Eq(PlacementFileName(" "), SharedFileName, "blank key: the shared file");
Check(a != SharedFileName && a.StartsWith("ac_window.") && a.EndsWith(".txt"), "per-client name shape: " + a);
foreach (string name in new[] { a, b, c, PlacementFileName("we/ird:na*me?<>|\"x"), PlacementFileName(new string('x', 500)) })
{
Check(name.IndexOfAny(Path.GetInvalidFileNameChars()) < 0, "valid file name: " + name);
Check(name.Length < 90, "short file name: " + name.Length);
}
// Names that sanitise to the same letters still differ (the hash).
Check(PlacementFileName("S/a b") != PlacementFileName("S/a_b"), "'a b' and 'a_b' stay apart");
// The key is only usable after login; the shared file only after a long wait without one.
Check(!TryResolveKey("S", "", 1000, 90000, out _), "no character yet, just started: not ready");
Check(TryResolveKey("S", "", 91000, 90000, out string? fallback) && fallback == null, "no character after the wait: shared file");
Check(TryResolveKey("S", "Char", 0, 90000, out string? k) && k == "S/Char", "character known: its key at once");
}
private static void PlacementFileRoundTrips()
{
var r = new Rect(-1280, 40, -280, 840);
Check(TryParsePlacement(FormatPlacement(r).Split('\n'), out Rect back), "own output parses");
Eq(back, r, "round trip (negative coordinates, secondary monitor)");
Check(!TryParsePlacement(new[] { "left=1", "top=2", "width=0", "height=5" }, out _), "zero width: refused");
Check(!TryParsePlacement(new[] { "width=500", "height=500" }, out _), "no position: refused");
Check(!TryParsePlacement(new[] { "garbage", "left=x", "" }, out _), "garbage: refused");
Check(TryParsePlacement(new[] { "# c", "LEFT = 5", "Top=6", "width=300", "height=200", "extra=1" }, out Rect loose) && loose == new Rect(5, 6, 305, 206),
"case, spaces, comments and unknown keys are tolerated");
}
// engine.json HoldReloadInWorld (2026-10-18, opt-in from SilentKelpie's PR 6): default off, only a true
// is written, other saves keep it, a non-boolean is ignored. HoldReloadInWorldMaxMinutes: default 10,
// clamped to 1-240, only a non-default value is written, a non-number is ignored.
private static void HoldReloadInWorldOptInAndSaved()
{
string dir = NewDir("holdreload");
string path = Path.Combine(dir, "engine.json");
File.WriteAllText(path, LauncherFile);
string dump = RunChild(path, "dump").Out;
Eq(DumpValue(dump, "HoldReloadInWorld"), "False", "missing: off");
Eq(DumpValue(dump, "HoldReloadInWorldMaxMinutes"), "10", "missing: 10 minutes");
Eq(RunChild(path, "hook-off", "StartTooltip").Exit, 0, "save with the defaults");
Check(!ReadJson(path).TryGetProperty("HoldReloadInWorld", out _), "off isn't written to the file");
Check(!ReadJson(path).TryGetProperty("HoldReloadInWorldMaxMinutes", out _), "10 isn't written to the file");
var (exit, output) = RunChild(path, "hold-on");
Eq(exit, 0, "turn on (" + output.Trim() + ")");
Eq(ReadJson(path).GetProperty("HoldReloadInWorld").GetRawText(), "true", "on is saved");
Check(ReadJson(path).TryGetProperty("LauncherWindow", out _), "launcher keys kept");
Eq(DumpValue(RunChild(path, "dump").Out, "HoldReloadInWorld"), "True", "on read back at the next start");
Eq(RunChild(path, "hook-off", "CheckTooltip").Exit, 0, "another save");
Eq(ReadJson(path).GetProperty("HoldReloadInWorld").GetRawText(), "true", "on survives other saves");
Eq(RunChild(path, "hold-minutes", "30").Exit, 0, "set 30 minutes");
Eq(ReadJson(path).GetProperty("HoldReloadInWorldMaxMinutes").GetRawText(), "30", "30 is saved");
Eq(DumpValue(RunChild(path, "dump").Out, "HoldReloadInWorldMaxMinutes"), "30", "30 read back");
Eq(RunChild(path, "hold-minutes", "10").Exit, 0, "back to 10");
Check(!ReadJson(path).TryGetProperty("HoldReloadInWorldMaxMinutes", out _), "10 again: dropped from the file");
Eq(RunChild(path, "hold-off").Exit, 0, "turn off");
Check(!ReadJson(path).TryGetProperty("HoldReloadInWorld", out _), "off again: dropped from the file");
foreach (string bad in new[] { "\"yes\"", "1", "null" })
{
File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"HoldReloadInWorld\": {bad}, \"LoggingLevel\""));
Eq(DumpValue(RunChild(path, "dump").Out, "HoldReloadInWorld"), "False", $"{bad}: ignored, off");
}
// Hand-set minutes: in range is kept, out of range is clamped to 1-240, junk is the default.
foreach (var (json, expected) in new[] { ("1", "1"), ("240", "240"), ("0", "1"), ("-5", "1"), ("241", "240"), ("100000", "240"), ("45", "45"), ("\"x\"", "10"), ("12.5", "10"), ("null", "10") })
{
File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"HoldReloadInWorldMaxMinutes\": {json}, \"LoggingLevel\""));
Eq(DumpValue(RunChild(path, "dump").Out, "HoldReloadInWorldMaxMinutes"), expected, $"{json}: read as {expected}");
}
}
// /rc server names ilt add|remove (2026.10.5.46): the first edit starts from the defaults,
// the edit is saved with the launcher's keys kept, and repeats, unknown, empty and overlong
// patterns change nothing.

View file

@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the Enl calculator's data (Skills > Progression; idea and first version from
Silentkelpie, rynth PR 6): src\RynthCore.Engine\UI\Data\ProgressionData.cs (the Progression snapshot DTOs and
ProgressionSource.ParseJson), EnlRowConverters.cs and UiSource.cs, compiled in. Parses a sample shaped like
RynthILT's IltProgression.AppendEnlCalculatorJson output: the full data, an older RynthILT without the
calculator fields, null / mistyped containers, partial and malformed rows, unknown extra fields, the row cap.
No ImGui, no game, no files. 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>EnlCalculatorTests</RootNamespace>
<!-- ProgressionSource polls a native export through a function pointer. -->
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ProgressionData.cs" Link="Engine\ProgressionData.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\EnlRowConverters.cs" Link="Engine\EnlRowConverters.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\UiSource.cs" Link="Engine\UiSource.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,269 @@
using System.Text;
using RynthCore.Engine.UI.Data;
namespace EnlCalculatorTests;
// Offline tests for the Enl calculator's data. 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 int Main()
{
FullSample();
OlderIltWithoutCalculator();
NoEnlObjectAndBadPayloads();
NullAndMistypedContainers();
PartialAndMalformedChainRows();
PartialAndMalformedLevelAndMaterialRows();
UnknownFieldsAreIgnored();
RowCap();
ViewLimits();
Console.WriteLine();
Console.WriteLine(_fails == 0 ? $"PASS ({_asserts} checks)" : $"FAIL ({_fails} of {_asserts} checks failed)");
return _fails == 0 ? 0 : 1;
}
// What RynthILT's AppendEnlCalculatorJson emits (IltProgression.cs, RynthSuite integration/pr-fixes-2026-10-18),
// inside AppendEnlJson's "enl" object, for a character at enlightenment 298 planning to 303:
// levels 299-303 (EnlStepCost: medallions to 300, sigils from 301, Compact lum), materials from the totals,
// the 8 chain rows (only when sigils are needed), chainNote, ecoins, ecoinsLum. Property order as emitted.
private const string Sample = """
{"available":true,"world":"InfiniteLeaftide",
"aug":{"off":false,"status":"loaded 2026-10-18 09:12","lumPerCoin":0,"rows":[],"total":"","short":"","banked":"Banked luminance: 650.00B"},
"enl":{"off":false,"header":"Enlightenment 298 Level 275 Unassigned XP 1.20T",
"next":"Next (299): 294 Enlightenment Medallions (have 300) + 299.00B lum","enl":298,"target":303,
"plan":["589 Enlightenment Medallions","891 Enlightenment Sigils","2.41T luminance (banked 650.00B)"],
"coinsPerToken":0,"tokensShort":"",
"levels":[
{"t":299,"item":"Medallions","count":294,"lum":"299.00B","ok":true},
{"t":300,"item":"Medallions","count":295,"lum":"300.00B","ok":false},
{"t":301,"item":"Sigils","count":296,"lum":"602.00B","ok":false},
{"t":302,"item":"Sigils","count":297,"lum":"604.00B","ok":false},
{"t":303,"item":"Sigils","count":298,"lum":"606.00B","ok":false}],
"materials":[
{"label":"Luminance","need":"1.76T","have":"650.00B","ok":false},
{"label":"Medallions","need":"289","have":"300","ok":false},
{"label":"Sigils","need":"891","have":"0","ok":false}],
"chain":[
{"label":"Ascension Coins","need":891,"have":40,"ok":false,"craft":true},
{"label":"Lifeblood Elixirs","need":891,"have":0,"ok":false,"craft":true},
{"label":"Lifebloom Resins","need":1782,"have":12,"ok":false,"craft":true},
{"label":"E-coins","need":1234567,"have":1500,"ok":false,"craft":false},
{"label":"Ancient Yalani Trinkets","need":0,"have":3,"ok":true,"craft":false},
{"label":"Necrolytic Extracts","need":891,"have":0,"ok":false,"craft":false},
{"label":"Life Splitters","need":0,"have":0,"ok":true,"craft":false},
{"label":"Plants","need":1782,"have":9,"ok":false,"craft":false}],
"chainNote":"Sigil = Lifeblood Elixir + Ascension Coin. 891 to craft; Need = crafts left (in-between items) or mats to get (raw items).",
"ecoins":"E-coins needed: 1,234,567 have 1,500 (bank + pack) Ascension Coins use 851",
"ecoinsLum":"Lum to buy e-coins: ~12.35T",
"blockers":["Need 2.41T banked luminance."],
"serverChecks":"Server also checks: not in a dungeon, free pack slots (40 free), all luminance augs (past 10), society master (past 30).",
"auto":false,"armed":false,"spendFirst":true,"checkEvery":60,"status":"idle"}}
""";
/// <summary>The sample with the enl object's body replaced (everything else of the payload stays).</summary>
private static string WithEnl(string enlBody) =>
"{\"available\":true,\"world\":\"W\",\"aug\":{\"off\":false,\"status\":\"ok\",\"banked\":\"B\"},\"enl\":{" + enlBody + "}}";
private static EnlPlanner Enl(string enlBody) => ProgressionSource.ParseJson(WithEnl(enlBody)).Enl;
// ── The full payload ────────────────────────────────────────────────
private static void FullSample()
{
ProgressionInfo info = ProgressionSource.ParseJson(Sample);
Check(info.Available, "full: available");
Eq(info.World, "InfiniteLeaftide", "full: world");
Eq(info.Aug.Banked, "Banked luminance: 650.00B", "full: the Augmentation planner still parses");
EnlPlanner e = info.Enl;
Eq(e.Level, 298, "full: enl level"); Eq(e.Target, 303, "full: target");
Eq(e.Plan.Length, 3, "full: plan lines"); Eq(e.Blockers.Length, 1, "full: blockers");
Eq(e.CheckEvery, 60, "full: checkEvery"); Check(e.SpendFirst, "full: spendFirst"); Eq(e.Status, "idle", "full: status");
Check(e.HasCalculator, "full: HasCalculator");
Eq(e.Levels.Length, 5, "full: level rows");
Eq(e.Levels[0].Level, 299, "level 0: t"); Eq(e.Levels[0].Item, "Medallions", "level 0: item");
Eq(e.Levels[0].Count, 294, "level 0: count"); Eq(e.Levels[0].Lum, "299.00B", "level 0: lum"); Check(e.Levels[0].Ok, "level 0: ok");
Check(!e.Levels[1].Ok, "level 1: not ok"); Eq(e.Levels[2].Item, "Sigils", "level 2: item"); Eq(e.Levels[4].Level, 303, "level 4: t");
Eq(e.Levels[0].LevelText, "299", "level 0: LevelText"); Eq(e.Levels[2].CountText, "296", "level 2: CountText");
Check(ReferenceEquals(e.Levels[0].LevelText, e.Levels[0].LevelText), "level text is formatted once");
Eq(e.Materials.Length, 3, "full: material rows");
Eq(e.Materials[0].Label, "Luminance", "material 0: label"); Eq(e.Materials[0].Need, "1.76T", "material 0: need");
Eq(e.Materials[0].Have, "650.00B", "material 0: have"); Check(!e.Materials[0].Ok, "material 0: not ok");
Eq(e.Materials[2].Label, "Sigils", "material 2: label"); Eq(e.Materials[2].Have, "0", "material 2: have");
Eq(e.Chain.Length, 8, "full: chain rows");
Eq(e.Chain[0].Label, "Ascension Coins", "chain 0: label"); Eq(e.Chain[0].Need, 891L, "chain 0: need");
Eq(e.Chain[0].Have, 40L, "chain 0: have"); Check(e.Chain[0].Craft, "chain 0: craft"); Check(!e.Chain[0].Ok, "chain 0: not ok");
Eq(e.Chain[3].Label, "E-coins", "chain 3: label"); Eq(e.Chain[3].Need, 1234567L, "chain 3: need > a short");
Check(!e.Chain[3].Craft, "chain 3: not craft"); Eq(e.Chain[3].NeedText, "1,234,567", "chain 3: NeedText"); Eq(e.Chain[3].HaveText, "1,500", "chain 3: HaveText");
Eq(e.Chain[0].DisplayLabel, "Ascension Coins (craft)", "chain 0: craft rows are tagged"); Eq(e.Chain[3].DisplayLabel, "E-coins", "chain 3: raw rows are not");
Check(e.Chain[4].Ok && !e.Chain[4].Craft, "chain 4: ok raw row"); Eq(e.Chain[7].Label, "Plants", "chain 7: label");
Check(e.ChainNote.StartsWith("Sigil = Lifeblood Elixir", StringComparison.Ordinal), "full: chainNote");
Check(e.Ecoins.Contains("1,234,567", StringComparison.Ordinal), "full: ecoins");
Eq(e.EcoinsLum, "Lum to buy e-coins: ~12.35T", "full: ecoinsLum");
}
// ── Graceful absence ────────────────────────────────────────────────
private static void OlderIltWithoutCalculator()
{
// An ILT from before the calculator: the enl object has the planner fields only.
EnlPlanner e = Enl("\"off\":false,\"header\":\"H\",\"next\":\"N\",\"enl\":10,\"target\":15,\"plan\":[\"5 Enlightenment Tokens\"],"
+ "\"coinsPerToken\":0,\"tokensShort\":\"\",\"blockers\":[],\"serverChecks\":\"S\",\"auto\":false,\"armed\":false,"
+ "\"spendFirst\":false,\"checkEvery\":60,\"status\":\"\"");
Eq(e.Levels.Length, 0, "older ILT: no levels"); Eq(e.Materials.Length, 0, "older ILT: no materials"); Eq(e.Chain.Length, 0, "older ILT: no chain");
Eq(e.ChainNote, "", "older ILT: chainNote"); Eq(e.Ecoins, "", "older ILT: ecoins"); Eq(e.EcoinsLum, "", "older ILT: ecoinsLum");
Check(!e.HasCalculator, "older ILT: no calculator");
Eq(e.Header, "H", "older ILT: the planner itself still reads"); Eq(e.Plan.Length, 1, "older ILT: plan");
EnlPlanner empty = Enl("");
Check(!empty.HasCalculator && empty.Levels.Length == 0 && empty.Chain.Length == 0 && empty.Materials.Length == 0, "empty enl object: nothing");
}
private static void NoEnlObjectAndBadPayloads()
{
ProgressionInfo noEnl = ProgressionSource.ParseJson("{\"available\":true,\"world\":\"W\"}");
Check(noEnl.Available && !noEnl.Enl.HasCalculator, "no enl object: default planner, nothing to draw");
foreach (string bad in new[] { "{}", "", " ", "not json", "{\"available\":", "[1,2,3]", "null", "{\"enl\":5}", "{\"available\":\"yes\"}" })
{
ProgressionInfo info = null!;
try { info = ProgressionSource.ParseJson(bad); }
catch (Exception ex) { Check(false, $"bad payload '{bad}' threw {ex.GetType().Name}"); continue; }
Check(info != null && !info.Available && !info.Enl.HasCalculator, $"bad payload '{bad}': empty snapshot, tab hidden");
}
Check(!ProgressionSource.ParseJson(null).Available, "null payload: empty snapshot");
}
private static void NullAndMistypedContainers()
{
// null / scalar / object where an array belongs: empty array, and the sibling fields still read.
foreach (string bad in new[] { "null", "\"oops\"", "12", "true", "{\"t\":1}", "{}", "[]" })
{
ProgressionInfo info = ProgressionSource.ParseJson(WithEnl(
$"\"header\":\"H\",\"levels\":{bad},\"materials\":{bad},\"chain\":{bad},\"chainNote\":\"note\",\"enl\":7"));
Check(info.Available, $"containers = {bad}: snapshot stays available");
Eq(info.Enl.Levels.Length + info.Enl.Materials.Length + info.Enl.Chain.Length, 0, $"containers = {bad}: empty arrays");
Eq(info.Enl.Header, "H", $"containers = {bad}: header before"); Eq(info.Enl.ChainNote, "note", $"containers = {bad}: chainNote after");
Eq(info.Enl.Level, 7, $"containers = {bad}: enl after"); Eq(info.Aug.Status, "ok", $"containers = {bad}: Augmentation planner untouched");
}
// JSON null into a string: the UI reads .Length, so ParseJson turns it into "".
EnlPlanner e = Enl("\"chainNote\":null,\"ecoins\":null,\"ecoinsLum\":null,\"levels\":[{\"t\":1,\"ok\":true}]");
Eq(e.ChainNote, "", "null chainNote"); Eq(e.Ecoins, "", "null ecoins"); Eq(e.EcoinsLum, "", "null ecoinsLum");
Eq(e.Levels.Length, 1, "null strings: rows still read");
}
// ── Partial and malformed rows ──────────────────────────────────────
private static void PartialAndMalformedChainRows()
{
EnlPlanner e = Enl("\"header\":\"H\",\"chain\":["
+ "{\"label\":\"Only label\"}," // 0: partial
+ "{}," // 1: empty object
+ "{\"label\":\"Str nums\",\"need\":\"12\",\"have\":\"1,000\",\"ok\":true}," // 2: numbers as strings
+ "{\"label\":\"Bad nums\",\"need\":\"abc\",\"have\":{\"x\":[1,2]},\"ok\":\"yes\",\"craft\":1}," // 3: wrong types
+ "42,\"text\",null,[1,2],true," // not objects: skipped
+ "{\"label\":null,\"need\":null,\"have\":1.0e3,\"ok\":null,\"craft\":true}," // 7: nulls, a float
+ "{\"label\":\"Huge\",\"need\":1e30,\"have\":-1e30}," // 8: out of range
+ "{\"label\":\"Last\",\"need\":5,\"have\":2,\"ok\":false,\"craft\":true}" // 9: still read after all that
+ "],\"chainNote\":\"after\",\"enl\":3");
Eq(e.Header, "H", "chain: header before"); Eq(e.ChainNote, "after", "chain: chainNote after the rows"); Eq(e.Level, 3, "chain: enl after the rows");
Eq(e.Chain.Length, 7, "chain: 7 object rows kept, 5 non-objects skipped");
EnlChainRow r = e.Chain[0];
Eq(r.Label, "Only label", "partial: label"); Eq(r.Need, 0L, "partial: need default"); Eq(r.Have, 0L, "partial: have default");
Check(!r.Ok && !r.Craft, "partial: flags default false");
r = e.Chain[1];
Eq(r.Label, "", "empty row: label"); Eq(r.NeedText, "0", "empty row: need text");
r = e.Chain[2];
Eq(r.Need, 12L, "string number: need"); Eq(r.Have, 1000L, "string number with a separator: have"); Check(r.Ok, "string number row: ok");
r = e.Chain[3];
Eq(r.Label, "Bad nums", "wrong types: label"); Eq(r.Need, 0L, "wrong types: need"); Eq(r.Have, 0L, "wrong types: have");
Check(!r.Ok && !r.Craft, "wrong types: flags default");
r = e.Chain[4];
Eq(r.Label, "", "nulls: label"); Eq(r.Need, 0L, "nulls: need"); Eq(r.Have, 1000L, "float have"); Check(r.Craft, "nulls: craft still read");
r = e.Chain[5];
Eq(r.Label, "Huge", "range: label"); Eq(r.Need, long.MaxValue, "range: need clamps"); Eq(r.Have, long.MinValue, "range: have clamps");
r = e.Chain[6];
Eq(r.Label, "Last", "last row: label"); Eq(r.Need, 5L, "last row: need"); Eq(r.Have, 2L, "last row: have");
Check(!r.Ok && r.Craft, "last row: flags");
}
private static void PartialAndMalformedLevelAndMaterialRows()
{
EnlPlanner e = Enl("\"levels\":[{\"t\":300},{\"t\":\"301\",\"item\":5,\"count\":2.0,\"lum\":null,\"ok\":\"true\"},"
+ "{\"t\":302,\"item\":\"Sigils\",\"count\":99999999999,\"lum\":\"1.00B\",\"ok\":true},{\"item\":{\"deep\":[1]},\"lum\":[]},3,null],"
+ "\"materials\":[{\"label\":\"Tokens\"},{\"label\":\"Crests\",\"need\":7,\"have\":null,\"ok\":true},\"x\",{\"need\":{}}],\"enl\":1");
Eq(e.Level, 1, "rows: enl after the arrays");
Eq(e.Levels.Length, 4, "levels: 4 object rows");
Eq(e.Levels[0].Level, 300, "level partial: t"); Eq(e.Levels[0].Item, "-", "level partial: item default"); Eq(e.Levels[0].Lum, "-", "level partial: lum default");
Eq(e.Levels[0].CountText, "-", "level partial: no count shows '-'"); Check(!e.Levels[0].Ok, "level partial: not ok");
Eq(e.Levels[1].Level, 301, "level strings: t"); Eq(e.Levels[1].Item, "5", "level number item reads as text"); Eq(e.Levels[1].Count, 2, "level float count");
Eq(e.Levels[1].Lum, "-", "level null lum keeps '-'"); Check(!e.Levels[1].Ok, "level string 'true' is not a bool");
Eq(e.Levels[2].Count, int.MaxValue, "level huge count clamps"); Check(e.Levels[2].Ok, "level ok");
Eq(e.Levels[3].Level, 0, "level without t"); Eq(e.Levels[3].Item, "-", "level with object item"); Eq(e.Levels[3].Lum, "-", "level with array lum");
Eq(e.Materials.Length, 3, "materials: 3 object rows");
Eq(e.Materials[0].Label, "Tokens", "material partial: label"); Eq(e.Materials[0].Need, "0", "material partial: need"); Eq(e.Materials[0].Have, "0", "material partial: have");
Eq(e.Materials[1].Need, "7", "material numeric need reads as text"); Eq(e.Materials[1].Have, "0", "material null have"); Check(e.Materials[1].Ok, "material ok");
Eq(e.Materials[2].Label, "", "material object need: label empty"); Eq(e.Materials[2].Need, "0", "material object need: default");
Check(e.HasCalculator, "partial rows still count as calculator data");
}
private static void UnknownFieldsAreIgnored()
{
ProgressionInfo info = ProgressionSource.ParseJson("""
{"future":{"a":[1,{"b":2}]},"available":true,"world":"W","aug":{"off":false,"status":"s","newAugField":[1,2,3]},
"enl":{"header":"H","newTop":{"x":1},"levels":[{"extra":[{"deep":true}],"t":9,"item":"Crests","count":1,"lum":"1.32T","ok":true,"more":{"k":"v"}}],
"materials":[{"label":"Crests","tier":3,"need":"4","have":"5","ok":true,"hint":null}],
"chain":[{"label":"Plants","note":"x","need":3,"have":1,"ok":false,"craft":false,"icon":{"wcid":1}}],
"chainNote":"n","ecoins":"e","ecoinsLum":"l","zzz":[[]],"enl":300,"target":310},"tail":"yes"}
""");
Check(info.Available, "unknown: available"); Eq(info.Aug.Status, "s", "unknown: aug");
EnlPlanner e = info.Enl;
Eq(e.Header, "H", "unknown: header"); Eq(e.Level, 300, "unknown: enl after unknown fields"); Eq(e.Target, 310, "unknown: target");
Eq(e.Levels.Length, 1, "unknown: levels"); Eq(e.Levels[0].Level, 9, "unknown: level t after an unknown array"); Eq(e.Levels[0].Item, "Crests", "unknown: level item");
Eq(e.Levels[0].Lum, "1.32T", "unknown: level lum"); Check(e.Levels[0].Ok, "unknown: level ok (after an unknown object)");
Eq(e.Materials.Length, 1, "unknown: materials"); Eq(e.Materials[0].Need, "4", "unknown: material need"); Eq(e.Materials[0].Have, "5", "unknown: material have");
Eq(e.Chain.Length, 1, "unknown: chain"); Eq(e.Chain[0].Label, "Plants", "unknown: chain label"); Eq(e.Chain[0].Need, 3L, "unknown: chain need"); Eq(e.Chain[0].Have, 1L, "unknown: chain have");
Eq(e.ChainNote, "n", "unknown: chainNote"); Eq(e.Ecoins, "e", "unknown: ecoins"); Eq(e.EcoinsLum, "l", "unknown: ecoinsLum");
// Case matters (the producer's names are exact): a differently cased name is an unknown field.
EnlPlanner cased = Enl("\"levels\":[{\"T\":5,\"Item\":\"X\",\"t\":6}]");
Eq(cased.Levels[0].Level, 6, "case: only the exact name counts"); Eq(cased.Levels[0].Item, "-", "case: Item is unknown");
}
private static void RowCap()
{
var sb = new StringBuilder("\"levels\":[");
for (int i = 0; i < 250; i++) sb.Append(i > 0 ? "," : "").Append("{\"t\":").Append(i + 1).Append(",\"item\":\"Tokens\",\"count\":1,\"lum\":\"-\",\"ok\":true}");
sb.Append("],\"enl\":4");
EnlPlanner e = Enl(sb.ToString());
Eq(e.Levels.Length, 200, "250 rows: the parse keeps the first 200");
Eq(e.Levels[0].Level, 1, "cap: first row"); Eq(e.Levels[199].Level, 200, "cap: last kept row"); Eq(e.Level, 4, "cap: field after the array");
// The producer's own range, 100 level rows, comes through whole.
var hundred = new StringBuilder("\"levels\":[");
for (int i = 0; i < 100; i++) hundred.Append(i > 0 ? "," : "").Append("{\"t\":").Append(i + 299).Append('}');
hundred.Append(']');
Eq(Enl(hundred.ToString()).Levels.Length, 100, "100 rows (the producer's cap) all kept");
}
private static void ViewLimits()
{
Eq(EnlCalculatorView.VisibleLevels(0, false), 0, "view: none"); Eq(EnlCalculatorView.VisibleLevels(-3, true), 0, "view: negative");
Eq(EnlCalculatorView.VisibleLevels(5, false), 5, "view: few rows all shown"); Eq(EnlCalculatorView.VisibleLevels(100, false), EnlCalculatorView.PreviewLevels, "view: preview limit");
Eq(EnlCalculatorView.VisibleLevels(100, true), 100, "view: show all"); Eq(EnlCalculatorView.VisibleLevels(500, true), EnlCalculatorView.MaxLevels, "view: hard cap");
Check(!EnlCalculatorView.CanExpand(EnlCalculatorView.PreviewLevels), "view: no toggle at the preview size");
Check(EnlCalculatorView.CanExpand(EnlCalculatorView.PreviewLevels + 1), "view: toggle above the preview size");
}
}

View file

@ -0,0 +1,13 @@
// The engine file ProgressionData.cs has these two dependencies; stand-ins keep the test free of the engine.
namespace RynthCore.Engine.Plugins
{
internal static class EnlTestAnchor { } // ProgressionData.cs has "using RynthCore.Engine.Plugins;"
}
namespace RynthCore.Engine.UI.Data
{
internal static class PluginExportBinder
{
public static IntPtr Resolve(string pluginNamePart, string exportName) => IntPtr.Zero;
}
}

View file

@ -29,6 +29,7 @@
<Compile Include="..\..\src\RynthCore.App\LaunchAccountProfile.cs" Link="App\LaunchAccountProfile.cs" />
<Compile Include="..\..\src\RynthCore.App\AccountPasswordProtection.cs" Link="App\AccountPasswordProtection.cs" />
<Compile Include="..\..\src\RynthCore.App\LaunchServerProfile.cs" Link="App\LaunchServerProfile.cs" />
<Compile Include="..\..\src\RynthCore.App\KnownServerCatalog.cs" Link="App\KnownServerCatalog.cs" />
<Compile Include="..\..\src\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="App\AcLaunchArgumentBuilder.cs" />
<Compile Include="..\..\src\RynthCore.App\FirstLoginRules.cs" Link="App\FirstLoginRules.cs" />
<Compile Include="..\..\src\RynthCore.App\UserPrefsSwapRecovery.cs" Link="App\UserPrefsSwapRecovery.cs" />

View file

@ -292,6 +292,37 @@ internal static class Program
CheckNoPlainText("LEAK-CHECK-PW");
});
Scenario("known servers: picking one fills the profile, saved profiles find theirs", root, () =>
{
var all = KnownServerCatalog.All;
Check(all.Count == 17, $"17 known servers (16 + ILT), got {all.Count}");
Check(all.Select(s => s.Id).Distinct(StringComparer.OrdinalIgnoreCase).Count() == all.Count, "ids unique");
Check(all.Select(s => s.Host).Distinct(StringComparer.OrdinalIgnoreCase).Count() == all.Count, "hosts unique");
Check(all.All(s => s.Port is > 0 and < 65536 && s.PluginName.StartsWith("Rynth", StringComparison.Ordinal)),
"every entry has a port and a Rynth plugin");
Check(all.Select(s => s.Name).SequenceEqual(all.Select(s => s.Name).OrderBy(n => n, StringComparer.OrdinalIgnoreCase)),
"listed by name");
KnownServer? reef = KnownServerCatalog.FindById("REEFCULL");
Check(reef?.Emulator == AcEmulatorKind.Gdle, "Reefcull is GDLE (id lookup ignores case)");
Check(KnownServerCatalog.FindById("portalstorm")?.Port == 9020, "PortalStorm uses 9020");
var p = new LaunchServerProfile { Id = "keep", Alias = "Main", RodatEnabled = true, Host = "x", Port = 1 };
KnownServerCatalog.ApplyTo(KnownServerCatalog.FindById("ilt")!, p);
Check(p.Name == "Infinite Leaftide" && p.ConnectionString == "game.infiniteleaftide.online:9000" && p.Emulator == AcEmulatorKind.Ace,
"ILT fills name, host, port, emulator: " + p.ConnectionString);
Check(p.Id == "keep" && p.Alias == "Main" && p.RodatEnabled, "id, alias and Rodat kept");
Check(KnownServerCatalog.FindByHost("PLAY.COLDEVE.AC.")?.Id == "coldeve", "exact host (case, trailing dot)");
Check(KnownServerCatalog.FindByHost("infiniteleaftide.online")?.Id == "ilt", "ILT's parent domain finds ILT");
Check(KnownServerCatalog.FindByHost("aelrynth.com")?.Id == "aelrynth", "Aelrynth");
Check(KnownServerCatalog.FindByHost("other.ddns.net") == null, "a shared dynamic-DNS domain matches nothing");
Check(KnownServerCatalog.FindByHost("harvestbud.gdleac.com") == null, "Reefcull's shared host domain isn't Reefcull");
Check(KnownServerCatalog.FindByHost("172.111.230.12") == null, "an IP matches only itself");
Check(KnownServerCatalog.FindByHost("172.111.230.127")?.Id == "frostace", "FrostACE by IP");
Check(KnownServerCatalog.FindByHost("") == null && KnownServerCatalog.FindByHost(null) == null, "empty host");
});
// ── First Login dialog rules (a new server: no password, no characters yet) ──
Scenario("first login on a new server", root, () =>
{

View file

@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the engine half of the "Add to loot profile" attribute checklist (taken
2026-10-19): the popup's DTOs (UI\Data\LootEditData.cs) must read what RynthAi's LootEditWire
writes and write what it reads, and an older RynthAi (no attributes) must leave the popup on
its single "Include T11 attributes" box. Reaches the internal types by reflection (the
engine has no test seam). x86, like the engine: needs the x86 .NET runtime.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<Platforms>x86</Platforms>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>LootAddWireTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RynthCore.Engine\RynthCore.Engine.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,96 @@
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
namespace LootAddWireTests
{
// The engine half of the "Add to loot profile" attribute checklist, against what RynthAi's
// LootEditWire (RynthSuite Shared/RynthCore.LootSdk/Editing) writes and reads. The JSON literals
// below are LootEditJsonContext's output / input (PascalCase, case-insensitive on read).
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 const string Ns = "RynthCore.Engine.UI.Data.";
private const BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
private static int Main()
{
Assembly engine = Assembly.Load("RynthCore.Engine");
Type ctxType = engine.GetType(Ns + "LootEditJsonContext", throwOnError: true)!;
object ctx = ctxType.GetProperty("Default", All)!.GetValue(null)!;
var stateInfo = (JsonTypeInfo)ctxType.GetProperty("LootEditStateDto", All)!.GetValue(ctx)!;
var cmdInfo = (JsonTypeInfo)ctxType.GetProperty("LootEditCmd", All)!.GetValue(ctx)!;
Type stateType = engine.GetType(Ns + "LootEditStateDto", throwOnError: true)!;
Type draftType = engine.GetType(Ns + "LootEditItemDraftDto", throwOnError: true)!;
Type rowType = engine.GetType(Ns + "LootEditItemAttributeDto", throwOnError: true)!;
Type cmdType = engine.GetType(Ns + "LootEditCmd", throwOnError: true)!;
Type reqType = engine.GetType(Ns + "LootEditItemRequestDto", throwOnError: true)!;
Type choiceType = engine.GetType(Ns + "LootEditItemChoiceDto", throwOnError: true)!;
Type opsType = engine.GetType(Ns + "LootAttrOps", throwOnError: true)!;
// ── RynthAi -> engine: a draft with the checklist ───────────────────────────
const string draftJson =
"{\"ItemDraft\":{\"Seq\":7,\"ItemId\":2147483648,\"ItemName\":\"Gold Sword\",\"AttributesSupported\":true," +
"\"Attributes\":[" +
"{\"Id\":\"L:131\",\"Group\":\"Item\",\"Label\":\"Material\",\"ItemValue\":\"Gold\",\"Value\":\"Gold\",\"Op\":1,\"Ops\":[1,3],\"Editable\":false,\"On\":true,\"Tip\":\"t\"}," +
"{\"Id\":\"spell:Major Strength\",\"Group\":\"Spells\",\"Label\":\"Major Strength\",\"ItemValue\":\"Major\",\"Value\":\"Major\",\"Op\":11,\"Ops\":[10,11,12],\"Editable\":false,\"On\":false,\"Tip\":\"\"}," +
"{\"Id\":\"L:5\",\"Group\":\"Item\",\"Label\":\"Burden\",\"ItemValue\":\"8\",\"Value\":\"9\",\"Op\":2,\"Ops\":[0,1,2],\"Editable\":true,\"On\":true,\"Tip\":\"\"}]}}";
object state = JsonSerializer.Deserialize(draftJson, stateInfo)!;
object draft = stateType.GetProperty("ItemDraft", All)!.GetValue(state)!;
Check((bool)draftType.GetProperty("AttributesSupported", All)!.GetValue(draft)!, "AttributesSupported is read");
var rows = ((System.Collections.IEnumerable)draftType.GetProperty("Attributes", All)!.GetValue(draft)!).Cast<object>().ToList();
Check(rows.Count == 3, "three rows read");
object spell = rows.First(r => (string)rowType.GetProperty("Id")!.GetValue(r)! == "spell:Major Strength");
Check((int)rowType.GetProperty("Op")!.GetValue(spell)! == 11 && ((List<int>)rowType.GetProperty("Ops")!.GetValue(spell)!).SequenceEqual(new[] { 10, 11, 12 }), "a spell row: op and the ops it offers");
Check(!(bool)rowType.GetProperty("On")!.GetValue(spell)!, "a spell row is unticked");
object burden = rows.First(r => (string)rowType.GetProperty("Id")!.GetValue(r)! == "L:5");
Check((bool)rowType.GetProperty("Editable")!.GetValue(burden)! && (string)rowType.GetProperty("Value")!.GetValue(burden)! == "9" && (string)rowType.GetProperty("ItemValue")!.GetValue(burden)! == "8", "a numeric row: editable, the rule's value and the item's");
// The op codes the popup labels are the SDK's LootItemAttributeOp.
MethodInfo label = opsType.GetMethod("Label", All)!;
string L(int op) => (string)label.Invoke(null, new object[] { op })!;
Check(L(0) == ">=" && L(1) == "=" && L(2) == "<=" && L(3) == "not", "numeric / named ops label as >= = <= not");
Check(L(10) == "exact" && L(11) == "or better" && L(12) == "any tier", "spell ops label as exact / or better / any tier");
// ── An older RynthAi: no checklist -> the popup keeps its T11 box ───────────
object older = JsonSerializer.Deserialize("{\"ItemDraft\":{\"Seq\":3,\"ItemName\":\"Gold Sword\",\"IncludeT11\":true,\"IsT11\":true}}", stateInfo)!;
object olderDraft = stateType.GetProperty("ItemDraft", All)!.GetValue(older)!;
Check(!(bool)draftType.GetProperty("AttributesSupported", All)!.GetValue(olderDraft)!, "an older RynthAi: AttributesSupported is false (the T11 box shows)");
Check(((System.Collections.ICollection)draftType.GetProperty("Attributes", All)!.GetValue(olderDraft)!).Count == 0, "and there are no rows");
Check((bool)draftType.GetProperty("IncludeT11", All)!.GetValue(olderDraft)!, "its T11 answer is still read");
// ── Engine -> RynthAi: the ask ───────────────────────────────────────────────
object choice = Activator.CreateInstance(choiceType, nonPublic: true)!;
choiceType.GetProperty("Id")!.SetValue(choice, "L:5");
choiceType.GetProperty("On")!.SetValue(choice, true);
choiceType.GetProperty("Op")!.SetValue(choice, 2);
choiceType.GetProperty("Value")!.SetValue(choice, "9");
object req = Activator.CreateInstance(reqType, nonPublic: true)!;
reqType.GetProperty("ItemId")!.SetValue(req, 0x80000001u);
var list = (System.Collections.IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(choiceType))!;
list.Add(choice);
reqType.GetProperty("Choices")!.SetValue(req, list);
object cmd = Activator.CreateInstance(cmdType, nonPublic: true)!;
cmdType.GetProperty("Op")!.SetValue(cmd, "item_preview");
cmdType.GetProperty("Item")!.SetValue(cmd, req);
string cj = JsonSerializer.Serialize(cmd, cmdInfo);
Check(cj.Contains("\"Choices\":[{\"Id\":\"L:5\",\"On\":true,\"Op\":2,\"Value\":\"9\"}]"), "choices are written as RynthAi's LootEditItemChoice reads them: " + cj);
// Until the player changes a row the ask carries none: RynthAi's own defaults (and notes) apply.
object bare = Activator.CreateInstance(reqType, nonPublic: true)!;
Check(reqType.GetProperty("Choices")!.GetValue(bare) == null, "a fresh ask has no choices");
cmdType.GetProperty("Item")!.SetValue(cmd, bare);
Check(JsonSerializer.Serialize(cmd, cmdInfo).Contains("\"Choices\":null"), "which is written as null (an older RynthAi ignores the field)");
Console.WriteLine(_fails == 0 ? $"All {_asserts} checks passed." : $"{_fails} of {_asserts} checks FAILED.");
return _fails == 0 ? 0 : 1;
}
}
}

View file

@ -592,10 +592,10 @@ internal static class Program
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 follow v78's, then v80's two and v81's GetMergeStackResultFn (v82-v85 follow).
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(7).TakeLast(6).ToArray();
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(8).TakeLast(6).ToArray();
Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn", "GetContainerOrderFn", "PutItemInContainerFn", "GetMergeStackResultFn" }),
"v79, v80 then v81 slots last: " + string.Join(",", names));
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(7).TakeLast(6).ToArray();
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(8).TakeLast(6).ToArray();
Check(sdkNames.SequenceEqual(names), "SDK v79, v80 and v81 slots in the same order");
}
@ -607,17 +607,19 @@ internal static class Program
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray();
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).ToArray();
// v81's GetMergeStackResultFn follows v80's two slots.
Check(names.SkipLast(8).TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots before v81's to v85's: " + string.Join(",", names.SkipLast(8).TakeLast(2)));
Check(sdkNames.SkipLast(8).TakeLast(2).SequenceEqual(names.SkipLast(8).TakeLast(2)), "SDK v80 slots in the same order");
Check(names.SkipLast(6).Last() == "SalvageDirectFn", "v82 slot before v83's");
Check(names.SkipLast(9).TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots before v81's to v85's: " + string.Join(",", names.SkipLast(9).TakeLast(2)));
Check(sdkNames.SkipLast(9).TakeLast(2).SequenceEqual(names.SkipLast(9).TakeLast(2)), "SDK v80 slots in the same order");
Check(names.SkipLast(7).Last() == "SalvageDirectFn", "v82 slot before v83's");
// v83: GetObjectServerAge and RemoveClientObject (ghost creatures), then v84's slot.
Check(names.SkipLast(4).TakeLast(2).SequenceEqual(new[] { "GetObjectServerAgeFn", "RemoveClientObjectFn" }), "v83 slots before v84's: " + string.Join(",", names.SkipLast(4).TakeLast(2)));
Check(names.SkipLast(5).TakeLast(2).SequenceEqual(new[] { "GetObjectServerAgeFn", "RemoveClientObjectFn" }), "v83 slots before v84's: " + string.Join(",", names.SkipLast(5).TakeLast(2)));
// v84: GetObjectProperties (every property of an object, /ub propertydump), then v85's two.
Check(names.SkipLast(3).Last() == "GetObjectPropertiesFn", "v84 slot before v85's: " + names.SkipLast(3).Last());
Check(names.SkipLast(4).Last() == "GetObjectPropertiesFn", "v84 slot before v85's: " + names.SkipLast(4).Last());
// v85: ArmConfirmation and GetLastConfirmation (the server's yes/no prompts), then v86's slot.
Check(names.SkipLast(1).TakeLast(2).SequenceEqual(new[] { "ArmConfirmationFn", "GetLastConfirmationFn" }), "v85 slots before v86's: " + string.Join(",", names.SkipLast(1).TakeLast(2)));
// v86: GetServerStateJson ends the table (which server this is, for every plugin).
Check(names.Last() == "GetServerStateJsonFn", "v86 slot last: " + names.Last());
Check(names.SkipLast(2).TakeLast(2).SequenceEqual(new[] { "ArmConfirmationFn", "GetLastConfirmationFn" }), "v85 slots before v86's: " + string.Join(",", names.SkipLast(2).TakeLast(2)));
// v86: GetServerStateJson (which server this is, for every plugin), then v87's slot.
Check(names.SkipLast(1).Last() == "GetServerStateJsonFn", "v86 slot before v87's: " + names.SkipLast(1).Last());
// v87: GetWieldedItems ends the table (what the player wields, from the server's messages).
Check(names.Last() == "GetWieldedItemsFn", "v87 slot last: " + names.Last());
Check(typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SequenceEqual(typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name)), "SDK table has the engine's slots in the same order");
Eq(Marshal.SizeOf<RynthCore.PluginSdk.RynthCoreApiNative>(), Marshal.SizeOf<RynthCore.Engine.Plugins.RynthCoreAPI>(), "SDK table size = engine table size");
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("PutItemInContainerFn"),
@ -640,6 +642,8 @@ internal static class Program
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("GetLastConfirmationFn"), "GetLastConfirmationFn offset");
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("GetServerStateJsonFn"),
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("GetServerStateJsonFn"), "GetServerStateJsonFn offset");
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("GetWieldedItemsFn"),
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("GetWieldedItemsFn"), "GetWieldedItemsFn offset");
}
private sealed class ProbePlugin : RynthCore.PluginCore.RynthPluginBase { }

View file

@ -0,0 +1,274 @@
using RynthCore.Engine;
namespace ReloadInWorldGateTests;
/// <summary>
/// Offline checks for ReloadInWorldGate (the opt-in hold of an automatic hot reload while the
/// player is in the world). See the csproj comment for the cases.
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static string _case = "";
private static readonly TimeSpan Ten = TimeSpan.FromMinutes(10);
private static readonly DateTime T0 = new(2026, 10, 18, 9, 0, 0, DateTimeKind.Utc);
private static int Main()
{
ShouldHoldRules();
DefaultOffNeverHolds();
ClearWhenNotHolding();
WaitsUntilLeftWorld();
ManualReloadBypassesTheHold();
ManualReloadMidWaitReleases();
SettingSwitchedOffMidWaitReleases();
TimeoutGivesUpAndLogsOnce();
TimeoutIsNotLateByAPoll();
LeavingAtTheBoundIsStillCleared();
ThrowingHoldNeverWedges();
ThrowingHoldMidWaitReleases();
MaxMinutesClamp();
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}");
}
private static void ShouldHoldRules()
{
_case = "ShouldHold";
Check(ReloadInWorldGate.ShouldHold(byHand: false, holdEnabled: true, inWorld: true), "automatic + in world + hold on: hold");
Check(!ReloadInWorldGate.ShouldHold(byHand: true, holdEnabled: true, inWorld: true), "by hand + in world + hold on: never held");
Check(!ReloadInWorldGate.ShouldHold(byHand: false, holdEnabled: true, inWorld: false), "out of world: never hold");
Check(!ReloadInWorldGate.ShouldHold(byHand: true, holdEnabled: true, inWorld: false), "by hand + out of world: never hold");
}
// The default (HoldReloadInWorld off) must never hold, whatever the world state or the origin.
private static void DefaultOffNeverHolds()
{
_case = "default off";
foreach (bool byHand in new[] { false, true })
foreach (bool inWorld in new[] { false, true })
Check(!ReloadInWorldGate.ShouldHold(byHand, holdEnabled: false, inWorld), $"hold off, byHand={byHand}, inWorld={inWorld}: never hold");
// The query EntryPoint hands to Run is ShouldHold(..., holdEnabled: false, ...): Run returns at once.
var logs = new List<string>();
int sleeps = 0;
var outcome = ReloadInWorldGate.Run(
stillHold: () => ReloadInWorldGate.ShouldHold(false, holdEnabled: false, inWorld: true),
log: logs.Add,
notify: _ => throw new InvalidOperationException("must not notify"),
maxWait: Ten,
waited: out TimeSpan waited,
sleep: _ => sleeps++);
Check(outcome == ReloadInWorldGate.Outcome.Clear, $"Clear (got {outcome})");
Check(waited == TimeSpan.Zero && sleeps == 0, "no wait, no sleep");
Check(logs.Count == 0, "no new log line");
}
private static void ClearWhenNotHolding()
{
_case = "clear";
var logs = new List<string>();
var outcome = ReloadInWorldGate.Run(
stillHold: () => false,
log: logs.Add,
notify: null,
maxWait: Ten,
waited: out TimeSpan waited,
clock: () => T0,
sleep: _ => { });
Check(outcome == ReloadInWorldGate.Outcome.Clear, $"Clear (got {outcome})");
Check(waited == TimeSpan.Zero, "no wait");
Check(logs.Count == 0, "nothing logged");
}
private static void WaitsUntilLeftWorld()
{
_case = "wait then clear";
var now = T0;
int polls = 0;
var logs = new List<string>();
var notes = new List<string>();
var outcome = ReloadInWorldGate.Run(
stillHold: () => ++polls <= 5, // hold for 5 polls, then clear
log: logs.Add,
notify: notes.Add,
maxWait: Ten,
waited: out TimeSpan waited,
clock: () => now,
sleep: t => now += t,
poll: TimeSpan.FromSeconds(2),
logEvery: TimeSpan.FromSeconds(30));
Check(outcome == ReloadInWorldGate.Outcome.ClearedAfterWait, $"ClearedAfterWait (got {outcome})");
Check(Math.Abs(waited.TotalSeconds - 10) < 0.01, $"waited 10 s (got {waited.TotalSeconds})");
Check(logs.Count >= 2 && logs[0].Contains("player is in the world", StringComparison.Ordinal),
$"first log names the world: {logs.FirstOrDefault()}");
Check(logs[^1].Contains("hold released", StringComparison.Ordinal), $"last log: {logs[^1]}");
Check(!logs.Any(l => l.Contains("reloading anyway", StringComparison.Ordinal)), "no give-up line when the player left");
Check(notes.Count == 1 && notes[0].Contains("in the world", StringComparison.Ordinal), "chat notify once");
}
// A reload asked for by hand is never held: modelled the way EntryPoint wires it (the hold query is
// ShouldHold(byHand, ...)), so the gate returns Clear without a wait.
private static void ManualReloadBypassesTheHold()
{
_case = "manual bypass";
int sleeps = 0;
var outcome = ReloadInWorldGate.Run(
stillHold: () => ReloadInWorldGate.ShouldHold(byHand: true, holdEnabled: true, inWorld: true),
log: _ => { },
notify: null,
maxWait: Ten,
waited: out TimeSpan waited,
sleep: _ => sleeps++);
Check(outcome == ReloadInWorldGate.Outcome.Clear, $"Clear (got {outcome})");
Check(waited == TimeSpan.Zero && sleeps == 0, "no wait");
}
// An automatic reload is being held, then the player presses RL / ERl: the next poll releases it.
private static void ManualReloadMidWaitReleases()
{
_case = "manual mid-wait";
var now = T0;
bool byHand = false;
var logs = new List<string>();
var outcome = ReloadInWorldGate.Run(
stillHold: () => ReloadInWorldGate.ShouldHold(byHand, holdEnabled: true, inWorld: true),
log: logs.Add,
notify: null,
maxWait: Ten,
waited: out TimeSpan waited,
clock: () => now,
sleep: t => { now += t; if (now - T0 >= TimeSpan.FromSeconds(60)) byHand = true; });
Check(outcome == ReloadInWorldGate.Outcome.ClearedAfterWait, $"ClearedAfterWait (got {outcome})");
Check(Math.Abs(waited.TotalSeconds - 60) < 0.01, $"released at the poll after the press, 60 s (got {waited.TotalSeconds})");
Check(!logs.Any(l => l.Contains("reloading anyway", StringComparison.Ordinal)), "not a give-up");
}
private static void SettingSwitchedOffMidWaitReleases()
{
_case = "setting off mid-wait";
var now = T0;
bool enabled = true;
var outcome = ReloadInWorldGate.Run(
stillHold: () => ReloadInWorldGate.ShouldHold(false, holdEnabled: enabled, inWorld: true),
log: _ => { },
notify: null,
maxWait: Ten,
waited: out TimeSpan waited,
clock: () => now,
sleep: t => { now += t; if (now - T0 >= TimeSpan.FromSeconds(6)) enabled = false; });
Check(outcome == ReloadInWorldGate.Outcome.ClearedAfterWait, $"ClearedAfterWait (got {outcome})");
Check(Math.Abs(waited.TotalSeconds - 6) < 0.01, $"released after 6 s (got {waited.TotalSeconds})");
}
private static void TimeoutGivesUpAndLogsOnce()
{
_case = "timeout";
var now = T0;
int polls = 0;
var logs = new List<string>();
var outcome = ReloadInWorldGate.Run(
stillHold: () => { polls++; return true; }, // never leaves the world
log: logs.Add,
notify: null,
maxWait: TimeSpan.FromMinutes(3),
waited: out TimeSpan waited,
clock: () => now,
sleep: t => now += t,
poll: TimeSpan.FromSeconds(2),
logEvery: TimeSpan.FromSeconds(30));
Check(outcome == ReloadInWorldGate.Outcome.TimedOut, $"TimedOut (got {outcome})");
Check(Math.Abs(waited.TotalMinutes - 3) < 0.001, $"waited exactly the bound, 3 min (got {waited.TotalMinutes})");
int gaveUp = logs.Count(l => l.Contains("reloading anyway", StringComparison.Ordinal));
Check(gaveUp == 1, $"the give-up is logged once (got {gaveUp})");
Check(logs[^1].Contains("held 3 min, reloading anyway", StringComparison.Ordinal), $"last log: {logs[^1]}");
Check(logs.Count(l => l.Contains("still in the world", StringComparison.Ordinal)) >= 3, "periodic 'still in the world' lines while waiting");
Check(polls < 200, $"bounded number of polls (got {polls})");
}
// The bound is not a poll late: with a 1 min bound and a 7 s poll the last sleep is shortened.
private static void TimeoutIsNotLateByAPoll()
{
_case = "timeout on time";
var now = T0;
var outcome = ReloadInWorldGate.Run(
stillHold: () => true,
log: _ => { },
notify: null,
maxWait: TimeSpan.FromMinutes(1),
waited: out TimeSpan waited,
clock: () => now,
sleep: t => now += t,
poll: TimeSpan.FromSeconds(7));
Check(outcome == ReloadInWorldGate.Outcome.TimedOut, $"TimedOut (got {outcome})");
Check(Math.Abs(waited.TotalSeconds - 60) < 0.001, $"gave up at 60 s, not 63 (got {waited.TotalSeconds})");
}
// Leaving the world and the bound landing on the same poll: leaving wins (the reload is not "anyway").
private static void LeavingAtTheBoundIsStillCleared()
{
_case = "leaves at the bound";
var now = T0;
var outcome = ReloadInWorldGate.Run(
stillHold: () => now - T0 < TimeSpan.FromMinutes(1),
log: _ => { },
notify: null,
maxWait: TimeSpan.FromMinutes(1),
waited: out TimeSpan waited,
clock: () => now,
sleep: t => now += t,
poll: TimeSpan.FromSeconds(2));
Check(outcome == ReloadInWorldGate.Outcome.ClearedAfterWait, $"ClearedAfterWait (got {outcome})");
}
private static void ThrowingHoldNeverWedges()
{
_case = "throwing stillHold";
var outcome = ReloadInWorldGate.Run(
stillHold: () => throw new InvalidOperationException("boom"),
log: _ => { },
notify: null,
maxWait: Ten,
waited: out TimeSpan waited,
clock: () => DateTime.UtcNow,
sleep: _ => { });
Check(outcome == ReloadInWorldGate.Outcome.Clear, "throwing query fails open to Clear");
Check(waited == TimeSpan.Zero, "no wait on throw");
}
private static void ThrowingHoldMidWaitReleases()
{
_case = "throwing mid-wait";
var now = T0;
int calls = 0;
var outcome = ReloadInWorldGate.Run(
stillHold: () => ++calls <= 3 ? true : throw new InvalidOperationException("boom"),
log: _ => { },
notify: null,
maxWait: Ten,
waited: out TimeSpan waited,
clock: () => now,
sleep: t => now += t);
Check(outcome == ReloadInWorldGate.Outcome.ClearedAfterWait, $"fails open to ClearedAfterWait (got {outcome})");
}
private static void MaxMinutesClamp()
{
_case = "max minutes";
Check(ReloadInWorldGate.DefaultMaxMinutes == 10, "default 10");
Check(ReloadInWorldGate.ClampMaxMinutes(10) == 10, "10 stays");
Check(ReloadInWorldGate.ClampMaxMinutes(1) == 1 && ReloadInWorldGate.ClampMaxMinutes(240) == 240, "1 and 240 are valid");
Check(ReloadInWorldGate.ClampMaxMinutes(0) == 1 && ReloadInWorldGate.ClampMaxMinutes(-3) == 1, "below 1 clamps to 1");
Check(ReloadInWorldGate.ClampMaxMinutes(241) == 240 && ReloadInWorldGate.ClampMaxMinutes(int.MaxValue) == 240, "above 240 clamps to 240");
}
}

View file

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the opt-in in-world hot-reload hold (2026-10-18, from SilentKelpie's PR 6):
src\RynthCore.Engine\ReloadInWorldGate.cs. Off by default: never holds. On: an automatic reload
waits while the player is in the world; a reload asked for by hand is never held; leaving the
world (or switching the hold off, or a hand reload arriving mid-wait) releases it; at the
HoldReloadInWorldMaxMinutes bound it gives up, logs once, and the reload goes ahead; a
throwing query never wedges. Clock and sleep are fakes.
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>ReloadInWorldGateTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\ReloadInWorldGate.cs" Link="Engine\ReloadInWorldGate.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,99 @@
using System.Collections;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
namespace VaultedSettingTests
{
// Reaches RynthCore.Engine's internal settings mirror by reflection. 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 const string Ns = "RynthCore.Engine.UI.Data.";
private const BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
private static int Main()
{
Assembly engine = Assembly.Load("RynthCore.Engine");
Type settingsType = engine.GetType(Ns + "RynthAiSettings", throwOnError: true)!;
Type ctxType = engine.GetType(Ns + "RynthAiSettingsJsonContext", throwOnError: true)!;
Type schemaType = engine.GetType(Ns + "SettingsSchema", throwOnError: true)!;
PropertyInfo? prop = settingsType.GetProperty("EnableVaultedDungeons", All);
Check(prop != null && prop.PropertyType == typeof(bool?), "the mirror has a nullable EnableVaultedDungeons (RynthAi's payload name)");
if (prop == null) return Finish();
object ctx = ctxType.GetProperty("Default", All)!.GetValue(null)!;
var info = (JsonTypeInfo)ctxType.GetProperty("RynthAiSettings", All)!.GetValue(ctx)!;
object Parse(string json) => JsonSerializer.Deserialize(json, info)!;
// What a payload carries: nothing from an older RynthAi, the value from a newer one.
object fresh = Activator.CreateInstance(settingsType, nonPublic: true)!;
Check(prop.GetValue(fresh) == null, "a fresh mirror holds no value (nothing is claimed until RynthAi sends it)");
Check(prop.GetValue(Parse("{\"BoostNavPriority\":true}")) == null, "an older RynthAi's payload: absent (null)");
Check((bool?)prop.GetValue(Parse("{\"EnableVaultedDungeons\":false}")) == false, "RynthAi sends false");
Check((bool?)prop.GetValue(Parse("{\"EnableVaultedDungeons\":true}")) == true, "RynthAi sends true");
Check((bool?)prop.GetValue(Parse("{\"enablevaulteddungeons\":true}")) == true, "the key is matched ignoring case, like the rest");
// A save sends exactly what the mirror holds: unset stays null (RynthAi leaves its switch alone).
Check(JsonSerializer.Serialize(fresh, info).Contains("\"EnableVaultedDungeons\":null"), "an unset mirror saves null, never a made-up false");
Check(JsonSerializer.Serialize(Parse("{\"EnableVaultedDungeons\":true}"), info).Contains("\"EnableVaultedDungeons\":true"), "an On mirror saves true");
// The schema row.
object? nav = null;
foreach (object t in (IEnumerable)schemaType.GetField("Tabs", All)!.GetValue(null)!)
if ((string)t.GetType().GetProperty("Name")!.GetValue(t)! == "Navigation") nav = t;
Check(nav != null, "a Navigation tab");
if (nav == null) return Finish();
string label = (string)schemaType.GetField("VaultedDungeonsLabel", All)!.GetValue(null)!;
Check(label == "Vaulted Dungeons", "the row is called Vaulted Dungeons");
var matches = new List<object>();
foreach (object r in (IEnumerable)nav.GetType().GetProperty("Rows")!.GetValue(nav)!)
if ((string?)r.GetType().GetProperty("Label")!.GetValue(r) == label) matches.Add(r);
Check(matches.Count == 1, "exactly one Vaulted Dungeons row, under Navigation");
if (matches.Count != 1) return Finish();
object row = matches[0];
Type rt = row.GetType();
Check(rt.GetProperty("Kind")!.GetValue(row)!.ToString() == "Bool", "a checkbox");
var get = (Delegate)rt.GetProperty("Get")!.GetValue(row)!;
var set = (Delegate)rt.GetProperty("Set")!.GetValue(row)!;
MethodInfo visible = rt.GetMethod("IsVisible")!;
string tip = (string?)rt.GetProperty("Tooltip")!.GetValue(row) ?? "";
Check(tip.Contains("Off by default") && tip.Contains("Infinite Leaftide"), "the tooltip says it is the master switch, off by default, ILT only");
Check(tip.Contains("do NOT"), "and warns that pet/fellow kills don't restart the Kill Client timer");
object unset = Activator.CreateInstance(settingsType, nonPublic: true)!;
Check(!(bool)visible.Invoke(row, new[] { unset })!, "hidden while RynthAi hasn't sent the value (an older RynthAi)");
Check((double)get.DynamicInvoke(unset)! == 0, "an unset mirror reads Off");
object off = Parse("{\"EnableVaultedDungeons\":false}");
Check((bool)visible.Invoke(row, new[] { off })!, "shown once RynthAi sends it");
Check((double)get.DynamicInvoke(off)! == 0, "reads Off by default");
set.DynamicInvoke(off, 1.0);
Check((bool?)prop.GetValue(off) == true, "ticking it sets EnableVaultedDungeons to true");
Check((double)get.DynamicInvoke(off)! == 1, "and it reads On");
set.DynamicInvoke(off, 0.0);
Check((bool?)prop.GetValue(off) == false, "unticking sets false (not null)");
// Ticking it changes nothing else in the payload.
object before = Parse("{\"BoostNavPriority\":true,\"EnableVaultedDungeons\":false}");
set.DynamicInvoke(before, 1.0);
string after = JsonSerializer.Serialize(before, info);
Check(after.Contains("\"BoostNavPriority\":true") && after.Contains("\"EnableVaultedDungeons\":true"), "the other settings ride along unchanged");
return Finish();
}
private static int Finish()
{
Console.WriteLine(_fails == 0 ? $"All {_asserts} checks passed." : $"{_fails} of {_asserts} checks FAILED.");
return _fails == 0 ? 0 : 1;
}
}
}

View file

@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the Settings > Navigation "Vaulted Dungeons" row (2026-10-18; the keeper is
Silentkelpie's, RynthSuite PR 12): the mirror of RynthAi's EnableVaultedDungeons master switch in
UI\Data\SettingsData.cs. Nothing is claimed until RynthAi sends the value (an older RynthAi omits
it: the row stays hidden and a save sends null, which RynthAi leaves alone); the row edits only
that property; it reads Off by default.
The engine has no test seam for SettingsData.cs (it pulls in the whole ImGui layer), so this
references the built engine assembly and reaches the internal types by reflection. x86, like
the engine: needs the x86 .NET runtime (C:\Program Files (x86)\dotnet).
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<Platforms>x86</Platforms>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>VaultedSettingTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RynthCore.Engine\RynthCore.Engine.csproj" />
</ItemGroup>
</Project>