Snapshot for release 2026.10.12.1 (internal ef4d41d)

This commit is contained in:
Tom Bohar 2026-10-12 00:33:12 -04:00
commit b0f9d74b21
54 changed files with 5062 additions and 935 deletions

View file

@ -0,0 +1,79 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
How much a longer RynthChat history costs (2026-10-11, the "Chat history" setting), and
a check of the ImGui scroll behaviour the chat's follow-the-newest-line fix relies on.
Measures, with the real classes compiled in:
- managed memory per 1,000 lines: the engine's ChatLine (+ its route) and RynthChat's
ring (the plugin's ChatBuffer), filled with realistic AC lines;
- per poll: the plugin's BuildJson for a few new lines (0.3.0 vs the 0.2.1 copy in
OldChatBuffer.cs) and the engine's merge into a new published array;
- the first read after a bind or reload (the whole ring as JSON, parsed and routed);
- re-routing every kept line when a rule changes, on the pump;
- the chat face's work: a tab or search rebuild, unread counts, the tops, and
measuring wrapped heights with the engine's own cimgui.dll;
at 500, 2,000, 5,000 and 10,000 lines.
x86 on purpose, like acclient (object sizes, the 32-bit address space). Needs the x86
.NET runtime (C:\Program Files (x86)\dotnet). RynthChat's files come from the sibling
RynthSuite checkout (..\..\..\RynthSuite, or -p:RynthSuiteDir=...); without it the
plugin-side numbers are skipped.
Run: dotnet run -c Release (exit 0 = every check passed, 1 = one failed)
2026-10-11 (Tom's PC, x86, 8 cores; medians, run-to-run noise ~20%):
lines 500 2,000 5,000 10,000
memory, engine + plugin + face 0.9 MB 3.7 MB 9.1 MB 18 MB
plugin BuildJson, 3 new 0.2.1 / 0.3.0 19/4 us 50/6 us 82/5 us 136/4 us
engine merge per poll 0.3 us 1.2 us 3.4 us 11 us
first read (bind / reload, once) 3.2 ms 14.6 ms 29.8 ms 58.5 ms
re-route all lines (rule edit) 2.4 ms 6.6 ms 17.1 ms 27.2 ms
face: tab rebuild / search rebuild 11/177 us 45/716 us 0.1/1.8 ms 0.7/3.6 ms
face: unread, full (was) / incremental 100/0.5 us 396/0.5 us 1.1ms/0.7us 4.1ms/0.5us
face: measure every wrapped line 0.6 ms 3.7 ms 6.7 ms 14.8 ms
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<ServerGarbageCollector>false</ServerGarbageCollector>
<ConcurrentGarbageCollection>false</ConcurrentGarbageCollection>
<TieredPGO>true</TieredPGO>
<RootNamespace>ChatHistoryBench</RootNamespace>
<RynthSuiteDir Condition="'$(RynthSuiteDir)' == ''">$(MSBuildThisFileDirectory)..\..\..\RynthSuite</RynthSuiteDir>
<RynthChatDir>$(RynthSuiteDir)\Plugins\RynthCore.Plugin.RynthChat</RynthChatDir>
<DefineConstants Condition="Exists('$(RynthChatDir)\ChatBuffer.cs')">$(DefineConstants);HAVE_RYNTHCHAT</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatRouting.cs" Link="Engine\ChatRouting.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatHistory.cs" Link="Engine\ChatHistory.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatLineColors.cs" Link="Engine\ChatLineColors.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatRuleMatching.cs" Link="Engine\ChatRuleMatching.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ChatSettingsDto.cs" Link="Engine\ChatSettingsDto.cs" />
</ItemGroup>
<ItemGroup Condition="Exists('$(RynthChatDir)\ChatBuffer.cs')">
<Compile Include="$(RynthChatDir)\ChatBuffer.cs" Link="RynthChat\ChatBuffer.cs" />
<Compile Include="$(RynthChatDir)\ChatClassifier.cs" Link="RynthChat\ChatClassifier.cs" />
<Compile Include="$(RynthChatDir)\ChatLine.cs" Link="RynthChat\ChatLine.cs" />
</ItemGroup>
<ItemGroup Condition="!Exists('$(RynthChatDir)\ChatBuffer.cs')">
<Compile Remove="OldChatBuffer.cs" />
</ItemGroup>
<!-- The engine's own cimgui.dll (x86, obsolete APIs compiled out), over the package's. -->
<Target Name="CopyEngineCimgui" AfterTargets="Build">
<Copy SourceFiles="..\..\src\RynthCore.Engine\Native\cimgui.dll" DestinationFolder="$(OutputPath)" />
</Target>
</Project>

View file

@ -0,0 +1,159 @@
// RynthChat 0.2.1's ChatBuffer as the per-poll baseline for ChatHistoryBench: unchanged
// but for its name and its capacity (a const 500 there). It cloned and walked the whole
// ring on every poll.
using System;
using System.Text;
using RynthCore.Plugin.RynthChat;
namespace ChatHistoryBench;
/// <summary>
/// The newest 500 chat lines, exported to the engine as JSON
/// (RynthChatGetScrollbackJson). Add runs on the game thread (chat dispatch),
/// BuildJson on the engine's pump thread; the lock covers both.
///
/// JSON per line: {"seq":N,"ts":"HH:mm:ss","chan":"Chat","type":3,"sender":"Bob"|null,"text":"..."}.
/// "type" (AC's ChatMessageType) was added in 0.2.0; engines before it ignore it.
/// Every non-ASCII character is written as a \uXXXX escape, so the export is
/// pure ASCII and survives the ANSI marshalling on both sides (before 0.2.0 an
/// accented name or the "→" of an outgoing tell arrived as "?").
/// </summary>
internal sealed class OldChatBuffer
{
private readonly int Capacity; // bench: a const 500 in 0.2.1
private readonly ChatLine[] _ring;
public OldChatBuffer(int capacity) { Capacity = capacity; _ring = new ChatLine[capacity]; }
private readonly object _lock = new();
private int _head; // next write index (mod Capacity)
private int _count; // total items stored (≤ Capacity)
private ulong _nextSeq = 1;
internal void Add(string? text, int chatType)
{
if (string.IsNullOrEmpty(text)) return;
string channel = ChatClassifier.IsItemInfo(text) ? ChatClassifier.Items
: ChatClassifier.IsRynthOutput(text) ? ChatClassifier.Rynth
: ChatClassifier.ChannelFor(chatType);
string? sender = ChatClassifier.SenderFor(text, chatType);
string ts = DateTime.Now.ToString("HH:mm:ss");
lock (_lock)
{
// Numbered under the lock, so the ring is always in seq order (the
// engine skips anything at or below the last seq it has seen).
_ring[_head % Capacity] = new ChatLine
{
Seq = _nextSeq++,
Timestamp = ts,
Channel = channel,
ChatType = chatType,
Sender = sender,
Text = text,
};
_head = (_head + 1) % Capacity;
if (_count < Capacity) _count++;
}
}
// Returns JSON array of lines with Seq > sinceSeq, oldest-first.
internal string BuildJson(ulong sinceSeq)
{
ChatLine[] snapshot;
int count;
int head;
lock (_lock)
{
snapshot = (ChatLine[])_ring.Clone();
count = _count;
head = _head;
}
var sb = new StringBuilder(256);
sb.Append('[');
bool first = true;
// Iterate oldest→newest. Oldest entry is at (head - count + Capacity) % Capacity.
int start = (head - count + Capacity) % Capacity;
for (int i = 0; i < count; i++)
{
var line = snapshot[(start + i) % Capacity];
if (line == null || line.Seq <= sinceSeq) continue;
if (!first) sb.Append(',');
first = false;
sb.Append("{\"seq\":");
sb.Append(line.Seq);
sb.Append(",\"ts\":\"");
AppendEscaped(sb, line.Timestamp);
sb.Append("\",\"chan\":\"");
AppendEscaped(sb, line.Channel);
sb.Append("\",\"type\":");
sb.Append(line.ChatType);
sb.Append(",\"sender\":");
if (line.Sender != null)
{
sb.Append('"');
AppendEscaped(sb, line.Sender);
sb.Append('"');
}
else
{
sb.Append("null");
}
sb.Append(",\"text\":\"");
AppendEscaped(sb, line.Text);
sb.Append("\"}");
}
sb.Append(']');
return sb.ToString();
}
private static void AppendEscaped(StringBuilder sb, string s)
{
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
// A surrogate pair is escaped as two \uXXXX; a lone half becomes U+FFFD.
// System.Text.Json refuses a lone surrogate, and before 0.2.1 one such line
// failed the engine's whole batch (and every poll after it).
if (char.IsSurrogate(c))
{
if (char.IsHighSurrogate(c) && i + 1 < s.Length && char.IsLowSurrogate(s[i + 1]))
{
AppendUnicodeEscape(sb, c);
AppendUnicodeEscape(sb, s[++i]);
}
else
sb.Append("\\uFFFD");
continue;
}
switch (c)
{
case '"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
// Control characters and everything outside ASCII: the string is
// marshalled as ANSI, which would turn those into '?'.
if (c < 0x20 || c > 0x7E)
AppendUnicodeEscape(sb, c);
else
sb.Append(c);
break;
}
}
}
private static void AppendUnicodeEscape(StringBuilder sb, char c)
{
sb.Append("\\u");
sb.Append(((int)c).ToString("X4"));
}
}

