Snapshot for release 2026.10.13.1 (internal 90a2f4a)
This commit is contained in:
parent
b0f9d74b21
commit
1d86acdf27
218 changed files with 24019 additions and 1517 deletions
23
tools/CharactersPanelTests/CharactersPanelTests.csproj
Normal file
23
tools/CharactersPanelTests/CharactersPanelTests.csproj
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for the Characters panel's logic (src\RynthCore.Engine\UI\Data\
|
||||
CharactersModel.cs, compiled in): parsing RynthNet's snapshot (new and older status
|
||||
shapes), distance / compass / "elsewhere" across landblocks and dungeons, the state text,
|
||||
the stale marker and the stable alphabetical row order.
|
||||
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>CharactersPanelTests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\CharactersModel.cs" Link="Engine\CharactersModel.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
251
tools/CharactersPanelTests/Program.cs
Normal file
251
tools/CharactersPanelTests/Program.cs
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace CharactersPanelTests;
|
||||
|
||||
/// <summary>
|
||||
/// The Characters panel's logic (CharactersModel): RynthNet snapshot parsing, where another
|
||||
/// character is from you, what it is doing, and the row order.
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
private static int _checks, _failed;
|
||||
|
||||
private static int Main()
|
||||
{
|
||||
ParsesCurrentSnapshot();
|
||||
ParsesOlderEntries();
|
||||
RejectsBadJson();
|
||||
DistanceSameLandblock();
|
||||
DistanceAcrossLandblocks();
|
||||
DungeonRules();
|
||||
SurfaceBuildings();
|
||||
CoordsText();
|
||||
CompassPoints();
|
||||
States();
|
||||
Stale();
|
||||
StableOrder();
|
||||
Vitals();
|
||||
|
||||
Console.WriteLine($"{_checks} checks, {_failed} failed");
|
||||
return _failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static void Check(bool ok, string what)
|
||||
{
|
||||
_checks++;
|
||||
if (ok) return;
|
||||
_failed++;
|
||||
Console.WriteLine("FAIL: " + what);
|
||||
}
|
||||
|
||||
private static bool Near(double a, double b, double tol = 0.01) => Math.Abs(a - b) <= tol;
|
||||
|
||||
// RynthNet 0.1.1's shape: id and cmode in the status, RynthAi's bot object, age after status.
|
||||
private const string Current = """
|
||||
{"version":"0.1.1","online":true,"node":"n1","char":"Drakkon","world":"Aelrynth","login":true,"tags":["main"],
|
||||
"acceptRemote":true,"clients":[
|
||||
{"node":"n2","pid":4242,"char":"Zed Healer","world":"Aelrynth","login":true,"tags":["heal","box"],"rtt":3,
|
||||
"status":{"hp":300,"hpMax":400,"st":150,"stMax":200,"mp":50,"mpMax":500,"cell":2847146009,"x":40.5,"y":50.25,"z":12.0,
|
||||
"ns":42.1,"ew":33.3,"heading":90.0,"portal":false,"busy":0,"vitae":1.0,"id":1342177281,"cmode":2,
|
||||
"bot":{"macro":true,"action":"Combat","state":"Default","combat":true}},"age":420},
|
||||
{"node":"n3","pid":5151,"char":"Alpha","world":"Aelrynth","login":true,"tags":[],"rtt":2,"status":null}
|
||||
]}
|
||||
""";
|
||||
|
||||
private static void ParsesCurrentSnapshot()
|
||||
{
|
||||
NetCharSnapshot? s = CharactersModel.Parse(Current);
|
||||
Check(s != null, "current snapshot parses");
|
||||
if (s == null) return;
|
||||
Check(s.Online && s.Version == "0.1.1" && s.MyName == "Drakkon" && s.MyWorld == "Aelrynth", "snapshot header");
|
||||
Check(s.Clients.Count == 2, "two clients");
|
||||
NetCharEntry z = s.Clients[0];
|
||||
Check(z.Name == "Zed Healer" && z.Pid == 4242 && z.World == "Aelrynth" && z.LoggedIn, "client identity");
|
||||
Check(z.Tags.Length == 2 && z.Tags[0] == "heal", "client tags");
|
||||
Check(z.HasStatus && z.AgeMs == 420, "status age");
|
||||
Check(z.HasVitals && z.Hp == 300 && z.HpMax == 400 && z.St == 150 && z.StMax == 200 && z.Mp == 50 && z.MpMax == 500, "vitals");
|
||||
Check(z.HasPose && z.Cell == 2847146009u && Near(z.X, 40.5) && Near(z.Y, 50.25) && Near(z.Z, 12), "pose");
|
||||
Check(z.HasCoords && Near(z.Ns, 42.1) && Near(z.Ew, 33.3), "coords");
|
||||
Check(z.Id == 1342177281u && z.CombatMode == 2, "id and cmode (0.1.1)");
|
||||
Check(z.HasBot && z.Macro && z.Action == "Combat", "bot state");
|
||||
NetCharEntry a = s.Clients[1];
|
||||
Check(a.LoggedIn && !a.HasStatus && !a.HasVitals && !a.HasPose && a.AgeMs == -1, "null status");
|
||||
Check(CharactersModel.State(a).Kind == CharStateKind.NoStatus, "null status reads 'no status yet'");
|
||||
}
|
||||
|
||||
private static void ParsesOlderEntries()
|
||||
{
|
||||
// RynthNet 0.1.0 (no id / cmode), a client without RynthAi (no bot), one at character
|
||||
// select (no char, status {} sent as null), and an entry with odd types.
|
||||
const string old = """
|
||||
{"online":true,"char":"Me","world":"W","clients":[
|
||||
{"node":"a","pid":1,"char":"Old","world":"W","login":true,"tags":[],"rtt":-1,
|
||||
"status":{"hp":10,"hpMax":20,"st":5,"stMax":5,"mp":0,"mpMax":0,"cell":16777217,"x":1,"y":2,"z":3},"age":100},
|
||||
{"node":"b","pid":2,"char":"","world":"","login":false,"tags":[],"rtt":5,"status":null},
|
||||
{"node":"c","pid":3,"char":"Odd","login":true,"tags":"notarray","status":{"hp":"lots","cell":0}}
|
||||
]}
|
||||
""";
|
||||
NetCharSnapshot? s = CharactersModel.Parse(old);
|
||||
Check(s != null && s.Clients.Count == 3, "old snapshot parses");
|
||||
if (s == null || s.Clients.Count != 3) return;
|
||||
NetCharEntry o = s.Clients[0];
|
||||
Check(o.HasVitals && o.Hp == 10 && o.HpMax == 20, "old vitals");
|
||||
Check(o.Id == 0 && o.CombatMode == 0 && !o.HasBot, "old entry: no id, no cmode, no bot");
|
||||
Check(o.HasPose && o.Cell == 0x01000001u, "old pose");
|
||||
Check(!o.HasCoords, "no ns/ew -> no coords");
|
||||
Check(CharactersModel.State(o) == ("idle", CharStateKind.Idle), "no bot, peace -> idle");
|
||||
NetCharEntry b = s.Clients[1];
|
||||
Check(!b.LoggedIn && CharactersModel.State(b).Kind == CharStateKind.LoggedOut, "character select -> logged out");
|
||||
NetCharEntry c = s.Clients[2];
|
||||
Check(c.Tags.Length == 0 && !c.HasVitals && !c.HasPose && c.World == "", "wrong types are ignored, cell 0 is no pose");
|
||||
Check(CharactersModel.Parse("{\"online\":false,\"clients\":[]}") is { Online: false, Clients.Count: 0 }, "RynthNet's fallback string");
|
||||
Check(CharactersModel.Parse("{\"online\":false,\"offline\":\"pipe busy\",\"version\":\"0.1.1\"}") is { Offline: "pipe busy" }, "offline reason");
|
||||
}
|
||||
|
||||
private static void RejectsBadJson()
|
||||
{
|
||||
Check(CharactersModel.Parse(null) == null, "null");
|
||||
Check(CharactersModel.Parse("") == null, "empty");
|
||||
Check(CharactersModel.Parse("{\"clients\":[") == null, "truncated");
|
||||
Check(CharactersModel.Parse("[1,2]") == null, "array root");
|
||||
}
|
||||
|
||||
private const uint Outdoor = 0xA9B40001; // landblock A9B4, outdoor cell 1
|
||||
|
||||
private static void DistanceSameLandblock()
|
||||
{
|
||||
CharPlace p = CharactersModel.Locate(Outdoor, 10, 10, 0, Outdoor, 40, 50, 0, null, null);
|
||||
Check(p.Measured && Near(p.Distance, 50), "3-4-5 distance");
|
||||
Check(Near(p.Bearing, 36.87, 0.05) && p.Compass == "NE", "bearing NE");
|
||||
Check(p.DistanceText == "50 yd", "distance text");
|
||||
Check(p.Location == CharactersModel.Coords(Outdoor, 40, 50), "outdoor location is map coords");
|
||||
CharPlace up = CharactersModel.Locate(Outdoor, 10, 10, 0, Outdoor, 10, 10, 20, null, null);
|
||||
Check(up.Measured && Near(up.Distance, 20) && up.Compass == "here", "straight above: here, 3D distance");
|
||||
}
|
||||
|
||||
private static void DistanceAcrossLandblocks()
|
||||
{
|
||||
CharPlace east = CharactersModel.Locate(Outdoor, 10, 10, 0, 0xAAB40001, 10, 10, 0, null, null);
|
||||
Check(east.Measured && Near(east.Distance, 192) && east.Compass == "E", "one landblock east");
|
||||
CharPlace north = CharactersModel.Locate(Outdoor, 10, 10, 0, 0xA9B50001, 10, 10, 0, null, null);
|
||||
Check(north.Measured && Near(north.Distance, 192) && north.Compass == "N", "one landblock north");
|
||||
CharPlace sw = CharactersModel.Locate(Outdoor, 100, 100, 0, 0xA8B30001, 100, 100, 0, null, null);
|
||||
Check(sw.Measured && Near(sw.Distance, 192 * Math.Sqrt(2), 0.1) && sw.Compass == "SW", "diagonal south-west");
|
||||
CharPlace far = CharactersModel.Locate(Outdoor, 0, 0, 0, 0x10100001, 0, 0, 0, null, null);
|
||||
Check(far.Measured && far.Distance > 10000, "far across the map is still a distance");
|
||||
}
|
||||
|
||||
private static void DungeonRules()
|
||||
{
|
||||
Func<uint, string> names = lb => lb == 0x01D9 ? "Hive" : "";
|
||||
const uint dungeonA = 0x01D90105, dungeonA2 = 0x01D90142, dungeonB = 0x02AB0110;
|
||||
CharPlace same = CharactersModel.Locate(dungeonA, 10, 10, -6, dungeonA2, 10, 30, -6, null, names);
|
||||
Check(same.Measured && Near(same.Distance, 20) && same.Compass == "N", "same dungeon landblock: measured");
|
||||
Check(same.Location == "Hive", "dungeon location is its name");
|
||||
CharPlace fromOutside = CharactersModel.Locate(Outdoor, 10, 10, 0, dungeonA, 10, 10, 0, null, names);
|
||||
Check(!fromOutside.Measured && fromOutside.Location == "Hive" && fromOutside.DistanceText == "", "outdoors -> dungeon: elsewhere");
|
||||
Check(float.IsPositiveInfinity(fromOutside.Distance) && float.IsNaN(fromOutside.Bearing), "elsewhere has no distance or bearing");
|
||||
CharPlace other = CharactersModel.Locate(dungeonA, 0, 0, 0, dungeonB, 0, 0, 0, null, names);
|
||||
Check(!other.Measured && other.Location == "dungeon LB 02AB", "another, unnamed dungeon");
|
||||
CharPlace outFromDungeon = CharactersModel.Locate(dungeonA, 0, 0, 0, Outdoor, 12, 12, 0, null, names);
|
||||
Check(!outFromDungeon.Measured && outFromDungeon.Location == "42.1N 33.3E", "dungeon -> outdoors: elsewhere with coords");
|
||||
CharPlace noPose = CharactersModel.Locate(0, 0, 0, 0, Outdoor, 12, 12, 0, null, null);
|
||||
Check(!noPose.Measured && noPose.Location == "42.1N 33.3E", "no own pose: location only");
|
||||
}
|
||||
|
||||
private static void SurfaceBuildings()
|
||||
{
|
||||
// An indoor cell of a landblock the caller knows is overworld (a cottage): same space as outdoors.
|
||||
const uint cottage = 0xAAB40102;
|
||||
Func<uint, bool> over = lb => lb == 0xAAB4;
|
||||
CharPlace p = CharactersModel.Locate(Outdoor, 10, 10, 0, cottage, 10, 10, 0, over, null);
|
||||
Check(p.Measured && Near(p.Distance, 192) && p.Compass == "E", "surface building next door: measured");
|
||||
Check(p.Location == CharactersModel.Coords(cottage, 10, 10), "surface building location is coords");
|
||||
CharPlace q = CharactersModel.Locate(Outdoor, 10, 10, 0, cottage, 10, 10, 0, null, null);
|
||||
Check(!q.Measured, "unknown indoor landblock counts as a dungeon");
|
||||
CharPlace r = CharactersModel.Locate(cottage, 10, 10, 0, Outdoor, 10, 10, 0, over, null);
|
||||
Check(r.Measured && r.Compass == "W", "from inside the building out");
|
||||
}
|
||||
|
||||
private static void CoordsText()
|
||||
{
|
||||
Check(CharactersModel.Coords(Outdoor, 12, 12) == "42.1N 33.3E", "Coords NE quadrant");
|
||||
Check(CharactersModel.Coords(0x10100001, 12, 12) == "89.1S 89.1W", "Coords SW quadrant");
|
||||
Check(CharactersModel.CoordsText(-0.04, 0.04) == "0.0S 0.0E", "near zero keeps its sign letter");
|
||||
}
|
||||
|
||||
private static void CompassPoints()
|
||||
{
|
||||
(float b, string c)[] cases =
|
||||
{
|
||||
(0, "N"), (22.4f, "N"), (22.6f, "NE"), (44, "NE"), (90, "E"), (135, "SE"), (180, "S"),
|
||||
(225, "SW"), (270, "W"), (315, "NW"), (337.4f, "NW"), (337.6f, "N"), (359, "N"), (-90, "W"), (450, "E"),
|
||||
};
|
||||
foreach (var (b, c) in cases)
|
||||
Check(CharactersModel.Compass(b) == c, $"compass {b} -> {c} (got {CharactersModel.Compass(b)})");
|
||||
}
|
||||
|
||||
private static NetCharEntry Entry(string name = "A", bool macro = false, string action = "", int cmode = 0, uint hp = 10,
|
||||
bool bot = true, bool portal = false) => new()
|
||||
{
|
||||
Name = name, LoggedIn = true, HasStatus = true, AgeMs = 100,
|
||||
HasVitals = true, Hp = hp, HpMax = 20, St = 1, StMax = 1, Mp = 1, MpMax = 1,
|
||||
HasBot = bot, Macro = macro, Action = action, CombatMode = cmode, Portal = portal,
|
||||
};
|
||||
|
||||
private static void States()
|
||||
{
|
||||
Check(CharactersModel.State(Entry(hp: 0, macro: true)) == ("dead", CharStateKind.Dead), "hp 0 -> dead (before botting)");
|
||||
Check(CharactersModel.State(Entry(portal: true, macro: true)) == ("portal space", CharStateKind.Portal), "portal space");
|
||||
Check(CharactersModel.State(Entry(macro: true, action: "Combat")) == ("botting: fighting", CharStateKind.Fighting), "fighting");
|
||||
Check(CharactersModel.State(Entry(macro: true, action: "Navigating")) == ("botting: navigating", CharStateKind.Botting), "navigating");
|
||||
Check(CharactersModel.State(Entry(macro: true, action: "Default")) == ("botting", CharStateKind.Botting), "botting, default");
|
||||
Check(CharactersModel.State(Entry(macro: false, cmode: 2)) == ("idle, melee", CharStateKind.CombatMode), "macro off, melee stance");
|
||||
Check(CharactersModel.State(Entry(macro: false, cmode: 8)) == ("idle, magic", CharStateKind.CombatMode), "macro off, magic stance");
|
||||
Check(CharactersModel.State(Entry(macro: false, cmode: 1)) == ("idle (macro off)", CharStateKind.Idle), "macro off, peace");
|
||||
Check(CharactersModel.State(Entry(bot: false)) == ("idle", CharStateKind.Idle), "no RynthAi");
|
||||
var maxZero = Entry(hp: 0);
|
||||
maxZero.HpMax = 0;
|
||||
Check(CharactersModel.State(maxZero).Kind != CharStateKind.Dead, "0/0 vitals (not known yet) isn't dead");
|
||||
}
|
||||
|
||||
private static void Stale()
|
||||
{
|
||||
var e = Entry();
|
||||
e.AgeMs = 1000;
|
||||
Check(!CharactersModel.IsStale(e), "1 s old: fresh");
|
||||
e.AgeMs = 6000;
|
||||
Check(CharactersModel.IsStale(e), "6 s old: stale");
|
||||
e.LoggedIn = false;
|
||||
Check(!CharactersModel.IsStale(e), "logged out: not stale");
|
||||
}
|
||||
|
||||
private static void StableOrder()
|
||||
{
|
||||
var zed = Entry("zed"); zed.Cell = Outdoor; zed.X = 1;
|
||||
var alpha = Entry("Alpha"); alpha.Cell = Outdoor; alpha.X = 100;
|
||||
var bob = Entry("bob"); bob.Cell = 0x01D90105;
|
||||
var nobody = new NetCharEntry { Name = "", LoggedIn = false, Pid = 7 };
|
||||
var nobody2 = new NetCharEntry { Name = "", LoggedIn = false, Pid = 3 };
|
||||
var list = new List<NetCharEntry> { nobody, zed, bob, nobody2, alpha };
|
||||
list.Sort(CharactersModel.CompareRows);
|
||||
Check(string.Join(",", list.Select(e => e.Name.Length > 0 ? e.Name : "pid" + e.Pid)) == "Alpha,bob,zed,pid3,pid7",
|
||||
"alphabetical (case-insensitive), clients without a character last by pid");
|
||||
// Moving characters around never changes the order.
|
||||
alpha.X = 0; zed.X = 500; bob.Cell = Outdoor;
|
||||
list.Sort(CharactersModel.CompareRows);
|
||||
Check(list[0] == alpha && list[1] == bob && list[2] == zed, "positions don't reorder rows");
|
||||
// A new character slots in; a gone one just disappears.
|
||||
list.Add(Entry("Carl"));
|
||||
list.Remove(bob);
|
||||
list.Sort(CharactersModel.CompareRows);
|
||||
Check(string.Join(",", list.Take(3).Select(e => e.Name)) == "Alpha,Carl,zed", "new character slots in alphabetically");
|
||||
}
|
||||
|
||||
private static void Vitals()
|
||||
{
|
||||
Check(CharactersModel.VitalText(300, 400) == "300/400", "vital text");
|
||||
Check(Near(CharactersModel.Fraction(300, 400), 0.75), "fraction");
|
||||
Check(CharactersModel.Fraction(5, 0) == 0 && CharactersModel.Fraction(500, 400) == 1, "fraction clamps");
|
||||
}
|
||||
}
|
||||
28
tools/CleaveGhostTests/CleaveGhostTests.csproj
Normal file
28
tools/CleaveGhostTests/CleaveGhostTests.csproj
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for two 2026-10-12 pieces (Drakkon, Tetsubo, Olthoi in 0x6146):
|
||||
src\RynthCore.Engine\ImGui\MonsterHud\CleaveHealth.cs - which nameplate a cleave/AoE hit's
|
||||
share of max health belongs to (AttackerNotification names the monster, no id), so the
|
||||
bars of monsters the server doesn't stream health for move too;
|
||||
src\RynthCore.Engine\Compatibility\ObjectFreshness.cs - when the server last sent anything
|
||||
about an object (the safety check behind plugin API v83 RemoveClientObject: a "ghost"
|
||||
creature the server talked about recently is real and is never removed).
|
||||
Both compiled in; no game, no engine.
|
||||
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>CleaveGhostTests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\CleaveHealth.cs" Link="Engine\CleaveHealth.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\ObjectFreshness.cs" Link="Engine\ObjectFreshness.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
112
tools/CleaveGhostTests/Program.cs
Normal file
112
tools/CleaveGhostTests/Program.cs
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.ImGuiBackend.Hud;
|
||||
|
||||
namespace CleaveGhostTests;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
private static int _checks, _failed;
|
||||
private static string _case = "";
|
||||
|
||||
private static int Main()
|
||||
{
|
||||
Run("cleave: the second mob a Tetsubo hits loses its share", CleaveOntoUnfedPlate);
|
||||
Run("cleave: a hit the server already reported (queried target) changes nothing", ServerAlreadyReported);
|
||||
Run("cleave: a plate with a live server feed is left to the server", LiveFeedLeftAlone);
|
||||
Run("cleave: never a kill, never a bad share, nothing to match", Bounds);
|
||||
Run("cleave: an earlier estimate counts down further", EstimateChains);
|
||||
Run("freshness: object messages are noted, a delete forgets, others are ignored", Freshness);
|
||||
Console.WriteLine($"{_checks} check(s), {_failed} failed.");
|
||||
return _failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static void Run(string name, Action test)
|
||||
{
|
||||
_case = name;
|
||||
int before = _failed;
|
||||
try { test(); }
|
||||
catch (Exception ex) { Fail($"threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
Console.WriteLine($"[{(_failed == before ? "PASS" : "FAIL")}] {name}");
|
||||
}
|
||||
|
||||
private static void Check(bool ok, string what) { _checks++; if (!ok) Fail(what); }
|
||||
private static void Fail(string what) { _failed++; Console.WriteLine($" FAIL {_case}: {what}"); }
|
||||
private static bool Near(float a, float b) => Math.Abs(a - b) < 0.0005f;
|
||||
|
||||
private const float Share204 = 204f / 2300f; // 204 on an Olthoi Slasher (2300 hp): 0.089
|
||||
|
||||
private static void CleaveOntoUnfedPlate()
|
||||
{
|
||||
// The queried target (0x10) got its 0x01C0 for its own hit; the second mob (0x20, 1.6 m)
|
||||
// and a third further off (0x30, 4 m) have no feed.
|
||||
CleaveHealth.Candidate[] c =
|
||||
[
|
||||
new(0x10, 1.4f, true, 0.60f, 0.70f, false, -0.05), // queried target: its own 0x01C0 for its own (bigger) hit
|
||||
new(0x20, 1.6f, false, 1f, -1f, false, 0),
|
||||
new(0x30, 4.0f, true, 0.80f, -1f, true, 3.0), // an older estimate
|
||||
];
|
||||
uint id = CleaveHealth.Pick(c, Share204, out float ratio);
|
||||
Check(id == 0x20, $"nearest unfed plate takes it (got 0x{id:X})");
|
||||
Check(Near(ratio, 1f - Share204), $"full -> {1f - Share204:0.000} (got {ratio:0.000})");
|
||||
}
|
||||
|
||||
private static void ServerAlreadyReported()
|
||||
{
|
||||
// Same name, the queried target's 0x01C0 dropped it by the same share 0.1 s after the hit.
|
||||
CleaveHealth.Candidate[] c =
|
||||
[
|
||||
new(0x10, 1.4f, true, 0.70f - Share204, 0.70f, false, -0.1),
|
||||
new(0x20, 1.6f, false, 1f, -1f, false, 0),
|
||||
];
|
||||
Check(CleaveHealth.Pick(c, Share204, out _) == 0, "the server's own update was this hit: no estimate anywhere");
|
||||
}
|
||||
|
||||
private static void LiveFeedLeftAlone()
|
||||
{
|
||||
// The only plate with the name has a live feed (updated 0.5 s before) but the drop doesn't match.
|
||||
CleaveHealth.Candidate[] c = [new(0x10, 1.4f, true, 0.5f, 0.52f, false, 0.5)];
|
||||
Check(CleaveHealth.Pick(c, Share204, out _) == 0, "live-fed plate: no estimate");
|
||||
// An old feed (20 s) is not live: the plate takes the hit.
|
||||
CleaveHealth.Candidate[] old = [new(0x10, 1.4f, true, 0.5f, 0.52f, false, 20)];
|
||||
Check(CleaveHealth.Pick(old, Share204, out float r) == 0x10 && Near(r, 0.5f - Share204), "stale feed: estimate from its last ratio");
|
||||
}
|
||||
|
||||
private static void Bounds()
|
||||
{
|
||||
CleaveHealth.Candidate[] c = [new(0x20, 1.6f, true, 0.05f, -1f, true, 2)];
|
||||
Check(CleaveHealth.Pick(c, 0.25f, out float r) == 0x20 && Near(r, CleaveHealth.MinRatio), "never below MinRatio (a kill comes from the kill message)");
|
||||
Check(CleaveHealth.Pick(c, 0f, out _) == 0, "no share: nothing");
|
||||
Check(CleaveHealth.Pick(c, float.NaN, out _) == 0, "NaN share: nothing");
|
||||
Check(CleaveHealth.Pick(c, 3f, out _) == 0, "an impossible share: nothing");
|
||||
Check(CleaveHealth.Pick(ReadOnlySpan<CleaveHealth.Candidate>.Empty, Share204, out _) == 0, "no plate with the name: nothing");
|
||||
}
|
||||
|
||||
private static void EstimateChains()
|
||||
{
|
||||
// Two hits on the same unfed mob: the second starts from the first estimate (estimates are never "live feed").
|
||||
CleaveHealth.Candidate[] first = [new(0x20, 1.6f, false, 1f, -1f, false, 0)];
|
||||
CleaveHealth.Pick(first, Share204, out float r1);
|
||||
CleaveHealth.Candidate[] second = [new(0x20, 1.6f, true, r1, 1f, true, 1.2)];
|
||||
Check(CleaveHealth.Pick(second, Share204, out float r2) == 0x20 && Near(r2, 1f - 2 * Share204), $"second hit: {r2:0.000}");
|
||||
}
|
||||
|
||||
private static void Freshness()
|
||||
{
|
||||
ObjectFreshness.Clear();
|
||||
Check(ObjectFreshness.AgeMs(0x800B87E3, 1000) == -1, "never heard of: -1");
|
||||
ObjectFreshness.Note(0xF74C, 0x800B87E3, 1000); // UpdateMotion
|
||||
Check(ObjectFreshness.AgeMs(0x800B87E3, 4000) == 3000, "3 s since its motion update");
|
||||
ObjectFreshness.Note(0xF748, 0x800B87E3, 5000); // UpdatePosition
|
||||
Check(ObjectFreshness.AgeMs(0x800B87E3, 5200) == 200, "position update refreshes it");
|
||||
ObjectFreshness.Note(0xF7B0, 0x800B87E3, 9000); // a game event: not about the object
|
||||
Check(ObjectFreshness.AgeMs(0x800B87E3, 9000) == 4000, "game events don't count");
|
||||
ObjectFreshness.Note(0xF747, 0x800B87E3, 9500); // DeleteObject
|
||||
Check(ObjectFreshness.AgeMs(0x800B87E3, 9600) == -1, "deleted: forgotten");
|
||||
ObjectFreshness.Note(0xF745, 0x800B87E3, 10000); // CreateObject again
|
||||
Check(ObjectFreshness.AgeMs(0x800B87E3, 10000) == 0, "created again: fresh");
|
||||
Check(ObjectFreshness.IsObjectMessage(0xF74E) && ObjectFreshness.IsObjectMessage(0xF7DB) && !ObjectFreshness.IsObjectMessage(0xF7E0),
|
||||
"vector/update-object count, server text doesn't");
|
||||
ObjectFreshness.Note(0xF74C, 0, 1);
|
||||
Check(ObjectFreshness.AgeMs(0, 2) == -1, "id 0 ignored");
|
||||
}
|
||||
}
|
||||
288
tools/ClrFatalTriage/clr_fatal_triage.py
Normal file
288
tools/ClrFatalTriage/clr_fatal_triage.py
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
"""
|
||||
clr_fatal_triage.py - first look at an x86 acclient crash dump (no debugger needed).
|
||||
|
||||
Written for the CoreCLR fatal errors of 2026-09-29..10-12 (.NET Runtime event 1023,
|
||||
"internal error in the .NET Runtime at IP coreclr.dll+0x256E19", exit 0x80131506),
|
||||
where dotnet-dump only showed an ExecutionEngineException with no stack.
|
||||
|
||||
For every thread it finds an exception being dispatched on (the EXCEPTION_RECORD /
|
||||
CONTEXT pair KiUserExceptionDispatcher leaves on the stack), it prints the exception,
|
||||
the faulting registers, and the return addresses on that thread's stack as
|
||||
module+offset. coreclr.dll offsets are named when you pass its public PDB (--pdb,
|
||||
fetched once from https://msdl.microsoft.com/download/symbols/coreclr.pdb/<GUID><age>/coreclr.pdb;
|
||||
the GUID/age are printed below). Known fatal sites are named even without it.
|
||||
|
||||
python -I tools\\ClrFatalTriage\\clr_fatal_triage.py <dump.dmp> [--pdb coreclr.pdb] [--all-threads]
|
||||
[--image Name.dll=C:\\path\\to\\matching\\Name.dll]
|
||||
|
||||
Needs Python 3 and pefile (only to read code bytes from the module files when the dump
|
||||
has none, which is what tells real return addresses from stale stack values). Read-only.
|
||||
JIT'd code has no module; those addresses print as raw hex (SOS `ip2md` resolves them
|
||||
when the dump holds the code heap: `dotnet-dump analyze` under the x86 dotnet host).
|
||||
"""
|
||||
import argparse
|
||||
import bisect
|
||||
import mmap
|
||||
import os
|
||||
import pickle
|
||||
import struct
|
||||
import sys
|
||||
|
||||
# Fatal sites by coreclr.dll file version -> offset -> meaning.
|
||||
KNOWN_SITES = {
|
||||
"10.0.1226.42308": {
|
||||
0x256E19: "ReversePInvokeBadTransition: a reverse P/Invoke (a managed hook/callback) was entered "
|
||||
"on a thread already in cooperative mode, i.e. native code running inside managed "
|
||||
"code's context (an exception handler / VEH on a managed fault) called a function "
|
||||
"with a managed detour. In the listing, the first module frame after "
|
||||
"JIT_ReversePInvokeEnter* (next higher address, past the stub's raw frame) is the "
|
||||
"native code that called the hooked function.",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class Dump:
|
||||
def __init__(self, path, images):
|
||||
f = open(path, "rb")
|
||||
self.m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
|
||||
sig, _ver, nstreams, dirrva = struct.unpack_from("<IIII", self.m, 0)
|
||||
if sig != 0x504D444D:
|
||||
raise SystemExit("not a minidump")
|
||||
self.streams = {}
|
||||
for i in range(nstreams):
|
||||
st, size, rva = struct.unpack_from("<III", self.m, dirrva + 12 * i)
|
||||
self.streams.setdefault(st, []).append((size, rva))
|
||||
self.images = images
|
||||
self.imgcache = {}
|
||||
self.mods, self.mem, self.threads = [], [], []
|
||||
self._parse()
|
||||
|
||||
def _str(self, rva):
|
||||
n = struct.unpack_from("<I", self.m, rva)[0]
|
||||
return self.m[rva + 4:rva + 4 + n].decode("utf-16le", "replace")
|
||||
|
||||
def _parse(self):
|
||||
m = self.m
|
||||
for _size, rva in self.streams.get(4, []): # ModuleListStream
|
||||
for i in range(struct.unpack_from("<I", m, rva)[0]):
|
||||
o = rva + 4 + 108 * i
|
||||
base, sz, _cs, ts, namerva = struct.unpack_from("<QIIII", m, o)
|
||||
ms, ls = struct.unpack_from("<II", m, o + 32)
|
||||
ver = "%d.%d.%d.%d" % (ms >> 16, ms & 0xFFFF, ls >> 16, ls & 0xFFFF)
|
||||
self.mods.append((base, sz, self._str(namerva), ts, ver))
|
||||
self.mods.sort()
|
||||
for _size, rva in self.streams.get(5, []): # MemoryListStream
|
||||
for i in range(struct.unpack_from("<I", m, rva)[0]):
|
||||
start, dsz, drva = struct.unpack_from("<QII", m, rva + 4 + 16 * i)
|
||||
self.mem.append((start, dsz, drva))
|
||||
for _size, rva in self.streams.get(9, []): # Memory64ListStream
|
||||
n, off = struct.unpack_from("<QQ", m, rva)
|
||||
for i in range(n):
|
||||
start, dsz = struct.unpack_from("<QQ", m, rva + 16 + 16 * i)
|
||||
self.mem.append((start, dsz, off))
|
||||
off += dsz
|
||||
self.mem.sort()
|
||||
self.memstarts = [x[0] for x in self.mem]
|
||||
for _size, rva in self.streams.get(3, []): # ThreadListStream
|
||||
for i in range(struct.unpack_from("<I", m, rva)[0]):
|
||||
(tid, _s, _pc, _p, _teb, sstart, ssize, _srva, _csz,
|
||||
crva) = struct.unpack_from("<IIIIQQIIII", m, rva + 4 + 48 * i)
|
||||
sstart &= 0xFFFFFFFF # WOW64 dumps can sign-extend 32-bit stack addresses
|
||||
self.threads.append((tid, sstart, sstart + ssize, crva))
|
||||
|
||||
def read(self, addr, size):
|
||||
i = bisect.bisect_right(self.memstarts, addr) - 1
|
||||
if i < 0:
|
||||
return None
|
||||
start, dsz, off = self.mem[i]
|
||||
if addr + size > start + dsz:
|
||||
return None
|
||||
return self.m[off + addr - start:off + addr - start + size]
|
||||
|
||||
def u32(self, addr):
|
||||
b = self.read(addr, 4)
|
||||
return None if b is None else struct.unpack("<I", b)[0]
|
||||
|
||||
def module(self, addr):
|
||||
for mod in self.mods:
|
||||
if mod[0] <= addr < mod[0] + mod[1]:
|
||||
return mod
|
||||
return None
|
||||
|
||||
def code(self, addr, n):
|
||||
b = self.read(addr, n)
|
||||
if b is not None:
|
||||
return b
|
||||
mod = self.module(addr)
|
||||
if mod is None:
|
||||
return None
|
||||
name = mod[2]
|
||||
if name not in self.imgcache:
|
||||
leaf = name.split("\\")[-1].lower()
|
||||
path = self.images.get(leaf, name)
|
||||
if path.lower().startswith("c:\\windows\\system32\\"):
|
||||
path = "C:\\Windows\\SysWOW64\\" + path[20:]
|
||||
try:
|
||||
import pefile
|
||||
pe = pefile.PE(path, fast_load=True)
|
||||
# An --image the user named is trusted; otherwise the file must match the dump's
|
||||
# timestamp. (The dump's module list can show the file that was on disk at dump
|
||||
# time when a loaded DLL was replaced by rename-aside: on 10-12 a v4 trampoline
|
||||
# was listed while the client still ran the v1 it started with.)
|
||||
trusted = leaf in self.images or pe.FILE_HEADER.TimeDateStamp == mod[3]
|
||||
self.imgcache[name] = pe.get_memory_mapped_image() if trusted else None
|
||||
except Exception:
|
||||
self.imgcache[name] = None
|
||||
img = self.imgcache[name]
|
||||
o = addr - mod[0]
|
||||
return None if img is None else img[o:o + n]
|
||||
|
||||
def after_call(self, ra):
|
||||
b = self.code(ra - 7, 7)
|
||||
if b is None or len(b) < 7:
|
||||
return None # unknown: no code bytes
|
||||
return (b[2] == 0xE8 or (b[5] == 0xFF and (b[6] >> 3) & 7 == 2) or
|
||||
(b[4] == 0xFF and (b[5] >> 3) & 7 == 2) or (b[1] == 0xFF and (b[2] >> 3) & 7 == 2) or
|
||||
(b[0] == 0xFF and (b[1] >> 3) & 7 == 2))
|
||||
|
||||
|
||||
def load_pdb_publics(path):
|
||||
"""S_PUB32 records of an MSF 7.0 PDB as a sorted [(rva, name)]; cached next to the PDB."""
|
||||
cache = path + ".publics.pkl"
|
||||
if os.path.exists(cache):
|
||||
return pickle.load(open(cache, "rb"))
|
||||
data = open(path, "rb").read()
|
||||
bs, _fbm, _nb, ndir, _u, bmaddr = struct.unpack_from("<IIIIII", data, 32)
|
||||
dirblocks = struct.unpack_from("<%dI" % ((ndir + bs - 1) // bs), data, bmaddr * bs)
|
||||
d = b"".join(data[b * bs:(b + 1) * bs] for b in dirblocks)[:ndir]
|
||||
nstreams = struct.unpack_from("<I", d, 0)[0]
|
||||
sizes = struct.unpack_from("<%dI" % nstreams, d, 4)
|
||||
off, streams = 4 + 4 * nstreams, []
|
||||
for s in sizes:
|
||||
s = 0 if s == 0xFFFFFFFF else s
|
||||
nb = (s + bs - 1) // bs
|
||||
streams.append((s, struct.unpack_from("<%dI" % nb, d, off)))
|
||||
off += 4 * nb
|
||||
|
||||
def stream(i):
|
||||
s, blks = streams[i]
|
||||
return b"".join(data[b * bs:(b + 1) * bs] for b in blks)[:s]
|
||||
|
||||
dbi = stream(3)
|
||||
f = struct.unpack_from("<iIIHHHHHHiiiiiIiiHHI", dbi, 0)
|
||||
symrec, sub = f[7], f[9:14] + (f[16],)
|
||||
optdbg = f[15]
|
||||
o = 64 + sum(sub)
|
||||
sechdr = stream(struct.unpack_from("<%dH" % (optdbg // 2), dbi, o)[5])
|
||||
secs = [struct.unpack_from("<I", sechdr, i * 40 + 12)[0] for i in range(len(sechdr) // 40)]
|
||||
sr, p, out = stream(symrec), 0, []
|
||||
while p + 4 <= len(sr):
|
||||
reclen, kind = struct.unpack_from("<HH", sr, p)
|
||||
if kind == 0x110E: # S_PUB32
|
||||
_fl, offs, seg = struct.unpack_from("<IIH", sr, p + 4)
|
||||
if 1 <= seg <= len(secs):
|
||||
out.append((secs[seg - 1] + offs, sr[p + 14:sr.index(b"\0", p + 14)].decode("latin1")))
|
||||
p += reclen + 2
|
||||
out.sort()
|
||||
pickle.dump(out, open(cache, "wb"))
|
||||
return out
|
||||
|
||||
|
||||
def pdb_identity(path):
|
||||
try:
|
||||
import pefile
|
||||
pe = pefile.PE(path, fast_load=True)
|
||||
pe.parse_data_directories(directories=[pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_DEBUG"]])
|
||||
for e in getattr(pe, "DIRECTORY_ENTRY_DEBUG", []):
|
||||
if hasattr(e.entry, "Signature_String"):
|
||||
return "%s%X" % (e.entry.Signature_String, e.entry.Age)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("dump")
|
||||
ap.add_argument("--pdb", help="coreclr.pdb matching the dump's coreclr.dll")
|
||||
ap.add_argument("--all-threads", action="store_true", help="scan every thread, not just ones dispatching an exception")
|
||||
ap.add_argument("--image", action="append", default=[], help="Name.dll=path: module file to read code bytes from")
|
||||
a = ap.parse_args()
|
||||
images = {k.lower(): v for k, v in (x.split("=", 1) for x in a.image)}
|
||||
d = Dump(a.dump, images)
|
||||
|
||||
clr = next((mod for mod in d.mods if mod[2].lower().endswith("\\coreclr.dll")), None)
|
||||
pubs = load_pdb_publics(a.pdb) if a.pdb else None
|
||||
known = KNOWN_SITES.get(clr[4], {}) if clr else {}
|
||||
if clr:
|
||||
print("coreclr.dll %s at 0x%08X (%s); PDB id %s" % (clr[4], clr[0], clr[2], pdb_identity(clr[2]) or "?"))
|
||||
|
||||
seen_known = set()
|
||||
|
||||
def sym(v):
|
||||
mod = d.module(v)
|
||||
if mod is None:
|
||||
return None
|
||||
leaf, off = mod[2].split("\\")[-1], v - mod[0]
|
||||
s = "%s+0x%X" % (leaf, off)
|
||||
if mod is clr:
|
||||
if pubs:
|
||||
i = bisect.bisect_right(pubs, (off, "\uffff")) - 1
|
||||
if i >= 0:
|
||||
s += " %s+0x%X" % (pubs[i][1], off - pubs[i][0])
|
||||
if off in known:
|
||||
s += " <== KNOWN FATAL SITE"
|
||||
seen_known.add(off)
|
||||
return s
|
||||
|
||||
for tid, lo, hi, crva in d.threads:
|
||||
esp = struct.unpack_from("<I", d.m, crva + 0xC4)[0]
|
||||
records = []
|
||||
a_ = esp
|
||||
while a_ + 8 <= hi:
|
||||
per, pctx = d.u32(a_), d.u32(a_ + 4)
|
||||
if per is None:
|
||||
break
|
||||
if per and pctx and lo <= per < hi and pctx == per + 0x50 and all(r[1] != per for r in records):
|
||||
code = d.u32(per)
|
||||
if code is not None and code & 0xC0000000 == 0xC0000000:
|
||||
records.append((a_, per, pctx))
|
||||
a_ += 4
|
||||
if not records and not a.all_threads:
|
||||
continue
|
||||
print("\n=== thread 0x%X stack 0x%08X..0x%08X" % (tid, lo, hi))
|
||||
for at, per, pctx in records:
|
||||
code, flags, _rec, addr, n = struct.unpack("<IIIII", d.read(per, 20))
|
||||
info = struct.unpack("<%dI" % min(n, 15), d.read(per + 20, 4 * min(n, 15))) if n else ()
|
||||
regs = dict(zip(["edi", "esi", "ebx", "edx", "ecx", "eax", "ebp", "eip", "cs", "efl", "esp"],
|
||||
struct.unpack("<11I", d.read(pctx + 0x9C, 44))))
|
||||
print(" exception at stack 0x%08X: code=0x%08X flags=%X address=0x%08X %s info=%s" % (
|
||||
at, code, flags, addr, sym(addr) or "(no module: JIT'd code or a stub)",
|
||||
" ".join("0x%X" % x for x in info)))
|
||||
if code == 0xC0000005 and len(info) >= 2:
|
||||
print(" %s of 0x%08X%s" % ({0: "read", 1: "write", 8: "execute"}.get(info[0], "?"), info[1],
|
||||
" (null page: a NullReferenceException if this is managed code)" if info[1] < 0x10000 else ""))
|
||||
print(" " + " ".join("%s=%08X" % (k, regs[k]) for k in ["eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp", "eip"]))
|
||||
print(" return addresses (esp -> stack base):")
|
||||
a_ = esp
|
||||
while a_ + 4 <= hi:
|
||||
v = d.u32(a_)
|
||||
if v is None:
|
||||
print(" <stack unreadable at 0x%08X>" % a_)
|
||||
break
|
||||
s = sym(v)
|
||||
if s:
|
||||
call = d.after_call(v)
|
||||
if call or call is None:
|
||||
print(" 0x%08X: 0x%08X %s%s" % (a_, v, s, "" if call else " (no code bytes to check)"))
|
||||
a_ += 4
|
||||
|
||||
for off in sorted(seen_known):
|
||||
print("\nKNOWN FATAL SITE coreclr.dll+0x%X: %s" % (off, known[off]))
|
||||
if seen_known:
|
||||
print("The 2026-10-12 cause: RynthCore.SehTrampoline.dll's VEH (v1-v4) called CreateFileW while a managed\n"
|
||||
"NullReferenceException was being dispatched; DatFileShareHooks detours CreateFileW in managed code.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
22
tools/DungeonMapNavTests/DungeonMapNavTests.csproj
Normal file
22
tools/DungeonMapNavTests/DungeonMapNavTests.csproj
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for the Dungeon Map's coordinate mapping (src\RynthCore.Engine\UI\Data\
|
||||
DungeonMapMath.cs, compiled in): screen <-> world through pan, zoom and rotation, world <->
|
||||
RynthAi nav coordinates, a route point's floor by Z, the floor under a click, picking.
|
||||
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>DungeonMapNavTests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\DungeonMapMath.cs" Link="Engine\DungeonMapMath.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
181
tools/DungeonMapNavTests/Program.cs
Normal file
181
tools/DungeonMapNavTests/Program.cs
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
using System.Numerics;
|
||||
using RynthCore.Engine.UI.Data;
|
||||
|
||||
namespace DungeonMapNavTests;
|
||||
|
||||
/// <summary>
|
||||
/// The Dungeon Map's coordinate mapping (DungeonMapMath): what a click on the map turns into as
|
||||
/// a RynthAi nav point, and where a nav point is drawn, through pan, zoom and rotation.
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
private static int _checks, _failed;
|
||||
|
||||
private static int Main()
|
||||
{
|
||||
NavWorldMatchesRynthAi();
|
||||
NorthUpProjection();
|
||||
RotatedProjection();
|
||||
InverseRoundTrips();
|
||||
ClickToNavAndBack();
|
||||
LayerForZ();
|
||||
FloorUnderClick();
|
||||
Picking();
|
||||
|
||||
Console.WriteLine($"{_checks} checks, {_failed} failed");
|
||||
return _failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static void Check(bool ok, string what)
|
||||
{
|
||||
_checks++;
|
||||
if (ok) return;
|
||||
_failed++;
|
||||
Console.WriteLine("FAIL: " + what);
|
||||
}
|
||||
|
||||
private static bool Near(double a, double b, double tol) => Math.Abs(a - b) <= tol;
|
||||
private static bool Near(Vector2 a, Vector2 b, float tol) => Vector2.Distance(a, b) <= tol;
|
||||
|
||||
/// <summary>
|
||||
/// RynthAi's own formula (NavCoordinateHelper.TryConvertPoseToCoords): EW = (lbX * 8 + x / 24
|
||||
/// - 1019.5) / 10 from the cell id and local x; the radar's world X is lbX * 192 + x. A patrol
|
||||
/// log waypoint: (18665.0, 13300.0, -24.0) in cell 0x61460127 (local 41, -140).
|
||||
/// </summary>
|
||||
private static void NavWorldMatchesRynthAi()
|
||||
{
|
||||
uint cell = 0x61460127;
|
||||
int lbX = (int)(cell >> 24), lbY = (int)((cell >> 16) & 0xFF);
|
||||
float lx = 41f, ly = -140f, z = -24f;
|
||||
double ew = (lbX * 8.0 + lx / 24.0 - 1019.5) / 10.0;
|
||||
double ns = (lbY * 8.0 + ly / 24.0 - 1019.5) / 10.0;
|
||||
float wx = lbX * 192f + lx, wy = lbY * 192f + ly;
|
||||
Check(Near(wx, 18665.0, 1e-3) && Near(wy, 13300.0, 1e-3), "world from cell + local");
|
||||
Check(Near(DungeonMapMath.WorldToNav(wx), ew, 1e-9), "WorldToNav = RynthAi EW");
|
||||
Check(Near(DungeonMapMath.WorldToNav(wy), ns, 1e-9), "WorldToNav = RynthAi NS");
|
||||
Vector2 back = DungeonMapMath.NavToWorld(ns, ew);
|
||||
Check(Near(back, new Vector2(wx, wy), 0.01f), "NavToWorld(NS, EW) = (world x, world y)");
|
||||
Check(Near(DungeonMapMath.NavZToWorld(z / 240.0), z, 1e-4), "nav Z = world Z / 240 (addWaypoint)");
|
||||
Check(Near(DungeonMapMath.WorldZToNav(z), -0.1, 1e-9), "WorldZToNav");
|
||||
// One nav unit is 240 world units (yards): 0.01 nav = 2.4.
|
||||
Check(Near(DungeonMapMath.NavToWorld(10.01) - DungeonMapMath.NavToWorld(10.0), 2.4, 1e-6), "0.01 nav = 2.4 world");
|
||||
}
|
||||
|
||||
private static void NorthUpProjection()
|
||||
{
|
||||
var at = new Vector2(400, 300);
|
||||
var p = new DungeonMapProjection(at, 1000f, 2000f, 37f, rotate: false, zoom: 5f);
|
||||
Check(Near(p.P(1000f, 2000f), at, 1e-4f), "player at the centre");
|
||||
Check(Near(p.P(1010f, 2000f), at + new Vector2(50, 0), 1e-3f), "east is right");
|
||||
Check(Near(p.P(1000f, 2010f), at + new Vector2(0, -50), 1e-3f), "north is up");
|
||||
}
|
||||
|
||||
private static void RotatedProjection()
|
||||
{
|
||||
var at = new Vector2(400, 300);
|
||||
// Heading 90 = facing north: north is up, east right (same as north-up).
|
||||
var n = new DungeonMapProjection(at, 0f, 0f, 90f, rotate: true, zoom: 2f);
|
||||
Check(Near(n.P(0f, 10f), at + new Vector2(0, -20), 1e-3f), "facing north: ahead (north) is up");
|
||||
Check(Near(n.P(10f, 0f), at + new Vector2(20, 0), 1e-3f), "facing north: east is right");
|
||||
// Heading 0 = facing east: east is up, south is right.
|
||||
var e = new DungeonMapProjection(at, 0f, 0f, 0f, rotate: true, zoom: 2f);
|
||||
Check(Near(e.P(10f, 0f), at + new Vector2(0, -20), 1e-3f), "facing east: east is up");
|
||||
Check(Near(e.P(0f, -10f), at + new Vector2(20, 0), 1e-3f), "facing east: south is right");
|
||||
Check(Near(e.P(0f, 10f), at + new Vector2(-20, 0), 1e-3f), "facing east: north is left");
|
||||
}
|
||||
|
||||
private static void InverseRoundTrips()
|
||||
{
|
||||
var rng = new Random(12345);
|
||||
foreach (bool rotate in new[] { false, true })
|
||||
for (int t = 0; t < 400; t++)
|
||||
{
|
||||
var at = new Vector2(rng.Next(0, 1200), rng.Next(0, 900));
|
||||
float pwx = 18000f + (float)rng.NextDouble() * 1000f, pwy = 13000f + (float)rng.NextDouble() * 1000f;
|
||||
float heading = (float)rng.NextDouble() * 360f, zoom = 1f + (float)rng.NextDouble() * 19f;
|
||||
var p = new DungeonMapProjection(at, pwx, pwy, heading, rotate, zoom);
|
||||
var w = new Vector2(pwx + (float)(rng.NextDouble() * 200 - 100), pwy + (float)(rng.NextDouble() * 200 - 100));
|
||||
Vector2 s = p.P(w.X, w.Y);
|
||||
if (!Near(p.World(s), w, 0.01f)) { Check(false, $"World(P(w)) = w (rotate {rotate}, h {heading}, z {zoom})"); return; }
|
||||
var screen = new Vector2(rng.Next(0, 1200), rng.Next(0, 900));
|
||||
if (!Near(p.P(p.World(screen).X, p.World(screen).Y), screen, 0.05f)) { Check(false, $"P(World(s)) = s (rotate {rotate})"); return; }
|
||||
}
|
||||
Check(true, "projection round trips");
|
||||
}
|
||||
|
||||
/// <summary>A click on the map, as the face sends it (addPointAt), lands back on the pixel clicked.</summary>
|
||||
private static void ClickToNavAndBack()
|
||||
{
|
||||
var canvasCentre = new Vector2(500, 400);
|
||||
var pan = new Vector2(-37, 22);
|
||||
foreach (bool rotate in new[] { false, true })
|
||||
{
|
||||
var p = new DungeonMapProjection(canvasCentre + pan, 18665f, 13300f, 123.4f, rotate, 6.5f);
|
||||
var click = new Vector2(610, 333);
|
||||
Vector2 w = p.World(click);
|
||||
double ns = DungeonMapMath.WorldToNav(w.Y), ew = DungeonMapMath.WorldToNav(w.X);
|
||||
Vector2 w2 = DungeonMapMath.NavToWorld(ns, ew);
|
||||
Check(Near(p.P(w2.X, w2.Y), click, 0.05f), $"click -> nav -> screen is the same pixel (rotate {rotate})");
|
||||
}
|
||||
// Panning moves the map, not the mapping: the same world spot moves by the pan.
|
||||
var a = new DungeonMapProjection(canvasCentre, 100f, 100f, 45f, true, 4f);
|
||||
var b = new DungeonMapProjection(canvasCentre + pan, 100f, 100f, 45f, true, 4f);
|
||||
Check(Near(b.P(120f, 90f) - a.P(120f, 90f), pan, 1e-3f), "pan shifts the drawing by the pan");
|
||||
}
|
||||
|
||||
private static void LayerForZ()
|
||||
{
|
||||
var layers = new List<float> { -24f, -12f, 0f, 6f };
|
||||
Check(DungeonMapMath.NearestLayer(layers, -23.995f) == 0, "a point recorded on the floor (feet just above)");
|
||||
Check(DungeonMapMath.NearestLayer(layers, 5f) == 3, "nearest floor");
|
||||
Check(DungeonMapMath.NearestLayer(layers, -0.1f * 240f) == 0, "nav Z -0.1 = world -24");
|
||||
Check(DungeonMapMath.NearestLayer(layers, 60f) == -1, "far above every floor: none");
|
||||
Check(DungeonMapMath.NearestLayer(new List<float>(), 0f) == -1, "no floors");
|
||||
Check(DungeonMapMath.NearestLayer(layers, float.NaN) == -1, "NaN Z");
|
||||
}
|
||||
|
||||
private static void FloorUnderClick()
|
||||
{
|
||||
// Three floors: 0 covers x 0..10, 1 covers x 5..20, 2 covers x 30..40 (y 0..10 each).
|
||||
var fills = new float[]?[]
|
||||
{
|
||||
new float[] { 0, 0, 10, 10, 0 },
|
||||
new float[] { 5, 0, 20, 10, 1 },
|
||||
new float[] { 30, 0, 40, 10, 0 },
|
||||
};
|
||||
var visible = new HashSet<int> { 0, 1, 2 };
|
||||
Span<int> order = stackalloc int[3];
|
||||
int n = DungeonMapMath.LayerOrder(1, visible, 3, order);
|
||||
Check(n == 3 && order[0] == 1, "the player's floor is tried first");
|
||||
Check(DungeonMapMath.FloorAt(7, 5, fills, order[..n]) == 1, "overlap: the player's floor wins");
|
||||
Check(DungeonMapMath.FloorAt(2, 5, fills, order[..n]) == 0, "only floor 0 there");
|
||||
Check(DungeonMapMath.FloorAt(35, 5, fills, order[..n]) == 2, "floor 2");
|
||||
Check(DungeonMapMath.FloorAt(25, 5, fills, order[..n]) == -1, "between floors: none");
|
||||
Check(DungeonMapMath.FloorAt(7, 11, fills, order[..n]) == -1, "off every floor: none");
|
||||
|
||||
// Hidden floors don't count.
|
||||
var only0 = new HashSet<int> { 0 };
|
||||
n = DungeonMapMath.LayerOrder(1, only0, 3, order);
|
||||
Check(n == 1 && order[0] == 0, "the player's floor hidden: only the shown one");
|
||||
Check(DungeonMapMath.FloorAt(15, 5, fills, order[..n]) == -1, "a hidden floor isn't clickable");
|
||||
|
||||
// Order: nearest the player's floor first.
|
||||
var all5 = new HashSet<int> { 0, 1, 2, 3, 4 };
|
||||
Span<int> o5 = stackalloc int[5];
|
||||
n = DungeonMapMath.LayerOrder(2, all5, 5, o5);
|
||||
Check(n == 5 && o5[0] == 2 && o5[1] == 1 && o5[2] == 3 && o5[3] == 0 && o5[4] == 4, "2, 1, 3, 0, 4");
|
||||
n = DungeonMapMath.LayerOrder(-1, all5, 5, o5);
|
||||
Check(n == 5 && o5[0] == 0 && o5[4] == 4, "no current floor: ascending");
|
||||
|
||||
Check(DungeonMapMath.FillBounds(fills, out Vector4 bb) && bb == new Vector4(0, 0, 40, 10), "fill bounds");
|
||||
Check(!DungeonMapMath.FillBounds(new float[]?[] { null }, out _), "no fills: no bounds");
|
||||
}
|
||||
|
||||
private static void Picking()
|
||||
{
|
||||
var drawn = new List<(int, Vector2)> { (0, new Vector2(10, 10)), (3, new Vector2(20, 10)), (7, new Vector2(100, 100)) };
|
||||
Check(DungeonMapMath.Pick(new Vector2(12, 11), drawn, 8f) == 0, "nearest within the radius");
|
||||
Check(DungeonMapMath.Pick(new Vector2(17, 10), drawn, 8f) == 3, "the closer of two");
|
||||
Check(DungeonMapMath.Pick(new Vector2(50, 50), drawn, 8f) == -1, "nothing near");
|
||||
}
|
||||
}
|
||||
298
tools/EngineRobustnessTests/AutoIdDrainTests.cs
Normal file
298
tools/EngineRobustnessTests/AutoIdDrainTests.cs
Normal file
|
|
@ -0,0 +1,298 @@
|
|||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.Net;
|
||||
|
||||
namespace EngineRobustnessTests;
|
||||
|
||||
/// <summary>
|
||||
/// AutoIdDrain against a fake world and a fake clock: the pack
|
||||
/// created before the object snapshot is warm still gets appraised, a refused enqueue
|
||||
/// is kept, and the bounds.
|
||||
/// </summary>
|
||||
internal static partial class Program
|
||||
{
|
||||
private sealed class FakeWorld : IAutoIdWorld
|
||||
{
|
||||
public bool Warm;
|
||||
public readonly Dictionary<uint, (uint Container, uint Wielder)> Snapshot = new();
|
||||
public readonly HashSet<uint> Cached = new();
|
||||
public readonly HashSet<uint> Released = new();
|
||||
public bool Refuse;
|
||||
public readonly HashSet<uint> Containers = new();
|
||||
public readonly List<uint> Looked = new(); // every CollectOwned call
|
||||
public readonly List<(uint Id, IdRequester Who, long At)> Sent = new();
|
||||
public long Now;
|
||||
|
||||
public bool TryGetOwnership(uint id, out uint container, out uint wielder)
|
||||
{
|
||||
container = wielder = 0;
|
||||
if (!Warm || !Snapshot.TryGetValue(id, out var e)) return false;
|
||||
container = e.Container; wielder = e.Wielder;
|
||||
return true;
|
||||
}
|
||||
public bool SnapshotWarm => Warm;
|
||||
public int CollectOwned(uint container, Span<uint> dest)
|
||||
{
|
||||
Looked.Add(container);
|
||||
if (!Warm) return 0;
|
||||
int n = 0;
|
||||
foreach (var kv in Snapshot)
|
||||
{
|
||||
if (n >= dest.Length) break;
|
||||
if (kv.Key != container && (kv.Value.Container == container || kv.Value.Wielder == container)) dest[n++] = kv.Key;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
public bool IsLive(uint id) => !Released.Contains(id);
|
||||
public bool HasAppraisal(uint id) => Cached.Contains(id);
|
||||
public bool IsFresh(uint id) => Cached.Contains(id);
|
||||
public bool IsContainer(uint id) => Containers.Contains(id);
|
||||
public bool QueueIdentify(uint id, IdRequester who)
|
||||
{
|
||||
if (Refuse) return false;
|
||||
Sent.Add((id, who, Now));
|
||||
Cached.Add(id); // the reply lands
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private const uint Me = 0x50000001, SidePack = 0x80000900;
|
||||
|
||||
private static AutoIdDrain.Context Ctx(FakeWorld w, long loginAt, AutoIdMode mode = AutoIdMode.Limited, long settle = 0, bool combat = false) => new()
|
||||
{
|
||||
Now = w.Now, Mode = mode, PlayerId = Me, OpenContainer = 0, OpenedAtMs = 0, SettleUntilMs = settle, LoginCompleteAtMs = loginAt,
|
||||
CombatBusy = combat,
|
||||
};
|
||||
|
||||
/// <summary>Runs the 100 ms drain from w.Now to <paramref name="until"/>.</summary>
|
||||
private static void RunUntil(AutoIdDrain d, FakeWorld w, long until, long loginAt, AutoIdMode mode = AutoIdMode.Limited, Action? each = null)
|
||||
{
|
||||
for (; w.Now <= until; w.Now += 100)
|
||||
{
|
||||
each?.Invoke();
|
||||
d.Tick(Ctx(w, loginAt, mode), 0);
|
||||
}
|
||||
}
|
||||
|
||||
private static void RunAutoIdDrainTests()
|
||||
{
|
||||
DrainLoginPackWithColdSnapshot();
|
||||
DrainLoginSweep();
|
||||
DrainUnknownWaitsForSnapshotThenGivesUp();
|
||||
DrainRefusedEnqueueIsKept();
|
||||
DrainBounds();
|
||||
DrainCombatHoldsInventory();
|
||||
DrainSweepRetriesAfterOverflow();
|
||||
}
|
||||
|
||||
// The pack is created at login, before the snapshot is warm; it must still go out.
|
||||
private static void DrainLoginPackWithColdSnapshot()
|
||||
{
|
||||
_case = "drain login pack, cold snapshot";
|
||||
var w = new FakeWorld { Now = 10_000 };
|
||||
var d = new AutoIdDrain(w);
|
||||
// The login create burst: 20 pack items and a side pack with 5 more, created at 10 s.
|
||||
var pack = new List<uint>();
|
||||
for (uint i = 1; i <= 20; i++) { pack.Add(0x80001000 + i); w.Snapshot[0x80001000 + i] = (Me, 0); }
|
||||
w.Snapshot[SidePack] = (Me, 0); w.Containers.Add(SidePack);
|
||||
pack.Add(SidePack);
|
||||
for (uint i = 1; i <= 5; i++) { pack.Add(0x80002000 + i); w.Snapshot[0x80002000 + i] = (SidePack, 0); }
|
||||
foreach (uint id in pack) d.Offer(id, w.Now);
|
||||
const long LoginAt = 12_000;
|
||||
const long WarmAt = 40_000; // the snapshot starts 28 s after login-complete (cold for N seconds)
|
||||
|
||||
// Before login completes, and while the snapshot is cold: nothing is sent, nothing dropped.
|
||||
RunUntil(d, w, LoginAt - 100, loginAt: 0);
|
||||
Check(w.Sent.Count == 0, $"nothing before login-complete, sent {w.Sent.Count}");
|
||||
RunUntil(d, w, WarmAt - 100, LoginAt);
|
||||
Check(w.Sent.Count == 0, $"nothing while the snapshot is cold, sent {w.Sent.Count}");
|
||||
Check(d.PendingCount == pack.Count, $"all {pack.Count} kept while the snapshot is cold, pending {d.PendingCount}");
|
||||
|
||||
w.Warm = true;
|
||||
RunUntil(d, w, 120_000, LoginAt);
|
||||
var sentIds = w.Sent.Select(s => s.Id).ToHashSet();
|
||||
Check(pack.All(sentIds.Contains), $"every pack item eventually sent ({sentIds.Count}/{pack.Count})");
|
||||
Check(w.Sent.All(s => s.Who == IdRequester.AutoIdInventory), "all as autoid-inventory");
|
||||
Check(w.Sent.Min(s => s.At) >= LoginAt + AutoIdPolicy.DeferMs, "none before login + DeferMs");
|
||||
int worst = w.Sent.Max(s => w.Sent.Count(t => t.At >= s.At && t.At < s.At + 1_000));
|
||||
Check(worst <= 5, $"at most 5 a second, got {worst}");
|
||||
}
|
||||
|
||||
// The one-shot sweep at login + DeferMs, also after a hot reload (a new login stamp).
|
||||
private static void DrainLoginSweep()
|
||||
{
|
||||
_case = "drain login sweep";
|
||||
var w = new FakeWorld { Now = 100_000, Warm = true };
|
||||
var d = new AutoIdDrain(w);
|
||||
for (uint i = 1; i <= 8; i++) w.Snapshot[0x80003000 + i] = (Me, 0); // main pack, never offered
|
||||
w.Snapshot[SidePack] = (Me, 0); w.Containers.Add(SidePack);
|
||||
for (uint i = 1; i <= 4; i++) w.Snapshot[0x80004000 + i] = (SidePack, 0); // side pack contents
|
||||
w.Snapshot[0x80005000] = (0, Me); // worn
|
||||
w.Cached.Add(0x80003001); // already appraised
|
||||
w.Snapshot[0x80006000] = (0, 0); // a ground item: not ours
|
||||
long loginAt = 100_000;
|
||||
|
||||
RunUntil(d, w, loginAt + AutoIdPolicy.DeferMs - 100, loginAt);
|
||||
Check(w.Sent.Count == 0, $"no sweep before login + DeferMs, sent {w.Sent.Count}");
|
||||
RunUntil(d, w, loginAt + AutoIdPolicy.DeferMs + 10_000, loginAt);
|
||||
var ids = w.Sent.Select(s => s.Id).ToHashSet();
|
||||
Check(Enumerable.Range(2, 7).All(i => ids.Contains(0x80003000 + (uint)i)), "the uncached main-pack items are swept");
|
||||
Check(!ids.Contains(0x80003001), "a cached one is not");
|
||||
Check(Enumerable.Range(1, 4).All(i => ids.Contains(0x80004000 + (uint)i)), "the side pack's contents are swept");
|
||||
Check(ids.Contains(SidePack) && ids.Contains(0x80005000), "the side pack itself and worn gear are swept");
|
||||
Check(!ids.Contains(0x80006000), "a ground item is not");
|
||||
// Only containers are looked into: the player, then the side pack; never a sword.
|
||||
Check(w.Looked.All(x => x == Me || x == SidePack) && w.Looked.Contains(SidePack),
|
||||
$"only containers looked into ({string.Join(",", w.Looked.Distinct().Select(x => x.ToString("X8")))})");
|
||||
Check(d.Swept == 13, $"13 swept (7 main pack, the side pack, its 4, 1 worn), got {d.Swept}");
|
||||
int count = w.Sent.Count;
|
||||
|
||||
// The same login: no second sweep, even with new uncached items.
|
||||
w.Snapshot[0x80007000] = (Me, 0);
|
||||
RunUntil(d, w, w.Now + 5_000, loginAt);
|
||||
Check(w.Sent.Count == count, "one sweep per login");
|
||||
|
||||
// A hot reload (MarkAlreadyComplete) stamps a new login: swept again after its defer.
|
||||
long reloadAt = w.Now;
|
||||
RunUntil(d, w, reloadAt + AutoIdPolicy.DeferMs + 2_000, reloadAt);
|
||||
Check(w.Sent.Any(s => s.Id == 0x80007000), "a new login stamp sweeps again");
|
||||
|
||||
// All mode never sweeps (it appraises every create anyway).
|
||||
var w2 = new FakeWorld { Now = 100_000, Warm = true };
|
||||
w2.Snapshot[0x80008000] = (Me, 0);
|
||||
var d2 = new AutoIdDrain(w2);
|
||||
RunUntil(d2, w2, 100_000 + AutoIdPolicy.DeferMs + 5_000, 100_000, AutoIdMode.All);
|
||||
Check(w2.Sent.Count == 0, "All mode: no sweep");
|
||||
}
|
||||
|
||||
private static void DrainUnknownWaitsForSnapshotThenGivesUp()
|
||||
{
|
||||
_case = "drain unknown";
|
||||
// Warm snapshot, object not in it: dropped at MinAgeMs (a creature gone, or never placed).
|
||||
var w = new FakeWorld { Now = 1_000_000, Warm = true };
|
||||
var d = new AutoIdDrain(w);
|
||||
d.Offer(0x80009001, w.Now);
|
||||
RunUntil(d, w, w.Now + AutoIdPolicy.MinAgeMs + 200, loginAt: 1);
|
||||
Check(d.PendingCount == 0 && d.SkipMode == 1, $"warm snapshot: dropped after MinAgeMs (pending {d.PendingCount}, skipMode {d.SkipMode})");
|
||||
|
||||
// Cold snapshot that never warms: kept until UnknownMaxWaitMs, then dropped.
|
||||
var c = new FakeWorld { Now = 1_000_000 };
|
||||
var e = new AutoIdDrain(c);
|
||||
e.Offer(0x80009002, c.Now);
|
||||
long t0 = c.Now;
|
||||
RunUntil(e, c, t0 + AutoIdPolicy.UnknownMaxWaitMs - 200, loginAt: 1);
|
||||
Check(e.PendingCount == 1, "cold snapshot: still kept just before UnknownMaxWaitMs");
|
||||
RunUntil(e, c, t0 + AutoIdPolicy.UnknownMaxWaitMs + 200, loginAt: 1);
|
||||
Check(e.PendingCount == 0 && e.SkipMode == 1, "cold snapshot: dropped at UnknownMaxWaitMs");
|
||||
}
|
||||
|
||||
// A refused enqueue (transition, full ring) is kept, not counted, and sent later.
|
||||
private static void DrainRefusedEnqueueIsKept()
|
||||
{
|
||||
_case = "drain refused enqueue";
|
||||
var w = new FakeWorld { Now = 1_000_000, Warm = true, Refuse = true };
|
||||
var d = new AutoIdDrain(w);
|
||||
for (uint i = 1; i <= 3; i++) { w.Snapshot[0x8000A000 + i] = (0, 0); d.Offer(0x8000A000 + i, w.Now); }
|
||||
int sent = d.Tick(Ctx(w, 1, AutoIdMode.All), 0);
|
||||
Check(sent == 0, $"a refused send is not counted as sent, got {sent}");
|
||||
Check(d.PendingCount == 3, $"all three kept, pending {d.PendingCount}");
|
||||
Check(d.Refused == 1, $"the first refusal ends the tick's sending (1 refused), got {d.Refused}");
|
||||
w.Now += 100;
|
||||
w.Refuse = false;
|
||||
sent = d.Tick(Ctx(w, 1, AutoIdMode.All), 0);
|
||||
Check(sent == 3 && w.Sent.Count == 3 && d.PendingCount == 0, $"sent once accepted (sent {sent}, pending {d.PendingCount})");
|
||||
|
||||
// The inventory cap counts only a send that was taken.
|
||||
var v = new FakeWorld { Now = 1_000_000, Warm = true, Refuse = true };
|
||||
var e = new AutoIdDrain(v);
|
||||
v.Snapshot[0x8000B001] = (Me, 0); v.Snapshot[0x8000B002] = (Me, 0);
|
||||
e.Offer(0x8000B001, 0); e.Offer(0x8000B002, 0);
|
||||
e.Tick(Ctx(v, 1), 0);
|
||||
v.Refuse = false; v.Now += 100;
|
||||
e.Tick(Ctx(v, 1), 0);
|
||||
Check(v.Sent.Count == 1, $"a refused inventory send did not use up the rate slot (sent {v.Sent.Count})");
|
||||
}
|
||||
|
||||
// All mode keeps the old unbounded backlog; Limited is capped; _incoming is bounded.
|
||||
private static void DrainBounds()
|
||||
{
|
||||
_case = "drain bounds";
|
||||
var w = new FakeWorld { Now = 1_000, Warm = true };
|
||||
var d = new AutoIdDrain(w);
|
||||
int n = AutoIdDrain.MaxPendingLimited + 500;
|
||||
for (uint i = 0; i < n; i++) { w.Snapshot[0x81000000 + i] = (0, 0); d.Offer(0x81000000 + i, w.Now); }
|
||||
d.Tick(Ctx(w, 0, AutoIdMode.All), AutoIdDrain.MaxPerTick); // no sends: just take them in
|
||||
Check(d.PendingCount == n && d.Overflow == 0, $"All: all {n} pending (got {d.PendingCount}, overflow {d.Overflow})");
|
||||
|
||||
var l = new FakeWorld { Now = 1_000, Warm = true };
|
||||
var e = new AutoIdDrain(l);
|
||||
for (uint i = 0; i < n; i++) e.Offer(0x82000000 + i, l.Now);
|
||||
e.Tick(Ctx(l, 0, AutoIdMode.Limited), AutoIdDrain.MaxPerTick);
|
||||
Check(e.PendingCount == AutoIdDrain.MaxPendingLimited && e.Overflow == 500,
|
||||
$"Limited: capped at {AutoIdDrain.MaxPendingLimited}, 500 counted (got {e.PendingCount}, {e.Overflow})");
|
||||
|
||||
// While the drain is held (a long death), _incoming keeps the newest MaxIncoming.
|
||||
var h = new FakeWorld { Now = 1_000, Warm = true };
|
||||
var f = new AutoIdDrain(h);
|
||||
int over = 37;
|
||||
for (uint i = 0; i < AutoIdDrain.MaxIncoming + over; i++) f.Offer(0x83000000 + i, h.Now);
|
||||
Check(f.IncomingDropped == over, $"{over} oldest dropped and counted, got {f.IncomingDropped}");
|
||||
f.Tick(Ctx(h, 0, AutoIdMode.All), AutoIdDrain.MaxPerTick);
|
||||
Check(f.PendingCount == AutoIdDrain.MaxIncoming, $"the newest {AutoIdDrain.MaxIncoming} kept, got {f.PendingCount}");
|
||||
}
|
||||
|
||||
// The pack waits through combat (a cast or attack in flight); kept, not
|
||||
// dropped; an open container is not held.
|
||||
private static void DrainCombatHoldsInventory()
|
||||
{
|
||||
_case = "drain combat";
|
||||
const uint Chest = 0x80000A00, Loot = 0x80000A01;
|
||||
var w = new FakeWorld { Now = 1_000_000, Warm = true };
|
||||
var d = new AutoIdDrain(w);
|
||||
for (uint i = 1; i <= 3; i++) { w.Snapshot[0x8000C000 + i] = (Me, 0); d.Offer(0x8000C000 + i, w.Now - 10_000); }
|
||||
w.Snapshot[Loot] = (Chest, 0); d.Offer(Loot, w.Now - 10_000);
|
||||
AutoIdDrain.Context Fight(bool combat) => new()
|
||||
{
|
||||
Now = w.Now, Mode = AutoIdMode.Limited, PlayerId = Me, OpenContainer = Chest, OpenedAtMs = w.Now - 5_000,
|
||||
SettleUntilMs = 0, LoginCompleteAtMs = 1, CombatBusy = combat,
|
||||
};
|
||||
for (int k = 0; k < 50; k++) { d.Tick(Fight(true), 0); w.Now += 100; }
|
||||
Check(w.Sent.Count == 1 && w.Sent[0].Id == Loot, $"in combat: only the open container's item is sent ({w.Sent.Count})");
|
||||
Check(d.PendingCount == 3, $"the pack is kept, pending {d.PendingCount}");
|
||||
Check(d.SkipCombat == 3, $"each counted once, got {d.SkipCombat}");
|
||||
for (int k = 0; k < 20; k++) { d.Tick(Fight(false), 0); w.Now += 100; }
|
||||
Check(w.Sent.Count == 4 && d.PendingCount == 0, $"out of combat: the pack goes out (sent {w.Sent.Count}, pending {d.PendingCount})");
|
||||
Check(w.Sent.Skip(1).All(s => s.Who == IdRequester.AutoIdInventory), "as autoid-inventory");
|
||||
}
|
||||
|
||||
// A sweep that overflowed the pending list is not marked done; it runs again once
|
||||
// there is room, and every pack item is still sent.
|
||||
private static void DrainSweepRetriesAfterOverflow()
|
||||
{
|
||||
_case = "drain sweep overflow";
|
||||
long loginAt = 100_000, sweepAt = loginAt + AutoIdPolicy.DeferMs;
|
||||
var pack = new List<uint>();
|
||||
for (uint i = 1; i <= 5; i++) pack.Add(0x8000D000 + i);
|
||||
|
||||
// Full: the sweep does not walk (no overflow counted) and is not done.
|
||||
var w = new FakeWorld { Now = sweepAt, Warm = true };
|
||||
foreach (uint id in pack) w.Snapshot[id] = (Me, 0);
|
||||
var d = new AutoIdDrain(w);
|
||||
for (uint i = 0; i < AutoIdDrain.MaxPendingLimited; i++) d.Offer(0x84000000 + i, w.Now); // young, unplaced: they wait
|
||||
d.Tick(Ctx(w, loginAt), AutoIdDrain.MaxPerTick);
|
||||
Check(d.PendingCount == AutoIdDrain.MaxPendingLimited && d.Swept == 0 && d.Overflow == 0,
|
||||
$"pending full: no sweep yet (pending {d.PendingCount}, swept {d.Swept}, overflow {d.Overflow})");
|
||||
RunUntil(d, w, sweepAt + 20_000, loginAt);
|
||||
Check(pack.All(id => w.Sent.Any(s => s.Id == id)), $"swept once there was room: all 5 sent ({w.Sent.Count})");
|
||||
|
||||
// Partly full: 2 fit, 3 overflow; the sweep runs again and the other 3 go out too.
|
||||
var v = new FakeWorld { Now = sweepAt, Warm = true };
|
||||
foreach (uint id in pack) v.Snapshot[id] = (Me, 0);
|
||||
var e = new AutoIdDrain(v);
|
||||
for (uint i = 0; i < AutoIdDrain.MaxPendingLimited - 2; i++) e.Offer(0x85000000 + i, v.Now);
|
||||
e.Tick(Ctx(v, loginAt), AutoIdDrain.MaxPerTick);
|
||||
Check(e.Swept == 2 && e.Overflow == 3, $"2 fit, 3 overflowed (swept {e.Swept}, overflow {e.Overflow})");
|
||||
RunUntil(e, v, sweepAt + 20_000, loginAt);
|
||||
Check(pack.All(id => v.Sent.Any(s => s.Id == id)), $"the overflowed 3 are swept again and sent ({v.Sent.Count})");
|
||||
Check(e.Swept == 5, $"5 swept in all, got {e.Swept}");
|
||||
}
|
||||
}
|
||||
347
tools/EngineRobustnessTests/AutoIdLimitTests.cs
Normal file
347
tools/EngineRobustnessTests/AutoIdLimitTests.cs
Normal file
|
|
@ -0,0 +1,347 @@
|
|||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.Net;
|
||||
using V = RynthCore.Engine.Compatibility.AutoIdPolicy.Verdict;
|
||||
using C = RynthCore.Engine.Compatibility.AutoIdPolicy.Class;
|
||||
|
||||
namespace EngineRobustnessTests;
|
||||
|
||||
/// <summary>
|
||||
/// AutoId limiting: the mode decision table, the post-transition defer, where an
|
||||
/// object is, and the engine-send marker that tags every engine 0xC8.
|
||||
/// </summary>
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunAutoIdLimitTests()
|
||||
{
|
||||
AutoIdDecisionTable();
|
||||
AutoIdDecisionSpotCases();
|
||||
AutoIdDeferWindow();
|
||||
AutoIdLoginDefer();
|
||||
AutoIdInventoryRate();
|
||||
AutoIdClassify();
|
||||
AutoIdModeParse();
|
||||
IdMarkerScopes();
|
||||
IdMarkerRidesTheQueue();
|
||||
IdHeartbeatNames();
|
||||
}
|
||||
|
||||
// ---- the decision table ---------------------------------------------------------
|
||||
|
||||
private static readonly long[] Ages = { 0, AutoIdPolicy.MinAgeMs - 1, AutoIdPolicy.MinAgeMs, 60_000, AutoIdPolicy.UnknownMaxWaitMs - 1, AutoIdPolicy.UnknownMaxWaitMs };
|
||||
|
||||
/// <summary>The rule as the spec states it, written out independently of AutoIdPolicy.Decide.</summary>
|
||||
private static V Expected(AutoIdMode mode, C cls, long age, bool defer, bool openedAfter, bool fresh, bool cached, bool rateOk, bool warm, bool combat)
|
||||
{
|
||||
if (mode == AutoIdMode.Off) return V.SkipMode;
|
||||
if (mode == AutoIdMode.All) return cls == C.Target && fresh ? V.SkipFresh : V.Send;
|
||||
bool young = age < AutoIdPolicy.MinAgeMs;
|
||||
return cls switch
|
||||
{
|
||||
C.Target => fresh ? V.SkipFresh : V.Send,
|
||||
C.Container => fresh ? V.SkipFresh : young ? V.WaitAge : defer && !openedAfter ? V.WaitDefer : V.Send,
|
||||
C.Inventory => cached ? V.SkipFresh : young ? V.WaitAge : defer ? V.WaitDefer : combat ? V.WaitCombat : !rateOk ? V.WaitRate : V.Send,
|
||||
C.Unknown => young ? V.WaitAge : !warm && age < AutoIdPolicy.UnknownMaxWaitMs ? V.WaitSnapshot : V.SkipMode,
|
||||
_ => V.SkipMode,
|
||||
};
|
||||
}
|
||||
|
||||
private static void AutoIdDecisionTable()
|
||||
{
|
||||
_case = "autoid decision table";
|
||||
int rows = 0, wrong = 0;
|
||||
foreach (AutoIdMode mode in Enum.GetValues<AutoIdMode>())
|
||||
foreach (C cls in Enum.GetValues<C>())
|
||||
foreach (long age in Ages)
|
||||
foreach (bool defer in new[] { false, true })
|
||||
foreach (bool opened in new[] { false, true })
|
||||
foreach (bool cached in new[] { false, true })
|
||||
foreach (bool fresh in new[] { false, true })
|
||||
foreach (bool rateOk in new[] { false, true })
|
||||
foreach (bool warm in new[] { false, true })
|
||||
foreach (bool combat in new[] { false, true })
|
||||
{
|
||||
if (fresh && !cached) continue; // fresh implies cached
|
||||
rows++;
|
||||
V got = AutoIdPolicy.Decide(mode, cls, age, defer, opened, fresh, cached, rateOk, warm, combat);
|
||||
V want = Expected(mode, cls, age, defer, opened, fresh, cached, rateOk, warm, combat);
|
||||
if (got != want && wrong++ < 10)
|
||||
Check(false, $"{mode} {cls} age={age} defer={defer} opened={opened} cached={cached} fresh={fresh} rateOk={rateOk} warm={warm} combat={combat}: want {want}, got {got}");
|
||||
}
|
||||
Check(wrong == 0, $"{wrong} of {rows} rows wrong");
|
||||
Check(rows == 3 * 5 * 6 * 2 * 2 * 3 * 2 * 2 * 2, $"row count {rows}");
|
||||
}
|
||||
|
||||
/// <summary>The same rules as named cases, so a mutation is easy to read off a failure.</summary>
|
||||
private static void AutoIdDecisionSpotCases()
|
||||
{
|
||||
_case = "autoid spot cases";
|
||||
const long Old = 10_000;
|
||||
// Off: nothing at all, the selected target included.
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Off, C.Target, 0, false, false, false, false) == V.SkipMode, "off skips the target");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Off, C.Container, Old, false, true, false, false) == V.SkipMode, "off skips an open container");
|
||||
// All: the old behaviour.
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.All, C.World, 0, true, false, false, false) == V.Send, "all sends a fresh-born world object, deferred or not");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.All, C.Target, 0, false, false, true, true) == V.SkipFresh, "all keeps the target fresh skip");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.All, C.Inventory, 0, false, false, false, true) == V.Send, "all sends a cached pack item (old behaviour)");
|
||||
// Limited: target.
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, true, false, false, false) == V.Send, "target exempt from age and defer");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, false, false, true, true) == V.SkipFresh, "target fresh skip");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, false, false, false, true) == V.Send, "target cached but stale is sent");
|
||||
// Limited: world never.
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.World, Old, false, false, false, false) == V.SkipMode, "creature / ground item skipped");
|
||||
// Limited: container.
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, AutoIdPolicy.MinAgeMs - 1, false, true, false, false) == V.WaitAge, "container item waits for the minimum age");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, AutoIdPolicy.MinAgeMs, false, false, false, false) == V.Send, "container item at the minimum age is sent");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, true, false, false, false) == V.WaitDefer, "container opened before the settle ended waits out the defer");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, true, true, false, false) == V.Send, "container opened after the settle is not deferred");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, false, false, true, true) == V.SkipFresh, "fresh container item skipped");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, false, false, false, true) == V.Send, "stale cached container item re-appraised");
|
||||
// Limited: inventory.
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, Old, false, false, false, true) == V.SkipFresh, "pack item with any cached appraisal skipped");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, AutoIdPolicy.MinAgeMs - 1, false, false, false, false) == V.WaitAge, "pack item waits for the minimum age");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, Old, true, true, false, false) == V.WaitDefer, "pack item deferred (the opened-container exemption does not apply)");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, Old, false, false, false, false) == V.Send, "uncached pack item sent");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, Old, false, false, false, false, inventoryRateOk: false) == V.WaitRate, "pack item over the rate waits");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, false, true, false, false, inventoryRateOk: false) == V.Send, "the rate cap is the inventory's only (container)");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, true, false, false, false, inventoryRateOk: false) == V.Send, "the rate cap never holds the selected target");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.All, C.Inventory, 0, false, false, false, false, inventoryRateOk: false) == V.Send, "All mode keeps the old behaviour (no cap)");
|
||||
// Combat: only the pack waits; the target and an open container do not.
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, Old, false, false, false, false, combatBusy: true) == V.WaitCombat, "pack item waits while in combat");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, false, false, false, false, combatBusy: true) == V.Send, "combat never holds the selected target");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, Old, false, true, false, false, combatBusy: true) == V.Send, "combat never holds an open container");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.All, C.Inventory, Old, false, false, false, false, combatBusy: true) == V.Send, "All mode: no combat hold (old behaviour)");
|
||||
// What counts as combat: a cast or an attack, never a selection alone (a hunting bot
|
||||
// nearly always has one, and the pack would never be appraised).
|
||||
Check(!AutoIdPolicy.InCombat(0x80001234, 0, false), "target selected, no cast, no attack: not combat");
|
||||
bool selectedOnly = AutoIdPolicy.InCombat(0x80001234, 0, false);
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, Old, false, false, false, false, combatBusy: selectedOnly) == V.Send, "target selected, no cast, no attack: the pack sends");
|
||||
Check(AutoIdPolicy.InCombat(0, 1, false), "a cast in flight is combat");
|
||||
Check(AutoIdPolicy.InCombat(0, 0, true), "an attack running is combat");
|
||||
Check(!AutoIdPolicy.InCombat(0, 0, false), "nothing at all: not combat");
|
||||
// Limited: unknown place.
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Unknown, 100, false, false, false, false) == V.WaitAge, "unknown place waits while young");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Unknown, Old, false, false, false, false) == V.SkipMode, "still unknown when old: skipped");
|
||||
Check(AutoIdPolicy.DefaultMode == AutoIdMode.Limited, "default mode is Limited");
|
||||
}
|
||||
|
||||
// ---- the post-transition defer -----------------------------------------------------
|
||||
|
||||
private static void AutoIdDeferWindow()
|
||||
{
|
||||
_case = "autoid defer window";
|
||||
const long D = AutoIdPolicy.DeferMs;
|
||||
const long S = WorldTransitionState.SettleMs;
|
||||
// Login completed long before (at 1); every time below is shifted past its defer.
|
||||
const long B = 1_000_000;
|
||||
static bool Def(long now, long settle, bool inTransition) =>
|
||||
AutoIdPolicy.InDefer(now + B, settle == 0 ? 0 : settle + B, 1, inTransition);
|
||||
|
||||
// No transition yet: nothing is deferred.
|
||||
var w = new WorldTransitionState();
|
||||
w.Sample(1000, dead: false, portaling: false, landblock: 0xA9B4);
|
||||
Check(!Def(1000, w.SettleUntilMs, w.InTransition(1000)), "no transition, no defer");
|
||||
|
||||
// Walking into the next landblock never defers.
|
||||
w.Sample(2000, false, false, 0xAAB4);
|
||||
w.Sample(3000, false, false, 0xAAB5);
|
||||
Check(w.SettleUntilMs == 0, "an adjacent walk sets no settle window");
|
||||
Check(!Def(3000, w.SettleUntilMs, w.InTransition(3000)), "adjacent walk: no defer");
|
||||
|
||||
// A portal: deferred through portal space, the settle window, and DeferMs after it.
|
||||
w.Sample(10_000, false, true, 0xAAB5);
|
||||
Check(Def(10_000, w.SettleUntilMs, w.InTransition(10_000)), "in portal space: deferred");
|
||||
w.Sample(12_000, false, false, 0x0007);
|
||||
long settleEnd = w.SettleUntilMs;
|
||||
Check(settleEnd == 12_000 + S, $"settle ends {S} ms after the portal exit, got {settleEnd}");
|
||||
Check(Def(settleEnd + D - 1, settleEnd, w.InTransition(settleEnd + D - 1)), "deferred until DeferMs after the settle");
|
||||
Check(!Def(settleEnd + D, settleEnd, w.InTransition(settleEnd + D)), "not deferred at DeferMs after the settle");
|
||||
|
||||
// A container opened after the settle ended is exempt; one opened before is not.
|
||||
Check(AutoIdPolicy.OpenedAfterSettle(settleEnd + 1, settleEnd), "opened after the settle: exempt");
|
||||
Check(!AutoIdPolicy.OpenedAfterSettle(settleEnd - 1, settleEnd), "opened during the settle: not exempt");
|
||||
Check(!AutoIdPolicy.OpenedAfterSettle(0, settleEnd), "never opened: not exempt");
|
||||
|
||||
// Death defers too.
|
||||
var d = new WorldTransitionState();
|
||||
d.Sample(1000, false, false, 0x1234);
|
||||
d.Sample(2000, true, false, 0x1234);
|
||||
d.Sample(3000, false, false, 0x1234);
|
||||
Check(Def(3000 + S + D - 1, d.SettleUntilMs, false), "death: deferred");
|
||||
Check(!Def(3000 + S + D, d.SettleUntilMs, false), "death: defer ends");
|
||||
|
||||
// A landblock jump without portal space defers.
|
||||
var j = new WorldTransitionState();
|
||||
j.Sample(1000, false, false, 0x00AE);
|
||||
j.Sample(1100, false, false, 0xA9B4);
|
||||
Check(Def(1100 + S + D - 1, j.SettleUntilMs, false), "landblock jump: deferred");
|
||||
|
||||
// A PlayerTeleport message (a recall into the next landblock) defers.
|
||||
var t = new WorldTransitionState();
|
||||
t.Sample(1000, false, false, 0x1234);
|
||||
t.OnTeleportMessage(5000);
|
||||
Check(Def(5000 + S + D - 1, t.SettleUntilMs, false), "teleport message: deferred");
|
||||
Check(!Def(5000 + S + D, t.SettleUntilMs, false), "teleport message: defer ends");
|
||||
|
||||
// In a transition right now: deferred whatever the settle time says.
|
||||
Check(Def(1, 0, inTransition: true), "in a transition: deferred");
|
||||
}
|
||||
|
||||
// ---- login is a transition (a client crashed in the login create burst) ----------------
|
||||
|
||||
private static void AutoIdLoginDefer()
|
||||
{
|
||||
_case = "autoid login defer";
|
||||
const long D = AutoIdPolicy.DeferMs;
|
||||
const long Login = 500_000;
|
||||
|
||||
// Before login completes (the create burst): everything background is deferred.
|
||||
Check(AutoIdPolicy.InDefer(Login - 1, 0, 0, false), "login not complete: deferred");
|
||||
Check(AutoIdPolicy.InDefer(10_000_000, 0, 0, false), "login never completed: still deferred");
|
||||
// After: DeferMs past login-complete, exactly like the post-teleport defer.
|
||||
Check(AutoIdPolicy.InDefer(Login, 0, Login, false), "at login-complete: deferred");
|
||||
Check(AutoIdPolicy.InDefer(Login + D - 1, 0, Login, false), "deferred until DeferMs after login");
|
||||
Check(!AutoIdPolicy.InDefer(Login + D, 0, Login, false), "not deferred at DeferMs after login");
|
||||
// The later of login and the last settle window decides.
|
||||
Check(AutoIdPolicy.TransitionEndMs(0, Login) == Login, "no transition yet: the login is the last one");
|
||||
Check(AutoIdPolicy.TransitionEndMs(Login + 9_000, Login) == Login + 9_000, "a portal after login: the portal's settle");
|
||||
Check(AutoIdPolicy.TransitionEndMs(Login - 9_000, Login) == Login, "a portal before login: the login");
|
||||
Check(AutoIdPolicy.InDefer(Login + 9_000 + D - 1, Login + 9_000, Login, false), "portal after login: its own defer");
|
||||
Check(AutoIdPolicy.InDefer(Login + D - 1, Login - 9_000, Login, false), "a settle before login does not shorten the login defer");
|
||||
// A container the player opens after login-complete is exempt; one opened before it is not.
|
||||
Check(AutoIdPolicy.OpenedAfterSettle(Login + 1, AutoIdPolicy.TransitionEndMs(0, Login)), "opened after login: exempt");
|
||||
Check(!AutoIdPolicy.OpenedAfterSettle(Login - 1, AutoIdPolicy.TransitionEndMs(0, Login)), "opened before login completed: not exempt");
|
||||
// The decision during the login defer: pack and container items wait, the target does not.
|
||||
bool inDefer = AutoIdPolicy.InDefer(Login + 1_000, 0, Login, false);
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, 60_000, inDefer, false, false, false) == V.WaitDefer, "login: pack item waits");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Container, 60_000, inDefer, false, false, false) == V.WaitDefer, "login: container item waits");
|
||||
Check(AutoIdPolicy.Decide(AutoIdMode.Limited, C.Target, 0, inDefer, false, false, false) == V.Send, "login: the selected target is exempt");
|
||||
}
|
||||
|
||||
private static void AutoIdInventoryRate()
|
||||
{
|
||||
_case = "autoid inventory rate";
|
||||
const long I = AutoIdPolicy.InventoryMinIntervalMs;
|
||||
Check(I == 200, "5 a second");
|
||||
Check(AutoIdPolicy.InventoryRateAllows(1_000, 0), "the first send is allowed");
|
||||
Check(!AutoIdPolicy.InventoryRateAllows(1_000 + I - 1, 1_000), "not again inside the interval");
|
||||
Check(AutoIdPolicy.InventoryRateAllows(1_000 + I, 1_000), "again at the interval");
|
||||
|
||||
// Simulate the drain: a 100 ms timer, 3 sends a tick at most, 50 uncached pack items
|
||||
// past their age and the defer. Sends per second never pass 5.
|
||||
long last = 0;
|
||||
int pending = 50;
|
||||
var sendTimes = new List<long>();
|
||||
for (long now = 100; now <= 20_000 && pending > 0; now += 100)
|
||||
{
|
||||
int sentThisTick = 0;
|
||||
for (int k = 0; k < pending && sentThisTick < 3; k++)
|
||||
{
|
||||
bool ok = AutoIdPolicy.InventoryRateAllows(now, last);
|
||||
V v = AutoIdPolicy.Decide(AutoIdMode.Limited, C.Inventory, 60_000, false, false, false, false, ok);
|
||||
if (v != V.Send) continue;
|
||||
last = now;
|
||||
sentThisTick++;
|
||||
sendTimes.Add(now);
|
||||
}
|
||||
pending -= sentThisTick;
|
||||
}
|
||||
Check(pending == 0, $"all 50 sent eventually, {pending} left");
|
||||
int worst = 0;
|
||||
foreach (long t0 in sendTimes)
|
||||
worst = Math.Max(worst, sendTimes.Count(t => t >= t0 && t < t0 + 1_000));
|
||||
Check(worst <= 5, $"at most 5 inventory sends in any second, got {worst}");
|
||||
Check(worst == 5, $"and the cap is reached (5), got {worst}");
|
||||
}
|
||||
|
||||
// ---- where an object is ------------------------------------------------------------
|
||||
|
||||
private static void AutoIdClassify()
|
||||
{
|
||||
_case = "autoid classify";
|
||||
const uint Me = 0x50000001, Corpse = 0x80000100, Pack = 0x80000200, Monster = 0x80000300, Chest = 0x80000400;
|
||||
Check(AutoIdPolicy.Classify(false, Me, Corpse, Corpse, 0, 0) == C.Unknown, "not in the snapshot: unknown");
|
||||
Check(AutoIdPolicy.Classify(true, Me, 0, Me, 0, 0) == C.Inventory, "in the main pack");
|
||||
Check(AutoIdPolicy.Classify(true, Me, 0, 0, Me, 0) == C.Inventory, "worn");
|
||||
Check(AutoIdPolicy.Classify(true, Me, 0, Pack, 0, Me) == C.Inventory, "in a side pack");
|
||||
Check(AutoIdPolicy.Classify(true, Me, Pack, Pack, 0, Me) == C.Inventory, "in an opened own side pack: inventory");
|
||||
Check(AutoIdPolicy.Classify(true, Me, Corpse, Corpse, 0, 0) == C.Container, "in the open corpse");
|
||||
Check(AutoIdPolicy.Classify(true, Me, Chest, Pack, 0, Chest) == C.Container, "in a pack inside the open chest");
|
||||
Check(AutoIdPolicy.Classify(true, Me, Chest, Corpse, 0, 0) == C.World, "in a corpse that is not open");
|
||||
Check(AutoIdPolicy.Classify(true, Me, 0, 0, 0, 0) == C.World, "on the ground, nothing open");
|
||||
Check(AutoIdPolicy.Classify(true, Me, Corpse, 0, 0, 0) == C.World, "on the ground while a corpse is open (container 0 is not the open one)");
|
||||
Check(AutoIdPolicy.Classify(true, Me, Corpse, 0, Monster, 0) == C.World, "wielded by a monster");
|
||||
Check(AutoIdPolicy.Classify(true, 0, 0, 0, 0, 0) == C.World, "player unknown: nothing is inventory");
|
||||
}
|
||||
|
||||
private static void AutoIdModeParse()
|
||||
{
|
||||
_case = "autoid mode parse";
|
||||
Check(AutoIdPolicy.TryParseMode("ALL", out AutoIdMode m) && m == AutoIdMode.All, "all");
|
||||
Check(AutoIdPolicy.TryParseMode(" limited ", out m) && m == AutoIdMode.Limited, "limited");
|
||||
Check(AutoIdPolicy.TryParseMode("off", out m) && m == AutoIdMode.Off, "off");
|
||||
Check(!AutoIdPolicy.TryParseMode("sometimes", out m) && m == AutoIdPolicy.DefaultMode, "unknown: false, default");
|
||||
foreach (AutoIdMode mode in Enum.GetValues<AutoIdMode>())
|
||||
Check(AutoIdPolicy.TryParseMode(AutoIdPolicy.Name(mode), out m) && m == mode, $"{mode} round-trips by name");
|
||||
foreach (AutoIdMode mode in Enum.GetValues<AutoIdMode>())
|
||||
Check(AutoIdPolicy.TryParseMode(mode.ToString(), out m) && m == mode, $"{mode} round-trips as engine.json writes it");
|
||||
}
|
||||
|
||||
// ---- the engine-send marker --------------------------------------------------------
|
||||
|
||||
private static void IdMarkerScopes()
|
||||
{
|
||||
_case = "id marker";
|
||||
Check(EngineSendMarker.Current == IdRequester.None, "no marker outside a scope");
|
||||
using (EngineSendMarker.Enter(IdRequester.Plugin))
|
||||
{
|
||||
Check(EngineSendMarker.Current == IdRequester.Plugin, "marked inside");
|
||||
using (EngineSendMarker.Enter(IdRequester.AutoIdContainer))
|
||||
Check(EngineSendMarker.Current == IdRequester.AutoIdContainer, "nested scope");
|
||||
Check(EngineSendMarker.Current == IdRequester.Plugin, "outer marker restored");
|
||||
|
||||
IdRequester seenElsewhere = IdRequester.Self;
|
||||
var th = new Thread(() => seenElsewhere = EngineSendMarker.Current);
|
||||
th.Start();
|
||||
th.Join();
|
||||
Check(seenElsewhere == IdRequester.None, "another thread is not marked (thread-local)");
|
||||
}
|
||||
Check(EngineSendMarker.Current == IdRequester.None, "cleared after the scope");
|
||||
try
|
||||
{
|
||||
using (EngineSendMarker.Enter(IdRequester.Ui))
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
catch (InvalidOperationException) { }
|
||||
Check(EngineSendMarker.Current == IdRequester.None, "cleared after an exception");
|
||||
}
|
||||
|
||||
private static void IdMarkerRidesTheQueue()
|
||||
{
|
||||
_case = "id marker queue";
|
||||
var q = new PendingIdQueue(8);
|
||||
q.Enqueue(1, 1000, 1, MergeMax, 0, (byte)IdRequester.AutoIdContainer);
|
||||
q.Enqueue(2, 1000, 1, MergeMax, 0, (byte)IdRequester.Plugin);
|
||||
Check(q.Enqueue(1, 1100, 1, MergeMax, 0, (byte)IdRequester.Plugin) == PendingIdQueue.Result.Merged, "merged");
|
||||
Check(q.TryDequeue(out var a) && a.Source == (byte)IdRequester.AutoIdContainer, "the requester rides with the entry; a merge keeps the first");
|
||||
Check(q.TryDequeue(out var b) && b.Source == (byte)IdRequester.Plugin, "second entry's requester");
|
||||
q.Enqueue(3, 1200, 1, MergeMax);
|
||||
Check(q.TryDequeue(out var c) && c.Source == 0, "unmarked stays None");
|
||||
}
|
||||
|
||||
private static void IdHeartbeatNames()
|
||||
{
|
||||
_case = "id heartbeat names";
|
||||
foreach (IdRequester who in Enum.GetValues<IdRequester>())
|
||||
{
|
||||
string s = IdRequesters.Short(who) + "=";
|
||||
foreach (string bad in new[] { "fps=", "plug=", "login=", "qd=" })
|
||||
Check(!s.Contains(bad) && !bad.Contains(s), $"{who}: \"{s}\" vs {bad}");
|
||||
if (who != IdRequester.None)
|
||||
Check(IdRequesters.Label((uint)who).Length > 0, $"{who} has a flight label");
|
||||
}
|
||||
Check(IdRequesters.Label(0) == "" && IdRequesters.Label(99) == "", "no label for none or an unknown code");
|
||||
var regex = new System.Text.RegularExpressions.Regex(@"hb #\d+ .*?fps=(\d+) .*?plug=(\d+)/s .*?login=(\d)(?:.*?qd=(\d+))?");
|
||||
string sample = "autoid 60s: mode=limited sent tgt=1 ctr=2 inv=0 wld=0 plg=5 slf=0 ui=0 cli=3 tot=11 skip mode=900 age=4 defer=0 fresh=1 pend=2";
|
||||
Check(!regex.IsMatch(sample), "the minute line does not match the launcher's heartbeat regex");
|
||||
}
|
||||
}
|
||||
55
tools/EngineRobustnessTests/EngineRobustnessTests.csproj
Normal file
55
tools/EngineRobustnessTests/EngineRobustnessTests.csproj
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for the engine-robustness pass, the pure parts compiled in:
|
||||
PendingIdQueue.cs the RequestId slot merges a pending appraisal for the same object
|
||||
AutoIdEligibility.cs no re-appraisal within 10 min of a client release; server delete
|
||||
re-arms; the map stays bounded
|
||||
MainThreadFreezeRule.cs plugin ticks pause while AC's main thread is frozen
|
||||
WorldTransitionState.cs queued game actions are held through a death / portal / landblock
|
||||
jump, then stale ones dropped while stops and cancels still run
|
||||
AddressSpace.cs the largest-free-block fold (and one live walk of this process)
|
||||
ActionRing.cs the action ring itself: teardown reserve, refusal in a transition
|
||||
CastStopRules.cs a cast waits for a movement stop queued at or before it
|
||||
MutatorGate.cs queue-or-call for every mutator (plus a source scan of the call sites)
|
||||
ReleasedObjectRetention identify data kept 10 min after a client release
|
||||
DumpInProgressRule.cs the launcher holds its wedge kill while an OOM dump is written (capped)
|
||||
CastSlot.cs the cast slot refuses during a world transition
|
||||
CrashExitRule.cs which exit codes are crash exits (not ExitProcess(-1))
|
||||
AutoIdPolicy.cs AutoIdMode All/Limited/Off: class, minimum age, post-transition defer
|
||||
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
|
||||
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)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>EngineRobustnessTests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\PendingIdQueue.cs" Link="Engine\PendingIdQueue.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AutoIdEligibility.cs" Link="Engine\AutoIdEligibility.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\MainThreadFreezeRule.cs" Link="Engine\MainThreadFreezeRule.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\WorldTransitionState.cs" Link="Engine\WorldTransitionState.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AddressSpace.cs" Link="Engine\AddressSpace.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\ActionRing.cs" Link="Engine\ActionRing.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\CastStopRules.cs" Link="Engine\CastStopRules.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\MutatorGate.cs" Link="Engine\MutatorGate.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\ReleasedObjectRetention.cs" Link="Engine\ReleasedObjectRetention.cs" />
|
||||
<Compile Include="..\..\src\Shared\DumpInProgressRule.cs" Link="Shared\DumpInProgressRule.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\CastSlot.cs" Link="Engine\CastSlot.cs" />
|
||||
<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\Net\IdRequester.cs" Link="Engine\IdRequester.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PumpGuards.cs" Link="Engine\PumpGuards.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
417
tools/EngineRobustnessTests/Program.cs
Normal file
417
tools/EngineRobustnessTests/Program.cs
Normal file
|
|
@ -0,0 +1,417 @@
|
|||
using RynthCore.Engine;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
|
||||
namespace EngineRobustnessTests;
|
||||
|
||||
/// <summary>
|
||||
/// The pure decision parts of the engine-robustness pass. Every clock is a plain
|
||||
/// number; nothing touches AC.
|
||||
/// </summary>
|
||||
internal static partial class Program
|
||||
{
|
||||
private static int _checks, _failed;
|
||||
private static string _case = "";
|
||||
|
||||
private static int Main()
|
||||
{
|
||||
QueueMergesSameObject();
|
||||
QueueDoesNotMergeAcrossLoginOrWhenStale();
|
||||
QueueFullStillMerges();
|
||||
|
||||
EligibilityCreateAndDuplicate();
|
||||
EligibilityWindowAfterClientRelease();
|
||||
EligibilityServerDeleteReArms();
|
||||
EligibilityUncachedIsAppraised();
|
||||
EligibilityReleaseBeforeSendRecordsNothing();
|
||||
EligibilityMapStaysBounded();
|
||||
PriorityFreshRule();
|
||||
|
||||
FreezeRule();
|
||||
PauseTracker();
|
||||
|
||||
TransitionHoldsWhileDead();
|
||||
TransitionLandblockJumpWithoutPortalHolds();
|
||||
TransitionAdjacentCrossingDoesNotHold();
|
||||
TransitionPortalHolds();
|
||||
TransitionShortTeleportToAdjacentLandblockHolds();
|
||||
TransitionDiagonalAndBorderWalksNeverHold();
|
||||
TransitionTwoLandblockJumpHolds();
|
||||
TransitionDrainHoldThenStopsSurvive();
|
||||
|
||||
AddressSpaceFold();
|
||||
|
||||
RunRingAndGateTests();
|
||||
|
||||
RunAutoIdLimitTests();
|
||||
RunAutoIdDrainTests();
|
||||
|
||||
RunPumpGuardTests();
|
||||
|
||||
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}");
|
||||
}
|
||||
|
||||
// ---- fix 1: the RequestId slot merges ---------------------------------------------
|
||||
|
||||
private const long MergeMax = 15_000;
|
||||
|
||||
private static void QueueMergesSameObject()
|
||||
{
|
||||
_case = "queue merge";
|
||||
var q = new PendingIdQueue(8);
|
||||
Check(q.Enqueue(0x80000001, 1000, 1, MergeMax) == PendingIdQueue.Result.Queued, "first request queued");
|
||||
Check(q.Enqueue(0x80000002, 1010, 1, MergeMax) == PendingIdQueue.Result.Queued, "other object queued");
|
||||
Check(q.Enqueue(0x80000001, 1100, 1, MergeMax) == PendingIdQueue.Result.Merged, "same object merged");
|
||||
Check(q.Enqueue(0x80000001, 1200, 1, MergeMax) == PendingIdQueue.Result.Merged, "merged again");
|
||||
Check(q.Count == 2, $"two pending, got {q.Count}");
|
||||
Check(q.MergedTotal == 2, $"two merges counted, got {q.MergedTotal}");
|
||||
Check(q.TryDequeue(out var a) && a.Id == 0x80000001 && a.At == 1000, "FIFO head is the first request, original time");
|
||||
Check(q.TryDequeue(out var b) && b.Id == 0x80000002, "then the second object");
|
||||
Check(!q.TryDequeue(out _), "empty");
|
||||
// Once sent (dequeued), a new request for the same object queues again.
|
||||
Check(q.Enqueue(0x80000001, 1300, 1, MergeMax) == PendingIdQueue.Result.Queued, "re-queued after the send");
|
||||
}
|
||||
|
||||
private static void QueueDoesNotMergeAcrossLoginOrWhenStale()
|
||||
{
|
||||
_case = "queue no merge";
|
||||
var q = new PendingIdQueue(8);
|
||||
q.Enqueue(7, 1000, 1, MergeMax);
|
||||
Check(q.Enqueue(7, 1100, 2, MergeMax) == PendingIdQueue.Result.Queued, "a new login's request is not absorbed by the old one");
|
||||
Check(q.Enqueue(7, 1200, 1, MergeMax) == PendingIdQueue.Result.Merged,
|
||||
"a later epoch-1 request still merges into the epoch-1 entry");
|
||||
Check(q.Enqueue(7, 1300, 2, MergeMax) == PendingIdQueue.Result.Merged,
|
||||
"and an epoch-2 one into the epoch-2 entry");
|
||||
Check(q.Count == 2, $"one entry per login, got {q.Count}");
|
||||
var r = new PendingIdQueue(8);
|
||||
r.Enqueue(9, 1000, 1, MergeMax);
|
||||
Check(r.Enqueue(9, 1000 + MergeMax + 1, 1, MergeMax) == PendingIdQueue.Result.Queued, "a stale pending entry takes no merge");
|
||||
Check(r.Count == 2, "both kept");
|
||||
}
|
||||
|
||||
private static void QueueFullStillMerges()
|
||||
{
|
||||
_case = "queue full";
|
||||
var q = new PendingIdQueue(3);
|
||||
q.Enqueue(1, 0, 1, MergeMax); q.Enqueue(2, 0, 1, MergeMax); q.Enqueue(3, 0, 1, MergeMax);
|
||||
Check(q.Enqueue(4, 1, 1, MergeMax) == PendingIdQueue.Result.Full, "a new object is refused when full");
|
||||
Check(q.Enqueue(2, 1, 1, MergeMax) == PendingIdQueue.Result.Merged, "a pending object still merges when full");
|
||||
// Wrap-around: dequeue one, add one, order holds.
|
||||
q.TryDequeue(out _);
|
||||
q.Enqueue(5, 2, 1, MergeMax);
|
||||
var order = new List<uint>();
|
||||
while (q.TryDequeue(out var it)) order.Add(it.Id);
|
||||
Check(string.Join(",", order) == "2,3,5", $"FIFO across the wrap, got {string.Join(",", order)}");
|
||||
}
|
||||
|
||||
// ---- fix 3: re-eligibility ---------------------------------------------------------
|
||||
|
||||
private const long Min = 60_000;
|
||||
|
||||
private static void EligibilityCreateAndDuplicate()
|
||||
{
|
||||
_case = "eligibility create";
|
||||
var e = new AutoIdEligibility();
|
||||
Check(e.OnCreate(10, 1000, false) == AutoIdEligibility.CreateDecision.Appraise, "a new object is appraised");
|
||||
Check(e.OnCreate(10, 1001, false) == AutoIdEligibility.CreateDecision.SkipDuplicate, "a second create while live is a duplicate");
|
||||
Check(e.IsLive(10), "live");
|
||||
e.OnClientRelease(10);
|
||||
Check(!e.IsLive(10), "released");
|
||||
Check(e.IsLive(999), "an untracked id counts as live (the drain sends it)");
|
||||
}
|
||||
|
||||
private static void EligibilityWindowAfterClientRelease()
|
||||
{
|
||||
_case = "eligibility window";
|
||||
var e = new AutoIdEligibility();
|
||||
e.OnCreate(10, 0, false);
|
||||
e.OnSent(10, 1000);
|
||||
e.OnClientRelease(10);
|
||||
Check(e.OnCreate(10, 1000 + 1 * Min, true) == AutoIdEligibility.CreateDecision.SkipRecent, "re-created 1 min later, cached: skipped");
|
||||
e.OnClientRelease(10);
|
||||
Check(e.OnCreate(10, 1000 + 9 * Min, true) == AutoIdEligibility.CreateDecision.SkipRecent, "9 min later: still skipped");
|
||||
e.OnClientRelease(10);
|
||||
Check(e.OnCreate(10, 1000 + 10 * Min, true) == AutoIdEligibility.CreateDecision.Appraise, "10 min later: appraised again");
|
||||
}
|
||||
|
||||
private static void EligibilityServerDeleteReArms()
|
||||
{
|
||||
_case = "eligibility server delete";
|
||||
var e = new AutoIdEligibility();
|
||||
e.OnCreate(20, 0, false);
|
||||
e.OnSent(20, 1000);
|
||||
e.OnServerDelete(20);
|
||||
e.OnClientRelease(20);
|
||||
Check(e.OnCreate(20, 2000, true) == AutoIdEligibility.CreateDecision.Appraise, "server delete then re-create inside the window: appraised");
|
||||
// Client release first, server delete after: same result.
|
||||
e.OnSent(20, 3000);
|
||||
e.OnClientRelease(20);
|
||||
e.OnServerDelete(20);
|
||||
Check(e.OnCreate(20, 4000, true) == AutoIdEligibility.CreateDecision.Appraise, "release then server delete: appraised");
|
||||
}
|
||||
|
||||
private static void EligibilityUncachedIsAppraised()
|
||||
{
|
||||
_case = "eligibility uncached";
|
||||
var e = new AutoIdEligibility();
|
||||
e.OnCreate(30, 0, false);
|
||||
e.OnSent(30, 1000);
|
||||
e.OnClientRelease(30);
|
||||
Check(e.OnCreate(30, 2000, false) == AutoIdEligibility.CreateDecision.Appraise, "nothing cached any more: appraised even inside the window");
|
||||
}
|
||||
|
||||
private static void EligibilityReleaseBeforeSendRecordsNothing()
|
||||
{
|
||||
_case = "eligibility unsent";
|
||||
var e = new AutoIdEligibility();
|
||||
e.OnCreate(40, 0, false);
|
||||
e.OnClientRelease(40); // released before the drain sent its appraisal
|
||||
Check(e.OnCreate(40, 500, true) == AutoIdEligibility.CreateDecision.Appraise, "never sent: the next create is appraised");
|
||||
}
|
||||
|
||||
private static void EligibilityMapStaysBounded()
|
||||
{
|
||||
_case = "eligibility bound";
|
||||
var e = new AutoIdEligibility(10 * Min, 100);
|
||||
for (uint i = 1; i <= 100; i++) e.OnCreate(i, 0, false);
|
||||
Check(e.Count == 100, $"100 tracked, got {e.Count}");
|
||||
Check(e.OnCreate(101, 0, false) == AutoIdEligibility.CreateDecision.Appraise, "past the bound a create is still appraised");
|
||||
Check(e.Count == 100 && e.UntrackedAdmits == 1, $"but not tracked (count {e.Count}, untracked {e.UntrackedAdmits})");
|
||||
Check(e.Prune(1000) == 0, "all live: nothing pruned");
|
||||
|
||||
// 80 of them appraised (sent at different times) and released, all inside the window.
|
||||
for (uint i = 1; i <= 80; i++) { e.OnSent(i, 1000 + i); e.OnClientRelease(i); }
|
||||
int removed = e.Prune(2 * Min);
|
||||
Check(e.Count <= 75, $"pruned to three quarters of the bound, count {e.Count} (removed {removed})");
|
||||
bool liveKept = true;
|
||||
for (uint i = 81; i <= 100; i++) liveKept &= e.IsLive(i) && e.OnCreate(i, 2 * Min, true) == AutoIdEligibility.CreateDecision.SkipDuplicate;
|
||||
Check(liveKept, "the 20 live entries are never pruned");
|
||||
// The newest-sent released entries survive the age passes before the oldest.
|
||||
Check(e.OnCreate(80, 2 * Min, true) == AutoIdEligibility.CreateDecision.SkipRecent, "the most recently sent released entry survived");
|
||||
|
||||
// Outside the window everything released goes.
|
||||
var f = new AutoIdEligibility(10 * Min, 100);
|
||||
for (uint i = 1; i <= 50; i++) { f.OnCreate(i, 0, false); f.OnSent(i, 1); f.OnClientRelease(i); }
|
||||
f.Prune(11 * Min);
|
||||
Check(f.Count == 0, $"expired released entries are pruned, count {f.Count}");
|
||||
}
|
||||
|
||||
private static void PriorityFreshRule()
|
||||
{
|
||||
_case = "priority fresh";
|
||||
long now = 1_800_000_000;
|
||||
Check(AutoIdEligibility.IsAppraisalFresh(true, now - 60, now, 10 * Min), "cached, 1 min old: fresh (skip)");
|
||||
Check(!AutoIdEligibility.IsAppraisalFresh(true, now - 601, now, 10 * Min), "cached, 10 min+ old: stale (appraise)");
|
||||
Check(!AutoIdEligibility.IsAppraisalFresh(false, now - 60, now, 10 * Min), "not cached: appraise");
|
||||
Check(!AutoIdEligibility.IsAppraisalFresh(true, 0, now, 10 * Min), "no receive time: appraise");
|
||||
}
|
||||
|
||||
// ---- fix 4: the plugin pump pauses while AC is frozen --------------------------------
|
||||
|
||||
private static void FreezeRule()
|
||||
{
|
||||
_case = "freeze rule";
|
||||
const long T = 4000;
|
||||
Check(!MainThreadFreezeRule.IsFrozen(100_000, 0, false, 0, T), "no beat yet: not frozen");
|
||||
Check(!MainThreadFreezeRule.IsFrozen(100_000, 99_000, true, 0, T), "beat 1 s ago: running");
|
||||
Check(MainThreadFreezeRule.IsFrozen(100_000, 96_000, true, 0, T), "beat 4 s ago: frozen (the hang watchdog's threshold)");
|
||||
Check(MainThreadFreezeRule.IsFrozen(100_000, 99_900, true, 1, T), "a main-thread message box: frozen at once");
|
||||
Check(MainThreadFreezeRule.IsFrozen(100_000, 0, false, 1, T), "a message box before the first beat: frozen");
|
||||
}
|
||||
|
||||
private static void PauseTracker()
|
||||
{
|
||||
_case = "pause tracker";
|
||||
var t = new PumpPauseTracker();
|
||||
Check(t.Update(false, 1000) == PumpPauseTracker.Transition.None && !t.Paused, "running");
|
||||
Check(t.Update(true, 2000) == PumpPauseTracker.Transition.Paused && t.Paused, "pauses");
|
||||
Check(t.Update(true, 2016) == PumpPauseTracker.Transition.None, "stays paused");
|
||||
Check(t.TicksSkippedThisPause == 2, $"2 ticks skipped, got {t.TicksSkippedThisPause}");
|
||||
Check(t.TotalPausedMs(5000) == 3000, $"3000 ms paused in progress, got {t.TotalPausedMs(5000)}");
|
||||
Check(t.Update(false, 14000) == PumpPauseTracker.Transition.Resumed && !t.Paused, "resumes");
|
||||
Check(t.FinishedPausedMs == 12000 && t.TotalPausedMs(20000) == 12000, $"12 s in total, got {t.FinishedPausedMs}");
|
||||
t.Update(true, 30000); t.Update(false, 30500);
|
||||
Check(t.Pauses == 2 && t.FinishedPausedMs == 12500 && t.TicksSkippedTotal == 3, "second pause adds up");
|
||||
}
|
||||
|
||||
// ---- the world-transition gate (coordinator items c and g) --------------------------
|
||||
|
||||
private static WorldTransitionState Started(uint landblock = 0x00AE)
|
||||
{
|
||||
var s = new WorldTransitionState();
|
||||
s.Sample(1000, false, false, landblock);
|
||||
return s;
|
||||
}
|
||||
|
||||
private static void TransitionHoldsWhileDead()
|
||||
{
|
||||
_case = "transition dead";
|
||||
var s = Started();
|
||||
Check(!s.InTransition(1100), "alive and still: no transition");
|
||||
Check(s.Decide(1100, 1050, false) == WorldTransitionState.Verdict.Run, "work runs normally");
|
||||
var edges = s.Sample(2000, true, false, 0x00AE);
|
||||
Check((edges & WorldTransitionState.Edge.Died) != 0, "death edge");
|
||||
Check(s.Decide(2000, 1900, false) == WorldTransitionState.Verdict.Hold, "a cast queued before the death is held");
|
||||
Check(s.Decide(2000, 1900, true) == WorldTransitionState.Verdict.Hold, "a stop is held too (never run into the death)");
|
||||
s.Sample(9000, false, false, 0x00AE); // revived
|
||||
Check(s.InTransition(9000 + WorldTransitionState.SettleMs - 1), "settle window after revival");
|
||||
Check(!s.InTransition(9000 + WorldTransitionState.SettleMs), "window ends");
|
||||
}
|
||||
|
||||
private static void TransitionLandblockJumpWithoutPortalHolds()
|
||||
{
|
||||
_case = "transition jump";
|
||||
// A real case: a death recall jumped 0x00AE -> 0xA9B4 with no portal-space edge.
|
||||
var s = Started(0x00AE);
|
||||
var edges = s.Sample(5000, false, false, 0xA9B4);
|
||||
Check((edges & WorldTransitionState.Edge.LandblockJump) != 0, "jump edge");
|
||||
Check(s.InTransition(5000) && s.InTransition(5000 + WorldTransitionState.SettleMs - 1), "the jump alone starts the settle window");
|
||||
Check(s.Decide(6000, 4900, false) == WorldTransitionState.Verdict.Hold, "queued work is held after the jump");
|
||||
Check(WorldTransitionState.IsJump(0x00AE, 0xA9B4) && !WorldTransitionState.IsJump(0xA9B4, 0xA9B5) && !WorldTransitionState.IsJump(0xA9B4, 0xAAB5),
|
||||
"adjacent (including diagonal) is not a jump");
|
||||
}
|
||||
|
||||
private static void TransitionAdjacentCrossingDoesNotHold()
|
||||
{
|
||||
_case = "transition adjacent";
|
||||
var s = Started(0xA9B4);
|
||||
var edges = s.Sample(5000, false, false, 0xA9B5);
|
||||
Check(edges == WorldTransitionState.Edge.None, "walking into the next landblock: no edge");
|
||||
Check(!s.InTransition(5000) && s.Decide(5000, 4990, false) == WorldTransitionState.Verdict.Run, "and no hold");
|
||||
}
|
||||
|
||||
private static void TransitionPortalHolds()
|
||||
{
|
||||
_case = "transition portal";
|
||||
var s = Started();
|
||||
s.Sample(2000, false, true, 0x00AE);
|
||||
Check(s.Decide(2500, 1990, false) == WorldTransitionState.Verdict.Hold, "held in portal space");
|
||||
s.Sample(4000, false, false, 0x00AE);
|
||||
Check(s.InTransition(4000 + WorldTransitionState.SettleMs - 1), "settle window after portal exit");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A recall or portal into the NEXT landblock (a lifestone just over the border): no
|
||||
/// non-adjacent jump, but teleport_in_progress (the portaling flag) is the signal, and the
|
||||
/// full settle follows it.
|
||||
/// </summary>
|
||||
private static void TransitionShortTeleportToAdjacentLandblockHolds()
|
||||
{
|
||||
_case = "transition short teleport";
|
||||
var s = Started(0xA9B4);
|
||||
s.Sample(2000, false, true, 0xA9B4); // teleport_in_progress set
|
||||
s.Sample(2500, false, true, 0xA9B5); // lands one landblock over
|
||||
var edges = s.Sample(3000, false, false, 0xA9B5);
|
||||
Check((edges & WorldTransitionState.Edge.PortalExited) != 0, "portal exit edge");
|
||||
Check(s.Decide(3000 + WorldTransitionState.SettleMs - 1, 2900, false) == WorldTransitionState.Verdict.Hold,
|
||||
"full 5 s settle after a teleport to an adjacent landblock");
|
||||
Check(s.Decide(3000 + WorldTransitionState.SettleMs, 2900, false) == WorldTransitionState.Verdict.Drop,
|
||||
"then the stale action is dropped");
|
||||
}
|
||||
|
||||
/// <summary>Walking across a border never gates, not even for a tick.</summary>
|
||||
private static void TransitionDiagonalAndBorderWalksNeverHold()
|
||||
{
|
||||
_case = "transition walk";
|
||||
var s = Started(0xA9B4);
|
||||
long now = 2000;
|
||||
foreach (uint lb in new uint[] { 0xA9B5, 0xAAB6, 0xA9B5, 0xA8B4, 0xA9B4, 0xAAB3 })
|
||||
{
|
||||
var edges = s.Sample(now, false, false, lb);
|
||||
Check(edges == WorldTransitionState.Edge.None, $"walk into 0x{lb:X4}: no edge");
|
||||
Check(!s.InTransition(now) && s.Decide(now, now - 1, false) == WorldTransitionState.Verdict.Run, $"walk into 0x{lb:X4}: runs at once");
|
||||
now += 16;
|
||||
}
|
||||
// A cell read of 0 (pose not available for a tick) is not a jump to 0x0000 and back.
|
||||
s.Sample(now, false, false, 0);
|
||||
var back = s.Sample(now + 16, false, false, 0xAAB3);
|
||||
Check(back == WorldTransitionState.Edge.None && !s.InTransition(now + 16), "an unknown pose for one tick is not a jump");
|
||||
}
|
||||
|
||||
private static void TransitionTwoLandblockJumpHolds()
|
||||
{
|
||||
_case = "transition two-block jump";
|
||||
var sx = Started(0xA9B4);
|
||||
Check((sx.Sample(2000, false, false, 0xABB4) & WorldTransitionState.Edge.LandblockJump) != 0 && sx.InTransition(2000), "2 apart in x: a teleport");
|
||||
var sy = Started(0xA9B4);
|
||||
Check((sy.Sample(2000, false, false, 0xA9B2) & WorldTransitionState.Edge.LandblockJump) != 0 && sy.InTransition(2000), "2 apart in y: a teleport");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The drain the gate sits in (AcMainThreadQueue.Drain): a FIFO walked head to tail, each
|
||||
/// entry's verdict asked of the gate. While held, nothing runs and nothing is lost; once
|
||||
/// the transition ends the stale cast and use are dropped, and both stops run, in order.
|
||||
/// </summary>
|
||||
private static void TransitionDrainHoldThenStopsSurvive()
|
||||
{
|
||||
_case = "transition drain";
|
||||
var s = Started();
|
||||
var fifo = new List<(string What, long At, bool Teardown)>
|
||||
{
|
||||
("cast", 1500, false),
|
||||
("autorun-off", 1600, true),
|
||||
("use", 1700, false),
|
||||
("cancel-attack", 1800, true),
|
||||
};
|
||||
s.Sample(2000, true, false, 0x00AE); // dies
|
||||
|
||||
var ran = new List<string>(); var dropped = new List<string>();
|
||||
long revivedAt = 0;
|
||||
bool queuedNew = false;
|
||||
for (long now = 2000; now < 20_000; now += 16)
|
||||
{
|
||||
// Game tick sample: dead until 9 s, alive after.
|
||||
s.Sample(now, now < 9000, false, 0x00AE);
|
||||
if (now >= 9000 && revivedAt == 0) revivedAt = now;
|
||||
if (!queuedNew && revivedAt != 0 && now >= revivedAt + WorldTransitionState.SettleMs + 500)
|
||||
{
|
||||
fifo.Add(("cast-new", now, false)); // queued after the window
|
||||
queuedNew = true;
|
||||
}
|
||||
Drain(s, now, fifo, ran, dropped);
|
||||
if (revivedAt == 0 || now < revivedAt + WorldTransitionState.SettleMs)
|
||||
Check(ran.Count == 0 && dropped.Count == 0 && fifo.Count == 4, $"held: nothing runs or drops (t={now})");
|
||||
}
|
||||
Check(dropped.SequenceEqual(new[] { "cast", "use" }), $"stale cast and use dropped, got [{string.Join(",", dropped)}]");
|
||||
Check(ran.SequenceEqual(new[] { "autorun-off", "cancel-attack", "cast-new" }),
|
||||
$"stops run in queue order as a group, then new work, got [{string.Join(",", ran)}]");
|
||||
Check(fifo.Count == 0, "queue empty");
|
||||
}
|
||||
|
||||
private static void Drain(WorldTransitionState s, long now, List<(string What, long At, bool Teardown)> fifo,
|
||||
List<string> ran, List<string> dropped)
|
||||
{
|
||||
while (fifo.Count > 0)
|
||||
{
|
||||
var e = fifo[0];
|
||||
var v = s.Decide(now, e.At, e.Teardown);
|
||||
if (v == WorldTransitionState.Verdict.Hold) return;
|
||||
fifo.RemoveAt(0);
|
||||
if (v == WorldTransitionState.Verdict.Drop) dropped.Add(e.What);
|
||||
else ran.Add(e.What);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- fix 7: largest free block -------------------------------------------------------
|
||||
|
||||
private static void AddressSpaceFold()
|
||||
{
|
||||
_case = "address space";
|
||||
ulong free = 0, largest = 0;
|
||||
AddressSpace.Accumulate(true, 10, ref free, ref largest);
|
||||
AddressSpace.Accumulate(false, 500, ref free, ref largest);
|
||||
AddressSpace.Accumulate(true, 40, ref free, ref largest);
|
||||
AddressSpace.Accumulate(true, 30, ref free, ref largest);
|
||||
Check(free == 80 && largest == 40, $"free 80 largest 40, got {free}/{largest}");
|
||||
var (f, l) = AddressSpace.FreeAndLargestMb();
|
||||
Check(f > 0 && l > 0 && l <= f, $"live walk of this process: free {f} MB, largest {l} MB");
|
||||
}
|
||||
}
|
||||
89
tools/EngineRobustnessTests/PumpGuardTests.cs
Normal file
89
tools/EngineRobustnessTests/PumpGuardTests.cs
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
using System.Text.RegularExpressions;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace EngineRobustnessTests;
|
||||
|
||||
/// <summary>
|
||||
/// TickAll's step guards and the pump-dispatch line for the hang watchdog (Plugins/PumpGuards.cs),
|
||||
/// plus a source scan that TickAll catches every one of its own steps.
|
||||
/// </summary>
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunPumpGuardTests()
|
||||
{
|
||||
StepFaultLogCadence();
|
||||
StepFaultLogText();
|
||||
PumpDispatchLine();
|
||||
TickAllGuardsEveryStep();
|
||||
}
|
||||
|
||||
private static void StepFaultLogCadence()
|
||||
{
|
||||
_case = "step fault log cadence";
|
||||
var log = new StepFaultLog((int)TickStep.Count);
|
||||
Check(log.Record((int)TickStep.Nav3DCommit, out int c1) && c1 == 1, "the first throw is logged");
|
||||
int logged = 0;
|
||||
for (int i = 2; i <= 2500; i++)
|
||||
if (log.Record((int)TickStep.Nav3DCommit, out _)) logged++;
|
||||
Check(logged == 2, $"then only every {StepFaultLog.RepeatEvery}th (1000, 2000): got {logged}");
|
||||
Check(log.CountOf((int)TickStep.Nav3DCommit) == 2500, "every throw counted");
|
||||
Check(log.Record((int)TickStep.FreezeCheck, out int other) && other == 1, "steps are counted apart");
|
||||
}
|
||||
|
||||
private static void StepFaultLogText()
|
||||
{
|
||||
_case = "step fault log text";
|
||||
string first = StepFaultLog.Describe(TickStep.DropFailedOwners, "InvalidOperationException", "Collection was modified", 1);
|
||||
Check(first.Contains("DropFailedOwners threw InvalidOperationException: Collection was modified"), "names the step and the exception");
|
||||
Check(first.Contains("the pump carries on"), "says the pump carries on");
|
||||
string later = StepFaultLog.Describe(TickStep.DropFailedOwners, "InvalidOperationException", "x", 3000);
|
||||
Check(later.Contains("3000 times"), "a repeat carries the count");
|
||||
}
|
||||
|
||||
private static void PumpDispatchLine()
|
||||
{
|
||||
_case = "pump dispatch line";
|
||||
Check(PumpDispatchInfo.Describe("RynthAi", "Tick", 1_000, 13_375) == "inside RynthAi Tick for 12375 ms",
|
||||
"names plugin, export and how long");
|
||||
Check(PumpDispatchInfo.Describe(null, "Tick", 1_000, 13_375) == null, "no plugin call in progress: nothing");
|
||||
Check(PumpDispatchInfo.Describe("RynthAi", "Tick", 0, 13_375) == null, "no start time: nothing");
|
||||
Check(PumpDispatchInfo.Describe("RynthAi", "Tick", 13_000, 13_375) == null, "a call under a second old is normal: nothing");
|
||||
Check(PumpDispatchInfo.Describe("RynthNav", null, 1_000, 3_000) == "inside RynthNav call for 2000 ms", "unnamed export");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TickAll may let nothing of its own escape: each step is wrapped and reported through
|
||||
/// TickStepFailed, every TickStep is used, and the plugin Tick is dispatched as "Tick".
|
||||
/// </summary>
|
||||
private static void TickAllGuardsEveryStep()
|
||||
{
|
||||
_case = "TickAll guards";
|
||||
string? plugins = FindRepoDir(Path.Combine("src", "RynthCore.Engine", "Plugins"));
|
||||
Check(plugins != null, "found src\\RynthCore.Engine\\Plugins by walking up");
|
||||
if (plugins == null) return;
|
||||
string src = File.ReadAllText(Path.Combine(plugins, "PluginManager.cs")).Replace("\r\n", "\n");
|
||||
int start = src.IndexOf("public static void TickAll()", StringComparison.Ordinal);
|
||||
Check(start >= 0, "TickAll found");
|
||||
if (start < 0) return;
|
||||
int end = src.IndexOf("\n }\n", start, StringComparison.Ordinal);
|
||||
string body = end > start ? src[start..end] : src[start..];
|
||||
|
||||
foreach (TickStep step in Enum.GetValues<TickStep>())
|
||||
{
|
||||
if (step == TickStep.Count) continue;
|
||||
Check(body.Contains($"TickStepFailed(TickStep.{step}, ex)"), $"{step} is caught and reported");
|
||||
}
|
||||
Check(body.Contains("EnterDispatch(plugin, \"Tick\")"), "the plugin Tick is dispatched as \"Tick\" (the hang watchdog's line)");
|
||||
Check(!Regex.IsMatch(body, @"catch\s*\{\s*\}"), "no silent catch {} left in TickAll");
|
||||
// The engine calls outside the plugin loop each sit inside a try.
|
||||
foreach (string call in new[] { "MainThreadFreeze.ShouldPausePluginTick()", "D3D9.Nav3DRenderer.ClearFrame()",
|
||||
"ScriptWindowRegistry.DropFailedOwners()", "D3D9.Nav3DRenderer.CommitFrame()" })
|
||||
{
|
||||
int at = body.IndexOf(call, StringComparison.Ordinal);
|
||||
string line = at < 0 ? "" : body[body.LastIndexOf('\n', at)..at];
|
||||
Check(at >= 0 && line.Contains("try {"), $"{call} is called inside try {{ }}");
|
||||
}
|
||||
string watchdog = File.ReadAllText(Path.Combine(Path.GetDirectoryName(plugins)!, "MainThreadHangWatchdog.cs"));
|
||||
Check(watchdog.Contains("PluginManager.DescribePumpDispatch()"), "the hang report names the plugin call the pump is inside");
|
||||
}
|
||||
}
|
||||
470
tools/EngineRobustnessTests/RingAndGateTests.cs
Normal file
470
tools/EngineRobustnessTests/RingAndGateTests.cs
Normal file
|
|
@ -0,0 +1,470 @@
|
|||
using System.Text.RegularExpressions;
|
||||
using RynthCore.Engine;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Install;
|
||||
|
||||
namespace EngineRobustnessTests;
|
||||
|
||||
/// <summary>Checks for the action ring, the mutator gate, appraisal retention, the dump rules and the cast slot.</summary>
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunRingAndGateTests()
|
||||
{
|
||||
RingTakesAStopWhenFullOfStarts();
|
||||
RingRefusesStartsDuringATransition();
|
||||
RingStopRunsFirstAfterTheWindow();
|
||||
CastStopFindsAnOutOfOrderStop();
|
||||
|
||||
GateTruthTable();
|
||||
GateCallSitesAllUseTheSameShape();
|
||||
|
||||
RequestIdNeverMergesIntoAHeldEntry();
|
||||
|
||||
ReleasedDataKeptSoRecreateSkips();
|
||||
ReleasedDataExpiresAndServerDeleteEvicts();
|
||||
|
||||
TeleportMessageStartsTheWindow();
|
||||
|
||||
OutOfMemoryBoxMatchesOnlyAcsBox();
|
||||
LauncherHoldsTheKillDuringADump();
|
||||
|
||||
// The cast slot, the dump hold cap and the crash exits
|
||||
CastRefusedDuringATransition();
|
||||
RingPeekAtWalksWithoutRemoving();
|
||||
EnqueueCastPassesTheTransitionState();
|
||||
LauncherDumpHoldIsCapped();
|
||||
CrashExitExcludesExitMinusOne();
|
||||
CrashExitPathsFlushTheCrashLog();
|
||||
}
|
||||
|
||||
// ---- the action ring (the real ActionRing, the one AcMainThreadQueue uses) --------
|
||||
|
||||
private readonly record struct Act(string What, long At, bool Teardown);
|
||||
|
||||
private static void RingTakesAStopWhenFullOfStarts()
|
||||
{
|
||||
_case = "ring reserve";
|
||||
var ring = new ActionRing<Act>(256, 32);
|
||||
int queued = 0, full = 0;
|
||||
for (int i = 0; i < 300; i++)
|
||||
{
|
||||
var r = ring.TryEnqueue(new Act("start", 1000, false), teardown: false, inTransition: false);
|
||||
if (r == ActionRing<Act>.Admit.Queued) queued++;
|
||||
else if (r == ActionRing<Act>.Admit.Full) full++;
|
||||
}
|
||||
Check(queued == 224 && full == 76, $"300 starts: 224 taken, the rest refused at the reserve (got {queued}/{full})");
|
||||
Check(ring.TryEnqueue(new Act("stop", 1001, true), teardown: true, inTransition: false) == ActionRing<Act>.Admit.Queued,
|
||||
"a stop is still taken");
|
||||
for (int i = 0; i < 31; i++)
|
||||
ring.TryEnqueue(new Act("cancel", 1002, true), teardown: true, inTransition: false);
|
||||
Check(ring.Count == 256, $"the reserve fills only with teardown (count {ring.Count})");
|
||||
Check(ring.TryEnqueue(new Act("stop", 1003, true), teardown: true, inTransition: false) == ActionRing<Act>.Admit.Full,
|
||||
"a completely full ring refuses even a stop");
|
||||
}
|
||||
|
||||
private static void RingRefusesStartsDuringATransition()
|
||||
{
|
||||
_case = "ring transition";
|
||||
var ring = new ActionRing<Act>(256, 32);
|
||||
int rejected = 0;
|
||||
for (int i = 0; i < 300; i++)
|
||||
if (ring.TryEnqueue(new Act("start", 2000, false), teardown: false, inTransition: true) == ActionRing<Act>.Admit.RejectedTransition)
|
||||
rejected++;
|
||||
Check(rejected == 300 && ring.Count == 0, $"300 starts during a hold are refused, none stored (rejected {rejected}, count {ring.Count})");
|
||||
Check(ring.TryEnqueue(new Act("stop", 2001, true), teardown: true, inTransition: true) == ActionRing<Act>.Admit.Queued,
|
||||
"a stop during the hold is taken");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The flood scenario against the real ring: a bot floods starts before the transition is
|
||||
/// seen (the ring fills to the reserve), the player dies, 300 more starts arrive during the
|
||||
/// hold, then a stop. Nothing runs during the hold; after it the stale starts are dropped and
|
||||
/// the stops are the first things to run.
|
||||
/// </summary>
|
||||
private static void RingStopRunsFirstAfterTheWindow()
|
||||
{
|
||||
_case = "ring drain";
|
||||
var ring = new ActionRing<Act>(256, 32);
|
||||
var s = new WorldTransitionState();
|
||||
s.Sample(900, false, false, 0x00AE);
|
||||
for (int i = 0; i < 300; i++)
|
||||
ring.TryEnqueue(new Act("start", 1000, false), false, s.InTransition(1000));
|
||||
s.Sample(1500, true, false, 0x00AE); // dies
|
||||
for (int i = 0; i < 300; i++)
|
||||
ring.TryEnqueue(new Act("start-held", 2000, false), false, s.InTransition(2000));
|
||||
var stopAdmit = ring.TryEnqueue(new Act("stop", 2500, true), true, s.InTransition(2500));
|
||||
Check(stopAdmit == ActionRing<Act>.Admit.Queued, $"the stop is accepted ({stopAdmit})");
|
||||
|
||||
var ran = new List<string>();
|
||||
int dropped = 0;
|
||||
bool heldClean = true;
|
||||
for (long now = 1500; now < 20_000; now += 16)
|
||||
{
|
||||
s.Sample(now, now < 9000, false, 0x00AE);
|
||||
int before = ring.Count;
|
||||
if (s.CheckHolding(now)) { heldClean &= ring.Count == before; continue; } // Drain's early return
|
||||
while (ring.TryDequeue(out Act e))
|
||||
{
|
||||
var v = s.Decide(now, e.At, e.Teardown);
|
||||
if (v == WorldTransitionState.Verdict.Drop) dropped++;
|
||||
else ran.Add(e.What);
|
||||
}
|
||||
}
|
||||
Check(heldClean, "nothing leaves the ring while held");
|
||||
Check(ran.Count > 0 && ran[0] == "stop", $"the stop runs first after the window (ran [{string.Join(",", ran.Take(3))}])");
|
||||
Check(ran.Count == 1 && dropped == 224, $"the 224 stale starts are dropped, nothing else runs (ran {ran.Count}, dropped {dropped})");
|
||||
}
|
||||
|
||||
// ---- the cast drain's stop check (the real CastStopRules over the real ActionRing) ------
|
||||
|
||||
/// <summary>
|
||||
/// A stop queued at or before the cast is found wherever it sits in the ring, including
|
||||
/// behind an entry stamped after the cast (two producers can land out of time order).
|
||||
/// </summary>
|
||||
private static void CastStopFindsAnOutOfOrderStop()
|
||||
{
|
||||
_case = "cast stop check";
|
||||
static bool Any(ActionRing<Act> r, long at) =>
|
||||
CastStopRules.AnyStopAtOrBefore(r, at, static e => e.At, static e => e.Teardown);
|
||||
|
||||
var empty = new ActionRing<Act>(8, 2);
|
||||
Check(!Any(empty, 1000), "an empty ring has no stop");
|
||||
|
||||
var outOfOrder = new ActionRing<Act>(8, 2);
|
||||
outOfOrder.TryEnqueue(new Act("start", 1200, false), false, false); // newer than the cast
|
||||
outOfOrder.TryEnqueue(new Act("stop", 900, true), true, false); // older, queued behind it
|
||||
Check(Any(outOfOrder, 1000), "a stop older than the cast, behind a newer entry, is found");
|
||||
|
||||
var onlyNewer = new ActionRing<Act>(8, 2);
|
||||
onlyNewer.TryEnqueue(new Act("start", 500, false), false, false);
|
||||
onlyNewer.TryEnqueue(new Act("stop", 1500, true), true, false);
|
||||
Check(!Any(onlyNewer, 1000), "a stop queued after the cast does not count");
|
||||
|
||||
var sameTime = new ActionRing<Act>(8, 2);
|
||||
sameTime.TryEnqueue(new Act("stop", 1000, true), true, false);
|
||||
Check(Any(sameTime, 1000), "a stop queued at the cast's own time counts");
|
||||
|
||||
var noStop = new ActionRing<Act>(8, 2);
|
||||
noStop.TryEnqueue(new Act("start", 100, false), false, false);
|
||||
noStop.TryEnqueue(new Act("start", 200, false), false, false);
|
||||
Check(!Any(noStop, 1000), "older entries that are not stops do not count");
|
||||
Check(noStop.Count == 2 && outOfOrder.Count == 2, "the check removes nothing");
|
||||
}
|
||||
|
||||
// ---- the mutator gate --------------------------------------------------------
|
||||
|
||||
private static void GateTruthTable()
|
||||
{
|
||||
_case = "mutator gate";
|
||||
int asked = 0;
|
||||
Func<bool> holding = () => { asked++; return true; };
|
||||
Func<bool> clear = () => { asked++; return false; };
|
||||
Check(MutatorGate.MustQueue(false, false, false, clear), "off the main thread: queue");
|
||||
Check(MutatorGate.MustQueue(false, true, true, clear), "off the main thread, even teardown in a drain: queue");
|
||||
Check(!MutatorGate.MustQueue(true, false, false, clear), "main thread, no transition: call now");
|
||||
Check(MutatorGate.MustQueue(true, false, false, holding), "main thread in a transition (render-thread host action): queue");
|
||||
Check(!MutatorGate.MustQueue(true, true, false, holding), "main thread in a transition, a stop: call now");
|
||||
asked = 0;
|
||||
Check(!MutatorGate.MustQueue(true, false, true, holding) && asked == 0, "called by a drain: call now, without asking the transition state");
|
||||
asked = 0;
|
||||
MutatorGate.MustQueue(false, false, false, holding);
|
||||
Check(asked == 0, "off the main thread the (main-thread-only) transition state is never asked");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every AC-mutating helper opens with the same gate: no helper may still decide with the old
|
||||
/// bare IsOnMainThread() check before an AcMainThreadQueue.Enqueue*, and each stop/cancel
|
||||
/// passes teardown: true while every other passes false (or !enabled for the two toggles).
|
||||
/// </summary>
|
||||
private static void GateCallSitesAllUseTheSameShape()
|
||||
{
|
||||
_case = "gate call sites";
|
||||
string? compat = FindRepoDir(Path.Combine("src", "RynthCore.Engine", "Compatibility"));
|
||||
Check(compat != null, "found src\\RynthCore.Engine\\Compatibility by walking up");
|
||||
if (compat == null) return;
|
||||
string[] files = { "ClientCombatHooks.cs", "CommandInterpreterHooks.cs", "ClientHelperHooks.cs", "CombatActionHooks.cs",
|
||||
"MovementActionHooks.cs", "PlayerPhysicsHooks.cs", "PlayerTrade.cs", "PlayerTraining.cs",
|
||||
"DeleteObjectHooks.cs" };
|
||||
var enqueue = new Regex(@"AcMainThreadQueue\.(Enqueue\w+)\(");
|
||||
var gate = new Regex(@"AcMainThreadQueue\.MustQueue\(teardown: (true|false|!enabled)\)");
|
||||
string[] teardownTrue = { "EnqueueStopCompletely", "EnqueueStopMovement", "EnqueueCancelAttack", "EnqueueCloseContainer" };
|
||||
string[] toggles = { "EnqueueSetAutoRun", "EnqueueSetMotion" };
|
||||
int sites = 0, bad = 0;
|
||||
foreach (string f in files)
|
||||
{
|
||||
string[] lines = File.ReadAllLines(Path.Combine(compat, f));
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
Match m = enqueue.Match(lines[i]);
|
||||
if (!m.Success) continue;
|
||||
string name = m.Groups[1].Value;
|
||||
if (name is "EnqueueWriteToChat" or "EnqueueChatCommand") continue;
|
||||
sites++;
|
||||
// The gate line is the nearest "if (" line above the enqueue (within 3 lines).
|
||||
string? gateLine = null;
|
||||
for (int j = i; j >= Math.Max(0, i - 3); j--)
|
||||
if (lines[j].TrimStart().StartsWith("if (", StringComparison.Ordinal)) { gateLine = lines[j]; break; }
|
||||
Match g = gateLine == null ? Match.Empty : gate.Match(gateLine);
|
||||
string want = teardownTrue.Contains(name) ? "true" : toggles.Contains(name) ? "!enabled" : "false";
|
||||
if (!g.Success || g.Groups[1].Value != want || gateLine!.Contains("IsOnMainThread"))
|
||||
{
|
||||
bad++;
|
||||
Console.WriteLine($"[gate] {f}:{i + 1} {name}: gate line '{gateLine?.Trim()}' (want teardown: {want})");
|
||||
}
|
||||
}
|
||||
}
|
||||
// 45 in PR #8, + SalvageDirect (v82, ClientHelperHooks) + RemoveClientObject (v83, DeleteObjectHooks).
|
||||
Check(sites == 47, $"47 gated mutator call sites found (got {sites})");
|
||||
Check(bad == 0, $"every one opens with AcMainThreadQueue.MustQueue(teardown: ...) and the right teardown value ({bad} wrong)");
|
||||
}
|
||||
|
||||
private static string? FindRepoDir(string relative)
|
||||
{
|
||||
string? dir = AppContext.BaseDirectory;
|
||||
while (dir != null)
|
||||
{
|
||||
string candidate = Path.Combine(dir, relative);
|
||||
if (Directory.Exists(candidate)) return candidate;
|
||||
dir = Path.GetDirectoryName(dir);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---- no merge into an entry a transition will drop -------------------------------
|
||||
|
||||
private static void RequestIdNeverMergesIntoAHeldEntry()
|
||||
{
|
||||
_case = "requestid merge floor";
|
||||
var q = new PendingIdQueue(8);
|
||||
q.Enqueue(42, 1000, 1, 7_500);
|
||||
// A transition held the drains up to 1500: the entry from 1000 will be dropped.
|
||||
Check(q.Enqueue(42, 2000, 1, 7_500, mergeOnlyAfterMs: 1500) == PendingIdQueue.Result.Queued,
|
||||
"a request after the window does not merge into the doomed entry");
|
||||
Check(q.Count == 2, "so it survives the drop");
|
||||
Check(q.Enqueue(42, 2100, 1, 7_500, mergeOnlyAfterMs: 1500) == PendingIdQueue.Result.Merged,
|
||||
"it merges into the new one");
|
||||
var r = new PendingIdQueue(8);
|
||||
r.Enqueue(43, 1000, 1, 7_500);
|
||||
Check(r.Enqueue(43, 2000, 1, 7_500, mergeOnlyAfterMs: 0) == PendingIdQueue.Result.Merged, "no transition: merges as before");
|
||||
}
|
||||
|
||||
// ---- identify data kept across a client release ---------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Wired as the engine wires them: AppraisalHooks' cache (here a set) keeps an object while
|
||||
/// ReleasedObjectRetention says so; AutoIdEligibility decides the re-create.
|
||||
/// </summary>
|
||||
private static void ReleasedDataKeptSoRecreateSkips()
|
||||
{
|
||||
_case = "release keeps data";
|
||||
var cache = new HashSet<uint>();
|
||||
var keep = new ReleasedObjectRetention();
|
||||
var elig = new AutoIdEligibility();
|
||||
long t = 1000;
|
||||
Check(elig.OnCreate(50, t, cache.Contains(50)) == AutoIdEligibility.CreateDecision.Appraise, "first create: appraised");
|
||||
elig.OnSent(50, t + 100);
|
||||
cache.Add(50); // the identify arrived
|
||||
// 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})");
|
||||
Check(elig.SkippedRecentTotal == 1, $"SkippedRecentCount moves (got {elig.SkippedRecentTotal})");
|
||||
}
|
||||
|
||||
private static void ReleasedDataExpiresAndServerDeleteEvicts()
|
||||
{
|
||||
_case = "release expiry";
|
||||
var keep = new ReleasedObjectRetention(10 * 60_000, 4);
|
||||
var expired = new List<uint>();
|
||||
keep.OnRelease(1, 1000);
|
||||
keep.OnRelease(2, 2000);
|
||||
Check(keep.Expire(1000 + 10 * 60_000 - 1, expired) == 0, "kept inside the 10 minutes");
|
||||
Check(keep.Expire(2000 + 10 * 60_000, expired) == 2 && expired.SequenceEqual(new uint[] { 1, 2 }), "both dropped once past it");
|
||||
Check(keep.Count == 0, "and no longer tracked");
|
||||
for (uint i = 10; i < 14; i++) keep.OnRelease(i, 5000);
|
||||
Check(!keep.OnRelease(99, 5000), "at the bound a release is not kept (the caller evicts it at once)");
|
||||
keep.Forget(10);
|
||||
Check(keep.OnRelease(99, 5000), "room again once one is forgotten (re-created or server-deleted)");
|
||||
}
|
||||
|
||||
// ---- 0xF751: the teleport message as its own signal ----------------------------------
|
||||
|
||||
private static void TeleportMessageStartsTheWindow()
|
||||
{
|
||||
_case = "teleport message";
|
||||
var s = new WorldTransitionState();
|
||||
s.Sample(1000, false, false, 0xA9B4);
|
||||
Check(!s.InTransition(2000), "no transition before the message");
|
||||
Check(s.OnTeleportMessage(2000), "PlayerTeleport received: the window starts");
|
||||
// No portal flag, no landblock change, alive: only the message.
|
||||
s.Sample(2016, false, false, 0xA9B4);
|
||||
Check(s.InTransition(2000 + WorldTransitionState.SettleMs - 1), "held for the full settle on the message alone");
|
||||
Check(s.Decide(3000, 2500, false) == WorldTransitionState.Verdict.Hold, "queued work held");
|
||||
Check(!s.InTransition(2000 + WorldTransitionState.SettleMs), "window ends 5 s after it");
|
||||
Check(s.Decide(2000 + WorldTransitionState.SettleMs, 2500, false) == WorldTransitionState.Verdict.Drop, "then stale work is dropped");
|
||||
Check(!s.OnTeleportMessage(1500), "an older message never shortens a running window");
|
||||
}
|
||||
|
||||
// ---- the OOM dump trigger ------------------------------------------------------
|
||||
|
||||
private static void OutOfMemoryBoxMatchesOnlyAcsBox()
|
||||
{
|
||||
_case = "oom box rule";
|
||||
// The real text, from a real log line.
|
||||
const string real = "OUT OF MEMORY: Failed to allocate -778718788 bytes.";
|
||||
Check(OutOfMemoryBoxRule.IsOutOfMemoryBox(real, onMainThread: true), "AC's box on its main thread: dump");
|
||||
Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox(real, onMainThread: false), "the same text off the main thread: no dump");
|
||||
Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox("Plugin X: OUT OF MEMORY: Failed to allocate 4 bytes.", true), "prefix not at the start: no dump");
|
||||
Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox("out of memory: failed to allocate 4 bytes.", true), "other case: no dump (ordinal)");
|
||||
Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox("OUT OF MEMORY", true), "the bare words: no dump");
|
||||
Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox(null, true), "no text: no dump");
|
||||
}
|
||||
|
||||
// ---- the launcher holds its kill while a dump is written ---------------------------
|
||||
|
||||
private static void LauncherHoldsTheKillDuringADump()
|
||||
{
|
||||
_case = "dump in progress";
|
||||
var now = new DateTime(2026, 10, 10, 22, 18, 30, DateTimeKind.Utc);
|
||||
string started = $"[18:18:16] {DumpInProgressRule.MarkerStarted} pid=123 - ...\n";
|
||||
string ended = $"[18:20:01] {DumpInProgressRule.MarkerEnded} pid=123.\n";
|
||||
Check(DumpInProgressRule.IsDumping("hb #1\n" + started, now.AddMinutes(-3), null, now), "marker 3 min old, no end: hold the kill");
|
||||
Check(!DumpInProgressRule.IsDumping("hb #1\n" + started, now.AddMinutes(-11), null, now), "marker over 10 min old: a client that died mid-dump is killed");
|
||||
Check(!DumpInProgressRule.IsDumping(started + ended, now.AddMinutes(-3), null, now), "dump ended: no hold");
|
||||
Check(DumpInProgressRule.IsDumping(started + ended + started, now.AddMinutes(-1), null, now), "the LAST marker decides");
|
||||
Check(DumpInProgressRule.IsDumping("hb #1\n", now.AddMinutes(-5), now.AddSeconds(-10), now), "no marker, but the dump file was written 10 s ago: hold");
|
||||
Check(!DumpInProgressRule.IsDumping("hb #1\n", now.AddMinutes(-5), now.AddMinutes(-2), now), "a dump file quiet for 2 min: no hold");
|
||||
Check(!DumpInProgressRule.IsDumping(null, now, null, now), "nothing at all: no hold");
|
||||
}
|
||||
|
||||
// ---- the cast slot refuses during a transition (the real CastSlot) -------------
|
||||
|
||||
private static void CastRefusedDuringATransition()
|
||||
{
|
||||
_case = "cast slot transition";
|
||||
var slot = new CastSlot();
|
||||
Check(slot.TryEnqueue(0x50000001, 1234, 1000, inTransition: true) == CastSlot.Admit.RejectedTransition,
|
||||
"an empty slot refuses a cast during a transition");
|
||||
Check(slot.Pending == 0 && slot.TargetId == 0 && slot.SpellId == 0 && slot.QueuedAt == 0,
|
||||
"and stays untouched");
|
||||
|
||||
Check(slot.TryEnqueue(0x50000002, 99, 2000, inTransition: false) == CastSlot.Admit.Queued, "outside one, a cast is queued");
|
||||
Check(slot.TryEnqueue(0x50000003, 77, 2500, inTransition: true) == CastSlot.Admit.RejectedTransition,
|
||||
"a transition refuses even with a cast pending (counted as a transition refusal, not busy)");
|
||||
Check(slot.Pending == 1 && slot.TargetId == 0x50000002 && slot.SpellId == 99 && slot.QueuedAt == 2000,
|
||||
"the pending cast is unchanged");
|
||||
Check(slot.TryEnqueue(0x50000004, 55, 2600, inTransition: false) == CastSlot.Admit.Busy, "busy outside a transition");
|
||||
slot.Pending = 0;
|
||||
Check(slot.TryEnqueue(0x50000005, 66, 9000, inTransition: false) == CastSlot.Admit.Queued
|
||||
&& slot.SpellId == 66 && slot.QueuedAt == 9000, "after the transition, casts queue again");
|
||||
|
||||
// The drain's once-per-cast stop-wait note belongs to the cast: a new cast clears it, a
|
||||
// refused one leaves the pending cast's note alone.
|
||||
slot.StopWaitNoted = true;
|
||||
Check(slot.TryEnqueue(0x50000006, 67, 9100, inTransition: false) == CastSlot.Admit.Busy && slot.StopWaitNoted,
|
||||
"a busy refusal keeps the pending cast's stop-wait note");
|
||||
slot.Pending = 0;
|
||||
Check(slot.TryEnqueue(0x50000007, 68, 9200, inTransition: false) == CastSlot.Admit.Queued && !slot.StopWaitNoted,
|
||||
"a newly queued cast starts with no stop-wait note");
|
||||
}
|
||||
|
||||
// ---- The cast drain's walk of the ring (ActionRing.TryPeekAt) --------------------------
|
||||
|
||||
private static void RingPeekAtWalksWithoutRemoving()
|
||||
{
|
||||
_case = "ring peek-at";
|
||||
var ring = new ActionRing<Act>(8, 2);
|
||||
Check(!ring.TryPeekAt(0, out _), "an empty ring has nothing at 0");
|
||||
// Wrap the ring once so the walk crosses the end of the storage.
|
||||
for (int i = 0; i < 5; i++) ring.TryEnqueue(new Act("old" + i, i, false), false, false);
|
||||
for (int i = 0; i < 5; i++) ring.TryDequeue(out _);
|
||||
for (int i = 0; i < 6; i++) ring.TryEnqueue(new Act("e" + i, 100 + i, i == 4), i == 4, false);
|
||||
var seen = new List<string>();
|
||||
for (int i = 0; ring.TryPeekAt(i, out Act e); i++) seen.Add(e.What);
|
||||
Check(string.Join(",", seen) == "e0,e1,e2,e3,e4,e5", $"oldest first across the wrap, got [{string.Join(",", seen)}]");
|
||||
Check(ring.Count == 6, $"nothing removed (count {ring.Count})");
|
||||
Check(!ring.TryPeekAt(6, out _) && !ring.TryPeekAt(-1, out _), "out of range is false");
|
||||
Check(ring.TryDequeue(out Act head) && head.What == "e0" && ring.TryPeekAt(0, out Act next) && next.What == "e1",
|
||||
"after a dequeue, offset 0 is the new oldest");
|
||||
}
|
||||
|
||||
private static void EnqueueCastPassesTheTransitionState()
|
||||
{
|
||||
_case = "EnqueueCast wiring";
|
||||
string? compat = FindRepoDir(Path.Combine("src", "RynthCore.Engine", "Compatibility"));
|
||||
Check(compat != null, "found src\\RynthCore.Engine\\Compatibility by walking up");
|
||||
if (compat == null) return;
|
||||
string src = File.ReadAllText(Path.Combine(compat, "AcMainThreadQueue.cs"));
|
||||
int start = src.IndexOf("public static bool EnqueueCast(", StringComparison.Ordinal);
|
||||
int end = start < 0 ? -1 : src.IndexOf("\n }", start, StringComparison.Ordinal);
|
||||
string body = start < 0 || end < 0 ? "" : src.Substring(start, end - start);
|
||||
Check(body.Contains("_cast.TryEnqueue(targetId, spellId, NowMs, PlayerLifecycleLog.InWorldTransition)", StringComparison.Ordinal),
|
||||
"EnqueueCast hands CastSlot the live transition state");
|
||||
Check(Regex.IsMatch(body, @"RejectedTransition\)\s*Interlocked\.Increment\(ref _transitionRejected\)"),
|
||||
"and counts a refusal in TransitionRejectedCount (the heartbeat's qrej)");
|
||||
Check(!Regex.IsMatch(src, @"_cast\.(TargetId|SpellId|QueuedAt)\s*=[^=]"),
|
||||
"nothing else writes the slot's cast fields");
|
||||
}
|
||||
|
||||
// ---- the launcher's dump hold is capped per client --------------------------------
|
||||
|
||||
private static void LauncherDumpHoldIsCapped()
|
||||
{
|
||||
_case = "dump hold cap";
|
||||
var now = new DateTime(2026, 10, 10, 22, 18, 30, DateTimeKind.Utc);
|
||||
string open = $"hb #1\n[18:00:00] {DumpInProgressRule.MarkerStarted} pid=123 - ...\nhb #2\n";
|
||||
DateTime freshLog = now.AddSeconds(-5);
|
||||
Check(DumpInProgressRule.Decide(open, freshLog, null, null, now) == DumpInProgressRule.Hold.Holding,
|
||||
"an open marker, first seen now: hold");
|
||||
Check(DumpInProgressRule.Decide(open, freshLog, null, now.AddMinutes(-5), now) == DumpInProgressRule.Hold.Holding,
|
||||
"held 5 min: still holding");
|
||||
Check(DumpInProgressRule.Decide(open, freshLog, null, now.AddMinutes(-16), now) == DumpInProgressRule.Hold.Expired,
|
||||
"fresh log, marker held over 15 min: the kill checks run");
|
||||
Check(DumpInProgressRule.Decide("hb #1\n", freshLog, now.AddSeconds(-3), now.AddMinutes(-16), now) == DumpInProgressRule.Hold.Expired,
|
||||
"a dump file still being written does not extend the cap either");
|
||||
Check(DumpInProgressRule.Decide(open, freshLog, null, DateTime.MinValue, now) == DumpInProgressRule.Hold.Expired,
|
||||
"the launcher's 'expired, logged' mark stays expired");
|
||||
Check(DumpInProgressRule.Decide("hb #1\n", freshLog, null, now.AddMinutes(-16), now) == DumpInProgressRule.Hold.None,
|
||||
"no sign of a dump: None (the launcher forgets the pid)");
|
||||
}
|
||||
|
||||
// ---- which exit codes are crash exits ---------------------------------------------
|
||||
|
||||
private static void CrashExitExcludesExitMinusOne()
|
||||
{
|
||||
_case = "crash exit rule";
|
||||
Check(CrashExitRule.IsCrashExit(0xC0000005u), "0xC0000005 access violation: crash");
|
||||
Check(CrashExitRule.IsCrashExit(0xC0000409u), "0xC0000409 stack buffer overrun: crash");
|
||||
Check(CrashExitRule.IsCrashExit(0xC0000374u), "0xC0000374 heap corruption: crash");
|
||||
Check(CrashExitRule.IsCrashExit(0xC00000FDu), "0xC00000FD stack overflow: crash");
|
||||
Check(CrashExitRule.IsCrashExit(0xE0434352u), "0xE0434352 CLR unhandled exception: crash (as before)");
|
||||
Check(!CrashExitRule.IsCrashExit(0xFFFFFFFFu), "ExitProcess(-1): not a crash");
|
||||
Check(!CrashExitRule.IsCrashExit(0u), "0: not a crash");
|
||||
Check(!CrashExitRule.IsCrashExit(1u), "1: not a crash");
|
||||
Check(!CrashExitRule.IsCrashExit(0x80000003u), "0x80000003 (warning severity): not a crash");
|
||||
Check(!CrashExitRule.IsCrashExit(0x40010004u), "0x40010004 (informational): not a crash");
|
||||
}
|
||||
|
||||
private static void CrashExitPathsFlushTheCrashLog()
|
||||
{
|
||||
_case = "crash exit flush";
|
||||
string? compat = FindRepoDir(Path.Combine("src", "RynthCore.Engine", "Compatibility"));
|
||||
Check(compat != null, "found src\\RynthCore.Engine\\Compatibility by walking up");
|
||||
if (compat == null) return;
|
||||
string src = File.ReadAllText(Path.Combine(compat, "ProcessExitHooks.cs"));
|
||||
Check(src.Contains("private static bool IsCrashExit(uint code) => CrashExitRule.IsCrashExit(code);", StringComparison.Ordinal),
|
||||
"ProcessExitHooks uses CrashExitRule");
|
||||
foreach (string detour in new[] { "ExitProcessDetour", "TerminateProcessDetour", "RtlExitUserProcessDetour", "NtTerminateProcessDetour" })
|
||||
{
|
||||
int start = src.IndexOf($"private static {(detour.Contains("Terminate") ? (detour.StartsWith("Nt") ? "uint" : "bool") : "void")} {detour}(", StringComparison.Ordinal);
|
||||
int end = start < 0 ? -1 : src.IndexOf("\n }", start, StringComparison.Ordinal);
|
||||
string body = start < 0 || end < 0 ? "" : src.Substring(start, end - start);
|
||||
int flush = body.IndexOf("SehTrampoline.FlushCrashLog(", StringComparison.Ordinal);
|
||||
int orig = body.IndexOf("Original!(", StringComparison.Ordinal);
|
||||
Check(flush >= 0 && orig > flush, $"{detour}: a crash exit flushes the crash log before the original");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -23,6 +23,7 @@
|
|||
<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" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AutoIdPolicy.cs" Link="Engine\AutoIdPolicy.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -47,6 +47,7 @@ namespace EngineSettingsTests
|
|||
Run(nameof(OwnedKeysMatchEngineSettings), OwnedKeysMatchEngineSettings);
|
||||
Run(nameof(SaveKeepsLauncherKeys), SaveKeepsLauncherKeys);
|
||||
Run(nameof(SaveRoundTripsOwnedKeys), SaveRoundTripsOwnedKeys);
|
||||
Run(nameof(AutoIdModeRoundTrips), AutoIdModeRoundTrips);
|
||||
Run(nameof(SaveWithoutFileWritesOwnedKeys), SaveWithoutFileWritesOwnedKeys);
|
||||
Run(nameof(SaveLeavesMalformedFileAlone), SaveLeavesMalformedFileAlone);
|
||||
Run(nameof(MaxHotReloadsReadAndKept), MaxHotReloadsReadAndKept);
|
||||
|
|
@ -83,7 +84,12 @@ namespace EngineSettingsTests
|
|||
case "imgui-off": EngineSettings.EnableImGuiBackend = false; break;
|
||||
case "dcclose-off": EngineSettings.CloseOnServerDisconnect = false; break;
|
||||
case "dcclose-on": EngineSettings.CloseOnServerDisconnect = true; break;
|
||||
case "autoid":
|
||||
if (!RynthCore.Engine.Compatibility.AutoIdPolicy.TryParseMode(args[1], out var aim)) throw new ArgumentException(args[1]);
|
||||
EngineSettings.AutoIdMode = aim;
|
||||
break;
|
||||
case "dump":
|
||||
Console.WriteLine("AutoIdMode=" + EngineSettings.AutoIdMode);
|
||||
Console.WriteLine("PluginPaths=" + string.Join("|", EngineSettings.PluginPaths));
|
||||
Console.WriteLine("StartTooltip=" + EngineSettings.IsUiHookEnabled("StartTooltip"));
|
||||
Console.WriteLine("DecalBridge=" + EngineSettings.DecalBridgeMode);
|
||||
|
|
@ -216,6 +222,33 @@ namespace EngineSettingsTests
|
|||
Check(ReadJson(path).TryGetProperty("EnableDcompOverlay", out _), "launcher key still there");
|
||||
}
|
||||
|
||||
private static void AutoIdModeRoundTrips()
|
||||
{
|
||||
string dir = NewDir("autoid");
|
||||
string path = Path.Combine(dir, "engine.json");
|
||||
File.WriteAllText(path, LauncherFile);
|
||||
var (exit, output) = RunChild(path, "dump");
|
||||
Eq(exit, 0, "dump");
|
||||
Check(output.Contains("AutoIdMode=Limited"), "default is Limited: " + output);
|
||||
|
||||
Eq(RunChild(path, "autoid", "off").Exit, 0, "set off");
|
||||
Eq(ReadJson(path).GetProperty("AutoIdMode").GetString(), "Off", "saved as \"Off\"");
|
||||
(exit, output) = RunChild(path, "dump");
|
||||
Check(output.Contains("AutoIdMode=Off"), "Off read back: " + output);
|
||||
|
||||
Eq(RunChild(path, "autoid", "all").Exit, 0, "set all");
|
||||
(exit, output) = RunChild(path, "dump");
|
||||
Check(output.Contains("AutoIdMode=All"), "All read back: " + output);
|
||||
|
||||
Eq(RunChild(path, "autoid", "limited").Exit, 0, "back to limited");
|
||||
Check(!ReadJson(path).TryGetProperty("AutoIdMode", out _), "the default leaves the key out");
|
||||
Check(ReadJson(path).TryGetProperty("EnableDcompOverlay", out _), "launcher key still there");
|
||||
|
||||
File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", "\"AutoIdMode\": \"bogus\", \"LoggingLevel\""));
|
||||
(exit, output) = RunChild(path, "dump");
|
||||
Check(output.Contains("AutoIdMode=Limited"), "an unknown value reads as the default: " + output);
|
||||
}
|
||||
|
||||
private static void SaveWithoutFileWritesOwnedKeys()
|
||||
{
|
||||
string dir = NewDir("nofile");
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@
|
|||
<Compile Include="..\..\src\RynthCore.Engine\Net\FlightRing.cs" Link="Engine\FlightRing.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Net\FlightCapture.cs" Link="Engine\FlightCapture.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Net\FlightFormat.cs" Link="Engine\FlightFormat.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Net\IdRequester.cs" Link="Engine\IdRequester.cs" />
|
||||
<Compile Include="..\NetMessageTests\WireBuilder.cs" Link="WireBuilder.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ internal static unsafe class Program
|
|||
RetransmitDedupe();
|
||||
ResendRequestMarker();
|
||||
EngineTagging();
|
||||
IdentifyTagging();
|
||||
EngineRepeatFolding();
|
||||
|
||||
DetectUseRefusal();
|
||||
|
|
@ -378,6 +379,98 @@ internal static unsafe class Program
|
|||
Has(engineLines, "engine UseObject(0x80068ACE, 0)", "engine call markers written");
|
||||
}
|
||||
|
||||
private static byte[] Identify(uint obj) => Action(0x00C8, new Body().U32(obj));
|
||||
|
||||
private static void IdentifyTagging()
|
||||
{
|
||||
Case("capture: an IdentifyObject is [eng:<who>] after an engine send for that id, otherwise [cli]");
|
||||
var c = NewCapture();
|
||||
LoginAs(c);
|
||||
int marks = Count(c, FlightDir.Mark);
|
||||
c.EngineSend((byte)IdRequester.AutoIdContainer, Corpse);
|
||||
Eq(Count(c, FlightDir.Mark), marks, "an engine send writes no marker line");
|
||||
_t += 30;
|
||||
Out(c, Identify(Corpse));
|
||||
Has(Last(c), "[eng:autoid-container] IdentifyObject 0x80068ACE", "autoid container send");
|
||||
Eq(c.IdentifyForeignTotal, 0L, "not counted as foreign");
|
||||
|
||||
Out(c, Identify(Corpse));
|
||||
Has(Last(c), "[cli] IdentifyObject", "a second 0xC8 with no engine send is AC's or Decal's");
|
||||
Eq(c.IdentifyForeignTotal, 1L, "counted as foreign");
|
||||
|
||||
c.EngineSend((byte)IdRequester.Plugin, Other);
|
||||
Out(c, Identify(Corpse));
|
||||
Has(Last(c), "[cli]", "an engine send for another id does not tag this one");
|
||||
Out(c, Identify(Other));
|
||||
Has(Last(c), "[eng:plugin] IdentifyObject 0x80012345", "plugin send matched by id");
|
||||
|
||||
c.EngineSend((byte)IdRequester.AutoIdTarget, Other);
|
||||
_t += FlightCapture.EngineMatchMs + 1;
|
||||
Out(c, Identify(Other));
|
||||
Has(Last(c), "[cli]", "too late to match");
|
||||
|
||||
c.EngineSend((byte)IdRequester.AutoIdTarget, Other);
|
||||
c.EngineSend((byte)IdRequester.AutoIdInventory, Other);
|
||||
Out(c, Identify(Other));
|
||||
Has(Last(c), "[eng:autoid-target]", "two sends for one id: the older first");
|
||||
Out(c, Identify(Other));
|
||||
Has(Last(c), "[eng:autoid-inventory]", "then the newer");
|
||||
|
||||
c.EngineSend(0, Corpse);
|
||||
Out(c, Identify(Corpse));
|
||||
Has(Last(c), "[cli]", "a send without a requester is not registered");
|
||||
Eq(c.EngineSend(0, Corpse), -1, "no requester: no token");
|
||||
|
||||
// Registered before the call (CombatActionHooks.RequestId): a 0xC8 that AC sends
|
||||
// synchronously, inside the call, is still tagged.
|
||||
int sync = c.EngineSend((byte)IdRequester.AutoIdInventory, Corpse);
|
||||
Out(c, Identify(Corpse));
|
||||
Has(Last(c), "[eng:autoid-inventory] IdentifyObject 0x80068ACE", "a send made inside the call is tagged");
|
||||
c.EngineSendFailed(sync, Corpse); // already matched: a no-op
|
||||
Out(c, Identify(Corpse));
|
||||
Has(Last(c), "[cli]", "a matched entry is not revived");
|
||||
|
||||
// The call returned false (or threw): its entry is retired, so a later 0xC8 for the
|
||||
// same id is AC's or Decal's.
|
||||
long foreignFail = c.IdentifyForeignTotal;
|
||||
int failed = c.EngineSend((byte)IdRequester.AutoIdInventory, Corpse);
|
||||
Check(failed >= 0, "a registration returns a token");
|
||||
c.EngineSendFailed(failed, Corpse);
|
||||
Out(c, Identify(Corpse));
|
||||
Has(Last(c), "[cli]", "a failed send leaves no live entry");
|
||||
Eq(c.IdentifyForeignTotal, foreignFail + 1, "and that 0xC8 counts as foreign");
|
||||
|
||||
// Retiring a token whose slot now holds another id leaves that entry alone.
|
||||
int stale = c.EngineSend((byte)IdRequester.AutoIdTarget, Other);
|
||||
c.EngineSendFailed(stale, Corpse);
|
||||
c.EngineSendFailed(-1, Other);
|
||||
c.EngineSendFailed(int.MaxValue, Other);
|
||||
Out(c, Identify(Other));
|
||||
Has(Last(c), "[eng:autoid-target]", "a retire for another id, or a bad token, is a no-op");
|
||||
|
||||
// 200 sends in a burst (a full RequestId queue drained at once) do not push out other
|
||||
// engine calls (their own table), and every one of them is matched.
|
||||
c.EngineCall("UseObject", Corpse, 0);
|
||||
for (uint i = 0; i < 200; i++) c.EngineSend((byte)IdRequester.AutoIdWorld, 0x80100000 + i);
|
||||
Out(c, Use(Corpse));
|
||||
Has(Last(c), "[eng] Use", "an identify burst leaves the pending use intact");
|
||||
long foreignBefore = c.IdentifyForeignTotal;
|
||||
int matched = 0;
|
||||
for (uint i = 0; i < 200; i++)
|
||||
{
|
||||
Out(c, Identify(0x80100000 + i));
|
||||
if (Last(c).Contains("[eng:autoid-world] IdentifyObject", StringComparison.Ordinal)) matched++;
|
||||
}
|
||||
Eq(matched, 200, "200 registrations, 200 tagged identifies (oldest to newest)");
|
||||
Eq(c.IdentifyForeignTotal, foreignBefore, "none of the burst counted as foreign");
|
||||
|
||||
foreach (IdRequester who in Enum.GetValues<IdRequester>())
|
||||
{
|
||||
if (who == IdRequester.None) continue;
|
||||
Check(IdRequesters.Label((byte)who).Length > 0, $"{who} has a label");
|
||||
}
|
||||
}
|
||||
|
||||
private static void EngineRepeatFolding()
|
||||
{
|
||||
Case("capture: identical engine calls within 1 s fold into one line plus a 'repeated' line");
|
||||
|
|
@ -603,7 +696,7 @@ internal static unsafe class Program
|
|||
Has(DescribeIn(Event(0x01A7, new Body().U32(0))), "AttackDone err 0x0000", "attack done");
|
||||
Has(DescribeIn(Event(0x01B8, new Body())), "CombatCommenceAttack", "commence attack");
|
||||
Has(DescribeIn(Event(0x01B1, new Body().Str("Drudge Ravener").U32(1).Bytes(BitConverter.GetBytes(0.4)).U32(37).U32(1).U32(0).U32(0))),
|
||||
"AttackerNotification hit 'Drudge Ravener' for 37 (crit), 40% left", "attacker notification");
|
||||
"AttackerNotification hit 'Drudge Ravener' for 37 (crit) (40% of its max health)", "attacker notification");
|
||||
var ench = new Body().U16(2053).U16(1).U16(5).U16(0).U32(400).Bytes(BitConverter.GetBytes(0.0)).Bytes(BitConverter.GetBytes(1800.0)).U32(Player);
|
||||
Has(DescribeIn(Event(0x02C2, ench)), "MagicUpdateEnchantment spell 2053 layer 1 duration 1800 s caster 0x50000ABC", "enchantment");
|
||||
Has(DescribeIn(Event(0x02C3, new Body().U16(2053).U16(1))), "MagicRemoveEnchantment spell 2053 layer 1", "remove enchantment");
|
||||
|
|
|
|||
24
tools/FolderAccessTests/FolderAccessTests.csproj
Normal file
24
tools/FolderAccessTests/FolderAccessTests.csproj
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline tests for the launcher's folder checks and Recovery Actions > Fix folder permissions
|
||||
(src/RynthCore.App/FolderAccess.cs, compiled in): the write probe and read-only count, the
|
||||
elevated step's command line, which folders it refuses, junctions not followed, the
|
||||
Controlled folder access event parsing. Only a temp folder is written. Permissions are NEVER
|
||||
changed: Repair runs with changePermissions: false (its read-only part only).
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>FolderAccessTests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="../../src/RynthCore.App/FolderAccess.cs" Link="App/FolderAccess.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
303
tools/FolderAccessTests/Program.cs
Normal file
303
tools/FolderAccessTests/Program.cs
Normal file
|
|
@ -0,0 +1,303 @@
|
|||
using System.Diagnostics;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using RynthCore.App;
|
||||
|
||||
namespace FolderAccessTests;
|
||||
|
||||
/// <summary>
|
||||
/// FolderAccess (launcher: start-up folder check, Recovery Actions > Fix folder permissions).
|
||||
/// Players reported RynthAi metas and navs not saving and "read only" plugin folders (2026-10-13).
|
||||
/// Writes only under %TEMP%\FolderAccessTests-*; never changes permissions.
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
private static int _checks, _failed;
|
||||
private static string _temp = "";
|
||||
|
||||
private static int Main()
|
||||
{
|
||||
_temp = Path.Combine(Path.GetTempPath(), $"FolderAccessTests-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(_temp);
|
||||
try
|
||||
{
|
||||
Scenario("folders checked: RynthSuite, RynthAi and its data folders, RynthCore and Logs", FoldersToCheck);
|
||||
Scenario("check: a writable folder passes and leaves no probe file", WritableFolder);
|
||||
Scenario("check: read-only files are counted and reported", ReadOnlyFilesCounted);
|
||||
Scenario("check: a folder that doesn't exist (or a file in its place) has nothing to save, so no problem", MissingFolder);
|
||||
Scenario("elevated step: command line round-trips (spaces, report file)", ArgumentsRoundTrip);
|
||||
Scenario("elevated step: malformed command lines are refused", ArgumentsMalformed);
|
||||
Scenario("elevated step: refuses drive roots, Windows, Program Files, user folders, strangers", SafeRoots);
|
||||
Scenario("elevated step: accepts a RynthCore or RynthSuite folder", OurRoots);
|
||||
Scenario("repair (read-only part): clears read-only everywhere, never through a junction", RepairClearsReadOnly);
|
||||
Scenario("repair: refused roots are reported, not touched", RepairRefusesStrangers);
|
||||
Scenario("repair: the rule is Modify for the account, inherited by folders and files", RuleShape);
|
||||
Scenario("controlled folder access: 1123/1124 events parsed (process, path, blocked)", CfaEvents);
|
||||
Scenario("controlled folder access: the live query never throws", CfaLive);
|
||||
Scenario("virtualized location: Program Files yes, C:\\Games no", Virtualized);
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (string f in Directory.GetFiles(_temp, "*", SearchOption.AllDirectories)) File.SetAttributes(f, FileAttributes.Normal);
|
||||
Directory.Delete(_temp, recursive: true);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
Console.WriteLine();
|
||||
Console.WriteLine($"{_checks} check(s), {_failed} failed.");
|
||||
return _failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static void Scenario(string name, Action body)
|
||||
{
|
||||
int before = _failed;
|
||||
try { body(); }
|
||||
catch (Exception ex) { Check(false, $"threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
Console.WriteLine($"[{(_failed == before ? "PASS" : "FAIL")}] {name}");
|
||||
}
|
||||
|
||||
private static void Check(bool ok, string what)
|
||||
{
|
||||
_checks++;
|
||||
if (ok) return;
|
||||
_failed++;
|
||||
Console.WriteLine(" - " + what);
|
||||
}
|
||||
|
||||
private static string Dir(string name)
|
||||
{
|
||||
string d = Path.Combine(_temp, name);
|
||||
Directory.CreateDirectory(d);
|
||||
return d;
|
||||
}
|
||||
|
||||
private static void FoldersToCheck()
|
||||
{
|
||||
var f = FolderAccess.FoldersToCheck(@"D:\X\RynthSuite", @"D:\X\RynthCore");
|
||||
Check(f.Contains(@"D:\X\RynthSuite\RynthAi\MetaFiles"), "MetaFiles");
|
||||
Check(f.Contains(@"D:\X\RynthSuite\RynthAi\NavProfiles"), "NavProfiles");
|
||||
Check(f.Contains(@"D:\X\RynthSuite\RynthAi\LootProfiles"), "LootProfiles");
|
||||
Check(f.Contains(@"D:\X\RynthSuite\RynthAi\SettingsProfiles"), "SettingsProfiles");
|
||||
Check(f.Contains(@"D:\X\RynthCore\Logs"), "RynthCore Logs");
|
||||
Check(f[0] == @"D:\X\RynthSuite", "the suite root first");
|
||||
}
|
||||
|
||||
private static void WritableFolder()
|
||||
{
|
||||
string d = Dir("writable");
|
||||
var s = FolderAccess.Check(d);
|
||||
Check(s.Exists && s.Writable && s.Ok, "writable and ok");
|
||||
Check(Directory.GetFiles(d).Length == 0, "probe removed");
|
||||
Check(FolderAccess.DescribeProblems(new[] { s }).Count == 0, "no problem lines");
|
||||
}
|
||||
|
||||
private static void ReadOnlyFilesCounted()
|
||||
{
|
||||
string d = Dir("ro");
|
||||
File.WriteAllText(Path.Combine(d, "a.af"), "x");
|
||||
File.WriteAllText(Path.Combine(d, "b.nav"), "x");
|
||||
File.SetAttributes(Path.Combine(d, "a.af"), FileAttributes.ReadOnly);
|
||||
var s = FolderAccess.Check(d);
|
||||
Check(s.Writable, "folder still writable");
|
||||
Check(s.ReadOnlyFiles == 1, $"one read-only file (got {s.ReadOnlyFiles})");
|
||||
Check(!s.Ok, "not ok");
|
||||
var lines = FolderAccess.DescribeProblems(new[] { s });
|
||||
Check(lines.Count == 1 && lines[0].Contains("1 file(s) marked read-only"), "described: " + string.Join(" | ", lines));
|
||||
}
|
||||
|
||||
private static void MissingFolder()
|
||||
{
|
||||
var s = FolderAccess.Check(Path.Combine(_temp, "nope"));
|
||||
Check(!s.Exists && s.Ok, "missing is fine");
|
||||
string blocker = Path.Combine(_temp, "blocker");
|
||||
File.WriteAllText(blocker, "x");
|
||||
var under = FolderAccess.Check(Path.Combine(blocker, "sub"));
|
||||
Check(under.Ok, "a path under a file doesn't exist either (nothing to save there)");
|
||||
}
|
||||
|
||||
private static void ArgumentsRoundTrip()
|
||||
{
|
||||
string sid = WindowsIdentity.GetCurrent().User!.Value;
|
||||
string args = FolderAccess.BuildRepairArguments(sid, new[] { @"C:\Games\Rynth Suite\", @"D:\RynthCore" }, @"C:\Temp\rynthcore-folderfix-1.txt");
|
||||
string[] argv = SplitLikeWindows(args);
|
||||
Check(FolderAccess.TryParseRepairArguments(argv, out string s2, out var roots, out string? report), "parses: " + args);
|
||||
Check(s2 == sid, "sid");
|
||||
Check(roots.Count == 2 && roots[0] == @"C:\Games\Rynth Suite" && roots[1] == @"D:\RynthCore", "roots: " + string.Join(" | ", roots));
|
||||
Check(report == @"C:\Temp\rynthcore-folderfix-1.txt", "report path");
|
||||
}
|
||||
|
||||
/// <summary>The command line as the elevated launcher's Main gets it (Windows' quoting; our builder never embeds quotes).</summary>
|
||||
private static string[] SplitLikeWindows(string commandLine)
|
||||
{
|
||||
var list = new List<string>();
|
||||
var cur = new System.Text.StringBuilder();
|
||||
bool quoted = false, any = false;
|
||||
foreach (char c in commandLine)
|
||||
{
|
||||
if (c == '"') { quoted = !quoted; any = true; continue; }
|
||||
if (c == ' ' && !quoted) { if (any || cur.Length > 0) list.Add(cur.ToString()); cur.Clear(); any = false; continue; }
|
||||
cur.Append(c);
|
||||
}
|
||||
if (any || cur.Length > 0) list.Add(cur.ToString());
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
private static void ArgumentsMalformed()
|
||||
{
|
||||
Check(!FolderAccess.TryParseRepairArguments(new[] { "--other" }, out _, out _, out _), "not the command");
|
||||
Check(!FolderAccess.TryParseRepairArguments(new[] { FolderAccess.RepairArgument }, out _, out _, out _), "no SID");
|
||||
Check(!FolderAccess.TryParseRepairArguments(new[] { FolderAccess.RepairArgument, "not-a-sid", @"C:\Games\RynthSuite" }, out _, out _, out _), "bad SID");
|
||||
Check(!FolderAccess.TryParseRepairArguments(new[] { FolderAccess.RepairArgument, "S-1-5-32-545" }, out _, out _, out _), "no folders");
|
||||
Check(!FolderAccess.TryParseRepairArguments(new[] { FolderAccess.RepairArgument, "S-1-5-32-545", "--report" }, out _, out _, out _), "--report without a file");
|
||||
}
|
||||
|
||||
private static void SafeRoots()
|
||||
{
|
||||
string[] refused =
|
||||
{
|
||||
@"C:\", "C:", @"relative\path", "",
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.Windows),
|
||||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Temp"),
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
|
||||
Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile))!,
|
||||
Path.Combine(_temp, "does-not-exist"),
|
||||
Dir("stranger"), // exists, but nothing of ours in it
|
||||
};
|
||||
foreach (string r in refused)
|
||||
Check(!FolderAccess.IsSafeRepairRoot(r, out string why) && why.Length > 0, $"refused: '{r}'");
|
||||
}
|
||||
|
||||
private static void OurRoots()
|
||||
{
|
||||
string suite = Dir("suite");
|
||||
Directory.CreateDirectory(Path.Combine(suite, "RynthAi"));
|
||||
Check(FolderAccess.IsSafeRepairRoot(suite, out string w1), "suite folder (has RynthAi): " + w1);
|
||||
string core = Dir("core");
|
||||
File.WriteAllText(Path.Combine(core, "RynthCore.exe"), "x");
|
||||
Check(FolderAccess.IsSafeRepairRoot(core + "\\", out string w2), "core folder (has RynthCore.exe), trailing slash: " + w2);
|
||||
string plug = Dir("plugonly");
|
||||
Directory.CreateDirectory(Path.Combine(plug, "RynthNav"));
|
||||
File.WriteAllText(Path.Combine(plug, "RynthNav", "RynthCore.Plugin.RynthNav.dll"), "x");
|
||||
Check(FolderAccess.IsSafeRepairRoot(plug, out string w3), "suite without RynthAi but with a plugin: " + w3);
|
||||
}
|
||||
|
||||
private static bool MakeJunction(string link, string target)
|
||||
{
|
||||
var psi = new ProcessStartInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "cmd.exe"))
|
||||
{
|
||||
UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true,
|
||||
};
|
||||
psi.ArgumentList.Add("/c");
|
||||
psi.ArgumentList.Add("mklink");
|
||||
psi.ArgumentList.Add("/J");
|
||||
psi.ArgumentList.Add(link);
|
||||
psi.ArgumentList.Add(target);
|
||||
using var p = Process.Start(psi)!;
|
||||
p.WaitForExit(10_000);
|
||||
return p.ExitCode == 0 && Directory.Exists(link);
|
||||
}
|
||||
|
||||
private static void RepairClearsReadOnly()
|
||||
{
|
||||
string suite = Dir("repair-suite");
|
||||
string meta = Path.Combine(suite, "RynthAi", "MetaFiles");
|
||||
Directory.CreateDirectory(meta);
|
||||
string a = Path.Combine(meta, "farm.af");
|
||||
string b = Path.Combine(suite, "RynthAi", "settings.json");
|
||||
File.WriteAllText(a, "x");
|
||||
File.WriteAllText(b, "x");
|
||||
File.SetAttributes(a, FileAttributes.ReadOnly);
|
||||
File.SetAttributes(b, FileAttributes.ReadOnly | FileAttributes.Archive);
|
||||
|
||||
string outside = Dir("outside");
|
||||
string o = Path.Combine(outside, "not-ours.txt");
|
||||
File.WriteAllText(o, "x");
|
||||
File.SetAttributes(o, FileAttributes.ReadOnly);
|
||||
bool junction = MakeJunction(Path.Combine(suite, "link"), outside);
|
||||
|
||||
var report = FolderAccess.Repair(new[] { suite }, WindowsIdentity.GetCurrent().User!, changePermissions: false);
|
||||
Check(report.Roots == 1 && report.Errors == 0, "one root, no errors: " + report);
|
||||
Check(report.ReadOnlyCleared == 2, $"two files cleared (got {report.ReadOnlyCleared})");
|
||||
Check((File.GetAttributes(a) & FileAttributes.ReadOnly) == 0, "meta writable");
|
||||
Check((File.GetAttributes(b) & FileAttributes.ReadOnly) == 0 && (File.GetAttributes(b) & FileAttributes.Archive) != 0, "other attributes kept");
|
||||
if (junction)
|
||||
Check((File.GetAttributes(o) & FileAttributes.ReadOnly) != 0, "the file behind the junction is untouched");
|
||||
else
|
||||
Console.WriteLine(" (no junction could be made here; that part skipped)");
|
||||
Check(report.ExplicitGrants == 0, "no permission changes in this mode");
|
||||
try { Directory.Delete(Path.Combine(suite, "link")); } catch { }
|
||||
}
|
||||
|
||||
private static void RepairRefusesStrangers()
|
||||
{
|
||||
string stranger = Dir("repair-stranger");
|
||||
string f = Path.Combine(stranger, "x.txt");
|
||||
File.WriteAllText(f, "x");
|
||||
File.SetAttributes(f, FileAttributes.ReadOnly);
|
||||
var report = FolderAccess.Repair(new[] { stranger, @"C:\" }, WindowsIdentity.GetCurrent().User!, changePermissions: false);
|
||||
Check(report.Roots == 0 && report.Errors == 2 && !report.Ok, "both refused: " + report);
|
||||
Check((File.GetAttributes(f) & FileAttributes.ReadOnly) != 0, "nothing touched");
|
||||
}
|
||||
|
||||
private static void RuleShape()
|
||||
{
|
||||
var user = new SecurityIdentifier("S-1-5-21-1-2-3-1001");
|
||||
var dir = FolderAccess.ModifyRule(user, container: true);
|
||||
Check((dir.FileSystemRights & FileSystemRights.Modify) == FileSystemRights.Modify, "Modify");
|
||||
Check((dir.FileSystemRights & (FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership)) == 0, "not Full Control");
|
||||
Check(dir.InheritanceFlags == (InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit), "inherited by folders and files");
|
||||
Check(dir.PropagationFlags == PropagationFlags.None && dir.AccessControlType == AccessControlType.Allow, "applies here too, allow");
|
||||
Check(dir.IdentityReference.Value == user.Value, "for that account");
|
||||
Check(FolderAccess.ModifyRule(user, container: false).InheritanceFlags == InheritanceFlags.None, "a file's rule doesn't inherit");
|
||||
}
|
||||
|
||||
private static void CfaEvents()
|
||||
{
|
||||
const string xml =
|
||||
"<Event xmlns='http://schemas.microsoft.com/win/2004/08/events/event'><System><EventID>1123</EventID>" +
|
||||
"<TimeCreated SystemTime='2026-10-12T20:01:02.000Z'/></System><EventData>" +
|
||||
"<Data Name='Product Name'>Microsoft Defender Antivirus</Data><Data Name='Path'>C:\\Users\\p\\Documents\\RynthSuite\\RynthAi\\MetaFiles\\farm.af</Data>" +
|
||||
"<Data Name='Process Name'>C:\\Turbine\\Asheron's Call\\acclient.exe</Data></EventData></Event>" +
|
||||
"<Event xmlns='http://schemas.microsoft.com/win/2004/08/events/event'><System><EventID>1124</EventID>" +
|
||||
"<TimeCreated SystemTime='2026-10-11T08:00:00.000Z'/></System><EventData>" +
|
||||
"<Data Name='Path'>C:\\Users\\p\\Desktop\\x.txt</Data><Data Name='Process Name'>C:\\Tools\\other.exe</Data></EventData></Event>";
|
||||
var list = FolderAccess.ParseCfaEvents(xml);
|
||||
Check(list.Count == 2, $"two events (got {list.Count})");
|
||||
if (list.Count == 2)
|
||||
{
|
||||
Check(list[0].Blocked && FolderAccess.IsGameClient(list[0].Process), "1123 = blocked, acclient");
|
||||
Check(list[0].Path.EndsWith("farm.af"), "path");
|
||||
Check(list[0].Time == new DateTime(2026, 10, 12, 20, 1, 2, DateTimeKind.Utc).ToLocalTime() || list[0].Time.ToUniversalTime().Hour == 20, "time");
|
||||
Check(!list[1].Blocked && !FolderAccess.IsGameClient(list[1].Process), "1124 = audit only, another app");
|
||||
}
|
||||
var day = new DateTime(2026, 10, 13, 12, 0, 0, DateTimeKind.Utc);
|
||||
var info = new FolderAccess.CfaInfo(1, true, list);
|
||||
Check(info.On && info.GameClientBlocks(day).Count == 1, "on and blocking the client");
|
||||
Check(info.GameClientBlocks(day.AddDays(10)).Count == 0, "a block from 10 days ago is history");
|
||||
Check(new FolderAccess.CfaInfo(1, true, list, new() { list[0].Process.ToUpperInvariant() }).GameClientBlocks(day).Count == 0,
|
||||
"the client was allowed through since");
|
||||
Check(new FolderAccess.CfaInfo(0, true, new() { list[1] }).GameClientBlocks(day).Count == 0, "an audit of another app isn't a block of the client");
|
||||
Check(FolderAccess.ParseCfaEvents("").Count == 0 && FolderAccess.ParseCfaEvents("not xml <").Count == 0, "empty / garbage");
|
||||
}
|
||||
|
||||
private static void CfaLive()
|
||||
{
|
||||
var info = FolderAccess.QueryControlledFolderAccess(5);
|
||||
Console.WriteLine($" (this PC: Controlled folder access mode {info.Mode}{(info.ModeKnown ? "" : " (unknown)")}, {info.RecentBlocks.Count} recent event(s))");
|
||||
Check(info.RecentBlocks.Count <= 5, "at most the events asked for");
|
||||
}
|
||||
|
||||
private static void Virtualized()
|
||||
{
|
||||
Check(FolderAccess.IsVirtualizedLocation(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "RynthSuite")), "Program Files (x86)");
|
||||
Check(FolderAccess.IsVirtualizedLocation(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "RynthSuite")), "Program Files");
|
||||
Check(!FolderAccess.IsVirtualizedLocation(@"C:\Games\RynthSuite"), "C:\\Games");
|
||||
Check(!FolderAccess.IsVirtualizedLocation(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + " Extra\\X"), "a look-alike name");
|
||||
Check(FolderAccess.IsSameOrInside(@"C:\A\B", @"C:\A\") && !FolderAccess.IsSameOrInside(@"C:\AB", @"C:\A"), "inside vs prefix");
|
||||
}
|
||||
}
|
||||
26
tools/HotkeyTests/HotkeyTests.csproj
Normal file
26
tools/HotkeyTests/HotkeyTests.csproj
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for the user hotkeys (Settings > Hotkeys, /rc hotkey). src\RynthCore.Engine\
|
||||
Hotkeys\HotkeyModel.cs is compiled in as is (it has no engine dependencies): combo parsing and
|
||||
formatting, matching with exact modifiers, the key-down edge (auto-repeat never re-fires; the
|
||||
keystroke a hotkey takes is eaten, other keys pass), the typing rule (never while a RynthCore
|
||||
text box or AC's chat has the keyboard), conflict warnings, the /rc hotkey parser and the
|
||||
hotkeys.txt round trip. Uses RYNTHCORE_HOTKEYS_FILE (a temp file); never touches
|
||||
%LOCALAPPDATA%\RynthCore.
|
||||
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>HotkeyTests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Hotkeys\HotkeyModel.cs" Link="Engine\HotkeyModel.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
467
tools/HotkeyTests/Program.cs
Normal file
467
tools/HotkeyTests/Program.cs
Normal file
|
|
@ -0,0 +1,467 @@
|
|||
using RynthCore.Engine.Hotkeys;
|
||||
|
||||
namespace HotkeyTests;
|
||||
|
||||
// Offline tests for the user hotkeys. 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 int VK_F1 = 0x70, VK_F5 = 0x74, VK_F12 = 0x7B, VK_NUMPAD3 = 0x63, VK_ADD = 0x6B, VK_PRIOR = 0x21,
|
||||
VK_NEXT = 0x22, VK_RETURN = 0x0D, VK_ESCAPE = 0x1B, VK_LSHIFT = 0xA0, VK_RCONTROL = 0xA3, VK_SHIFT = 0x10,
|
||||
VK_CONTROL = 0x11, VK_OEM_PLUS = 0xBB, VK_OEM_3 = 0xC0, VK_HOME = 0x24, VK_SPACE = 0x20, VK_UP = 0x26;
|
||||
|
||||
private static int Main()
|
||||
{
|
||||
string root = Path.Combine(Path.GetTempPath(), "rynth-hotkey-tests-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(root);
|
||||
try
|
||||
{
|
||||
Run("ComboParsing", ComboParsing);
|
||||
Run("ComboFormatting", ComboFormatting);
|
||||
Run("ComboRoundTripEveryKey", ComboRoundTripEveryKey);
|
||||
Run("ComboParseErrors", ComboParseErrors);
|
||||
Run("MatchingWithModifiers", MatchingWithModifiers);
|
||||
Run("NormalizeVk", NormalizeVk);
|
||||
Run("KeyRepeatEdge", KeyRepeatEdge);
|
||||
Run("TrackerEatsTheWholeKeystroke", TrackerEatsTheWholeKeystroke);
|
||||
Run("TypingSuppression", TypingSuppression);
|
||||
Run("PersistenceRoundTrip", () => PersistenceRoundTrip(root));
|
||||
Run("PersistenceToleratesJunk", PersistenceToleratesJunk);
|
||||
Run("ConflictDetection", ConflictDetection);
|
||||
Run("ActionsResolve", ActionsResolve);
|
||||
Run("CommandParsing", CommandParsing);
|
||||
Run("VTankActions", VTankActions);
|
||||
Run("MetaStateParam", MetaStateParam);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Environment.SetEnvironmentVariable(HotkeyStore.EnvOverride, null);
|
||||
try { Directory.Delete(root, true); } catch { }
|
||||
}
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(_fails == 0 && _asserts > 0 ? $"PASS ({_asserts} checks)" : $"FAIL ({_fails} of {_asserts} checks)");
|
||||
return _fails == 0 && _asserts > 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static void Run(string name, Action body)
|
||||
{
|
||||
Console.WriteLine(name);
|
||||
try { body(); }
|
||||
catch (Exception ex) { _fails++; _asserts++; Console.WriteLine($" [FAIL] threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
|
||||
private static KeyCombo P(string text)
|
||||
{
|
||||
bool ok = HotkeyKeys.TryParse(text, out KeyCombo c, out string err);
|
||||
Check(ok, $"'{text}' parses ({err})");
|
||||
return c;
|
||||
}
|
||||
|
||||
private static void ComboParsing()
|
||||
{
|
||||
Check(P("F1") == new KeyCombo(VK_F1, HotkeyMods.None), "F1");
|
||||
Check(P("ctrl+f5") == new KeyCombo(VK_F5, HotkeyMods.Ctrl), "ctrl+f5 (case)");
|
||||
Check(P("Ctrl + Shift + F12") == new KeyCombo(VK_F12, HotkeyMods.Ctrl | HotkeyMods.Shift), "spaces");
|
||||
Check(P("Shift+Ctrl+F12") == P("Ctrl+Shift+F12"), "modifier order doesn't matter");
|
||||
Check(P("Alt+Num3") == new KeyCombo(VK_NUMPAD3, HotkeyMods.Alt), "Num3");
|
||||
Check(P("Numpad3") == new KeyCombo(VK_NUMPAD3, HotkeyMods.None), "Numpad3 alias");
|
||||
Check(P("Ctrl+Num+") == new KeyCombo(VK_ADD, HotkeyMods.Ctrl), "Num+ after a modifier");
|
||||
Check(P("Num+") == new KeyCombo(VK_ADD, HotkeyMods.None), "Num+ alone");
|
||||
Check(P("Shift+=") == new KeyCombo(VK_OEM_PLUS, HotkeyMods.Shift), "= key");
|
||||
Check(P("Plus") == new KeyCombo(VK_OEM_PLUS, HotkeyMods.None), "Plus alias");
|
||||
Check(P("PgUp") == new KeyCombo(VK_PRIOR, HotkeyMods.None), "PgUp alias");
|
||||
Check(P("Page Down") == new KeyCombo(VK_NEXT, HotkeyMods.None), "Page Down (space)");
|
||||
Check(P("Control+`") == new KeyCombo(VK_OEM_3, HotkeyMods.Ctrl), "Control alias, backtick");
|
||||
Check(P("1") == new KeyCombo('1', HotkeyMods.None), "number row");
|
||||
Check(P("Alt+q") == new KeyCombo('Q', HotkeyMods.Alt), "letter, lower case");
|
||||
Check(P("Del") == new KeyCombo(0x2E, HotkeyMods.None), "Del alias");
|
||||
Check(P("Ctrl+Alt+Shift+Home") == new KeyCombo(VK_HOME, HotkeyMods.Ctrl | HotkeyMods.Alt | HotkeyMods.Shift), "all three");
|
||||
Check(P("\\") == new KeyCombo(0xDC, HotkeyMods.None), "backslash");
|
||||
}
|
||||
|
||||
private static void ComboFormatting()
|
||||
{
|
||||
Check(new KeyCombo(VK_F1, HotkeyMods.Shift | HotkeyMods.Ctrl).ToString() == "Ctrl+Shift+F1", "Ctrl before Shift");
|
||||
Check(new KeyCombo(VK_NUMPAD3, HotkeyMods.Alt | HotkeyMods.Ctrl | HotkeyMods.Shift).ToString() == "Ctrl+Alt+Shift+Num3", "all mods");
|
||||
Check(new KeyCombo(VK_PRIOR, HotkeyMods.None).ToString() == "PageUp", "PageUp");
|
||||
Check(new KeyCombo(VK_ADD, HotkeyMods.Ctrl).ToString() == "Ctrl+Num+", "Ctrl+Num+");
|
||||
Check(default(KeyCombo).ToString() == "(none)", "empty");
|
||||
Check(HotkeyKeys.KeyName(0xE7) == "Key 0xE7", "unnamed key");
|
||||
}
|
||||
|
||||
private static void ComboRoundTripEveryKey()
|
||||
{
|
||||
int named = 0;
|
||||
for (int vk = 1; vk < 256; vk++)
|
||||
{
|
||||
if (!HotkeyKeys.IsBindable(vk)) continue;
|
||||
named++;
|
||||
foreach (HotkeyMods m in new[] { HotkeyMods.None, HotkeyMods.Ctrl, HotkeyMods.Alt | HotkeyMods.Shift, HotkeyMods.Ctrl | HotkeyMods.Alt | HotkeyMods.Shift })
|
||||
{
|
||||
var c = new KeyCombo(vk, m);
|
||||
bool ok = HotkeyKeys.TryParse(c.ToString(), out KeyCombo back, out string err);
|
||||
Check(ok && back == c, $"{c} round-trips ({err})");
|
||||
}
|
||||
}
|
||||
// Letters, digits, F1-F24, numpad 0-9 + 5 ops, 6 nav keys + 4 arrows, space/tab/enter/backspace/pause/scroll, 11 punctuation.
|
||||
Check(named == 26 + 10 + 24 + 15 + 6 + 4 + 6 + 11, $"every named key but Esc is bindable ({named})");
|
||||
Check(!HotkeyKeys.IsBindable(VK_ESCAPE), "Esc not bindable");
|
||||
Check(!HotkeyKeys.IsBindable(VK_SHIFT) && HotkeyKeys.IsModifierKey(VK_LSHIFT) && HotkeyKeys.IsModifierKey(VK_RCONTROL), "modifiers");
|
||||
}
|
||||
|
||||
private static void ComboParseErrors()
|
||||
{
|
||||
foreach (string bad in new[] { "", " ", "Ctrl", "Ctrl+", "Shift+Alt", "Hyper+F1", "F25", "Esc", "Ctrl+Escape", "Banana" })
|
||||
{
|
||||
bool ok = HotkeyKeys.TryParse(bad, out _, out string err);
|
||||
Check(!ok && err.Length > 0, $"'{bad}' refused with a reason");
|
||||
}
|
||||
HotkeyKeys.TryParse("Ctrl", out _, out string e1);
|
||||
Check(e1.Contains("modifier", StringComparison.OrdinalIgnoreCase), "modifier-alone message");
|
||||
HotkeyKeys.TryParse("Esc", out _, out string e2);
|
||||
Check(e2.Contains("Esc"), "Esc message");
|
||||
}
|
||||
|
||||
private static void MatchingWithModifiers()
|
||||
{
|
||||
var list = new List<HotkeyBinding>
|
||||
{
|
||||
new(new KeyCombo(VK_F1, HotkeyMods.Ctrl), "macro"),
|
||||
new(new KeyCombo(VK_F1, HotkeyMods.None), "combat"),
|
||||
new(new KeyCombo(VK_F5, HotkeyMods.Shift), "command", "/ra start", Enabled: false),
|
||||
new(new KeyCombo(VK_F1, HotkeyMods.Ctrl), "looting"), // shadowed by the first
|
||||
};
|
||||
Check(HotkeyMatch.Find(list, new KeyCombo(VK_F1, HotkeyMods.Ctrl))?.Action == "macro", "Ctrl+F1 -> first binding");
|
||||
Check(HotkeyMatch.Find(list, new KeyCombo(VK_F1, HotkeyMods.None))?.Action == "combat", "F1 -> its own binding");
|
||||
Check(HotkeyMatch.Find(list, new KeyCombo(VK_F1, HotkeyMods.Ctrl | HotkeyMods.Shift)) == null, "Ctrl+Shift+F1 doesn't fire Ctrl+F1");
|
||||
Check(HotkeyMatch.Find(list, new KeyCombo(VK_F1, HotkeyMods.Alt)) == null, "Alt+F1 unbound");
|
||||
Check(HotkeyMatch.Find(list, new KeyCombo(VK_F5, HotkeyMods.Shift)) == null, "disabled binding doesn't fire");
|
||||
Check(HotkeyMatch.Find(list, default) == null, "empty combo");
|
||||
Check(HotkeyMatch.Mods(true, false, true) == (HotkeyMods.Ctrl | HotkeyMods.Shift), "Mods()");
|
||||
Check(HotkeyMatch.Mods(false, true, false) == HotkeyMods.Alt, "Mods() alt");
|
||||
}
|
||||
|
||||
private static void NormalizeVk()
|
||||
{
|
||||
Check(HotkeyMatch.NormalizeVk(VK_RETURN, extended: true) == 0, "numpad Enter is AC's");
|
||||
Check(HotkeyMatch.NormalizeVk(VK_RETURN, extended: false) == VK_RETURN, "main Enter");
|
||||
Check(HotkeyMatch.NormalizeVk(VK_LSHIFT, false) == VK_SHIFT, "LShift -> Shift");
|
||||
Check(HotkeyMatch.NormalizeVk(VK_RCONTROL, true) == VK_CONTROL, "RCtrl -> Ctrl");
|
||||
Check(HotkeyMatch.NormalizeVk(VK_HOME, extended: true) == VK_HOME && HotkeyMatch.NormalizeVk(VK_HOME, false) == VK_HOME,
|
||||
"Home on the nav block and on the numpad (NumLock off) are the same key");
|
||||
Check(HotkeyMatch.IsExtended(0x01000000) && !HotkeyMatch.IsExtended(0x00000001), "extended bit");
|
||||
}
|
||||
|
||||
private static void KeyRepeatEdge()
|
||||
{
|
||||
long firstDown = 0x00000001; // repeat count 1, previous state up
|
||||
long repeat = 0x40000001; // bit 30: the key was already down
|
||||
long extendedFirst = 0x01000001;
|
||||
Check(HotkeyMatch.IsFreshPress(firstDown), "first key-down fires");
|
||||
Check(!HotkeyMatch.IsFreshPress(repeat), "auto-repeat doesn't");
|
||||
Check(HotkeyMatch.IsFreshPress(extendedFirst), "extended first press fires");
|
||||
Check(!HotkeyMatch.IsFreshPress(unchecked((int)0xC0000001)), "key-up-shaped lParam (bits 30/31) isn't a fresh press");
|
||||
|
||||
// Simulate holding a bound key: one fire, then repeats, then a new press fires again.
|
||||
var list = new List<HotkeyBinding> { new(new KeyCombo(VK_F5, HotkeyMods.None), "macro") };
|
||||
int fires = 0;
|
||||
foreach (long lp in new[] { firstDown, repeat, repeat, repeat })
|
||||
if (HotkeyMatch.IsFreshPress(lp) && HotkeyMatch.Find(list, new KeyCombo(VK_F5, 0)) != null) fires++;
|
||||
Check(fires == 1, $"holding F5 fires once ({fires})");
|
||||
if (HotkeyMatch.IsFreshPress(firstDown)) fires++;
|
||||
Check(fires == 2, "release and press again fires again");
|
||||
}
|
||||
|
||||
private static void TrackerEatsTheWholeKeystroke()
|
||||
{
|
||||
var t = new HotkeyKeyTracker();
|
||||
// F5 fired: its char, repeats and key-up are eaten.
|
||||
t.Took(VK_F5);
|
||||
Check(t.TakeChar(), "the char from the hotkey's key-down is eaten");
|
||||
Check(!t.TakeChar(), "only that one char");
|
||||
Check(t.IsEaten(VK_F5), "repeat of the hotkey key is eaten");
|
||||
t.Took(VK_F5); // what the service does on a repeat
|
||||
Check(t.TakeChar(), "the repeat's char is eaten too");
|
||||
Check(!t.IsEaten('W'), "another key isn't eaten");
|
||||
t.OtherKeyDown();
|
||||
Check(!t.TakeChar(), "a char after another key's down passes");
|
||||
Check(!t.KeyUp('W'), "another key's up passes");
|
||||
Check(t.KeyUp(VK_F5), "the hotkey key's up is eaten");
|
||||
Check(!t.KeyUp(VK_F5), "a second up passes");
|
||||
Check(!t.IsEaten(VK_F5), "after the up the key is free again");
|
||||
|
||||
t.Took(VK_F1);
|
||||
t.Reset();
|
||||
Check(!t.IsEaten(VK_F1) && !t.TakeChar() && !t.KeyUp(VK_F1), "focus loss forgets held keys");
|
||||
Check(!t.KeyUp(999) && !t.IsEaten(-1), "out-of-range keys are ignored");
|
||||
}
|
||||
|
||||
private static void TypingSuppression()
|
||||
{
|
||||
var f1 = new KeyCombo(VK_F1, HotkeyMods.None);
|
||||
var w = new KeyCombo('W', HotkeyMods.None);
|
||||
var ctrlW = new KeyCombo('W', HotkeyMods.Ctrl);
|
||||
var altNum = new KeyCombo(VK_NUMPAD3, HotkeyMods.Alt);
|
||||
var shiftQ = new KeyCombo('Q', HotkeyMods.Shift);
|
||||
|
||||
var ok = new TypingState(InWorld: true, GameFocused: true, RynthTextFocus: false, AcTextFocus: false);
|
||||
Check(HotkeyRules.Check(ok, w) == HotkeyGate.Fire, "in game, nobody typing: fires");
|
||||
Check(HotkeyRules.Check(ok with { InWorld = false }, f1) == HotkeyGate.NotInWorld, "character select: no");
|
||||
Check(HotkeyRules.Check(ok with { GameFocused = false }, f1) == HotkeyGate.NotFocused, "another app in front: no");
|
||||
Check(HotkeyRules.Check(ok with { RynthTextFocus = true }, ctrlW) == HotkeyGate.RynthTyping, "RynthCore text box: no, even Ctrl combos");
|
||||
Check(HotkeyRules.Check(ok with { AcTextFocus = true }, f1) == HotkeyGate.AcTyping, "AC chat typing: no, even F keys");
|
||||
Check(HotkeyRules.Check(ok with { AcTextFocus = true, RynthTextFocus = true }, f1) == HotkeyGate.RynthTyping, "ours first");
|
||||
|
||||
var unknown = ok with { AcTextFocus = null };
|
||||
Check(HotkeyRules.Check(unknown, w) == HotkeyGate.AcUnknownTextKey, "AC focus unknown: a letter could be typing");
|
||||
Check(HotkeyRules.Check(unknown, shiftQ) == HotkeyGate.AcUnknownTextKey, "Shift+letter could be typing");
|
||||
Check(HotkeyRules.Check(unknown, ctrlW) == HotkeyGate.Fire, "AC focus unknown: Ctrl combo fires");
|
||||
Check(HotkeyRules.Check(unknown, altNum) == HotkeyGate.Fire, "AC focus unknown: Alt combo fires");
|
||||
Check(HotkeyRules.Check(unknown, f1) == HotkeyGate.Fire, "AC focus unknown: F key fires");
|
||||
Check(HotkeyRules.CantBeTyping(new KeyCombo(VK_F12, HotkeyMods.Shift)) && !HotkeyRules.CantBeTyping(w), "CantBeTyping");
|
||||
foreach (HotkeyGate g in Enum.GetValues<HotkeyGate>())
|
||||
Check(HotkeyRules.Describe(g).Length > 0, $"{g} described");
|
||||
}
|
||||
|
||||
private static void PersistenceRoundTrip(string root)
|
||||
{
|
||||
var file = new HotkeyFile(false, new List<HotkeyBinding>
|
||||
{
|
||||
new(new KeyCombo(VK_F1, HotkeyMods.Ctrl), "macro"),
|
||||
new(new KeyCombo(VK_ADD, HotkeyMods.Alt | HotkeyMods.Shift), "command", "/rn bc /ra stop", Enabled: false),
|
||||
new(new KeyCombo(0xDC, HotkeyMods.None), "panel:Dungeon Map"),
|
||||
new(new KeyCombo('5', HotkeyMods.Ctrl), "command", "/lua myscript go\twith a tab"),
|
||||
});
|
||||
string text = HotkeyStore.Serialize(file);
|
||||
HotkeyFile back = HotkeyStore.Parse(text);
|
||||
Check(!back.Enabled, "master switch round-trips");
|
||||
Check(back.Bindings.Count == 4, $"4 bindings ({back.Bindings.Count})");
|
||||
for (int i = 0; i < Math.Min(3, back.Bindings.Count); i++)
|
||||
Check(back.Bindings[i] == file.Bindings[i], $"binding {i} round-trips: {back.Bindings[i]}");
|
||||
Check(back.Bindings.Count > 3 && back.Bindings[3].Command == "/lua myscript go with a tab", "a tab in a command becomes a space");
|
||||
Check(back.Bindings.Count > 1 && back.Bindings[1].Combo.ToString() == "Alt+Shift+Num+", "Num+ survives the file");
|
||||
|
||||
// Through the real file (temp path via the override).
|
||||
string path = Path.Combine(root, "sub", "hotkeys.txt");
|
||||
Environment.SetEnvironmentVariable(HotkeyStore.EnvOverride, path);
|
||||
Check(HotkeyStore.FilePath == path, "override path used");
|
||||
HotkeyFile none = HotkeyStore.Load();
|
||||
Check(none.Enabled && none.Bindings.Count == 0, "no file: on, empty (nothing bound by default)");
|
||||
Check(HotkeyStore.LastWriteUtc() == DateTime.MinValue, "no file: no write time");
|
||||
Check(HotkeyStore.Save(file), "save");
|
||||
Check(File.Exists(path) && !File.Exists(path + ".tmp"), "file written, temp file gone");
|
||||
Check(HotkeyStore.LastWriteUtc() > DateTime.MinValue, "write time");
|
||||
HotkeyFile loaded = HotkeyStore.Load();
|
||||
Check(loaded.Bindings.Count == 4 && loaded.Bindings[0] == file.Bindings[0] && !loaded.Enabled, "load what was saved");
|
||||
Check(HotkeyStore.Save(loaded with { Enabled = true }), "save again (replace)");
|
||||
Check(HotkeyStore.Load().Enabled, "replaced");
|
||||
}
|
||||
|
||||
private static void PersistenceToleratesJunk()
|
||||
{
|
||||
string text = "# comment\r\n\r\nenabled=1\r\non\tF1\tmacro\t\r\nthis is junk\r\non\tBanana\tmacro\t\r\non\tF2\t\t\r\n" +
|
||||
"off\tCtrl+F3\tcombat\r\non\tF4\tcommand\t/ra stop\r\n # indented comment\n";
|
||||
HotkeyFile f = HotkeyStore.Parse(text);
|
||||
Check(f.Enabled, "enabled");
|
||||
Check(f.Bindings.Count == 3, $"junk, unknown key and empty action skipped ({f.Bindings.Count})");
|
||||
Check(f.Bindings.Count == 3 && !f.Bindings[1].Enabled && f.Bindings[1].Action == "combat", "off parsed");
|
||||
Check(f.Bindings.Count == 3 && f.Bindings[2].IsCommand && f.Bindings[2].Command == "/ra stop", "command parsed (CRLF trimmed)");
|
||||
Check(HotkeyStore.Parse(null).Bindings.Count == 0 && HotkeyStore.Parse("").Enabled, "empty text");
|
||||
Check(!HotkeyStore.Parse("enabled=0\n").Enabled, "enabled=0");
|
||||
}
|
||||
|
||||
private static void ConflictDetection()
|
||||
{
|
||||
var list = new List<HotkeyBinding>
|
||||
{
|
||||
new(new KeyCombo(VK_F1, HotkeyMods.None), "macro"),
|
||||
new(new KeyCombo(VK_F5, HotkeyMods.Ctrl), "combat", Enabled: false),
|
||||
new(new KeyCombo(VK_F1, HotkeyMods.None), "looting"),
|
||||
};
|
||||
List<string> add = HotkeyConflicts.Warnings(list, new KeyCombo(VK_F1, HotkeyMods.None));
|
||||
Check(add.Count == 2 && add[0].Contains("Start/stop the macro") && add[0].Contains("that one fires"), $"new F1: both existing reported ({string.Join(" | ", add)})");
|
||||
List<string> edit0 = HotkeyConflicts.Warnings(list, new KeyCombo(VK_F1, HotkeyMods.None), ignoreIndex: 0);
|
||||
Check(edit0.Count == 1 && edit0[0].Contains("this one fires"), "editing the first: it wins over the later duplicate");
|
||||
List<string> edit2 = HotkeyConflicts.Warnings(list, new KeyCombo(VK_F1, HotkeyMods.None), ignoreIndex: 2);
|
||||
Check(edit2.Count == 1 && edit2[0].Contains("that one fires"), "editing the later one: the first wins");
|
||||
List<string> off = HotkeyConflicts.Warnings(list, new KeyCombo(VK_F5, HotkeyMods.Ctrl));
|
||||
Check(off.Count == 1 && off[0].Contains("switched off"), "duplicate of a switched-off binding says so");
|
||||
Check(HotkeyConflicts.Warnings(list, new KeyCombo(VK_F12, HotkeyMods.Alt)).Count == 0, "free combo: no warning");
|
||||
Check(HotkeyConflicts.Warnings(list, default).Count == 0, "empty combo: no warning");
|
||||
|
||||
var shadowed = HotkeyConflicts.Shadowed(list);
|
||||
Check(shadowed.Count == 1 && shadowed[0] == 2, "the later F1 never fires");
|
||||
|
||||
// Keys AC uses.
|
||||
Check(HotkeyConflicts.CommonAcKey(new KeyCombo('W', HotkeyMods.None)) != null, "W");
|
||||
Check(HotkeyConflicts.CommonAcKey(new KeyCombo('D', HotkeyMods.Shift)) != null, "Shift+D (walk) still movement");
|
||||
Check(HotkeyConflicts.CommonAcKey(new KeyCombo('W', HotkeyMods.Ctrl)) == null, "Ctrl+W is free");
|
||||
Check(HotkeyConflicts.CommonAcKey(new KeyCombo(VK_UP, HotkeyMods.None)) != null, "arrow");
|
||||
Check(HotkeyConflicts.CommonAcKey(new KeyCombo(VK_SPACE, HotkeyMods.None)) != null, "Space");
|
||||
Check(HotkeyConflicts.CommonAcKey(new KeyCombo(VK_RETURN, HotkeyMods.None)) != null, "Enter");
|
||||
Check(HotkeyConflicts.CommonAcKey(new KeyCombo(0x09, HotkeyMods.None)) != null, "Tab");
|
||||
Check(HotkeyConflicts.CommonAcKey(new KeyCombo('3', HotkeyMods.None)) != null, "number row");
|
||||
Check(HotkeyConflicts.CommonAcKey(new KeyCombo('3', HotkeyMods.Alt)) == null, "Alt+3 free");
|
||||
Check(HotkeyConflicts.CommonAcKey(new KeyCombo('3', HotkeyMods.Shift)) == null, "Shift+3 not warned");
|
||||
Check(HotkeyConflicts.CommonAcKey(new KeyCombo(VK_NUMPAD3, HotkeyMods.None)) == null, "numpad not warned");
|
||||
Check(HotkeyConflicts.CommonAcKey(new KeyCombo(VK_F5, HotkeyMods.None)) == null, "F keys not warned");
|
||||
List<string> wWarn = HotkeyConflicts.Warnings(new List<HotkeyBinding>(), new KeyCombo('W', HotkeyMods.None));
|
||||
Check(wWarn.Count == 1 && wWarn[0].Contains("AC won't get that key"), "AC-key warning text");
|
||||
}
|
||||
|
||||
private static void ActionsResolve()
|
||||
{
|
||||
Check(HotkeyActions.Resolve("combat")?.Id == "combat", "id");
|
||||
Check(HotkeyActions.Resolve("Toggle Combat")?.Id == "combat", "friendly name");
|
||||
Check(HotkeyActions.Resolve("panel:Dungeon Map")?.Panel == "Dungeon Map", "panel id");
|
||||
Check(HotkeyActions.Resolve("panel dungeonmap")?.Panel == "Dungeon Map", "panel loosely");
|
||||
Check(HotkeyActions.Resolve("inventory")?.Panel == "Inventory", "panel title alone");
|
||||
Check(HotkeyActions.Resolve("force-rebuff")?.Id == "forcerebuff", "dashes ignored");
|
||||
Check(HotkeyActions.Resolve("meta")?.Id == "meta", "'meta' is the Meta toggle, not the Meta panel");
|
||||
Check(HotkeyActions.Resolve("panel meta")?.Panel == "Meta", "'panel meta' is the panel");
|
||||
Check(HotkeyActions.Resolve("nonsense") == null && HotkeyActions.Resolve("") == null, "unknown");
|
||||
var ids = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (HotkeyAction a in HotkeyActions.BuiltIns)
|
||||
{
|
||||
Check(ids.Add(a.Id), $"unique id {a.Id}");
|
||||
Check(HotkeyActions.Find(a.Id) == a, $"Find({a.Id})");
|
||||
Check(HotkeyActions.Resolve(a.Id) == a, $"Resolve({a.Id})");
|
||||
}
|
||||
Check(HotkeyActions.Describe(new HotkeyBinding(new KeyCombo(VK_F1, 0), "command", "/ra start")) == "Chat: /ra start", "describe command");
|
||||
Check(HotkeyActions.Describe(new HotkeyBinding(new KeyCombo(VK_F1, 0), "gone")).Contains("Unknown"), "describe unknown");
|
||||
}
|
||||
|
||||
private static void CommandParsing()
|
||||
{
|
||||
Check(HotkeyCommandParser.Parse("").Verb == HotkeyVerb.Help, "empty -> help");
|
||||
Check(HotkeyCommandParser.Parse("list").Verb == HotkeyVerb.List, "list");
|
||||
Check(HotkeyCommandParser.Parse("LIST").Verb == HotkeyVerb.List, "LIST (case)");
|
||||
Check(HotkeyCommandParser.Parse("actions").Verb == HotkeyVerb.Actions, "actions");
|
||||
Check(HotkeyCommandParser.Parse("status").Verb == HotkeyVerb.Status, "status");
|
||||
Check(HotkeyCommandParser.Parse("on").Verb == HotkeyVerb.On && HotkeyCommandParser.Parse("off").Verb == HotkeyVerb.Off, "on/off");
|
||||
|
||||
HotkeyCommand a = HotkeyCommandParser.Parse("add Ctrl+F1 /ra start");
|
||||
Check(a.Verb == HotkeyVerb.Add && a.Combo == new KeyCombo(VK_F1, HotkeyMods.Ctrl) && a.Action == "command" && a.ChatCommand == "/ra start", "add chat command");
|
||||
HotkeyCommand b = HotkeyCommandParser.Parse("add F5 macro");
|
||||
Check(b.Verb == HotkeyVerb.Add && b.Action == "macro" && b.ChatCommand == "", "add built-in");
|
||||
HotkeyCommand c = HotkeyCommandParser.Parse("add Alt+Num3 panel Dungeon Map");
|
||||
Check(c.Verb == HotkeyVerb.Add && c.Action == "panel:Dungeon Map", "add panel with a space in its name");
|
||||
HotkeyCommand d = HotkeyCommandParser.Parse("add Shift+F2 /rn bc /ra stop ");
|
||||
Check(d.Verb == HotkeyVerb.Add && d.ChatCommand == "/rn bc /ra stop", "command keeps inner spaces, trims ends");
|
||||
HotkeyCommand e = HotkeyCommandParser.Parse("bind Ctrl+Num+ toggle combat");
|
||||
Check(e.Verb == HotkeyVerb.Add && e.Combo == new KeyCombo(VK_ADD, HotkeyMods.Ctrl) && e.Action == "combat", "bind alias, Num+, friendly name");
|
||||
|
||||
Check(HotkeyCommandParser.Parse("add").Verb == HotkeyVerb.Error, "add with nothing");
|
||||
Check(HotkeyCommandParser.Parse("add F5").Verb == HotkeyVerb.Error, "add without action");
|
||||
Check(HotkeyCommandParser.Parse("add Banana macro").Error.Contains("Unknown key"), "add bad key");
|
||||
Check(HotkeyCommandParser.Parse("add F5 dance").Error.Contains("Unknown action"), "add bad action");
|
||||
Check(HotkeyCommandParser.Parse("add Esc macro").Verb == HotkeyVerb.Error, "add Esc refused");
|
||||
|
||||
HotkeyCommand r = HotkeyCommandParser.Parse("remove ctrl+f1");
|
||||
Check(r.Verb == HotkeyVerb.Remove && r.Combo == new KeyCombo(VK_F1, HotkeyMods.Ctrl), "remove");
|
||||
Check(HotkeyCommandParser.Parse("rm F5").Verb == HotkeyVerb.Remove && HotkeyCommandParser.Parse("del F5").Verb == HotkeyVerb.Remove, "rm/del aliases");
|
||||
Check(HotkeyCommandParser.Parse("remove").Verb == HotkeyVerb.Error, "remove without key");
|
||||
Check(HotkeyCommandParser.Parse("disable F5").Verb == HotkeyVerb.Disable && HotkeyCommandParser.Parse("enable F5").Verb == HotkeyVerb.Enable, "enable/disable");
|
||||
Check(HotkeyCommandParser.Parse("off F5").Verb == HotkeyVerb.Disable && HotkeyCommandParser.Parse("on F5").Verb == HotkeyVerb.Enable, "on/off <combo>");
|
||||
Check(HotkeyCommandParser.Parse("frobnicate").Verb == HotkeyVerb.Error, "unknown verb");
|
||||
}
|
||||
|
||||
// VTank's hotkey list (2026-10-13): every action, by VTank's name, in its own dropdown group.
|
||||
private static void VTankActions()
|
||||
{
|
||||
// name -> the /ra command it runs (null: the same code as a RynthCore built-in).
|
||||
var expected = new (string Name, string? Chat)[]
|
||||
{
|
||||
("Meta: set state...", "/ra setmetastate {0}"), ("Start/Stop", null), ("Target lock", "/ra targetlock"),
|
||||
("Navigation", null), ("Looting", null), ("Combat", null), ("Buffing", null), ("Force buff", null),
|
||||
("Cancel force buff", null), ("MeleeLow", "/ra meleelow"), ("MeleeMid", "/ra meleemid"), ("MeleeHigh", "/ra meleehigh"),
|
||||
("NavAddPt", "/ra navaddpt"), ("TestItem", "/ra testitem"), ("PropertyDump", "/ra propertydump"),
|
||||
("Recharge", "/ra recharge"), ("NavPrio", "/ra navprio"), ("LootPrio", "/ra lootprio"),
|
||||
("NavLootPrio", "/ra navlootprio"), ("LootThisCont", "/ra lootthis"),
|
||||
};
|
||||
var vt = HotkeyActions.BuiltIns.Where(a => a.Group == HotkeyActions.VTankGroup).ToList();
|
||||
Check(vt.Count == expected.Length, $"{expected.Length} VTank-style actions ({vt.Count})");
|
||||
for (int i = 0; i < Math.Min(vt.Count, expected.Length); i++)
|
||||
{
|
||||
HotkeyAction a = vt[i];
|
||||
Check(a.Name == expected[i].Name, $"#{i} named '{expected[i].Name}' ({a.Name})");
|
||||
Check(a.Chat == expected[i].Chat, $"{a.Name}: runs {expected[i].Chat ?? "a built-in"} ({a.Chat ?? "built-in"})");
|
||||
Check(a.Id.StartsWith(HotkeyActions.VTankPrefix), $"{a.Name}: id {a.Id} has the vt: prefix");
|
||||
Check(a.Tip.Length > 10 && !a.Tip.Contains("VTank"), $"{a.Name}: a plain tooltip");
|
||||
Check(a.HasParam == (a.Id == HotkeyActions.MetaStateId), $"{a.Name}: only the meta state takes a parameter");
|
||||
}
|
||||
// The VTank group comes after every RynthCore built-in (one block in the dropdown).
|
||||
int firstVt = Array.FindIndex(HotkeyActions.BuiltIns, a => a.Group.Length > 0);
|
||||
Check(firstVt > 0 && HotkeyActions.BuiltIns.Skip(firstVt).All(a => a.Group == HotkeyActions.VTankGroup), "one VTank block at the end");
|
||||
|
||||
// Resolve: ids, VTank names, ids without the prefix; the old built-ins keep winning their own words.
|
||||
Check(HotkeyActions.Resolve("vt:targetlock")?.Name == "Target lock", "vt: id");
|
||||
Check(HotkeyActions.Resolve("targetlock")?.Id == "vt:targetlock", "id without vt:");
|
||||
Check(HotkeyActions.Resolve("Target lock")?.Id == "vt:targetlock", "VTank name");
|
||||
Check(HotkeyActions.Resolve("startstop")?.Id == "vt:startstop", "startstop");
|
||||
Check(HotkeyActions.Resolve("Start/Stop")?.Id == "vt:startstop", "Start/Stop");
|
||||
Check(HotkeyActions.Resolve("LootThisCont")?.Id == "vt:lootthiscont", "LootThisCont");
|
||||
Check(HotkeyActions.Resolve("navlootprio")?.Id == "vt:navlootprio", "navlootprio");
|
||||
Check(HotkeyActions.Resolve("meleemid")?.Id == "vt:meleemid", "meleemid");
|
||||
Check(HotkeyActions.Resolve("combat")?.Id == "combat", "'combat' is still the RynthCore toggle");
|
||||
Check(HotkeyActions.Resolve("meta")?.Id == "meta", "'meta' is still the Meta toggle");
|
||||
Check(HotkeyActions.Resolve("forcerebuff")?.Id == "forcerebuff", "'forcerebuff' is still the RynthCore built-in");
|
||||
|
||||
// Describe and the chat command each runs.
|
||||
var f5 = new KeyCombo(VK_F5, 0);
|
||||
Check(HotkeyActions.Describe(new HotkeyBinding(f5, "vt:recharge")) == "Recharge (VTank-style)", "describe VTank action");
|
||||
Check(HotkeyActions.Describe(new HotkeyBinding(f5, "macro")) == "Start/stop the macro", "RynthCore built-ins unchanged");
|
||||
HotkeyAction tl = HotkeyActions.Find("vt:targetlock")!;
|
||||
Check(HotkeyActions.ChatFor(tl, new HotkeyBinding(f5, tl.Id)) == "/ra targetlock", "Target lock -> /ra targetlock");
|
||||
Check(HotkeyActions.ChatFor(HotkeyActions.Find("vt:startstop")!, new HotkeyBinding(f5, "vt:startstop")) == "", "a built-in has no chat command");
|
||||
|
||||
// /rc hotkey add with VTank actions.
|
||||
HotkeyCommand c = HotkeyCommandParser.Parse("add Ctrl+F5 Target lock");
|
||||
Check(c.Verb == HotkeyVerb.Add && c.Action == "vt:targetlock" && c.ChatCommand == "", "add by VTank name");
|
||||
c = HotkeyCommandParser.Parse("add Alt+1 lootthiscont");
|
||||
Check(c.Verb == HotkeyVerb.Add && c.Action == "vt:lootthiscont", "add by id without vt:");
|
||||
|
||||
// A file with VTank actions round-trips; a stray chat command on one is dropped.
|
||||
var file = new HotkeyFile(true, new List<HotkeyBinding>
|
||||
{
|
||||
new(f5, "vt:navlootprio"),
|
||||
new(new KeyCombo(VK_F1, HotkeyMods.Alt), "vt:recharge", "junk"),
|
||||
});
|
||||
HotkeyFile back = HotkeyStore.Parse(HotkeyStore.Serialize(file));
|
||||
Check(back.Bindings.Count == 2 && back.Bindings[0] == file.Bindings[0], "VTank action round-trips");
|
||||
Check(back.Bindings.Count == 2 && back.Bindings[1].Command == "", "no text kept for an action without a parameter");
|
||||
}
|
||||
|
||||
// "Meta: set state...": the state is the binding's parameter (its Command), kept in the file.
|
||||
private static void MetaStateParam()
|
||||
{
|
||||
var f6 = new KeyCombo(0x75, HotkeyMods.Ctrl);
|
||||
HotkeyAction meta = HotkeyActions.Find(HotkeyActions.MetaStateId)!;
|
||||
Check(meta.Param == "State", "the parameter is the state");
|
||||
var b = new HotkeyBinding(f6, meta.Id, "Hunting Grounds");
|
||||
Check(HotkeyActions.Describe(b) == "Meta: Hunting Grounds", $"describe ({HotkeyActions.Describe(b)})");
|
||||
Check(HotkeyActions.ChatFor(meta, b) == "/ra setmetastate Hunting Grounds", "chat command with the state");
|
||||
Check(HotkeyActions.Describe(new HotkeyBinding(f6, meta.Id)) == "Meta: (no state)", "no state yet");
|
||||
|
||||
HotkeyFile back = HotkeyStore.Parse(HotkeyStore.Serialize(new HotkeyFile(true, new List<HotkeyBinding> { b })));
|
||||
Check(back.Bindings.Count == 1 && back.Bindings[0] == b, "the state survives the file");
|
||||
|
||||
HotkeyCommand c = HotkeyCommandParser.Parse("add Ctrl+F6 metastate Hunting Grounds");
|
||||
Check(c.Verb == HotkeyVerb.Add && c.Action == meta.Id && c.ChatCommand == "Hunting Grounds", $"add metastate <state> ({c.Error})");
|
||||
c = HotkeyCommandParser.Parse("add Ctrl+F6 vt:metastate Default");
|
||||
Check(c.Verb == HotkeyVerb.Add && c.Action == meta.Id && c.ChatCommand == "Default", "add vt:metastate <state>");
|
||||
c = HotkeyCommandParser.Parse("add Ctrl+F6 Meta: set state... Go Home");
|
||||
Check(c.Verb == HotkeyVerb.Add && c.Action == meta.Id && c.ChatCommand == "Go Home", "add by its dropdown name");
|
||||
c = HotkeyCommandParser.Parse("add Ctrl+F6 metastate");
|
||||
Check(c.Verb == HotkeyVerb.Error && c.Error.Contains("needs a state"), $"no state: refused ({c.Error})");
|
||||
Check(HotkeyActions.ResolveWithParam("panel Dungeon Map") == null, "panels take no parameter");
|
||||
Check(HotkeyActions.ResolveWithParam("metastate") == null, "nothing after the action: no parameter");
|
||||
}
|
||||
}
|
||||
23
tools/InventorySelectionTests/InventorySelectionTests.csproj
Normal file
23
tools/InventorySelectionTests/InventorySelectionTests.csproj
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for the Inventory panel's multi-selection (src\RynthCore.Engine\ImGui\Panels\
|
||||
InventorySelection.cs, compiled in): click, Ctrl+click, Shift+click runs (both directions,
|
||||
Ctrl+Shift adding), select all, picked order, and forgetting items that left the inventory.
|
||||
Nothing native: no AC, no ImGui, no engine state.
|
||||
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>InventorySelectionTests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\ImGui\Panels\InventorySelection.cs" Link="Engine\InventorySelection.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
206
tools/InventorySelectionTests/Program.cs
Normal file
206
tools/InventorySelectionTests/Program.cs
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
using RynthCore.Engine.ImGuiBackend.Panels;
|
||||
|
||||
namespace InventorySelectionTests;
|
||||
|
||||
/// <summary>
|
||||
/// The Inventory panel's multi-selection (InventorySelection.cs) without AC or ImGui: the
|
||||
/// grid is a list of ids in the order it shows them, like the panel's filtered list.
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
private static int _checks, _failed;
|
||||
private static string _case = "";
|
||||
|
||||
// The grid as shown: ids in display order (deliberately not sorted).
|
||||
private static readonly uint[] Shown = { 50, 10, 40, 20, 30, 60 };
|
||||
private static readonly Func<uint, uint> Id = static id => id;
|
||||
|
||||
private static int Main()
|
||||
{
|
||||
SingleClick();
|
||||
CtrlToggle();
|
||||
ShiftRunForward();
|
||||
ShiftRunBackward();
|
||||
ShiftRunMovesWithAnchorKept();
|
||||
CtrlShiftAddsRun();
|
||||
ShiftWithoutAnchor();
|
||||
ShiftAnchorNotShown();
|
||||
SelectAllShown();
|
||||
PruneGone();
|
||||
ZeroIdsIgnored();
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
|
||||
Console.WriteLine(_failed == 0 ? "ALL INVENTORY SELECTION TESTS PASSED." : $"{_failed} FAILED.");
|
||||
return _failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static void SingleClick()
|
||||
{
|
||||
Case("click: just that item");
|
||||
var s = new InventorySelection();
|
||||
s.Single(40);
|
||||
Check(s.Count == 1 && s.Contains(40), "one picked");
|
||||
Check(!s.IsMulti, "one is not a group");
|
||||
Check(s.Anchor == 40, "anchor is the clicked item");
|
||||
s.Toggle(20);
|
||||
s.Single(10);
|
||||
Same(s.Ids, new uint[] { 10 }, "a plain click replaces the group");
|
||||
s.Clear();
|
||||
Check(s.Count == 0 && s.Anchor == 0, "clear empties and forgets the anchor");
|
||||
}
|
||||
|
||||
private static void CtrlToggle()
|
||||
{
|
||||
Case("ctrl+click: add or remove one, picked order kept");
|
||||
var s = new InventorySelection();
|
||||
s.Single(40);
|
||||
Check(s.Toggle(20), "ctrl+click adds");
|
||||
Check(s.Toggle(60), "ctrl+click adds another");
|
||||
Check(s.IsMulti, "three is a group");
|
||||
Same(s.Ids, new uint[] { 40, 20, 60 }, "picked order, not grid order");
|
||||
Check(!s.Toggle(20), "ctrl+click on a picked item removes it");
|
||||
Same(s.Ids, new uint[] { 40, 60 }, "the others stay in order");
|
||||
Check(s.Anchor == 20, "anchor follows the last ctrl+click, even a removal");
|
||||
Check(!s.Contains(20), "removed item no longer picked");
|
||||
}
|
||||
|
||||
private static void ShiftRunForward()
|
||||
{
|
||||
Case("shift+click: run forward in grid order");
|
||||
var s = new InventorySelection();
|
||||
s.Single(10); // index 1
|
||||
s.Range(Shown, Id, 30, additive: false); // index 4
|
||||
Same(s.Ids, new uint[] { 10, 40, 20, 30 }, "anchor..clicked, both included, grid order");
|
||||
Check(s.Anchor == 10, "anchor stays");
|
||||
}
|
||||
|
||||
private static void ShiftRunBackward()
|
||||
{
|
||||
Case("shift+click: run backward");
|
||||
var s = new InventorySelection();
|
||||
s.Single(30); // index 4
|
||||
s.Range(Shown, Id, 10, additive: false); // index 1
|
||||
Same(s.Ids, new uint[] { 30, 20, 40, 10 }, "anchor first, walking back to the clicked item");
|
||||
s.Range(Shown, Id, 30, additive: false);
|
||||
Same(s.Ids, new uint[] { 30 }, "shift+click on the anchor itself picks just it");
|
||||
}
|
||||
|
||||
private static void ShiftRunMovesWithAnchorKept()
|
||||
{
|
||||
Case("shift+click again: the run is redrawn from the same anchor");
|
||||
var s = new InventorySelection();
|
||||
s.Single(40); // index 2
|
||||
s.Range(Shown, Id, 60, additive: false); // 40,20,30,60
|
||||
s.Range(Shown, Id, 50, additive: false); // back past the anchor: 40,10,50
|
||||
Same(s.Ids, new uint[] { 40, 10, 50 }, "the old run is replaced, not extended");
|
||||
Check(s.Anchor == 40, "anchor unchanged");
|
||||
}
|
||||
|
||||
private static void CtrlShiftAddsRun()
|
||||
{
|
||||
Case("ctrl+shift+click: adds the run to what is picked");
|
||||
var s = new InventorySelection();
|
||||
s.Single(60);
|
||||
s.Toggle(10); // anchor = 10 (index 1)
|
||||
s.Range(Shown, Id, 20, additive: true); // 10,40,20
|
||||
Same(s.Ids, new uint[] { 60, 10, 40, 20 }, "earlier picks kept, no duplicates");
|
||||
Check(s.Count == 4, "count matches");
|
||||
}
|
||||
|
||||
private static void ShiftWithoutAnchor()
|
||||
{
|
||||
Case("shift+click with nothing picked");
|
||||
var s = new InventorySelection();
|
||||
s.Range(Shown, Id, 20, additive: false);
|
||||
Same(s.Ids, new uint[] { 20 }, "picks just the clicked item");
|
||||
Check(s.Anchor == 20, "and it becomes the anchor");
|
||||
var t = new InventorySelection();
|
||||
t.Range(Shown, Id, 20, additive: true);
|
||||
Same(t.Ids, new uint[] { 20 }, "ctrl+shift with nothing picked adds just it");
|
||||
}
|
||||
|
||||
private static void ShiftAnchorNotShown()
|
||||
{
|
||||
Case("shift+click when the anchor is not on show (other pack, new search)");
|
||||
var s = new InventorySelection();
|
||||
s.Single(999); // picked in another pack
|
||||
s.Range(Shown, Id, 30, additive: false);
|
||||
Same(s.Ids, new uint[] { 30 }, "plain shift: just the clicked item");
|
||||
var t = new InventorySelection();
|
||||
t.Single(999);
|
||||
t.Range(Shown, Id, 30, additive: true);
|
||||
Same(t.Ids, new uint[] { 999, 30 }, "ctrl+shift: the other pack's pick is kept");
|
||||
Check(t.Anchor == 30, "the clicked item is the new anchor");
|
||||
var u = new InventorySelection();
|
||||
u.Single(10);
|
||||
u.Range(Shown, Id, 777, additive: false); // clicked id not in the list (raced a rebuild)
|
||||
Same(u.Ids, new uint[] { 777 }, "clicked item not in the list: just it");
|
||||
}
|
||||
|
||||
private static void SelectAllShown()
|
||||
{
|
||||
Case("select all shown");
|
||||
var s = new InventorySelection();
|
||||
s.Single(999);
|
||||
s.SelectAll(Shown, Id);
|
||||
Same(s.Ids, Shown, "every shown item, in grid order, nothing else");
|
||||
Check(s.Anchor == 50, "anchor is the first shown");
|
||||
s.SelectAll(Array.Empty<uint>(), Id);
|
||||
Check(s.Count == 0 && s.Anchor == 0, "nothing shown: nothing picked");
|
||||
}
|
||||
|
||||
private static void PruneGone()
|
||||
{
|
||||
Case("prune: items that left the inventory are forgotten");
|
||||
var s = new InventorySelection();
|
||||
s.SelectAll(Shown, Id); // anchor 50
|
||||
var still = new HashSet<uint> { 10, 20, 60 };
|
||||
Check(s.Prune(still.Contains), "reports a change");
|
||||
Same(s.Ids, new uint[] { 10, 20, 60 }, "the rest stay, in order");
|
||||
Check(!s.Contains(50) && !s.Contains(40), "gone ones no longer picked");
|
||||
Check(s.Anchor == 0, "a gone anchor is forgotten");
|
||||
Check(!s.Prune(still.Contains), "nothing gone: no change");
|
||||
s.Single(10);
|
||||
s.Toggle(20); // anchor 20
|
||||
Check(!s.Prune(still.Contains) && s.Anchor == 20, "a kept anchor stays");
|
||||
s.Toggle(60); // anchor 60
|
||||
still.Remove(10);
|
||||
Check(s.Prune(still.Contains) && s.Anchor == 60, "an anchor still there survives others going");
|
||||
Same(s.Ids, new uint[] { 20, 60 }, "only the gone one left");
|
||||
}
|
||||
|
||||
private static void ZeroIdsIgnored()
|
||||
{
|
||||
Case("id 0 (no object) is never picked");
|
||||
var s = new InventorySelection();
|
||||
s.Single(0);
|
||||
Check(s.Count == 0 && s.Anchor == 0, "single(0) picks nothing");
|
||||
Check(!s.Toggle(0), "toggle(0) refused");
|
||||
s.SelectAll(new uint[] { 0, 10, 0 }, Id);
|
||||
Same(s.Ids, new uint[] { 10 }, "select all skips 0");
|
||||
}
|
||||
|
||||
// ── harness ─────────────────────────────────────────────────────────
|
||||
|
||||
private static void Case(string name)
|
||||
{
|
||||
_case = name;
|
||||
Console.WriteLine("- " + name);
|
||||
}
|
||||
|
||||
private static void Check(bool ok, string what)
|
||||
{
|
||||
_checks++;
|
||||
if (ok) return;
|
||||
_failed++;
|
||||
Console.WriteLine($" FAIL [{_case}] {what}");
|
||||
}
|
||||
|
||||
private static void Same(IReadOnlyList<uint> got, IReadOnlyList<uint> want, string what)
|
||||
{
|
||||
bool ok = got.Count == want.Count;
|
||||
for (int i = 0; ok && i < got.Count; i++) ok = got[i] == want[i];
|
||||
Check(ok, what + $" (got [{string.Join(",", got)}], want [{string.Join(",", want)}])");
|
||||
}
|
||||
}
|
||||
|
|
@ -19,6 +19,7 @@ internal static class Program
|
|||
UnknownLinesKept();
|
||||
BadFileValues();
|
||||
EditsAreImmutable();
|
||||
SlotSizes();
|
||||
|
||||
Console.WriteLine(_failed == 0 ? $"PASS ({_checks} assertions)" : $"FAIL ({_failed} of {_checks} assertions)");
|
||||
return _failed == 0 ? 0 : 1;
|
||||
|
|
@ -200,4 +201,34 @@ internal static class Program
|
|||
Check(b.Counts.Length == 2 && b.Slots[0] == null && b.Slots.Length == 12, "the new ones have the edits");
|
||||
Check(ItemHudCharacter.Empty.Counts.Length == 0 && ItemHudCharacter.Empty.Slots.All(s => s == null), "Empty stays empty");
|
||||
}
|
||||
|
||||
/// <summary>The Mini Remote's box size: clamped, kept through edits, and saved only when not the default.</summary>
|
||||
private static void SlotSizes()
|
||||
{
|
||||
Case("SlotSizes");
|
||||
var c = ItemHudCharacter.Empty;
|
||||
Check(c.SlotSize == ItemHudCharacter.DefaultSlotSize, "default size");
|
||||
Check(ReferenceEquals(c.WithSlotSize(ItemHudCharacter.DefaultSlotSize), c), "the same size: no change");
|
||||
Check(c.WithSlotSize(1).SlotSize == ItemHudCharacter.MinSlotSize, "clamped to the minimum");
|
||||
Check(c.WithSlotSize(1000).SlotSize == ItemHudCharacter.MaxSlotSize, "clamped to the maximum");
|
||||
var big = c.WithSlotSize(48);
|
||||
var edited = big.WithCount("Mana Scarab", out _).WithSlot(0, new RemoteSlot(1, "Pyreal")).WithSlotCount(12);
|
||||
Check(edited.SlotSize == 48, "other edits keep the size");
|
||||
|
||||
var file = new ItemHudFile.Contents();
|
||||
file.Set("A/Big", big);
|
||||
file.Set("A/Plain", c.WithCount("Healing Kit", out _));
|
||||
string text = ItemHudFile.Write(file);
|
||||
Check(text.Contains("slotsize=48\n"), "a non-default size is written");
|
||||
Check(text.Split("slotsize=").Length == 2, "the default size isn't written");
|
||||
var back = RoundTrip(file);
|
||||
Check(back.For("A/Big").SlotSize == 48 && back.For("A/Plain").SlotSize == ItemHudCharacter.DefaultSlotSize,
|
||||
"sizes read back per character");
|
||||
|
||||
string[] bad = { "[A/B]", "slotsize=banana", "[A/C]", "slotsize=5", "[A/D]", "slotsize=999" };
|
||||
var parsed = ItemHudFile.Parse(bad);
|
||||
Check(parsed.For("A/B").SlotSize == ItemHudCharacter.DefaultSlotSize, "an unreadable size keeps the default");
|
||||
Check(parsed.For("A/C").SlotSize == ItemHudCharacter.MinSlotSize, "a small size clamps up");
|
||||
Check(parsed.For("A/D").SlotSize == ItemHudCharacter.MaxSlotSize, "a large size clamps down");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -474,24 +474,37 @@ 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 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");
|
||||
// The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn end the table.
|
||||
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(3).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(3).TakeLast(6).ToArray();
|
||||
Check(sdkNames.SequenceEqual(names), "SDK v79, v80 and v81 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.
|
||||
// v80: GetContainerOrder and PutItemInContainer come right before v81's slot, engine and SDK alike;
|
||||
// v81: GetMergeStackResult, then v82: SalvageDirect is the table's last slot. The whole table has the same field names in the same
|
||||
// order on both sides, and the same size.
|
||||
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");
|
||||
// v81's GetMergeStackResultFn follows v80's two slots.
|
||||
Check(names.SkipLast(4).TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots before v81's, v82's and v83's: " + string.Join(",", names.SkipLast(4).TakeLast(2)));
|
||||
Check(sdkNames.SkipLast(4).TakeLast(2).SequenceEqual(names.SkipLast(4).TakeLast(2)), "SDK v80 slots in the same order");
|
||||
Check(names.SkipLast(2).Last() == "SalvageDirectFn", "v82 slot before v83's");
|
||||
// v83: GetObjectServerAge and RemoveClientObject end the table (ghost creatures).
|
||||
Check(names.TakeLast(2).SequenceEqual(new[] { "GetObjectServerAgeFn", "RemoveClientObjectFn" }), "v83 slots last: " + string.Join(",", names.TakeLast(2)));
|
||||
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"),
|
||||
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("PutItemInContainerFn"), "PutItemInContainerFn offset");
|
||||
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("SalvageDirectFn"),
|
||||
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("SalvageDirectFn"), "SalvageDirectFn offset");
|
||||
// ClientHelperHooks.MaxSalvageDirectItems (engine side, not linked here) is 100 too.
|
||||
Eq(RynthCore.PluginSdk.RynthCoreHost.MaxSalvageDirectItems, 100, "SalvageDirect item cap");
|
||||
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("RemoveClientObjectFn"),
|
||||
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("RemoveClientObjectFn"), "RemoveClientObjectFn offset");
|
||||
}
|
||||
|
||||
private sealed class ProbePlugin : RynthCore.PluginCore.RynthPluginBase { }
|
||||
|
|
|
|||
159
tools/RadarSettingsTests/Program.cs
Normal file
159
tools/RadarSettingsTests/Program.cs
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
using RynthCore.Engine.UI.Data;
|
||||
using RynthCore.Engine.UI.Panels;
|
||||
|
||||
namespace RynthCore.Engine.UI
|
||||
{
|
||||
/// <summary>Stub of the engine's background writer: runs the write at once.</summary>
|
||||
internal static class UiBackgroundWriter
|
||||
{
|
||||
public static void Enqueue(string label, Action work) => work();
|
||||
}
|
||||
}
|
||||
|
||||
namespace RadarSettingsTests
|
||||
{
|
||||
// Offline tests for the radar's show boxes. 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 readonly string[] FileKeys =
|
||||
{
|
||||
"showMonsters", "showNpcs", "showPortals", "showDoors", "showPlayers", "showFellows",
|
||||
"showPets", "showVendors", "showCorpses", "showOwnCorpses", "showLifestones", "showGroundItems",
|
||||
};
|
||||
|
||||
private static int Main()
|
||||
{
|
||||
string root = Path.Combine(Path.GetTempPath(), "rynth-radar-settings-tests-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(root);
|
||||
try
|
||||
{
|
||||
Run("KindNumbersMatchThePlugin", KindNumbersMatchThePlugin);
|
||||
Run("EachKindHasItsOwnBox", EachKindHasItsOwnBox);
|
||||
Run("CorpsesOffHidesYourCorpses", CorpsesOffHidesYourCorpses);
|
||||
Run("UnknownKindsHidden", UnknownKindsHidden);
|
||||
Run("SnapshotFiltersPerBox", SnapshotFiltersPerBox);
|
||||
Run("FileRoundTrip", () => FileRoundTrip(root));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Environment.SetEnvironmentVariable("RYNTHCORE_RADAR_SETTINGS", null);
|
||||
try { Directory.Delete(root, true); } catch { }
|
||||
}
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(_fails == 0 && _asserts > 0 ? $"PASS ({_asserts} checks)" : $"FAIL ({_fails} of {_asserts} checks)");
|
||||
return _fails == 0 && _asserts > 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static void Run(string name, Action body)
|
||||
{
|
||||
Console.WriteLine(name);
|
||||
SetAll(true);
|
||||
body();
|
||||
}
|
||||
|
||||
private static void SetAll(bool on)
|
||||
{
|
||||
for (byte k = 0; k < RadarKind.Count; k++) RadarSettingsStore.ShowFlag(k) = on;
|
||||
}
|
||||
|
||||
// RynthAi's RynthRadarUi (KindMonster = 0 ... KindGroundItem = 11) sends these numbers;
|
||||
// the legend's labels are bound to them.
|
||||
private static void KindNumbersMatchThePlugin()
|
||||
{
|
||||
Check(RadarKind.Monster == 0 && RadarKind.Npc == 1 && RadarKind.Portal == 2 && RadarKind.Door == 3, "kinds 0-3");
|
||||
Check(RadarKind.Player == 4 && RadarKind.Fellow == 5 && RadarKind.Pet == 6 && RadarKind.Vendor == 7, "kinds 4-7");
|
||||
Check(RadarKind.Corpse == 8 && RadarKind.OwnCorpse == 9 && RadarKind.Lifestone == 10 && RadarKind.GroundItem == 11, "kinds 8-11");
|
||||
Check(RadarKind.Count == 12, "12 kinds");
|
||||
}
|
||||
|
||||
// Turning one box off hides that kind and nothing else (your corpses aside: they sit under Corpses).
|
||||
private static void EachKindHasItsOwnBox()
|
||||
{
|
||||
for (byte off = 0; off < RadarKind.Count; off++)
|
||||
{
|
||||
SetAll(true);
|
||||
RadarSettingsStore.ShowFlag(off) = false;
|
||||
for (byte k = 0; k < RadarKind.Count; k++)
|
||||
{
|
||||
bool expected = k != off && !(off == RadarKind.Corpse && k == RadarKind.OwnCorpse);
|
||||
Check(RadarSettingsStore.ShowKind(k) == expected,
|
||||
$"{RadarKind.Name(off)} off: {RadarKind.Name(k)} shown={RadarSettingsStore.ShowKind(k)}, expected {expected}");
|
||||
}
|
||||
// and back on shows it again
|
||||
RadarSettingsStore.ShowFlag(off) = true;
|
||||
Check(RadarSettingsStore.ShowKind(off), $"{RadarKind.Name(off)} back on");
|
||||
}
|
||||
}
|
||||
|
||||
private static void CorpsesOffHidesYourCorpses()
|
||||
{
|
||||
RadarSettingsStore.ShowCorpses = false;
|
||||
Check(!RadarSettingsStore.ShowKind(RadarKind.Corpse), "Corpses off hides corpses");
|
||||
Check(!RadarSettingsStore.ShowKind(RadarKind.OwnCorpse), "Corpses off hides your corpses");
|
||||
RadarSettingsStore.ShowCorpses = true;
|
||||
RadarSettingsStore.ShowOwnCorpses = false;
|
||||
Check(RadarSettingsStore.ShowKind(RadarKind.Corpse), "Your corpses off keeps other corpses");
|
||||
Check(!RadarSettingsStore.ShowKind(RadarKind.OwnCorpse), "Your corpses off hides your corpses");
|
||||
}
|
||||
|
||||
private static void UnknownKindsHidden()
|
||||
{
|
||||
foreach (byte k in new byte[] { 12, 13, 100, 255 })
|
||||
Check(!RadarSettingsStore.ShowKind(k), $"kind {k} hidden");
|
||||
}
|
||||
|
||||
// One marker of each kind, as RynthAi writes the snapshot: the shown ones follow the boxes.
|
||||
private static void SnapshotFiltersPerBox()
|
||||
{
|
||||
var marks = string.Join(",", Enumerable.Range(0, RadarKind.Count)
|
||||
.Select(k => $"{{\"kind\":{k},\"x\":{k},\"y\":0,\"z\":0,\"label\":\"m{k}\",\"id\":{1000 + k}}}"));
|
||||
RadarSnapshot? snap = RadarSnapshot.Parse("{\"mapVersion\":1,\"markers\":[" + marks + "]}");
|
||||
Check(snap != null && snap.Markers.Count == RadarKind.Count, "snapshot parsed");
|
||||
if (snap == null) return;
|
||||
for (int k = 0; k < RadarKind.Count; k++)
|
||||
Check(snap.Markers[k].Kind == k && snap.Markers[k].Id == 1000 + k, $"marker {k} kind/id");
|
||||
|
||||
RadarSettingsStore.ShowMonsters = false;
|
||||
RadarSettingsStore.ShowPlayers = false;
|
||||
RadarSettingsStore.ShowDoors = false;
|
||||
var shown = snap.Markers.Where(m => RadarSettingsStore.ShowKind(m.Kind)).Select(m => m.Kind).ToHashSet();
|
||||
Check(!shown.Contains(RadarKind.Monster) && !shown.Contains(RadarKind.Player) && !shown.Contains(RadarKind.Door),
|
||||
"monsters, players and doors filtered out");
|
||||
Check(shown.Contains(RadarKind.Fellow), "fellows are their own box: still shown with Players off");
|
||||
Check(shown.Count == RadarKind.Count - 3, $"the other kinds still shown ({shown.Count})");
|
||||
}
|
||||
|
||||
// Every box loads from its key and saves back under it.
|
||||
private static void FileRoundTrip(string root)
|
||||
{
|
||||
string seed = Path.Combine(root, "seed.txt");
|
||||
var lines = new List<string> { "# test" };
|
||||
for (int k = 0; k < RadarKind.Count; k++)
|
||||
lines.Add($"{FileKeys[k]}={(k % 2 == 0 ? 0 : 1)}"); // even kinds off
|
||||
File.WriteAllLines(seed, lines);
|
||||
Environment.SetEnvironmentVariable("RYNTHCORE_RADAR_SETTINGS", seed);
|
||||
RadarSettingsStore.Load();
|
||||
for (byte k = 0; k < RadarKind.Count; k++)
|
||||
Check(RadarSettingsStore.ShowFlag(k) == (k % 2 == 1), $"loaded {FileKeys[k]}");
|
||||
|
||||
string saved = Path.Combine(root, "saved.txt");
|
||||
Environment.SetEnvironmentVariable("RYNTHCORE_RADAR_SETTINGS", saved);
|
||||
SetAll(false);
|
||||
RadarSettingsStore.ShowFlag(RadarKind.Fellow) = true;
|
||||
RadarSettingsStore.Save();
|
||||
string text = File.Exists(saved) ? File.ReadAllText(saved) : "";
|
||||
for (int k = 0; k < RadarKind.Count; k++)
|
||||
{
|
||||
string want = $"{FileKeys[k]}={(k == RadarKind.Fellow ? 1 : 0)}";
|
||||
Check(text.Contains(want + "\n") || text.Contains(want + "\r\n"), $"saved {want}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
27
tools/RadarSettingsTests/RadarSettingsTests.csproj
Normal file
27
tools/RadarSettingsTests/RadarSettingsTests.csproj
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for the radar's per-kind show boxes (RadarSettingsStore.ShowFlag / ShowKind)
|
||||
and the marker kinds (RadarKind) the RynthAi snapshot sends. src\RynthCore.Engine\UI\Panels\
|
||||
RadarSettingsStore.cs and UI\Data\RadarSnapshotJson.cs are compiled in, with a synchronous
|
||||
UiBackgroundWriter stub. Every kind must have its own box, Corpses off must hide your corpses
|
||||
too, unknown kinds stay hidden, a plugin-shaped snapshot filters per box, and every box must
|
||||
round-trip through the settings file. Uses RYNTHCORE_RADAR_SETTINGS (temp files); never
|
||||
touches %LOCALAPPDATA%\RynthCore.
|
||||
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>RadarSettingsTests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Panels\RadarSettingsStore.cs" Link="Engine\RadarSettingsStore.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\RadarSnapshotJson.cs" Link="Engine\RadarSnapshotJson.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -106,6 +106,18 @@ internal static class Program
|
|||
Make("hang_4_new.dmp", now.AddMinutes(-5));
|
||||
Check(UsageStats.CountCrashDumps(dumps, now.AddDays(-1), now) == 2, "only crash_*.dmp newer than the last report count (hangs don't)");
|
||||
Check(UsageStats.CountCrashDumps(Path.Combine(root, "nope"), now.AddDays(-1), now) == 0, "missing dump folder = 0");
|
||||
|
||||
// CoreCLR fatal-error dumps (the loader's clr_<pid>_<time>.dmp) land in the same folder and
|
||||
// count; the OUT OF MEMORY dumps do not. A folder of its own: the report tests below
|
||||
// count the dumps made above.
|
||||
string clrDumps = Path.Combine(root, "clr-dumps");
|
||||
Directory.CreateDirectory(clrDumps);
|
||||
void MakeIn(string name, DateTime t) { string p = Path.Combine(clrDumps, name); File.WriteAllText(p, "x"); File.SetLastWriteTimeUtc(p, t); }
|
||||
MakeIn("crash_5_new.dmp", now.AddMinutes(-4));
|
||||
MakeIn("clr_100_1760138700.dmp", now.AddMinutes(-3));
|
||||
MakeIn("clr_101_1759917600.dmp", now.AddDays(-2));
|
||||
MakeIn("acclient_oom_102_20261010_181816.dmp", now.AddMinutes(-3));
|
||||
Check(UsageStats.CountCrashDumps(clrDumps, now.AddDays(-1), now) == 2, "clr_*.dmp counts beside crash_*.dmp; old ones and OOM dumps don't");
|
||||
}
|
||||
|
||||
private static void OptInOut(string root)
|
||||
|
|
|
|||
|
|
@ -72,6 +72,8 @@ MUTATOR_DELEGATES = {
|
|||
"_eventCloseTradeNegotiations", "_tradeSystemAcceptTrade", "_tradeSystemDeclineTrade",
|
||||
# Salvage panel: open notice + gmSalvageUI AddNewItem/Salvage (UIElement tree)
|
||||
"_sendNoticeOpenSalvagePanel", "_gmSalvageUIAddNewItem", "_gmSalvageUISalvage",
|
||||
# CM_Inventory::Event_CreateTinkeringTool (0x027D salvage without the panel; v82 SalvageDirect)
|
||||
"_eventCreateTinkeringTool",
|
||||
# CombatActionHooks game-action sends (AC heap alloc + send queue; 0xC8 also bumps busy count)
|
||||
"_requestId", "_queryHealth", "_cancelAttack",
|
||||
# MovementActionHooks: CM_Movement::Event_AutonomyLevel (0xF752 game-action send)
|
||||
|
|
@ -84,6 +86,12 @@ MUTATOR_DELEGATES = {
|
|||
"_eventTrainSkillAdvancementClass", # 0x0047 TrainSkill (untrained -> trained with credits)
|
||||
}
|
||||
GATE = "MainThreadGuard.IsOnMainThread"
|
||||
# AcMainThreadQueue.MustQueue(teardown: ...) is the shared mutator gate (MutatorGate.cs): it
|
||||
# asks MainThreadGuard.IsOnMainThread() itself and returns true (queue) off the main thread.
|
||||
# Counted only in the gate's own shape, an if that opens with it (optionally after one
|
||||
# 'flag ||'), searched with // comments stripped, so a commented-out gate is not a gate.
|
||||
# The check is textual: a string literal that spells the shape would still count.
|
||||
GATE_SHAPE = re.compile(r"if\s*\((?:\w+\s*\|\|\s*)?AcMainThreadQueue\.MustQueue\(")
|
||||
ENQUEUE = "AcMainThreadQueue.Enqueue"
|
||||
|
||||
# Pure off-thread PRODUCERS: Timer/pump callbacks that ONLY enqueue (never call an
|
||||
|
|
@ -92,6 +100,7 @@ ENQUEUE = "AcMainThreadQueue.Enqueue"
|
|||
# (file, method) pairs, each verified to do no off-thread AC mutation.
|
||||
ENQUEUE_PRODUCER_ALLOW = {
|
||||
("AutoIdService.cs", "DrainTick"), # appraisal: enqueues 0xC8, sent on main thread in DrainRequestIds
|
||||
("AutoIdService.cs", "QueueIdentify"), # LiveWorld.QueueIdentify, AutoIdDrain's send on the drain timer: only EnqueueRequestId
|
||||
("RynthCoreChatCommands.cs", "Reply"), # /rc and /rv plates replies: only EnqueueWriteToChat
|
||||
("AcMouseOver.cs", "Say"), # /rc acmouse watch lines: only EnqueueWriteToChat (and the log)
|
||||
}
|
||||
|
|
@ -179,7 +188,8 @@ def main():
|
|||
# executor - exempt it from both checks.
|
||||
is_queue = fn == "AcMainThreadQueue.cs"
|
||||
for name, line, body, attrs in split_methods(src):
|
||||
gated = GATE in body
|
||||
gate_code = "\n".join(l.split("//", 1)[0] for l in body.splitlines())
|
||||
gated = GATE in body or GATE_SHAPE.search(gate_code) is not None
|
||||
allowed = is_allowed(name, attrs) or is_queue
|
||||
|
||||
# CHECK A: calls Enqueue but lacks the gate (unless it's a known pure producer).
|
||||
|
|
|
|||
Loading…
Reference in a new issue