View file

@ -0,0 +1,584 @@
using System.Diagnostics;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
namespace ChatHistoryBench;
/// <summary>
/// What a longer chat history costs, and whether ImGui scrolls the way ChatFace's
/// follow fix needs (see the csproj header). Prints tables; exit 1 if a scroll check fails.
/// </summary>
internal static unsafe class Program
{
private static readonly int[] Sizes = { 500, 2000, 5000, 10000 };
private static int _checks, _failed;
private static int Main(string[] args)
{
Console.WriteLine($"ChatHistoryBench: {(Environment.Is64BitProcess ? "x64" : "x86")} process, .NET {Environment.Version}, {Environment.ProcessorCount} cores");
#if !HAVE_RYNTHCHAT
Console.WriteLine("RynthSuite checkout not found: plugin-side numbers skipped.");
#endif
InitImGui();
ScrollChecks();
HistoryChecks();
Memory();
Cpu();
Console.WriteLine();
Console.WriteLine($"Checks: {_checks - _failed}/{_checks} passed.");
return _failed == 0 ? 0 : 1;
}
// ── Realistic lines ──────────────────────────────────────────────────
private static readonly string[] Names = { "Drakkon", "Aja", "Bob Smith", "Lucy", "Malar Zhavik", "Tusker Slayer", "Kel of the Vale" };
private static readonly string[] Monsters = { "Tusker Guard", "Olthoi Swarm Nymph", "Mattekar", "Banderling Raider", "Shadow Child", "Drudge Ravener" };
private static readonly string[] Spells = { "Incantation of Strength Self", "Aura of Defender", "Focus Self VII", "Incantation of Blade Protection Self" };
private static readonly string[] Words = (
"anyone selling mana stones need buffs at the portal north of town lfg for the olthoi dungeon " +
"key drop rate is terrible tonight wts pyreal motes lol thanks for the fellow invite where is " +
"the lifestone heading to the hub in a minute who has a legendary key ok see you there").Split(' ');
/// <summary>One AC chat line: (text as AC prints it, ChatMessageType), 60-150 characters.</summary>
private static (string Text, int Type) MakeLine(Random r)
{
int target = r.Next(60, 151);
string name = Names[r.Next(Names.Length)], mob = Monsters[r.Next(Monsters.Length)];
int k = r.Next(100);
(string head, int type, bool speech) = k switch
{
< 20 => ($"You hit {mob} for {r.Next(5, 400)} points of slashing damage!", 0x16, false),
< 35 => ($"{mob} grazes your foot for {r.Next(1, 90)} points of bludgeoning damage!", 0x15, false),
< 45 => ($"You cast {Spells[r.Next(Spells.Length)]} on yourself, refreshing {Spells[r.Next(Spells.Length)]}", 0x07, false),
< 50 => ("The spell consumed the following components: Prismatic Taper", 0x07, false),
< 62 => ($"[{(r.Next(2) == 0 ? "General" : "Trade")}] {name} says, \"", 0x08, true),
< 72 => ($"{name} says, \"", 0x02, true),
< 77 => ($"{name} tells you, \"", 0x03, true),
< 82 => ($"[Fellowship] {name} says, \"", 0x13, true),
< 88 => ($"[RynthAi] Meta state Combat -> Loot ({r.Next(1, 30)} corpses)", 0x00, false),
< 92 => ("You're too busy!", 0x1A, false),
_ => ($"You've earned {r.Next(1000, 900000)} experience.", 0x0D, false),
};
var sb = new System.Text.StringBuilder(head, 160);
if (speech)
{
if (r.Next(12) == 0) sb.Append("Drakkon "); // someone mentions you now and then
while (sb.Length < target - 1) sb.Append(Words[r.Next(Words.Length)]).Append(' ');
sb.Length = Math.Min(sb.Length, target - 1);
sb.Append('"');
}
else
{
while (sb.Length < target) sb.Append(sb.Length == head.Length ? " (" : " ").Append(Words[r.Next(Words.Length)]);
if (sb.Length > target) sb.Length = target;
}
return (sb.ToString(), type);
}
// ── The engine side, as ChatSource does it ───────────────────────────
private static ChatRouter MakeRouter()
{
ChatFilterRule Rule(ChatMatchMode mode, string pattern, ChatRuleAction action, string tab = "", string when = "",
ChatColorMode color = ChatColorMode.None)
{
var r = new ChatFilterRule { Mode = mode, Pattern = pattern, Action = action, Tab = tab, When = when, ColorMode = color };
r.Recompile();
return r;
}
// A rule set like a player's: hide spam, sort, copy tells, colour.
ChatFilterRule[] rules =
{
Rule(ChatMatchMode.Contains, "You're too busy!", ChatRuleAction.Hide),
Rule(ChatMatchMode.StartsWith, "The spell consumed the following components", ChatRuleAction.Hide),
Rule(ChatMatchMode.Regex, @"^\[RynthAi\]", ChatRuleAction.Move, "Bot"),
Rule(ChatMatchMode.Regex, @"tells you, """, ChatRuleAction.Copy, "Tells", color: ChatColorMode.Line),
Rule(ChatMatchMode.Regex, @"^\[(Trade|LFG)\]", ChatRuleAction.Move, "Trade"),
Rule(ChatMatchMode.Regex, @"^You cast .* on yourself", ChatRuleAction.Move, "Buffs", "type:7"),
Rule(ChatMatchMode.Regex, @"\b(Olthoi|Tusker)\b", ChatRuleAction.Color, color: ChatColorMode.Match),
Rule(ChatMatchMode.Contains, "Critical hit", ChatRuleAction.Color, color: ChatColorMode.Line),
};
var mention = new Regex(@"(?<![\w'])(?:Drakkon)(?![\w])", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant,
TimeSpan.FromMilliseconds(ChatFilterRule.TimeoutMs));
return new ChatRouter(rules, mention, "Drakkon", countHits: true);
}
private static long _nextId = 1;
/// <summary>ChatSource.PollLines' parse + construct + route for one read (no AC-link stripping: no links here).</summary>
private static List<ChatLine> ReadLines(string json, ChatRouter router)
{
RynthChatLineDto[]? dtos = JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatLineDtoArray);
var added = new List<ChatLine>(dtos?.Length ?? 0);
foreach (RynthChatLineDto dto in dtos ?? Array.Empty<RynthChatLineDto>())
{
var line = new ChatLine(_nextId++, dto.Ts ?? "", dto.Chan ?? "Other", dto.Type, dto.Sender, dto.Text ?? "") { Seq = dto.Seq };
line.Route = router.Evaluate(line, null);
added.Add(line);
}
return added;
}
#if HAVE_RYNTHCHAT
private static RynthCore.Plugin.RynthChat.ChatBuffer FilledPlugin(int n, Random r)
{
var b = new RynthCore.Plugin.RynthChat.ChatBuffer(n);
for (int i = 0; i < n; i++) { var (t, ty) = MakeLine(r); b.Add(t, ty); }
return b;
}
#endif
/// <summary>N engine lines, routed, built the way ChatSource builds them (from the plugin's JSON when it's here).</summary>
private static ChatLine[] EngineLines(int n, Random r, ChatRouter router)
{
#if HAVE_RYNTHCHAT
string json = FilledPlugin(n, r).BuildJson(0);
#else
var dtos = new RynthChatLineDto[n];
for (int i = 0; i < n; i++) { var (t, ty) = MakeLine(r); dtos[i] = new RynthChatLineDto { Seq = (ulong)i + 1, Ts = "12:34:56", Chan = "Combat", Type = ty, Text = t }; }
string json = JsonSerializer.Serialize(dtos, RynthChatJsonContext.Default.RynthChatLineDtoArray);
#endif
return ReadLines(json, router).ToArray();
}
// ── Memory ───────────────────────────────────────────────────────────
private static long Heap()
{
for (int i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); }
return GC.GetTotalMemory(true);
}
/// <summary>Bytes held by what <paramref name="make"/> returns.</summary>
private static long Held(Func<object> make)
{
make(); // once first, so lazy statics (regex caches, colour tables) aren't counted
long before = Heap();
object o = Make(make);
long after = Heap();
GC.KeepAlive(o);
return after - before;
}
// Not inlined: the temporaries of make() (JSON, DTOs, the plugin ring the engine lines
// were read from) must be unreachable when Held measures.
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private static object Make(Func<object> make) => make();
private static void Memory()
{
Console.WriteLine();
Console.WriteLine("Managed memory (x86 object sizes), measured with GC.GetTotalMemory:");
Console.WriteLine($"{"lines",8} | {"engine lines",13} | {"plugin ring",12} | {"face lists",11} | {"total",9} | {"per 1,000",10}");
var router = MakeRouter();
foreach (int n in Sizes)
{
long engine = Held(() => EngineLines(n, new Random(n), router));
#if HAVE_RYNTHCHAT
long plugin = Held(() => FilledPlugin(n, new Random(n + 1)));
#else
long plugin = 0;
#endif
ChatLine[] lines = EngineLines(n, new Random(n), router);
long face = Held(() =>
{
// ChatFace's per-line lists (_vis, _h, _lay, _tops), sized like List growth leaves them.
var vis = new List<ChatLine>(lines);
var h = new List<float>(new float[n]);
var lay = new List<object?>(new object?[n]);
var tops = new float[n + 1];
return new object[] { vis, h, lay, tops };
});
long total = engine + plugin + face;
Console.WriteLine($"{n,8:N0} | {Mb(engine),13} | {Mb(plugin),12} | {Mb(face),11} | {Mb(total),9} | {Mb(total * 1000 / n),10}");
}
Console.WriteLine("(The face's highlighted lines also keep a hand layout; first read of the whole ring is transient: see 'first read'.)");
}
private static string Mb(long bytes) => $"{bytes / 1048576.0:0.00} MB";
// ── CPU ──────────────────────────────────────────────────────────────
/// <summary>Median milliseconds per call of <paramref name="body"/> (setup outside the timing).</summary>
private static double Time(Action body, int iters = 50, int rounds = 7)
{
for (int i = 0; i < Math.Min(iters, 10); i++) body(); // warm up
var samples = new double[rounds];
for (int s = 0; s < rounds; s++)
{
long t0 = Stopwatch.GetTimestamp();
for (int i = 0; i < iters; i++) body();
samples[s] = (Stopwatch.GetTimestamp() - t0) * 1000.0 / Stopwatch.Frequency / iters;
}
Array.Sort(samples);
return samples[rounds / 2];
}
private static string Ms(double ms) => ms < 0.01 ? $"{ms * 1000:0.0} us" : ms < 1 ? $"{ms * 1000:0} us" : $"{ms:0.0} ms";
private static readonly string[] Tabs = { "All", "Chat", "Channels", "System", "Combat", "Rynth", "Items", "Other", "Bot", "Tells", "Trade", "Buffs" };
private static void Cpu()
{
Console.WriteLine();
Console.WriteLine("CPU, median per call (one batch = 3 new lines, the buffer full):");
var rows = new List<(string Name, string Where, string[] Cells)>();
void Row(string name, string where, Func<int, double> run)
{
var cells = new string[Sizes.Length];
for (int i = 0; i < Sizes.Length; i++) cells[i] = Ms(run(Sizes[i]));
rows.Add((name, where, cells));
}
#if HAVE_RYNTHCHAT
Row("plugin BuildJson, 3 new (0.2.1)", "pump, per poll", n =>
{
var r = new Random(n);
var b = new OldChatBuffer(n);
for (int i = 0; i < n; i++) { var (t, ty) = MakeLine(r); b.Add(t, ty); }
ulong seq = (ulong)n;
var adds = Enumerable.Range(0, 64).Select(_ => MakeLine(r)).ToArray();
int a = 0;
return Time(() =>
{
for (int i = 0; i < 3; i++) { var (t, ty) = adds[a++ & 63]; b.Add(t, ty); }
string json = b.BuildJson(seq);
seq += 3;
GC.KeepAlive(json);
}, 200);
});
Row("plugin BuildJson, 3 new (0.3.0)", "pump, per poll", n =>
{
var r = new Random(n);
var b = FilledPlugin(n, r);
ulong seq = (ulong)n;
var adds = Enumerable.Range(0, 64).Select(_ => MakeLine(r)).ToArray();
int a = 0;
return Time(() =>
{
for (int i = 0; i < 3; i++) { var (t, ty) = adds[a++ & 63]; b.Add(t, ty); }
string json = b.BuildJson(seq);
seq += 3;
GC.KeepAlive(json);
}, 200);
});
Row("plugin BuildJson, nothing new (0.2.1)", "pump, per poll", n =>
{
var r = new Random(n);
var b = new OldChatBuffer(n);
for (int i = 0; i < n; i++) { var (t, ty) = MakeLine(r); b.Add(t, ty); }
return Time(() => GC.KeepAlive(b.BuildJson((ulong)n)), 200);
});
Row("plugin BuildJson, nothing new (0.3.0)", "pump, per poll", n =>
{
var b = FilledPlugin(n, new Random(n));
return Time(() => GC.KeepAlive(b.BuildJson((ulong)n)), 200);
});
#endif
Row("engine read: parse+route 3 lines", "pump, per poll", n =>
{
var router = MakeRouter();
var r = new Random(n);
var dtos = Enumerable.Range(0, 3).Select(i => { var (t, ty) = MakeLine(r); return new RynthChatLineDto { Seq = (ulong)i + 1, Ts = "12:34:56", Chan = "Combat", Type = ty, Text = t }; }).ToArray();
string json = JsonSerializer.Serialize(dtos, RynthChatJsonContext.Default.RynthChatLineDtoArray);
return Time(() => GC.KeepAlive(ReadLines(json, router)), 200);
});
Row("engine merge into new array", "pump, per poll", n =>
{
var router = MakeRouter();
ChatLine[] kept = EngineLines(n, new Random(n), router);
var added = EngineLines(3, new Random(1), router).ToList();
return Time(() => { kept = ChatHistory.Merge(kept, added, n); }, 200);
});
Row("first read: whole ring, JSON+parse+route", "pump, once per bind/reload", n =>
{
var router = MakeRouter();
#if HAVE_RYNTHCHAT
var b = FilledPlugin(n, new Random(n));
return Time(() =>
{
string json = b.BuildJson(0);
IntPtr p = Marshal.StringToHGlobalAnsi(json); // RynthChatGetScrollbackJson
string got = Marshal.PtrToStringAnsi(p)!; // ChatSource
Marshal.FreeHGlobal(p);
GC.KeepAlive(ReadLines(got, router));
}, 3, 5);
#else
return double.NaN;
#endif
});
Row("re-route every kept line (rule edit)", "pump, per rule change", n =>
{
var router = MakeRouter();
ChatLine[] kept = EngineLines(n, new Random(n), router);
return Time(() =>
{
router.BeginPass();
try { foreach (ChatLine line in kept) line.Route = router.Evaluate(line, null); }
finally { router.EndPass(); }
}, 3, 5);
});
Row("face rebuild: tab Combat", "AC thread, tab switch", n =>
{
ChatLine[] kept = EngineLines(n, new Random(n), MakeRouter());
var vis = new List<ChatLine>(n);
return Time(() => { vis.Clear(); foreach (var l in kept) if (ChatModel.LineVisible(l, "Combat", "")) vis.Add(l); }, 20);
});
Row("face rebuild: All + search \"tusker\"", "AC thread, search keystroke", n =>
{
ChatLine[] kept = EngineLines(n, new Random(n), MakeRouter());
var vis = new List<ChatLine>(n);
return Time(() => { vis.Clear(); foreach (var l in kept) if (ChatModel.LineVisible(l, "All", "tusker")) vis.Add(l); }, 20);
});
Row("face new lines: filter 3 + drop 3 + tops", "AC thread, per batch", n =>
{
ChatLine[] kept = EngineLines(n, new Random(n), MakeRouter());
var vis = new List<ChatLine>(kept); var h = new List<float>(new float[n]); var lay = new List<object?>(new object?[n]);
var tops = new float[n + 1];
var added = EngineLines(3, new Random(2), MakeRouter());
return Time(() =>
{
vis.RemoveRange(0, 3); h.RemoveRange(0, 3); lay.RemoveRange(0, 3);
foreach (var l in added) if (ChatModel.LineVisible(l, "All", "")) { vis.Add(l); h.Add(13f); lay.Add(null); }
for (int i = 0; i < vis.Count; i++) tops[i + 1] = tops[i] + h[i];
}, 200);
});
Row("unread counts, full recount (before)", "AC thread, per batch (was)", n =>
{
ChatLine[] kept = EngineLines(n, new Random(n), MakeRouter());
var seen = Tabs.ToDictionary(t => t, _ => 0L); // worst case: no tab visited since the start
return Time(() => UnreadFull(kept, seen), 10);
});
Row("unread counts, incremental (now)", "AC thread, per batch", n =>
{
ChatLine[] kept = EngineLines(n, new Random(n), MakeRouter());
var seen = Tabs.ToDictionary(t => t, _ => 0L);
long countedTo = kept[^4].Id; // all but the newest 3 already counted
return Time(() => UnreadIncremental(kept, seen, countedTo), 200);
});
Row("measure wrapped heights, every line", "AC thread, resize/font/rebuild", n =>
{
ChatLine[] kept = EngineLines(n, new Random(n), MakeRouter());
double ms = 0;
InFrame(() => ms = Time(() => { foreach (var l in kept) GC.KeepAlive(ImGui.CalcTextSize(l.Text, false, 380f).Y); }, 3, 5));
return ms;
});
int nameW = rows.Max(r => r.Name.Length), whereW = rows.Max(r => r.Where.Length);
Console.WriteLine($"{"".PadRight(nameW)} | {"thread / when".PadRight(whereW)} | " + string.Join(" | ", Sizes.Select(s => $"{s,9:N0}")));
foreach (var (name, where, cells) in rows)
Console.WriteLine($"{name.PadRight(nameW)} | {where.PadRight(whereW)} | " + string.Join(" | ", cells.Select(c => $"{c,9}")));
}
private static int UnreadFull(ChatLine[] lines, Dictionary<string, long> seen)
{
int total = 0;
foreach (string tab in Tabs)
{
long s = seen[tab];
for (int i = lines.Length - 1; i >= 0 && lines[i].Id > s; i--)
if (ChatModel.LineInTab(lines[i], tab)) total++;
}
return total;
}
private static int UnreadIncremental(ChatLine[] lines, Dictionary<string, long> seen, long countedTo)
{
int total = 0;
foreach (string tab in Tabs)
{
long floor = Math.Max(seen[tab], countedTo);
for (int i = lines.Length - 1; i >= 0 && lines[i].Id > floor; i--)
if (ChatModel.LineInTab(lines[i], tab)) total++;
}
return total;
}
// ── ImGui ────────────────────────────────────────────────────────────
private static void InitImGui()
{
IntPtr ctx = ImGui.CreateContext();
ImGui.SetCurrentContext(ctx);
ImGuiIOPtr io = ImGui.GetIO();
io.NativePtr->IniFilename = null;
io.DisplaySize = new Vector2(1280, 800);
io.DeltaTime = 1f / 60f;
string fonts = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
string font = new[] { "CascadiaMono.ttf", "consola.ttf" }.Select(f => Path.Combine(fonts, f)).FirstOrDefault(File.Exists) ?? "";
if (font.Length > 0) io.Fonts.AddFontFromFileTTF(font, 13f);
else io.Fonts.AddFontDefault();
io.Fonts.GetTexDataAsRGBA32(out IntPtr _, out int _, out int _, out int _);
io.Fonts.SetTexID((IntPtr)1);
Console.WriteLine($"ImGui {ImGui.GetVersion()} (the engine's cimgui.dll), font {(font.Length > 0 ? Path.GetFileName(font) : "default")} 13 px");
}
private static void InFrame(Action body)
{
ImGui.GetIO().DeltaTime = 1f / 60f;
ImGui.NewFrame();
ImGui.SetNextWindowPos(Vector2.Zero);
ImGui.SetNextWindowSize(new Vector2(600, 500));
ImGui.Begin("host", ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.NoSavedSettings);
body();
ImGui.End();
ImGui.EndFrame();
}
private const float ViewH = 200f;
/// <summary>
/// One frame of a chat-like list: content <paramref name="total"/> high. "before" is
/// ChatFace until 2026-10-11 (SetScrollHereY at the end of the frame); "now" hands the
/// content size and the scroll to this frame's BeginChild. <paramref name="setScroll"/>
/// (now only): the scroll to ask for, or null. Returns (scroll, max) as seen inside the child.
/// </summary>
private static (float Scroll, float Max) ListFrame(string id, float total, bool now, float? setScroll, bool follow)
{
(float, float) seen = default;
InFrame(() =>
{
if (now)
{
ImGui.SetNextWindowContentSize(new Vector2(0, total));
if (setScroll is float s) ImGui.SetNextWindowScroll(new Vector2(-1, s));
}
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero);
ImGui.PushStyleVar(ImGuiStyleVar.ScrollbarSize, 10f);
ImGui.BeginChild(id, new Vector2(300, ViewH), ImGuiChildFlags.None, ImGuiWindowFlags.AlwaysVerticalScrollbar);
ImGui.PopStyleVar(2);
seen = (ImGui.GetScrollY(), ImGui.GetScrollMaxY());
ImGui.Dummy(new Vector2(280, total));
if (!now && follow && total > ViewH) ImGui.SetScrollHereY(1f);
ImGui.EndChild();
});
return seen;
}
private static void Check(string what, bool ok, string detail)
{
_checks++;
if (!ok) _failed++;
Console.WriteLine($" {(ok ? "ok " : "FAIL")} {what}: {detail}");
}
/// <summary>ChatHistory's arithmetic and RynthChat's resizable ring (newest kept, seq untouched).</summary>
private static void HistoryChecks()
{
Console.WriteLine();
Console.WriteLine("History checks:");
Check("Clamp: absent is the default, steps of 500, 500..10000",
ChatHistory.Clamp(0) == 2000 && ChatHistory.Clamp(-5) == 2000 && ChatHistory.Clamp(1) == 500
&& ChatHistory.Clamp(2240) == 2000 && ChatHistory.Clamp(2260) == 2500 && ChatHistory.Clamp(99999) == 10000,
$"0->{ChatHistory.Clamp(0)}, 1->{ChatHistory.Clamp(1)}, 2260->{ChatHistory.Clamp(2260)}, 99999->{ChatHistory.Clamp(99999)}");
int[] old = Enumerable.Range(1, 10).ToArray();
int[] m1 = ChatHistory.Merge(old, new[] { 11, 12, 13 }, 10);
int[] m2 = ChatHistory.Merge(old, new[] { 11, 12 }, 20);
int[] m3 = ChatHistory.Merge(old, Enumerable.Range(11, 30).ToArray(), 10);
Check("Merge keeps the newest, in order", m1.SequenceEqual(Enumerable.Range(4, 10)) && m2.SequenceEqual(Enumerable.Range(1, 12))
&& m3.SequenceEqual(Enumerable.Range(31, 10)), $"[{m1[0]}..{m1[^1]}], [{m2[0]}..{m2[^1]}], [{m3[0]}..{m3[^1]}]");
int[]? t1 = ChatHistory.Trim(old, 4);
Check("Trim drops the oldest, or nothing", t1 != null && t1.SequenceEqual(new[] { 7, 8, 9, 10 }) && ChatHistory.Trim(old, 10) == null, "");
#if HAVE_RYNTHCHAT
var r = new Random(5);
var b = new RynthCore.Plugin.RynthChat.ChatBuffer(500);
for (int i = 0; i < 700; i++) { var (t, ty) = MakeLine(r); b.Add(t, ty); }
ulong[] Seqs(string json) => JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatLineDtoArray)!.Select(d => d.Seq).ToArray();
ulong[] all = Seqs(b.BuildJson(0));
Check("ring of 500 after 700 lines: seq 201..700", all.Length == 500 && all[0] == 201 && all[^1] == 700, $"{all.Length} lines, {all[0]}..{all[^1]}");
b.SetCapacity(2000);
for (int i = 0; i < 100; i++) { var (t, ty) = MakeLine(r); b.Add(t, ty); }
all = Seqs(b.BuildJson(0));
Check("grown to 2000: keeps all 500, then grows; seq carries on", all.Length == 600 && all[0] == 201 && all[^1] == 800
&& all.Zip(all.Skip(1)).All(p => p.Second == p.First + 1), $"{all.Length} lines, {all[0]}..{all[^1]}");
b.SetCapacity(100);
all = Seqs(b.BuildJson(0));
ulong[] since = Seqs(b.BuildJson(790));
Check("shrunk to 100: the newest 100; 'since' still works", all.Length == 100 && all[0] == 701 && all[^1] == 800
&& since.SequenceEqual(Enumerable.Range(791, 10).Select(x => (ulong)x)) && b.BuildJson(800) == "[]" && b.BuildJson(5000) == "[]",
$"{all.Length} lines, {all[0]}..{all[^1]}; since 790: {since.Length}");
Check("capacity clamped to 100..10000", b.SetCapacity(5) == 100 && b.SetCapacity(50000) == 10000 && b.Capacity == 10000, "");
var old500 = new OldChatBuffer(500);
var new500 = new RynthCore.Plugin.RynthChat.ChatBuffer(500);
var r1 = new Random(9);
bool same = true;
for (int i = 0; i < 1200; i++)
{
var (t, ty) = MakeLine(r1);
old500.Add(t, ty);
new500.Add(t, ty);
if (i % 37 == 0)
foreach (ulong s in new ulong[] { 0, (ulong)Math.Max(0, i - 3), (ulong)i, (ulong)(i + 1), (ulong)(i + 5) })
{
string a = old500.BuildJson(s), c = new500.BuildJson(s);
// Same lines; only the timestamp may differ (each buffer stamps its own Add).
if (!Seqs(a).SequenceEqual(Seqs(c))) same = false;
}
}
Check("0.3.0 returns the same lines as 0.2.1 for any 'since'", same, "");
#endif
}
private static void ScrollChecks()
{
Console.WriteLine();
Console.WriteLine("Scroll checks (a 200 px list; 'gap' = how far the newest line's bottom is from the list's bottom in that frame):");
// Before: following with SetScrollHereY. New lines (40 px) arrive with nothing dropped,
// then a full buffer drops 60 px off the top while 20 px arrive.
for (int f = 0; f < 4; f++) ListFrame("before", 1000, false, null, true);
var a = ListFrame("before", 1040, false, null, true);
float gapGrow = 1040 - (a.Scroll + ViewH);
var b = ListFrame("before", 1040, false, null, true);
var c = ListFrame("before", 1000, false, null, true);
float gapShrink = 1000 - (c.Scroll + ViewH);
var d = ListFrame("before", 1000, false, null, true);
Console.WriteLine($" before: 40 px arrive -> gap {gapGrow:0} px that frame, {1040 - (b.Scroll + ViewH):0} the next; " +
$"60 px leave the top as 20 arrive -> gap {gapShrink:0} px (blank under the text), {1000 - (d.Scroll + ViewH):0} the next");
Check("the old follow lags a frame (the bounce)", gapGrow > 0.5f && Math.Abs(gapShrink) > 0.5f,
"reproduced: each batch is first drawn at the old scroll");
// Now: the content size and the scroll go into this frame's BeginChild.
for (int f = 0; f < 4; f++) ListFrame("now", 1000, true, 1000, true);
var e = ListFrame("now", 1040, true, 1040, true);
var g = ListFrame("now", 1000, true, 1000, true);
var h = ListFrame("now", 1000.4f, true, 1000.4f, true);
Check("following: newest line at the bottom in the same frame (grow)", Math.Abs(1040 - (e.Scroll + ViewH)) <= 0.5f && Math.Abs(e.Scroll - e.Max) < 0.01f,
$"scroll {e.Scroll:0.#} of max {e.Max:0.#}");
Check("following: newest line at the bottom in the same frame (shrink)", Math.Abs(1000 - (g.Scroll + ViewH)) <= 0.5f && Math.Abs(g.Scroll - g.Max) < 0.01f,
$"scroll {g.Scroll:0.#} of max {g.Max:0.#}");
Check("following: still pinned with a fractional height", h.Scroll >= h.Max - 24f && Math.Abs(1000.4f - (h.Scroll + ViewH)) < 1f,
$"scroll {h.Scroll:0.##} of max {h.Max:0.##} (stays within the 24 px stick threshold)");
// Scrolled up: lines of a fractional height (13.3 px) leave the top of a full buffer as
// as many arrive, 60 batches. The view moves up by exactly what left, fractions carried.
float total = 5000, start = 3000, scroll = start, carry = 0, worst = 0, worstNoCarry = 0, noCarry = start;
ListFrame("up", total, true, start, false);
for (int i = 1; i <= 60; i++)
{
const float dropped = 13.3f;
float target = scroll + carry - dropped;
float applied = MathF.Round(Math.Max(0, target));
carry = target > 0 ? target - applied : 0;
var s = ListFrame("up", total, true, applied, false);
scroll = s.Scroll;
float exact = start - i * dropped;
worst = Math.Max(worst, Math.Abs(scroll - exact));
noCarry = MathF.Round(noCarry - dropped);
worstNoCarry = Math.Max(worstNoCarry, Math.Abs(noCarry - exact));
}
Check("scrolled up: the view holds still across 60 batches (no creep)", worst <= 0.51f,
$"off by at most {worst:0.00} px (without carrying fractions: {worstNoCarry:0.00} px)");
// Scrolled up, nothing dropped (buffer not full yet): no scroll is set, nothing moves.
var u0 = ListFrame("up2", 3000, true, 1200, false);
var u1 = ListFrame("up2", 3040, true, null, false);
var u2 = ListFrame("up2", 3080, true, null, false);
Check("scrolled up: new lines below leave the view where it is", u1.Scroll == u0.Scroll && u2.Scroll == u0.Scroll,
$"scroll {u0.Scroll:0} -> {u1.Scroll:0} -> {u2.Scroll:0}");
}
}

View file

@ -0,0 +1,31 @@
// The two engine pieces ChatRouting.cs calls, without the engine. ChatModel's are copies
// of the real ones in src/RynthCore.Engine/UI/Data/ChatData.cs (MentionEligible, and
// LineInTab / LineVisible, which the chat face filters with).
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++;
public static bool LineInTab(ChatLine line, string tab) => line.Route.ShowsIn(tab, line.Channel);
public static bool LineVisible(ChatLine line, string tab, string search) =>
LineInTab(line, tab)
&& (search.Length == 0 || line.FormattedText.Contains(search, StringComparison.OrdinalIgnoreCase));
}
}

View file

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for closing the client on a server disconnect (2026-10-11):
src\RynthCore.Engine\Compatibility\ServerDisconnectClosePolicy.cs, compiled in. On AC's
Disconnected screen ("The server has disconnected", only Quit Game) the engine closes the
client 5 s later (longer while the flight dump is written, at most 10 s more), tries once more
20 s after that and gives up at 60 s; it does nothing while the client is already exiting,
nothing but the first log line when the setting is off, and starts over if the screen goes.
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>DisconnectCloseTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\ServerDisconnectClosePolicy.cs" Link="Engine\ServerDisconnectClosePolicy.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,164 @@
using RynthCore.Engine.Compatibility;
using V = RynthCore.Engine.Compatibility.ServerDisconnectClosePolicy.Verdict;
namespace DisconnectCloseTests;
/// <summary>
/// When the engine closes the client after AC lost the server (ServerDisconnectClosePolicy.cs).
/// Clients sat on "The server has disconnected" until someone clicked Quit Game, so no launcher
/// relaunched them (Drakkon and Aryze on DreamWeave, 2026-10-11 14:52, for 71+ minutes).
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static string _case = "";
private static int Main()
{
NothingOffTheScreen();
ClosesAfterTheDelay();
WaitsForTheFlightDumpButNotForever();
RetriesThenGivesUp();
SettingOffOnlyDetects();
TurnedOnWhileOnTheScreen();
NothingWhileExiting();
LeavingTheScreenStartsOver();
ZeroClockStillCounts();
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 Eq(V actual, V expected, string what) =>
Check(actual == expected, $"{what}: expected {expected}, got {actual}");
/// <summary>Ticks every 16 ms from <paramref name="from"/> to <paramref name="to"/> (exclusive);
/// returns the verdicts other than None with the time they came.</summary>
private static List<(long At, V Verdict)> Run(ServerDisconnectClosePolicy p, long from, long to,
bool disconnected = true, bool enabled = true, bool exiting = false, Func<long, bool>? dumpBusy = null)
{
var seen = new List<(long, V)>();
for (long t = from; t < to; t += 16)
{
V v = p.Update(t, disconnected, enabled, exiting, dumpBusy?.Invoke(t) ?? false);
if (v != V.None) seen.Add((t, v));
}
return seen;
}
private static void NothingOffTheScreen()
{
_case = nameof(NothingOffTheScreen);
var p = new ServerDisconnectClosePolicy();
Check(Run(p, 1000, 120_000, disconnected: false).Count == 0, "no verdicts in the world / at character select");
Check(!p.OnScreen, "not on the screen");
}
private static void ClosesAfterTheDelay()
{
_case = nameof(ClosesAfterTheDelay);
var p = new ServerDisconnectClosePolicy();
Eq(p.Update(10_000, true, true, false, false), V.Detected, "first tick on the screen");
Check(p.OnScreen, "on the screen");
var seen = Run(p, 10_016, 15_100);
Check(seen.Count == 1 && seen[0].Verdict == V.Close, $"one Close in the first 5.1 s ({seen.Count} verdicts)");
Check(seen.Count == 1 && seen[0].At >= 15_000 && seen[0].At < 15_016, $"Close 5 s after the screen came (at {(seen.Count > 0 ? seen[0].At : -1)})");
Eq(p.Update(15_200, true, true, false, false), V.None, "no second Close right after");
Check(p.Attempts == 1, "one attempt");
}
private static void WaitsForTheFlightDumpButNotForever()
{
_case = nameof(WaitsForTheFlightDumpButNotForever);
// Dump written from +3 s to +8 s: the close waits for it.
var p = new ServerDisconnectClosePolicy();
Eq(p.Update(0 + 100, true, true, false, true), V.Detected, "detected while the dump is scheduled");
var seen = Run(p, 116, 30_000, dumpBusy: t => t < 8_100);
Check(seen.Count >= 1 && seen[0].Verdict == V.Close && seen[0].At >= 8_100 && seen[0].At < 8_120, $"Close as soon as the dump is done (at {(seen.Count > 0 ? seen[0].At : -1)})");
// A dump that never finishes: the close waits at most DumpGraceMs more.
p = new ServerDisconnectClosePolicy();
p.Update(100, true, true, false, true);
seen = Run(p, 116, 30_000, dumpBusy: _ => true);
long expected = 100 + ServerDisconnectClosePolicy.DefaultDelayMs + ServerDisconnectClosePolicy.DumpGraceMs;
Check(seen.Count >= 1 && seen[0].Verdict == V.Close && seen[0].At >= expected && seen[0].At < expected + 16, $"Close at the 15 s cap (at {(seen.Count > 0 ? seen[0].At : -1)}, cap {expected})");
}
private static void RetriesThenGivesUp()
{
_case = nameof(RetriesThenGivesUp);
var p = new ServerDisconnectClosePolicy();
p.Update(1, true, true, false, false);
var seen = Run(p, 17, 300_000);
Check(seen.Count == 3, $"Close, Retry, GiveUp and nothing more ({string.Join(", ", seen)})");
if (seen.Count != 3) return;
Eq(seen[0].Verdict, V.Close, "first");
Eq(seen[1].Verdict, V.Retry, "second");
Eq(seen[2].Verdict, V.GiveUp, "third");
long close = seen[0].At;
Check(seen[1].At - close >= ServerDisconnectClosePolicy.RetryAfterMs && seen[1].At - close < ServerDisconnectClosePolicy.RetryAfterMs + 16, "Retry 20 s after Close");
Check(seen[2].At - close >= ServerDisconnectClosePolicy.GiveUpAfterMs && seen[2].At - close < ServerDisconnectClosePolicy.GiveUpAfterMs + 16, "GiveUp 60 s after Close");
Check(p.Attempts == 2, "two close attempts");
}
private static void SettingOffOnlyDetects()
{
_case = nameof(SettingOffOnlyDetects);
var p = new ServerDisconnectClosePolicy();
var seen = Run(p, 1, 600_000, enabled: false);
Check(seen.Count == 1 && seen[0].Verdict == V.Detected, $"only Detected with the setting off ({string.Join(", ", seen)})");
}
private static void TurnedOnWhileOnTheScreen()
{
_case = nameof(TurnedOnWhileOnTheScreen);
var p = new ServerDisconnectClosePolicy();
Run(p, 1, 60_000, enabled: false);
Eq(p.Update(60_000, true, true, false, false), V.Close, "turning it on past the delay closes at once");
}
private static void NothingWhileExiting()
{
_case = nameof(NothingWhileExiting);
var p = new ServerDisconnectClosePolicy();
Check(Run(p, 1, 120_000, exiting: true).Count == 0, "no verdicts while the client is already closing");
// Quit Game clicked after the screen came, before the close: nothing more from us.
p = new ServerDisconnectClosePolicy();
p.Update(1, true, true, false, false);
Run(p, 17, 2_000);
Check(Run(p, 2_000, 120_000, exiting: true).Count == 0, "no Close once the client started exiting on its own");
}
private static void LeavingTheScreenStartsOver()
{
_case = nameof(LeavingTheScreenStartsOver);
var p = new ServerDisconnectClosePolicy();
p.Update(1, true, true, false, false);
Run(p, 17, 2_000);
Eq(p.Update(2_000, false, true, false, false), V.Left, "the screen went away before the close");
Check(!p.OnScreen && p.Attempts == 0, "reset");
Eq(p.Update(2_016, false, true, false, false), V.None, "Left only once");
Eq(p.Update(50_000, true, true, false, false), V.Detected, "a second visit is detected again");
var seen = Run(p, 50_016, 55_100);
Check(seen.Count == 1 && seen[0].Verdict == V.Close && seen[0].At >= 55_000, "and closes 5 s into the second visit");
}
private static void ZeroClockStillCounts()
{
_case = nameof(ZeroClockStillCounts);
var p = new ServerDisconnectClosePolicy();
Eq(p.Update(0, true, true, false, false), V.Detected, "detected at clock 0");
Check(p.OnScreen, "a clock of 0 still marks the screen as seen");
var seen = Run(p, 16, 6_000);
Check(seen.Count == 1 && seen[0].Verdict == V.Close, "closes");
}
}

View file

@ -50,6 +50,7 @@ namespace EngineSettingsTests
Run(nameof(SaveWithoutFileWritesOwnedKeys), SaveWithoutFileWritesOwnedKeys);
Run(nameof(SaveLeavesMalformedFileAlone), SaveLeavesMalformedFileAlone);
Run(nameof(MaxHotReloadsReadAndKept), MaxHotReloadsReadAndKept);
Run(nameof(CloseOnServerDisconnectDefaultOnAndSaved), CloseOnServerDisconnectDefaultOnAndSaved);
}
finally
{
@ -80,6 +81,8 @@ 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 "dcclose-off": EngineSettings.CloseOnServerDisconnect = false; break;
case "dcclose-on": EngineSettings.CloseOnServerDisconnect = true; break;
case "dump":
Console.WriteLine("PluginPaths=" + string.Join("|", EngineSettings.PluginPaths));
Console.WriteLine("StartTooltip=" + EngineSettings.IsUiHookEnabled("StartTooltip"));
@ -87,6 +90,7 @@ namespace EngineSettingsTests
Console.WriteLine("ImGuiBackend=" + EngineSettings.EnableImGuiBackend);
Console.WriteLine("ServerMessageStream=" + EngineSettings.ServerMessageStream);
Console.WriteLine("MaxHotReloads=" + EngineSettings.MaxHotReloads);
Console.WriteLine("CloseOnServerDisconnect=" + EngineSettings.CloseOnServerDisconnect);
break;
default: throw new ArgumentException(args[0]);
}
@ -289,6 +293,39 @@ namespace EngineSettingsTests
}
}
// engine.json "CloseOnServerDisconnect" (close the client on AC's Disconnected screen):
// default on and not written while on; the Settings checkbox turning it off writes false,
// which a later start reads back; turning it on again drops it from the file; a value
// that isn't true/false is ignored.
private static void CloseOnServerDisconnectDefaultOnAndSaved()
{
string dir = NewDir("dcclose");
string path = Path.Combine(dir, "engine.json");
File.WriteAllText(path, LauncherFile);
Eq(DumpValue(RunChild(path, "dump").Out, "CloseOnServerDisconnect"), "True", "missing: on");
Eq(RunChild(path, "hook-off", "StartTooltip").Exit, 0, "save with the default");
Check(!ReadJson(path).TryGetProperty("CloseOnServerDisconnect", out _), "the default isn't written to the file");
var (exit, output) = RunChild(path, "dcclose-off");
Eq(exit, 0, "turn off (" + output.Trim() + ")");
Eq(ReadJson(path).GetProperty("CloseOnServerDisconnect").GetRawText(), "false", "off is saved");
Check(ReadJson(path).TryGetProperty("LauncherWindow", out _), "launcher keys kept");
Eq(DumpValue(RunChild(path, "dump").Out, "CloseOnServerDisconnect"), "False", "off read back at the next start");
Eq(RunChild(path, "hook-off", "CheckTooltip").Exit, 0, "another save");
Eq(ReadJson(path).GetProperty("CloseOnServerDisconnect").GetRawText(), "false", "off survives other saves");
Eq(RunChild(path, "dcclose-on").Exit, 0, "turn on");
Check(!ReadJson(path).TryGetProperty("CloseOnServerDisconnect", out _), "on again: dropped from the file");
Eq(DumpValue(RunChild(path, "dump").Out, "CloseOnServerDisconnect"), "True", "on read back");
foreach (string bad in new[] { "\"no\"", "0", "null" })
{
File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"CloseOnServerDisconnect\": {bad}, \"LoggingLevel\""));
Eq(DumpValue(RunChild(path, "dump").Out, "CloseOnServerDisconnect"), "True", $"{bad}: ignored, on");
}
}
/// <summary>The value of a "Name=value" line of the child's dump output ("" if none).</summary>
private static string DumpValue(string output, string name)
{

View file

@ -6,7 +6,7 @@
one .bak per session, placeholder rule, Add condition / action, finding a rule again by
content), MetaLocation.cs ("Set current" text for landblock / landcell, against a copy of
RynthAi's MetaManager reading; RynthSuite's RynthAiHostTests check the real one) and
MetaRuleDto.cs. Nothing native: no AC, no ImGui, no files.
MetaRuleDto.cs, the rule list's text (MetaRowText.cs) and its timers (MetaStateClock.cs). Nothing native: no AC, no ImGui, no files.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
@ -22,6 +22,8 @@
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\MetaEditing.cs" Link="Engine\MetaEditing.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\MetaLocation.cs" Link="Engine\MetaLocation.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\MetaRuleDto.cs" Link="Engine\MetaRuleDto.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\MetaRowText.cs" Link="Engine\MetaRowText.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\MetaStateClock.cs" Link="Engine\MetaStateClock.cs" />
</ItemGroup>
</Project>

View file

@ -25,6 +25,11 @@ internal static class Program
TakesData();
NoKillsMinutes();
SameContentAndLocate();
RuleNames();
StateClock();
RowTextLeaves();
RowTextLists();
RowTextActions();
Console.WriteLine();
Console.WriteLine(_failed == 0 ? $"PASS ({_checks} checks)" : $"FAIL: {_failed} of {_checks} checks");
@ -302,6 +307,168 @@ internal static class Program
// ── Checks ───────────────────────────────────────────────────────────
// ── Rule list text (MetaRowText) ─────────────────────────────────────
private static MetaRuleDto Cnd(int condition, string data = "", params MetaRuleDto[] kids)
{
var r = new MetaRuleDto { Condition = condition, ConditionData = data };
r.Children.AddRange(kids);
return r;
}
private static MetaRuleDto Act(int action, string data = "", params MetaRuleDto[] kids)
{
var r = new MetaRuleDto { Action = action, ActionData = data };
r.ActionChildren.AddRange(kids);
return r;
}
private static string CondLine(MetaRuleDto c, MetaTextContext? ctx = null) =>
MetaRowText.Plain(MetaRowText.ConditionCompact(c, ctx ?? new MetaTextContext()));
private static string ActLine(MetaRuleDto a, MetaTextContext? ctx = null) =>
MetaRowText.Plain(MetaRowText.ActionCompact(a, ctx ?? new MetaTextContext()));
private static string Lines(MetaLine[] lines)
{
var parts = new List<string>();
foreach (MetaLine l in lines)
parts.Add($"{l.Depth}{(l.Slot ? "s" : "")}:{l.Plain()}");
return string.Join(" | ", parts);
}
private static void RuleNames()
{
Case("rule names");
var a = new MetaRuleDto { State = "Hunt", Condition = 1, Action = 1, ActionData = "/x", Name = "Start" };
var b = a.Clone();
Eq(b.Name, "Start", "Clone keeps the name");
True(MetaRuleEdit.SameContent(a, b), "same name, same content");
b.Name = "Other";
False(MetaRuleEdit.SameContent(a, b), "a renamed rule is a different rule (Locate, delete confirm)");
var placeholder = MetaRuleEdit.Placeholder("Loot");
True(MetaRuleEdit.IsPlaceholder(placeholder), "an unnamed Never -> None is a placeholder");
placeholder.Name = "Parked";
False(MetaRuleEdit.IsPlaceholder(placeholder), "a named one isn't (delete asks first)");
Eq(MetaRuleEdit.CleanName("a\r\nb\tc"), "a b c", "one line");
Eq(MetaRuleEdit.CleanName(" keep the space "), " keep the space ", "ends kept while typing (trimmed when sent)");
Eq(MetaRuleEdit.CleanName(new string('x', 200)).Length, MetaRuleEdit.MaxNameLength, "cut to the longest name");
Eq(MetaRuleEdit.CleanName(null), "", "null");
}
private static void StateClock()
{
Case("seconds in state / watchdog clock");
var clock = new MetaStateClock();
False(clock.Known, "nothing before a snapshot");
Eq(clock.WatchdogLeft(0, out _), -1.0, "no watchdog before a snapshot");
clock.Snapshot(new MetaStateSnapshot { SecondsInState = 10, WatchdogActive = true, WatchdogState = "Default", WatchdogSecondsRemaining = 30 }, 1000);
True(clock.Known, "known");
Eq(clock.SecondsInState(1000), 10.0, "as snapshotted");
Eq(clock.SecondsInState(3500), 12.5, "counted on between snapshots");
Eq(clock.SecondsInState(500), 10.0, "a clock that went back doesn't count down");
Eq(clock.WatchdogLeft(3500, out string wdState), 27.5, "watchdog counts down");
Eq(wdState, "Default", "and says where it goes");
Eq(clock.WatchdogLeft(100_000, out _), 0.0, "never below 0");
clock.StateSet(4000);
Eq(clock.SecondsInState(4000), 0.0, "a state picked in the panel starts at 0");
Eq(clock.WatchdogLeft(4000, out _), -1.0, "...and drops the old state's watchdog");
clock.Snapshot(new MetaStateSnapshot { SecondsInState = 3 }, 5000);
Eq(clock.WatchdogLeft(5000, out _), -1.0, "no watchdog set");
clock.Snapshot(null, 6000);
False(clock.Known, "a RynthAi without the snapshot");
Eq(MetaStateClock.Format(42.9), "42 s", "whole seconds");
Eq(MetaStateClock.Format(3599), "3599 s", "seconds under an hour (rules count seconds)");
Eq(MetaStateClock.Format(3723), "1:02:03", "h:mm:ss from an hour");
Eq(MetaStateClock.Format(-5), "0 s", "never negative");
}
private static void RowTextLeaves()
{
Case("row text: conditions");
Eq(CondLine(Cnd(10, "Prismatic Taper,50")), "Count Prismatic Taper ≤ 50", "item count <=");
Eq(CondLine(Cnd(11, "Prismatic Taper, 50")), "Count Prismatic Taper ≥ 50", "item count >=, spaces trimmed");
Eq(CondLine(Cnd(10, "Foo, Bar,3")), "Count Foo, Bar ≤ 3", "a comma in the item name: the count is after the last one");
Eq(CondLine(Cnd(16, "5c45")), "Landblock 5C45", "landblock upper-cased");
Eq(CondLine(Cnd(26, "getcharintprop[25]<30")), "Expr getcharintprop[25]<30", "expression");
Eq(CondLine(Cnd(4, "")), "Chat matches (not set)", "an empty pattern says so");
Eq(CondLine(Cnd(12, "Drudge|Mite{1,2},20,3")), "Mobs Drudge|Mite{1,2} ≥ 3 within 20", "mob name regex with a comma");
Eq(CondLine(Cnd(13, "1,20")), "Priority mobs ≥ 1 within 20", "priority mobs");
Eq(CondLine(Cnd(15, "")), "No mobs within 20 (default)", "no mobs: RynthAi's default distance");
Eq(CondLine(Cnd(24, "250")), "Burden ≥ 250%", "burden");
Eq(CondLine(Cnd(35, "2.5")), "No kill for 2.5 min", "no kills");
Eq(CondLine(Cnd(6, "10")), "In state ≥ 10 s", "seconds in state");
Eq(CondLine(Cnd(99, "x")), "Condition 99 x", "an unknown condition shows its number and data");
var ctx = new MetaTextContext { SpellName = id => id == 2293 ? "Strength Other VI" : null };
Eq(CondLine(Cnd(22, "2293,30"), ctx), "Spell Strength Other VI ≥ 30 s left", "spell by name");
False(ctx.MissedSpellName, "no name missed yet");
Eq(CondLine(Cnd(23, "512,305"), ctx), "Spell 512 ≤ 305 s left", "unknown spell: its id");
True(ctx.MissedSpellName, "a missed name is noted (rebuild once the spell table loads)");
}
private static void RowTextLists()
{
Case("row text: all / any / not");
var ctx = new MetaTextContext();
MetaRuleDto one = Cnd(2, "", Cnd(16, "5C45"));
Eq(CondLine(one), "Landblock 5C45", "an All of one is that condition");
Eq(Lines(MetaRowText.ConditionLines(one, ctx)), "0:Landblock 5C45", "...on one line, no slot");
MetaRuleDto andNot = Cnd(2, "", Cnd(26, "a<1"), Cnd(20, "", Cnd(22, "512,305")));
Eq(CondLine(andNot), "Expr a<1 and not Spell 512 ≥ 305 s left", "compact: and, not");
Eq(Lines(MetaRowText.ConditionLines(andNot, ctx)), "0s:Expr a<1 | 0s:and not Spell 512 ≥ 305 s left",
"full: one line per condition, the second joined by and");
MetaRuleDto anyAll = Cnd(3, "", Cnd(1), Cnd(2, "", Cnd(8), Cnd(9)));
Eq(CondLine(anyAll), "Always or (Vendor open and Vendor closed)", "compact: nested list in brackets");
Eq(Lines(MetaRowText.ConditionLines(anyAll, ctx)),
"0s:Always | 0s:or all of | 1s:Vendor open | 1s:and Vendor closed", "full: nested list under an 'or all of' line");
MetaRuleDto notAll = Cnd(20, "", Cnd(2, "", Cnd(8), Cnd(9)));
Eq(CondLine(notAll), "not (Vendor open and Vendor closed)", "compact: not of a list");
Eq(Lines(MetaRowText.ConditionLines(notAll, ctx)), "0:not all of | 1s:Vendor open | 1s:and Vendor closed", "full: not all of");
Eq(CondLine(Cnd(3)), "any of (nothing)", "an empty Any says so");
Eq(CondLine(Cnd(20)), "not (nothing)", "an empty Not says so");
Eq(CondLine(Cnd(20, "", Cnd(20, "", Cnd(1)))), "not not Always", "not not");
MetaRuleDto deep = Cnd(1);
for (int i = 0; i < 20; i++) deep = Cnd(20, "", deep);
True(MetaRowText.ConditionLines(deep, ctx).Length == 1, "a very deep chain stops (no runaway recursion)");
}
private static void RowTextActions()
{
Case("row text: actions");
var ctx = new MetaTextContext { States = new[] { "Default", "ReBuff" } };
Eq(ActLine(Act(1, "/vt opt set enablecombat true"), ctx), "/vt opt set enablecombat true", "a command reads as itself");
Eq(ActLine(Act(1, "hello"), ctx), "Chat hello", "plain chat text");
Eq(ActLine(Act(1, ""), ctx), "Chat (empty)", "an empty chat command says so");
Eq(ActLine(Act(2, "rebuff"), ctx), "→ rebuff", "set state (a state in any case exists)");
MetaSeg[] missing = MetaRowText.ActionLeaf(Act(2, "ReBuf"), ctx);
Eq(MetaRowText.Plain(missing), "→ ReBuf (no such state)", "set state to a missing state");
True(Array.Exists(missing, s => s.Tone == MetaTone.Warn), "...in the warning colour");
Eq(ActLine(Act(5, "ReBuff"), ctx), "Call → ReBuff", "call state");
Eq(ActLine(Act(9, "Default;5;30"), ctx), "Watchdog 5 m in 30 s → Default", "watchdog");
Eq(ActLine(Act(3, "Tusker_Abode;205"), ctx), "Nav Tusker_Abode", "embedded nav: the name before ';'");
Eq(ActLine(Act(3, "Patrol"), ctx), "Nav Patrol (dungeon patrol)", "Patrol: RynthAi's dungeon patrol");
var withPatrolRoute = new MetaTextContext { RouteExists = n => n.Equals("patrol", StringComparison.OrdinalIgnoreCase) };
Eq(ActLine(Act(3, "Patrol"), withPatrolRoute), "Nav Patrol", "...unless a route is called Patrol");
Eq(ActLine(Act(12, "EnableBuffing;False"), ctx), "Set EnableBuffing = False", "set option");
Eq(ActLine(Act(11, "doors;OpenDoors"), ctx), "Get option OpenDoors → doors", "get option (variable;option)");
Eq(ActLine(Act(0), ctx), "None", "none");
MetaRuleDto all = Act(4, "", Act(1, "/a"), Act(4, "", Act(2, "Default")), Act(6));
Eq(Lines(MetaRowText.ActionLines(all, ctx)), "0:/a | 0:→ Default | 0:Return from call", "DoAll: one line per action, nested DoAll flattened");
Eq(ActLine(all, ctx), "/a · → Default · Return from call", "compact: joined by a dot");
Eq(ActLine(Act(4), ctx), "do all (nothing)", "an empty DoAll says so");
}
private static void Case(string name)
{
_case = name;

View file

@ -52,6 +52,7 @@ internal static class Program
Run(nameof(GatePlanFromFiles), GatePlanFromFiles);
Run(nameof(SdkApiVersionCannotDrift), SdkApiVersionCannotDrift);
Run(nameof(TrainingStructsMirror), TrainingStructsMirror);
Run(nameof(ContainerOrderSlots), ContainerOrderSlots);
Run(nameof(ManifestAttributeDrivesRuntimeMinimum), ManifestAttributeDrivesRuntimeMinimum);
Run(nameof(DedupeSamePathTwice), DedupeSamePathTwice);
Run(nameof(DedupeCaseAndSlashes), DedupeCaseAndSlashes);
@ -473,13 +474,26 @@ internal static class Program
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.TrainingEntryNative>(f.Name), (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.TrainingEntryNative>(f.Name), "TrainingEntryNative." + f.Name + " offset");
Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits");
Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits");
// The three v79 slots are the table's last three, in this order.
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).TakeLast(3).ToArray();
Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn" }), "v79 slots last: " + string.Join(",", names));
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).TakeLast(3).ToArray();
// The three v79 slots follow v78's and come right before v80's, in this order.
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(2).TakeLast(3).ToArray();
Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn" }), "v79 slots before v80's: " + string.Join(",", names));
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(2).TakeLast(3).ToArray();
Check(sdkNames.SequenceEqual(names), "SDK v79 slots in the same order");
}
// v80: GetContainerOrder and PutItemInContainer are the table's last two slots, engine and SDK alike,
// and the whole table has the same field names in the same order on both sides.
private static void ContainerOrderSlots()
{
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();
Check(names.TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots last: " + string.Join(",", names.TakeLast(2)));
Check(sdkNames.TakeLast(2).SequenceEqual(names.TakeLast(2)), "SDK v80 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"),
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("PutItemInContainerFn"), "PutItemInContainerFn offset");
}
private sealed class ProbePlugin : RynthCore.PluginCore.RynthPluginBase { }
private sealed class OverridingPlugin : RynthCore.PluginCore.RynthPluginBase { public override uint MinimumApiVersion => 70; }

View file

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the pre-cast stop (2026-10-12): src\RynthCore.Engine\Compatibility\
PreCastStopRules.cs, compiled in. While the player has control, a queued cast first sends
its stop and waits for the server's answer (or 750 ms), then casts without the stop that
FreeHandsAndCastSpell would otherwise send in the cast's frame. With the server in control
(or the state unreadable) the cast goes at once, as before. Pure code, nothing native.
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>PreCastStopTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\PreCastStopRules.cs" Link="Engine\PreCastStopRules.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,43 @@
using RynthCore.Engine.Compatibility;
namespace PreCastStopTests;
/// <summary>
/// The pre-cast stop (PreCastStopRules.cs). Flight 63260: runs of projectile casts that never
/// landed each began with a stop burst in a cast's frame; FreeHandsAndCastSpell's own
/// MaybeStopCompletely is one of those stops whenever the player has control.
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static int Main()
{
// Server in control (after a cast's server turn): no stop would ride, cast at once.
Check(PreCastStopRules.Decide(1, false, 0, 0) == PreCastStep.CastNow, "server in control: cast now");
// Unknown state: as before.
Check(PreCastStopRules.Decide(-1, false, 0, 0) == PreCastStep.CastNow, "unreadable: cast now (old behavior)");
// Player in control: send the stop first, never the cast in the same tick.
Check(PreCastStopRules.Decide(0, false, 0, 0) == PreCastStep.SendStop, "player in control: the stop goes first");
// Stop sent: wait for the answer.
Check(PreCastStopRules.Decide(0, true, 0, 0) == PreCastStep.Wait, "stop sent, no answer: wait");
Check(PreCastStopRules.Decide(0, true, 0, PreCastStopRules.EchoMaxMs - 1) == PreCastStep.Wait, "still waiting 1 ms before the limit");
// Answered: cast without the cast's own stop.
Check(PreCastStopRules.Decide(0, true, 1, 120) == PreCastStep.CastWithoutStop, "answered: cast, no stop in its frame");
// Control state is not re-read once the stop is out (the answer may be a server motion).
Check(PreCastStopRules.Decide(1, true, 1, 120) == PreCastStep.CastWithoutStop, "answered, server took control meanwhile: still no stop");
// No answer in time: cast anyway (never park a cast), still without a second stop.
Check(PreCastStopRules.Decide(0, true, 0, PreCastStopRules.EchoMaxMs) == PreCastStep.CastWithoutStop, "no answer in 750 ms: cast anyway");
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] {what}");
}
}