From b1c182b05ddf9af9da40c84f9130d0d210757046 Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Sun, 1 Nov 2026 18:47:28 -0500 Subject: [PATCH] Snapshot for release 2026.10.31.4 (internal 34cea02) --- native/Loader/Hooks.c | 33 + native/SehTrampoline/DumpArgs.h | 35 + native/SehTrampoline/SehTrampoline.c | 48 +- native/SehTrampoline/tests/DumpArgsTests.c | 47 ++ .../SehTrampoline/tests/Run-DumpArgsTests.ps1 | 28 + .../Compatibility/AcMainThreadQueue.cs | 13 +- .../Compatibility/ChatCommandReplies.cs | 15 +- .../Compatibility/CombatActionHooks.cs | 28 +- .../Compatibility/HeartbeatLogger.cs | 8 +- .../Compatibility/RynthCoreChatCommands.cs | 122 +++ .../Compatibility/SehTrampoline.cs | 21 + .../Compatibility/SessionStateRegistry.cs | 4 + .../Compatibility/SmartBoxHooks.cs | 4 +- .../Compatibility/VendorRatePolicy.cs | 61 ++ .../Compatibility/VendorTrade.cs | 32 +- src/RynthCore.Engine/CrashDump.cs | 105 ++- src/RynthCore.Engine/D3D9/EndSceneHook.cs | 18 +- .../D3D9/Nav3DRenderInjector.cs | 8 + src/RynthCore.Engine/EntryPoint.cs | 3 + src/RynthCore.Engine/HangDumpCommand.cs | 36 + src/RynthCore.Engine/ImGui/DX9Backend.cs | 140 +++- src/RynthCore.Engine/ImGui/DrawSubmitPlan.cs | 70 ++ .../ImGui/EngineFrameController.cs | 289 +++++-- src/RynthCore.Engine/ImGui/FontPixels.cs | 24 + src/RynthCore.Engine/ImGui/ImGuiBar.cs | 14 + src/RynthCore.Engine/ImGui/ImGuiFonts.cs | 163 +++- src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs | 110 ++- src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs | 3 + .../ImGui/MonsterHud/HealthProbe.cs | 194 +++++ .../ImGui/MonsterHud/MonsterHud.cs | 46 +- .../ImGui/MonsterHud/MonsterHudData.cs | 9 +- .../ImGui/MonsterHud/MonsterHudSettings.cs | 18 +- .../ImGui/MonsterHud/MonsterHudSettingsUi.cs | 8 + src/RynthCore.Engine/ImGui/Panels/ChatFace.cs | 16 +- .../ImGui/Panels/ChatFiltersFace.cs | 22 +- .../ImGui/Panels/Classic/ClassicLootTab.cs | 9 +- .../ImGui/Panels/DamageFace.cs | 49 +- .../ImGui/Panels/ItemsFace.cs | 4 + .../ImGui/Panels/LootEditorFace.cs | 84 +- src/RynthCore.Engine/ImGui/Panels/LuaFace.cs | 31 +- .../ImGui/Panels/MetaFace.Editor.cs | 16 +- .../ImGui/Panels/MetaFace.List.cs | 9 +- src/RynthCore.Engine/ImGui/Panels/MetaFace.cs | 48 +- src/RynthCore.Engine/ImGui/Panels/NavFace.cs | 40 +- src/RynthCore.Engine/ImGui/Panels/P1Faces.cs | 116 ++- .../ImGui/Panels/PluginWindowFace.cs | 21 +- .../ImGui/Panels/RadarFace.cs | 164 +++- .../ImGui/Panels/RadarSelection.cs | 116 +++ .../ImGui/Panels/RynthNavFace.cs | 22 + .../ImGui/Panels/SenseFace.cs | 263 +++++- .../ImGui/Panels/SettingsRows.cs | 42 +- src/RynthCore.Engine/ImGui/UiCost.cs | 216 +++++ src/RynthCore.Engine/ImGui/UiCostModel.cs | 649 +++++++++++++++ .../MainThreadHangWatchdog.cs | 46 +- .../Plugins/EngineSettings.cs | 88 ++ .../Plugins/PluginContract.cs | 3 +- .../Plugins/PluginManager.UiHooks.cs | 3 + src/RynthCore.Engine/Plugins/PluginManager.cs | 16 +- src/RynthCore.Engine/UI/AcWindowChrome.cs | 13 +- src/RynthCore.Engine/UI/Data/ChatData.cs | 22 +- src/RynthCore.Engine/UI/Data/ChatRouting.cs | 72 +- src/RynthCore.Engine/UI/Data/DamageData.cs | 4 + .../UI/Data/DamageRowStats.cs | 92 +++ src/RynthCore.Engine/UI/Data/LuaData.cs | 12 + src/RynthCore.Engine/UI/Data/LuaLiveReload.cs | 29 + src/RynthCore.Engine/UI/Data/MetaData.cs | 27 +- src/RynthCore.Engine/UI/Data/MetaEditing.cs | 71 ++ src/RynthCore.Engine/UI/Data/NavData.cs | 4 + src/RynthCore.Engine/UI/Data/SenseData.cs | 154 +--- src/RynthCore.Engine/UI/Data/SenseModel.cs | 411 ++++++++++ src/RynthCore.Engine/UI/Data/SettingsData.cs | 61 +- src/RynthCore.Engine/UI/LootPatternText.cs | 175 ++++ src/RynthCore.Engine/UI/PanelDrawScale.cs | 77 +- src/RynthCore.Engine/UI/PanelLayout.cs | 452 ++++++++++ src/RynthCore.Engine/UI/PanelLayoutFiles.cs | 123 +++ src/RynthCore.Engine/UI/PanelLayoutPolicy.cs | 354 ++++++++ src/RynthCore.Engine/UI/PanelStateStore.cs | 116 ++- .../UI/Panels/RadarSettingsStore.cs | 28 +- .../UI/Panels/SettingsPanel.cs | 2 + .../UI/Sections/PluginWindows.cs | 2 +- src/RynthCore.Engine/UI/TrackerSettings.cs | 40 +- src/RynthCore.PluginSdk/UiTypes.cs | 6 + .../ChatCommandReplyTests.csproj | 4 + tools/ChatCommandReplyTests/Program.cs | 35 + tools/ChatFilterTests/Program.cs | 215 +++++ .../CleaveGhostTests/CleaveGhostTests.csproj | 6 +- tools/CleaveGhostTests/Program.cs | 100 +++ .../DamageRowStatsTests.csproj | 23 + tools/DamageRowStatsTests/Program.cs | 102 +++ .../EngineRobustnessTests.csproj | 2 + tools/EngineRobustnessTests/Program.cs | 1 + .../EngineRobustnessTests/ReloadStallTests.cs | 65 ++ .../EngineSettingsTests.csproj | 2 + tools/EngineSettingsTests/Program.cs | 38 + tools/LoaderFreezeBench/Run-Bench.ps1 | 25 + tools/LoaderFreezeBench/bench.c | 118 +++ .../LootPatternTextTests.csproj | 23 + tools/LootPatternTextTests/Program.cs | 92 +++ tools/MetaEditTests/Program.cs | 45 + .../PanelLayoutTests/PanelLayoutTests.csproj | 34 + tools/PanelLayoutTests/Program.cs | 770 ++++++++++++++++++ .../PlateSizingTests/PlateSizingTests.csproj | 3 + tools/PlateSizingTests/Program.cs | 45 + tools/RadarSettingsTests/Program.cs | 165 ++++ .../RadarSettingsTests.csproj | 4 +- tools/SelfPlateTests/SelfPlateTests.csproj | 1 + tools/SenseTests/Program.cs | 248 ++++++ tools/SenseTests/SenseTests.csproj | 26 + tools/TrackerSettingsTests/Program.cs | 88 ++ .../TrackerSettingsTests.csproj | 23 + tools/UiCostTests/Program.cs | 498 +++++++++++ tools/UiCostTests/UiCostTests.csproj | 32 + tools/VendorRateTests/Program.cs | 97 +++ tools/VendorRateTests/VendorRateTests.csproj | 24 + 114 files changed, 8695 insertions(+), 456 deletions(-) create mode 100644 native/SehTrampoline/DumpArgs.h create mode 100644 native/SehTrampoline/tests/DumpArgsTests.c create mode 100644 native/SehTrampoline/tests/Run-DumpArgsTests.ps1 create mode 100644 src/RynthCore.Engine/Compatibility/VendorRatePolicy.cs create mode 100644 src/RynthCore.Engine/HangDumpCommand.cs create mode 100644 src/RynthCore.Engine/ImGui/DrawSubmitPlan.cs create mode 100644 src/RynthCore.Engine/ImGui/FontPixels.cs create mode 100644 src/RynthCore.Engine/ImGui/MonsterHud/HealthProbe.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/RadarSelection.cs create mode 100644 src/RynthCore.Engine/ImGui/UiCost.cs create mode 100644 src/RynthCore.Engine/ImGui/UiCostModel.cs create mode 100644 src/RynthCore.Engine/UI/Data/DamageRowStats.cs create mode 100644 src/RynthCore.Engine/UI/Data/LuaLiveReload.cs create mode 100644 src/RynthCore.Engine/UI/Data/SenseModel.cs create mode 100644 src/RynthCore.Engine/UI/LootPatternText.cs create mode 100644 src/RynthCore.Engine/UI/PanelLayout.cs create mode 100644 src/RynthCore.Engine/UI/PanelLayoutFiles.cs create mode 100644 src/RynthCore.Engine/UI/PanelLayoutPolicy.cs create mode 100644 tools/DamageRowStatsTests/DamageRowStatsTests.csproj create mode 100644 tools/DamageRowStatsTests/Program.cs create mode 100644 tools/EngineRobustnessTests/ReloadStallTests.cs create mode 100644 tools/LoaderFreezeBench/Run-Bench.ps1 create mode 100644 tools/LoaderFreezeBench/bench.c create mode 100644 tools/LootPatternTextTests/LootPatternTextTests.csproj create mode 100644 tools/LootPatternTextTests/Program.cs create mode 100644 tools/PanelLayoutTests/PanelLayoutTests.csproj create mode 100644 tools/PanelLayoutTests/Program.cs create mode 100644 tools/SenseTests/Program.cs create mode 100644 tools/SenseTests/SenseTests.csproj create mode 100644 tools/TrackerSettingsTests/Program.cs create mode 100644 tools/TrackerSettingsTests/TrackerSettingsTests.csproj create mode 100644 tools/UiCostTests/Program.cs create mode 100644 tools/UiCostTests/UiCostTests.csproj create mode 100644 tools/VendorRateTests/Program.cs create mode 100644 tools/VendorRateTests/VendorRateTests.csproj diff --git a/native/Loader/Hooks.c b/native/Loader/Hooks.c index 2f0afce..cc18194 100644 --- a/native/Loader/Hooks.c +++ b/native/Loader/Hooks.c @@ -29,6 +29,9 @@ // init export returns (HooksFlush; on a first launch AC's main thread is still suspended // then), on every reload, and ~20 ms after the last change otherwise (a background // flusher). A hook's slot is set at once; its patch follows within that window. +// Each freeze runs with the process in HIGH priority class (BoostForFreeze): on a busy +// machine the freeze otherwise waited seconds on low-priority threads, with AC's main +// thread suspended all that time (2026-11-01). // ============================================================================ #include "Loader.h" @@ -84,6 +87,8 @@ static HANDLE g_dirtyEvent; static volatile DWORD g_lastChange; static void FlushLocked(const char* why); +static DWORD BoostForFreeze(void); +static void RestoreAfterFreeze(DWORD cls); static DWORD WINAPI Flusher(LPVOID unused) { @@ -143,7 +148,9 @@ static void SetPatched(int i, int patched) { HookEntry* e = &g_hooks[i]; if (e->patched == patched) return; + DWORD cls = BoostForFreeze(); // each call is a freeze of its own int st = patched ? p_enable(e->target) : p_disable(e->target); + RestoreAfterFreeze(cls); if (st == MH_OK) e->patched = patched; else LoaderLog("ERR", "Hooks: MinHook %s %p failed: %d", patched ? "enable" : "disable", e->target, st); } @@ -162,6 +169,30 @@ static void Want(int i, int patched) SetEvent(g_dirtyEvent); } +// Raises the process to HIGH_PRIORITY_CLASS for one MinHook freeze; returns the class to put +// back (0 = left as it was). MinHook's freeze suspends the process's threads one by one and reads +// each one's context (GetThreadContext), and that read waits until the suspended thread itself +// gets a CPU to run the kernel's get-context APC. A LOWEST or BELOW_NORMAL thread (AC's d3d9 +// workers, the engine's heartbeat) on a machine saturated by normal-priority work (every client +// hot reloading at once) waits seconds for that, while the threads already suspended, AC's main +// thread first among them, stay frozen: the 4-7 s "applied in one freeze" lines and main-thread +// hangs of the 2026-10-31/11-01 reloads. In HIGH class a LOWEST thread is at 11, above every +// normal process, so the reads come back at once (tools\LoaderFreezeBench measures both). Every +// other thread is suspended for most of the window, so the boost doesn't let this process take +// CPU from the other clients beyond the freeze itself. +static DWORD BoostForFreeze(void) +{ + HANDLE self = GetCurrentProcess(); + DWORD cls = GetPriorityClass(self); + if (cls == 0 || cls == HIGH_PRIORITY_CLASS || cls == REALTIME_PRIORITY_CLASS) return 0; + return SetPriorityClass(self, HIGH_PRIORITY_CLASS) ? cls : 0; +} + +static void RestoreAfterFreeze(DWORD cls) +{ + if (cls != 0) SetPriorityClass(GetCurrentProcess(), cls); +} + // Applies every pending patch/unpatch in one MinHook freeze. (Caller holds g_lock.) static void FlushLocked(const char* why) { @@ -176,7 +207,9 @@ static void FlushLocked(const char* why) } if (n == 0) return; DWORD t0 = GetTickCount(); + DWORD cls = BoostForFreeze(); int st = p_applyQueued(); + RestoreAfterFreeze(cls); if (st == MH_OK) { for (int k = 0; k < n; k++) g_hooks[queued[k]].patched = g_hooks[queued[k]].want; LoaderLog("INF", "Hooks: %d patch(es) applied in one freeze (%lu ms, %s).", n, GetTickCount() - t0, why); diff --git a/native/SehTrampoline/DumpArgs.h b/native/SehTrampoline/DumpArgs.h new file mode 100644 index 0000000..1c35ed6 --- /dev/null +++ b/native/SehTrampoline/DumpArgs.h @@ -0,0 +1,35 @@ +/* + * DumpArgs.h - the command line of RC_DumpProcess (SehTrampoline.c): " ", the + * path being the rest of the line (spaces kept, trailing spaces and a closing quote dropped). + * The engine writes it (src\RynthCore.Engine\HangDumpCommand.cs). Pure: tests\DumpArgsTests.c. + */ +#pragma once +#include + +/* 1 when `cmd` holds a pid above 0 and a non-empty path that fits `cap` characters (with its 0). */ +static int ParseDumpArgs(const wchar_t* cmd, unsigned long* pid, wchar_t* path, int cap) +{ + unsigned long p = 0; + int n = 0; + if (!cmd || !pid || !path || cap < 2) return 0; + path[0] = 0; + while (*cmd == L' ' || *cmd == L'\t') cmd++; + if (*cmd < L'0' || *cmd > L'9') return 0; + while (*cmd >= L'0' && *cmd <= L'9') { + unsigned long d = (unsigned long)(*cmd - L'0'); + if (p > (4294967295UL - d) / 10) return 0; /* would overflow */ + p = p * 10 + d; + cmd++; + } + if (*cmd != L' ' && *cmd != L'\t') return 0; + while (*cmd == L' ' || *cmd == L'\t') cmd++; + if (*cmd == L'"') cmd++; + while (*cmd && *cmd != L'"') { + if (n >= cap - 1) return 0; /* too long: refuse rather than cut the name */ + path[n++] = *cmd++; + } + while (n > 0 && (path[n - 1] == L' ' || path[n - 1] == L'\t')) n--; + path[n] = 0; + *pid = p; + return p != 0 && n > 0; +} diff --git a/native/SehTrampoline/SehTrampoline.c b/native/SehTrampoline/SehTrampoline.c index f31a04e..3ea92d3 100644 --- a/native/SehTrampoline/SehTrampoline.c +++ b/native/SehTrampoline/SehTrampoline.c @@ -27,7 +27,9 @@ #include /* File version of this native module (bump with every behavioural change). */ -#define RC_SEH_TRAMPOLINE_VERSION 8 /* v8: noise repeats only at powers of two, capped relogs per address, +#define RC_SEH_TRAMPOLINE_VERSION 9 /* v9: RC_DumpProcess, the hang dump written from rundll32 (out of + the client's process); + v8: noise repeats only at powers of two, capped relogs per address, a total byte budget for native-crash.log (CrashLogFilter.h); v7: stack sweeps bounded by this thread's stack (TEB), never reading at or past StackBase; @@ -1008,3 +1010,47 @@ SEH_GameTickThiscall(void* fn, void* this_ptr, int* out_result, RC_SEH_LEAVE(); return 1; } + +/* ── Out-of-process minidump (rundll32 entry) ───────────────────────────── + * The engine's hang watchdog runs + * %windir%\SysWOW64\rundll32.exe "",RC_DumpProcess + * so the dump of a hung client is written from another process: MiniDumpWriteDump on the + * client itself suspends every other thread and then needs the process heap, which a + * suspended thread may hold (2026-10-31: a client deadlocked for good that way). dbghelp comes + * from the system folder, not AC's own 2003 copy. The process exit code says how it went: + * 0 written, 1 bad arguments, 2 OpenProcess, 3 CreateFile, 4 dbghelp, 5 MiniDumpWriteDump + * (the file is deleted). Nothing runs in the client's process. */ +#include "DumpArgs.h" + +typedef BOOL (WINAPI *Fn_MiniDumpWriteDump)(HANDLE, DWORD, HANDLE, DWORD, void*, void*, void*); + +static UINT DumpProcessCore(const wchar_t* cmd) +{ + unsigned long pid = 0; + wchar_t path[MAX_PATH]; + if (!ParseDumpArgs(cmd, &pid, path, MAX_PATH)) return 1; + + HANDLE proc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_DUP_HANDLE, FALSE, pid); + if (!proc) return 2; + HANDLE file = CreateFileW(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (file == INVALID_HANDLE_VALUE) { CloseHandle(proc); return 3; } + HMODULE dbghelp = LoadLibraryExW(L"dbghelp.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); + Fn_MiniDumpWriteDump write = dbghelp ? (Fn_MiniDumpWriteDump)GetProcAddress(dbghelp, "MiniDumpWriteDump") : NULL; + UINT rc = 4; + if (write) { + /* MiniDumpNormal (every thread's stack) | WithHandleData | WithUnloadedModules | WithThreadInfo */ + rc = write(proc, pid, file, 0x00000000 | 0x00000004 | 0x00000020 | 0x00001000, NULL, NULL, NULL) ? 0 : 5; + } + CloseHandle(file); + CloseHandle(proc); + if (rc != 0) DeleteFileW(path); + return rc; +} + +__declspec(dllexport) void CALLBACK RC_DumpProcessW(HWND hwnd, HINSTANCE inst, LPWSTR cmdLine, int show) +{ + (void)hwnd; (void)inst; (void)show; + ExitProcess(DumpProcessCore(cmdLine)); +} +/* rundll32 looks the entry up by its plain name (it tries RC_DumpProcessW first). */ +#pragma comment(linker, "/EXPORT:RC_DumpProcessW=_RC_DumpProcessW@16") diff --git a/native/SehTrampoline/tests/DumpArgsTests.c b/native/SehTrampoline/tests/DumpArgsTests.c new file mode 100644 index 0000000..a48f9e1 --- /dev/null +++ b/native/SehTrampoline/tests/DumpArgsTests.c @@ -0,0 +1,47 @@ +/* + * DumpArgsTests.c - offline checks for DumpArgs.h (RC_DumpProcess's command line, the hang + * dump written from rundll32). Build and run with Run-DumpArgsTests.ps1 (x86 MSVC). Exit 0 = pass. + */ +#include +#include +#include +#include "../DumpArgs.h" + +static int g_checks, g_failed; + +static void check(int ok, const char* what) +{ + g_checks++; + if (ok) return; + g_failed++; + printf("[FAIL] %s\n", what); +} + +int main(void) +{ + unsigned long pid; + wchar_t path[260]; + + /* What HangDumpCommand.Arguments leaves for the entry (rundll32 passes the text after the entry name). */ + check(ParseDumpArgs(L"17132 C:\\Games\\RynthCore\\Logs\\dumps\\hang_17132_20261031_211714.dmp", &pid, path, 260) + && pid == 17132 && wcscmp(path, L"C:\\Games\\RynthCore\\Logs\\dumps\\hang_17132_20261031_211714.dmp") == 0, + "pid and path"); + check(ParseDumpArgs(L" 42 C:\\Users\\Some One's PC\\a b.dmp ", &pid, path, 260) + && pid == 42 && wcscmp(path, L"C:\\Users\\Some One's PC\\a b.dmp") == 0, + "spaces and an apostrophe in the path are kept, the ends trimmed"); + check(ParseDumpArgs(L"7 \"C:\\x y\\z.dmp\"", &pid, path, 260) && pid == 7 && wcscmp(path, L"C:\\x y\\z.dmp") == 0, + "a quoted path loses its quotes"); + check(!ParseDumpArgs(L"", &pid, path, 260), "empty refused"); + check(!ParseDumpArgs(NULL, &pid, path, 260), "null refused"); + check(!ParseDumpArgs(L"123", &pid, path, 260), "no path refused"); + check(!ParseDumpArgs(L"0 C:\\a.dmp", &pid, path, 260), "pid 0 refused"); + check(!ParseDumpArgs(L"x C:\\a.dmp", &pid, path, 260), "no pid refused"); + check(!ParseDumpArgs(L"12x C:\\a.dmp", &pid, path, 260), "a pid run into text refused"); + check(!ParseDumpArgs(L"99999999999 C:\\a.dmp", &pid, path, 260), "an overflowing pid refused"); + check(ParseDumpArgs(L"4294967295 C:\\a.dmp", &pid, path, 260) && pid == 4294967295UL, "the largest pid"); + check(!ParseDumpArgs(L"5 C:\\abcdefgh.dmp", &pid, path, 8), "a path longer than the buffer refused, not cut"); + check(ParseDumpArgs(L"5 C:\\a.dmp", &pid, path, 9) && wcscmp(path, L"C:\\a.dmp") == 0, "a path that just fits"); + + printf("%d check(s), %d failed.\n", g_checks, g_failed); + return g_failed == 0 ? 0 : 1; +} diff --git a/native/SehTrampoline/tests/Run-DumpArgsTests.ps1 b/native/SehTrampoline/tests/Run-DumpArgsTests.ps1 new file mode 100644 index 0000000..b476d3b --- /dev/null +++ b/native/SehTrampoline/tests/Run-DumpArgsTests.ps1 @@ -0,0 +1,28 @@ +# Run-DumpArgsTests.ps1 +# Builds and runs DumpArgsTests.c (x86 MSVC, the same toolchain as the DLL). +# -OutDir: where the test exe goes (default: native\SehTrampoline\tests\bin). Exit 0 = pass. + +param([string]$OutDir = (Join-Path $PSScriptRoot "bin")) + +$ErrorActionPreference = "Stop" + +$vsPath = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" ` + -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 ` + -property installationPath 2>$null +if (-not $vsPath) { Write-Error "Visual Studio with C++ tools not found."; exit 1 } + +$vcVer = (Get-ChildItem "$vsPath\VC\Tools\MSVC" | Sort-Object Name -Descending | Select-Object -First 1).Name +$vcBase = "$vsPath\VC\Tools\MSVC\$vcVer" +$cl = "$vcBase\bin\Hostx86\x86\cl.exe" +$sdkVer = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" | Sort-Object Name -Descending | Select-Object -First 1).Name +$sdkInc = "C:\Program Files (x86)\Windows Kits\10\Include\$sdkVer" +$sdkLib = "C:\Program Files (x86)\Windows Kits\10\Lib\$sdkVer" +$env:INCLUDE = "$vcBase\include;$sdkInc\ucrt;$sdkInc\um;$sdkInc\shared" +$env:LIB = "$vcBase\lib\x86;$sdkLib\ucrt\x86;$sdkLib\um\x86" + +New-Item -ItemType Directory -Path $OutDir -Force | Out-Null +$exe = Join-Path $OutDir "DumpArgsTests.exe" +& $cl /nologo /W4 /WX "$PSScriptRoot\DumpArgsTests.c" /Fo"$OutDir\\" /Fe"$exe" /link /MACHINE:X86 +if ($LASTEXITCODE -ne 0) { Write-Error "Compilation failed."; exit $LASTEXITCODE } +& $exe +exit $LASTEXITCODE diff --git a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs index 414d5ab..602dd6f 100644 --- a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs +++ b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs @@ -1006,12 +1006,16 @@ internal static class AcMainThreadQueue // main-thread-only like 0xC8. Same shape as the RequestId slot: its own small // queue, NOT the gesture-deferred action ring (a packet send doesn't perturb the // motion graph and a health query must not wait out a swing). Callers ignore the - // result and only want the async 0x01C0 reply, so a target already waiting here is - // not queued twice. Pre-sized, so enqueue does not allocate. + // result and only want the async 0x01C0 reply, so a target that is already the LAST + // one waiting here is not queued twice. Only the last: the server streams health for + // the most recent query, so "pet, then the fight target again" must keep that order + // even when the fight target was already queued before the pet (deduping against any + // earlier entry left the stream on the pet). Pre-sized, so enqueue does not allocate. private const int MaxQueryHealthQueue = 64; private static readonly System.Collections.Generic.Queue<(uint Id, long At, int Epoch)> _queryHealthQueue = new(MaxQueryHealthQueue); private static readonly object _queryHealthLock = new(); private static int _queryHealthPending; // lock-free "anything queued?" for the per-frame drain + private static uint _queryHealthLastId; // the newest entry's id (under _queryHealthLock) // Pump-thread enqueue. Drops (returns false) if the queue is full. public static bool EnqueueQueryHealth(uint targetId) @@ -1019,14 +1023,15 @@ internal static class AcMainThreadQueue if (targetId == 0) return false; lock (_queryHealthLock) { - foreach (var q in _queryHealthQueue) - if (q.Id == targetId) return true; // already pending; one reply answers both + if (_queryHealthQueue.Count > 0 && _queryHealthLastId == targetId) + return true; // already the last pending; one reply answers both, the order holds if (_queryHealthQueue.Count >= MaxQueryHealthQueue) { Interlocked.Increment(ref _dropped); return false; } _queryHealthQueue.Enqueue((targetId, NowMs, Volatile.Read(ref _loginEpoch))); + _queryHealthLastId = targetId; Volatile.Write(ref _queryHealthPending, _queryHealthQueue.Count); return true; } diff --git a/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs b/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs index 08be2c9..a36ce99 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs @@ -122,7 +122,7 @@ internal static class ChatCommandReplies "debuffs [on|off] | debuffs size <50-200%> | others [on|off] | numbers [dealt|taken|heals|kills] [on|off] | " + "gains [xp|lum|radiance] [on|off] | npcs [on|off] | npcs dist |max | players [on|off] | portals [on|off] | portals dist | " + "all|engaged |dist |max |scale |opacity |lift | " + - "names|hp|level|weak|distance|fade|click [on|off] | reset | status | test"; + "names|hp|level|weak|distance|fade|click [on|off] | refresh [on|off] | refresh | reset | status | test"; public const string ServerUsage = "Usage: /rc server [ auto|on|off] | pick |auto | [aelrynth|other|auto] | names ilt [add|remove ]"; @@ -189,15 +189,26 @@ internal static class ChatCommandReplies V("hotkey", HotkeyUsage, null), V("rl", "Usage: /rc rl (reloads RynthCore, as the bar's RL button)", NoArgs, "reload"), V("inventory", "Usage: /rc inventory (opens or closes the Inventory panel)", NoArgs, "inv"), - V("sense", "Usage: /rc sense (opens or closes the Sense panel)", NoArgs), + V("sense", RynthCore.Engine.UI.Data.SenseLayout.Usage, RynthCore.Engine.UI.Data.SenseLayout.IsValidArgs), V("characters", "Usage: /rc characters (opens or closes RynthNet's Characters window)", NoArgs, "chars"), V("itemcount", "Usage: /rc itemcount (opens or closes the Item Count panel)", NoArgs, "itemhud"), V("resetbar", "Usage: /rc resetbar (moves the RynthCore bar back to the top-left corner)", NoArgs, "barreset"), V("actionstate", "Usage: /rc actionstate (the client's item-action gates)", NoArgs, "actions"), V("unlockactions", "Usage: /rc unlockactions (opens the client's item-action gates now)", NoArgs, "unlock"), V("vitals", "Usage: /rc vitals (the old vitals HUD is gone: /rv plates self)", NoArgs, "hud"), + V("layout", "Usage: /rc layout [status] | default | reset [confirm]", LayoutArgs), + V("uicost", UiCostUsage, null), }; + /// /rc uicost: the UI frame cost breakdown (ImGui/UiCost.cs). + public const string UiCostUsage = + "Usage: /rc uicost [on|off||now|status] (alone: now; = the slow-frame threshold, 5-2000)"; + + /// "/rc layout": nothing or status, default, reset, reset confirm (any spacing). + private static bool LayoutArgs(string a) => + string.Join(' ', a.Split(' ', StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant() + is "" or "status" or "default" or "reset" or "reset confirm"; + /// The verb names (its name or another spelling), or null. public static ChatVerb? Find(string word) { diff --git a/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs b/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs index f4b18fe..9602fbe 100644 --- a/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs @@ -438,6 +438,8 @@ internal static class CombatActionHooks if (AcMainThreadQueue.MustQueue(teardown: false)) return targetId != 0 && AcMainThreadQueue.EnqueueQueryHealth(targetId); + // The server streams health for the last id queried: the HUD's probes put it back here. + ImGuiBackend.Hud.HealthProbe.NoteQuery(targetId); try { return _queryHealth(targetId); @@ -448,6 +450,30 @@ internal static class CombatActionHooks } } + /// + /// The nameplates' health probe (MonsterHud.ProbeHealth): a 0x1BF for , then + /// one for (the stream's owner) so the selected / fight target keeps its + /// live 0x01C0 stream. Both go out back to back on AC's main thread, in order; false (nothing sent) off + /// it or in a death / portal window. No owner (0): no second query - the stream stays on the probed + /// monster and its updates stay the HUD's until someone else queries (HealthProbe.IsProbeReply). + /// + internal static bool SendHudHealthProbe(uint probeId, uint restoreId, long nowMs) + { + if (_queryHealth == null || probeId == 0 || probeId == restoreId || AcMainThreadQueue.MustQueue(teardown: false)) + return false; + try + { + ImGuiBackend.Hud.HealthProbe.NoteProbe(probeId, nowMs, sticky: restoreId == 0); + _queryHealth(probeId); + if (restoreId != 0) _queryHealth(restoreId); + return true; + } + catch + { + return false; + } + } + public static bool RequestId(uint objectId) { if (_requestId == null || objectId == 0) @@ -1016,7 +1042,7 @@ internal static class CombatActionHooks if (playerId != 0 && targetId == playerId && healthRatio > 0f && healthRatio <= 1f) PlayerVitalsHooks.UpdateMaxFromHealthRatio(healthRatio); - PluginManager.QueueUpdateHealth(targetId, healthRatio, currentHealth, maxHealth); + PluginManager.QueueUpdateHealth(targetId, healthRatio, currentHealth, maxHealth, healthReply: true); } } catch diff --git a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs index c48c9dd..6a1c1c3 100644 --- a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs +++ b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs @@ -155,7 +155,13 @@ internal static class HeartbeatLogger try { if (Plugins.EngineSettings.EnableImGuiBackend) - uiField = $" ui={ImGuiBackend.UiFrameStats.P95Ms:0.0}/{ImGuiBackend.UiFrameStats.MaxMs:0.0}ms"; + { + float uiP95 = ImGuiBackend.UiFrameStats.P95Ms; + uiField = $" ui={uiP95:0.0}/{ImGuiBackend.UiFrameStats.MaxMs:0.0}ms"; + // uitop=part:avg/max,... = the UI frame's top 3 parts over the last seconds + // (ImGui/UiCost), only while the p95 is over the slow-frame threshold. + uiField += ImGuiBackend.UiCost.HeartbeatField(uiP95); + } } catch { } // vafree = free address space (MB): reloads leak engine/plugin copies, diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index c45d55b..8f3f29e 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -101,6 +101,13 @@ namespace RynthCore.Engine.Compatibility; /// hotkeys (; saved for the PC in hotkeys.txt). /// /rc diagnostics (or /rc serverpick) - opens Settings > Diagnostics, the server /// picker: the one place a server is forced for this character (plugins' "Force a server" links). +/// /rc layout [status] | default | reset [confirm] - the panel layout this client uses +/// (: its character's own, or the PC-wide default and why) and its files; +/// default makes this character's layout the one new characters start from; reset (then reset +/// confirm) puts this character back to the default. Also Settings > Display. +/// /rc uicost [on|off|<ms>|now|status] - the UI frame cost breakdown +/// (): timing on or off, the slow-frame threshold, and (now, or +/// alone) which parts of the UI frame took the time over the last seconds. Also Settings > Diagnostics. /// /// internal static class RynthCoreChatCommands @@ -360,6 +367,13 @@ internal static class RynthCoreChatCommands return; } + // /rc uicost [on|off||now|status] : the UI frame cost breakdown (ImGui/UiCost; alone: now) + if (IsVerb(sub, "uicost", out string uiCostArgs)) + { + ReplyLines(ImGuiBackend.UiCost.HandleCommand(uiCostArgs)); + return; + } + // /rc netmsg [status|on|off|log on|off|capture on|off] : the v78 server message stream if (IsVerb(sub, "netmsg", out string netArgs)) { @@ -602,6 +616,17 @@ internal static class RynthCoreChatCommands SettingsCommand(settingsArgs); return; } + if (IsVerb(sub, "sense", out string senseArgs) && senseArgs.Length > 0) + { + SenseLayoutCommand(senseArgs); // alone, /rc sense opens or closes the panel (the switch below) + return; + } + // /rc layout [status] | default | reset [confirm]: this client's panel layout (UI/PanelLayout). + if (IsVerb(sub, "layout", out string layoutArgs)) + { + HandleLayoutCommand(layoutArgs); + return; + } if (IsVerb(sub, "hotkey", out hotkeyArgs) || IsVerb(sub, "hotkeys", out hotkeyArgs)) { // The parser's own errors (an unknown verb, a bad key) are the failures; the rest is what changed. @@ -1156,6 +1181,39 @@ internal static class RynthCoreChatCommands Reply(ChatCommandReplies.PanelReply(label, null, wasOpen)); } + /// + /// "/rc sense compact on|off | collapse on|off | view full|compact|collapsed": the Sense panel's + /// look (saved in sense.txt), and the look now; alone, compact / collapse / view say the look now. + /// + private static void SenseLayoutCommand(string args) + { + string title = ImGuiBackend.Panels.SenseFace.Title; + if (!ImGuiBackend.ImGuiPanelHost.HasFace(title)) + { + Fail("The Sense panel isn't available (the ImGui layer is off?)."); + return; + } + if (!UI.Data.SenseStore.Loaded) + { + UI.Data.SenseStore.EnsureLoadQueued(); + Fail("Can't change the Sense view yet: its settings are still loading. Try again in a moment."); + return; + } + UI.Data.SenseLayoutAnswer a = UI.Data.SenseLayout.Apply(args, UI.Data.SenseStore.Layout, + ImGuiBackend.ImGuiPanelHost.IsOpen(title)); + if (!a.Ok) + { + Fail(a.Reply); + return; + } + if (!UI.Data.SenseStore.SetLayout(a.Next)) + { + Fail("Can't change the Sense view yet: its settings are still loading. Try again in a moment."); + return; + } + Reply(a.Reply); + } + /// Settings, opened on (or switched to it when open). private static void OpenSettingsTab(string tab) { @@ -1403,6 +1461,22 @@ internal static class RynthCoreChatCommands case "click": case "clickselect": S.ClickToSelect = Flag(value, S.ClickToSelect); break; + case "refresh": + case "health": + // "refresh [on|off]" or "refresh " (between two health queries for other plates). + if (value != null && !IsOnOff(value)) + { + if (!TryNum(value, out float rs)) + { + Fail(FormattableString.Invariant( + $"Usage: /rv plates refresh [on|off] | refresh {ImGuiBackend.Hud.HealthProbe.MinIntervalSec:0.0}-{ImGuiBackend.Hud.HealthProbe.MaxIntervalSec:0.0} (seconds; now {S.HealthRefreshSec:0.0#})")); + return; + } + S.HealthRefreshSec = Math.Clamp(rs, ImGuiBackend.Hud.HealthProbe.MinIntervalSec, ImGuiBackend.Hud.HealthProbe.MaxIntervalSec); + S.RefreshOthersHealth = true; + } + else S.RefreshOthersHealth = Flag(value, S.RefreshOthersHealth); + break; case "onscreen": case "keeponscreen": S.KeepOnScreen = Flag(value, S.KeepOnScreen); break; @@ -1601,8 +1675,56 @@ internal static class RynthCoreChatCommands ReplyLines(UI.Data.Discord.ChatDiscord.HandleCommand(verb)); } + /// + /// /rc layout: which panel layout this client uses and its files (UI/PanelLayout: the character's own, + /// or the PC-wide default and why); default makes this character's the default for new characters; + /// reset asks, reset confirm copies the default over this character's. Those two answer when their + /// files are written (from the UI writer), or at once with why they can't run. + /// + private static void HandleLayoutCommand(string args) + { + UI.LayoutCommand cmd = UI.PanelLayoutPolicy.ParseCommand(args); + switch (cmd) + { + case UI.LayoutCommand.Status: + ReplyLines(UI.PanelLayout.DescribeLines()); + return; + case UI.LayoutCommand.ResetAsk: + { + string? problem = UI.PanelLayout.Check(cmd, out string ask); + Answer(problem == null, ask, problem ?? ""); + return; + } + case UI.LayoutCommand.MakeDefault: + case UI.LayoutCommand.ResetConfirm: + { + string? problem = UI.PanelLayout.Request(cmd, LaterReply()); + if (problem != null) Fail(problem); + return; + } + default: + Fail(UI.PanelLayoutPolicy.Usage); + return; + } + } + // ── replies (ChatCommandReplies says where each goes and its colour) ───── + /// + /// The answer of a command whose result comes later from another thread (a file job on the UI + /// writer): (text, ok), sent as this line's origin would send it. Marks this line answered. + /// + private static Action LaterReply() + { + ChatCommandOrigin origin = _origin; + _answered = true; + return (text, ok) => + { + ChatReplyKind kind = ok ? ChatReplyKind.Ok : ChatReplyKind.Fail; + Reply(text, kind, ChatCommandReplies.ToChat(kind, origin)); + }; + } + /// It worked, or the state now: in chat (green) for the player, the log only for a script. private static void Reply(string text) => Reply(text, ChatReplyKind.Ok, ChatCommandReplies.ToChat(ChatReplyKind.Ok, _origin)); diff --git a/src/RynthCore.Engine/Compatibility/SehTrampoline.cs b/src/RynthCore.Engine/Compatibility/SehTrampoline.cs index 53945ee..5992de8 100644 --- a/src/RynthCore.Engine/Compatibility/SehTrampoline.cs +++ b/src/RynthCore.Engine/Compatibility/SehTrampoline.cs @@ -122,6 +122,27 @@ internal static class SehTrampoline ((delegate* unmanaged[Cdecl])fn)(exitCode); } + /// + /// The loaded RynthCore.SehTrampoline.dll's file when it exports RC_DumpProcessW (v9+): the + /// hang watchdog runs it in rundll32 to write a dump of this process from outside it + /// (CrashDump.WriteHangDumpOutOfProcess). Null when the DLL is older or not loaded. + /// + public static string? DumpHelperPath() + { + try + { + nint module = GetModuleHandleW("RynthCore.SehTrampoline.dll"); + if (module == 0 || GetProcAddress(module, "RC_DumpProcessW") == 0) return null; + var buf = new char[1024]; + int n = GetModuleFileNameW(module, buf, buf.Length); + return n > 0 && n < buf.Length ? new string(buf, 0, n) : null; + } + catch { return null; } + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetModuleFileNameW")] + private static extern int GetModuleFileNameW(nint module, [Out] char[] path, int size); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetModuleHandleW")] private static extern nint GetModuleHandleW(string name); diff --git a/src/RynthCore.Engine/Compatibility/SessionStateRegistry.cs b/src/RynthCore.Engine/Compatibility/SessionStateRegistry.cs index 31d9cc2..513ec92 100644 --- a/src/RynthCore.Engine/Compatibility/SessionStateRegistry.cs +++ b/src/RynthCore.Engine/Compatibility/SessionStateRegistry.cs @@ -19,6 +19,10 @@ internal static class SessionStateRegistry internal static string LastCharacterName { get; private set; } = string.Empty; internal static string LastServerName { get; private set; } = string.Empty; + /// True once a login's identity is recorded (the names above are final for it; empty when + /// the launch context had none). UI/PanelLayout waits for it before it picks the character's layout. + internal static bool LoginRecorded => System.Threading.Volatile.Read(ref _loginRecorded); + public static void Initialize() { if (_initialized) diff --git a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs index f494b6a..25314d5 100644 --- a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs +++ b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs @@ -335,7 +335,7 @@ internal static class SmartBoxHooks _hpReadLogCount++; RynthLog.Compat($"Creature HP id=0x{targetId:X8}: sehRead={(gotReal ? realMax.ToString() : "none")} used={maxHealth} ratio={ratio:0.00}"); } - PluginManager.QueueUpdateHealth(targetId, ratio, currentHealth, maxHealth); + PluginManager.QueueUpdateHealth(targetId, ratio, currentHealth, maxHealth, healthReply: true); } break; @@ -765,7 +765,7 @@ internal static class SmartBoxHooks currentHealth = (uint)Math.Round(maxHealth * Math.Clamp(ratio, 0f, 1f)); } - PluginManager.QueueUpdateHealth(targetId, ratio, currentHealth, maxHealth); + PluginManager.QueueUpdateHealth(targetId, ratio, currentHealth, maxHealth, healthReply: true); } catch { diff --git a/src/RynthCore.Engine/Compatibility/VendorRatePolicy.cs b/src/RynthCore.Engine/Compatibility/VendorRatePolicy.cs new file mode 100644 index 0000000..c115360 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/VendorRatePolicy.cs @@ -0,0 +1,61 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/VendorRatePolicy.cs +// The pure part of VendorTrade's profile check: whether a buy/sell rate read +// from the client's vendor profile is a real rate or a misread. Compiled into +// tools\VendorRateTests. +// +// A rate of exactly 0 is a real rate. A custom server can run a free storage +// vendor (a "vault") whose BuyPrice and SellPrice are both 0; it pays nothing +// for what you hand it and charges nothing for what you take back. Refusing +// 0 turned trading off for such vendors. Negative, NaN, infinite and huge +// values still mean the profile was misread, and trading stays off for them. +// +// The price helpers live here too so the test can pin them: a 0 rate prices +// at 0 (the vault's own GetSellCost/GetBuyCost return 0), while any rate +// above 0 keeps ACE's 1-per-stack floor. The server stays the authority. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Compatibility; + +internal static class VendorRatePolicy +{ + /// Rates at or above this are taken as a misread profile. + public const float MaxRate = 1000f; + + /// True when is finite and in [0, MaxRate). + public static bool LooksSane(float rate) => float.IsFinite(rate) && rate >= 0f && rate < MaxRate; + + /// True when both rates are exactly 0: a free vendor (it neither charges nor pays). + public static bool IsFreeVendor(float buyRate, float sellRate) => buyRate == 0f && sellRate == 0f; + + public const uint ItemTypePromissoryNote = 0x00040000; + + /// + /// What the player pays for one created stack worth (ACE Vendor.GetSellCost): + /// max(1, ceil(rate * value - 0.1)), promissory notes at 1.15. A vendor rate of exactly 0 is a free + /// vendor and costs 0 (no 1-per-stack floor); every rate above 0 keeps the stock ACE floor. + /// + public static long PlayerPaysForStack(float sellRate, uint itemType, long stackValue) + { + if (sellRate == 0f) + return 0; + float rate = itemType == ItemTypePromissoryNote ? 1.15f : sellRate; + float product = rate * stackValue; + return Math.Max(1L, (long)Math.Ceiling(product - 0.1)); + } + + /// + /// What the vendor pays for one item worth (ACE Vendor.GetBuyCost): + /// max(1, floor(rate * value + 0.1)), promissory notes at 1.0. A vendor rate of exactly 0 pays 0. + /// + public static long VendorPaysForStack(float buyRate, uint itemType, long value) + { + if (buyRate == 0f) + return 0; + float rate = itemType == ItemTypePromissoryNote ? 1.0f : buyRate; + float product = rate * value; + return Math.Max(1L, (long)Math.Floor(product + 0.1)); + } +} diff --git a/src/RynthCore.Engine/Compatibility/VendorTrade.cs b/src/RynthCore.Engine/Compatibility/VendorTrade.cs index 8b089d6..9af8300 100644 --- a/src/RynthCore.Engine/Compatibility/VendorTrade.cs +++ b/src/RynthCore.Engine/Compatibility/VendorTrade.cs @@ -168,7 +168,7 @@ internal static class VendorTrade private const int PwdItemsCapacity = 48, PwdContainersCapacity = 52, PwdType = 56, PwdValue = 60; private const int PwdStackSize = 96, PwdMaxStackSize = 100, PwdBitfield = 104, PwdBurden = 116; - private const uint ItemTypePromissoryNote = 0x00040000; + private const uint ItemTypePromissoryNote = VendorRatePolicy.ItemTypePromissoryNote; private const int PyrealMaxStack = 25000; // coinstack MaxStackSize (payout slots) private const int MaxVendorItems = 1024; private const int MaxTradeEntries = 100; @@ -232,6 +232,8 @@ internal static class VendorTrade // Chat echo for /rc vendor (drained on the main thread; written from the drain, // never from inside the outgoing-chat detour). private static readonly object _echoLock = new(); + // Zero-rate (free) vendors already logged, so each vendor id is logged once per engine. + private static readonly HashSet _zeroRateLogged = new(); private static readonly Queue _echo = new(); private static volatile int _echoCount; private const int MaxEcho = 48; @@ -316,6 +318,13 @@ internal static class VendorTrade snap.ProfileRead = RateLooksSane(snap.BuyRate) && RateLooksSane(snap.SellRate); if (!snap.ProfileRead) RynthLog.Warn($"VendorTrade: vendor 0x{vendorId:X8} profile rates look wrong (buy={snap.BuyRate} sell={snap.SellRate}); trading with it is off."); + else if (VendorRatePolicy.IsFreeVendor(snap.BuyRate, snap.SellRate)) + { + bool first; + lock (_zeroRateLogged) first = _zeroRateLogged.Add(vendorId); + if (first) + RynthLog.Compat($"VendorTrade: vendor 0x{vendorId:X8} has buy=0 sell=0: a zero-rate (free) vendor; trades are priced at 0."); + } } if (list != IntPtr.Zero && Readable(list, ListSize)) @@ -962,20 +971,14 @@ internal static class VendorTrade // ════════════════════════════════════════════════════════════════════════════ /// What the player pays for one created stack worth (ACE Vendor.GetSellCost). - internal static long PlayerPaysForStack(float sellRate, uint itemType, long stackValue) - { - float rate = itemType == ItemTypePromissoryNote ? 1.15f : sellRate; - float product = rate * stackValue; - return Math.Max(1L, (long)Math.Ceiling(product - 0.1)); - } + // A 0 rate (free vendor) costs 0; see VendorRatePolicy. + internal static long PlayerPaysForStack(float sellRate, uint itemType, long stackValue) => + VendorRatePolicy.PlayerPaysForStack(sellRate, itemType, stackValue); /// What the vendor pays for one item worth (ACE Vendor.GetBuyCost). - internal static long VendorPaysForStack(float buyRate, uint itemType, long value) - { - float rate = itemType == ItemTypePromissoryNote ? 1.0f : buyRate; - float product = rate * value; - return Math.Max(1L, (long)Math.Floor(product + 0.1)); - } + // A 0 rate (free vendor) pays 0; see VendorRatePolicy. + internal static long VendorPaysForStack(float buyRate, uint itemType, long value) => + VendorRatePolicy.VendorPaysForStack(buyRate, itemType, value); /// /// Cost / slots / burden for buying of , @@ -1425,7 +1428,8 @@ internal static class VendorTrade return sb.ToString(); } - private static bool RateLooksSane(float rate) => float.IsFinite(rate) && rate > 0f && rate < 1000f; + // 0 is a real rate (a free storage vendor); see VendorRatePolicy. + private static bool RateLooksSane(float rate) => VendorRatePolicy.LooksSane(rate); private static bool InModule(IntPtr p) { diff --git a/src/RynthCore.Engine/CrashDump.cs b/src/RynthCore.Engine/CrashDump.cs index 497568b..7b742da 100644 --- a/src/RynthCore.Engine/CrashDump.cs +++ b/src/RynthCore.Engine/CrashDump.cs @@ -12,12 +12,18 @@ // (AutoRestartWedgedClients, kept as it is). The hang dump is a small type and // holds no heap, which is what an out-of-memory needs. // -// Safe to call from a background thread: MiniDumpWriteDump suspends all other -// threads internally while it snapshots them, which is exactly what we want for -// a hang. The dbghelp.dll P/Invoke is lazy-bound (no cost unless we ever fire). +// MiniDumpWriteDump on this process suspends all other threads and then allocates +// from the process heap: a suspended thread holding the heap lock deadlocks it for +// good. The hang watchdog's dump therefore goes out of process since 2026-11-01 +// (WriteHangDumpOutOfProcess, rundll32 + SehTrampoline): a client hung on a reload (10-31 +// 21:17) with AC's main thread suspended inside RtlAllocateHeap and the dumping +// thread waiting on that heap's lock. The crash-exit and OUT OF MEMORY dumps still +// run in process (the process is dying, or held in a modal box). +// The dbghelp.dll P/Invoke is lazy-bound (no cost unless we ever fire). // ============================================================================ using System; +using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Threading; @@ -95,6 +101,99 @@ internal static class CrashDump } } + // Longest the dump helper may take for the small hang dump before it is stopped. + private const int DumpToolTimeoutMs = 120_000; + + /// + /// The hang dump: a minidump of this process (thread stacks, no heap) written to + /// Logs\dumps\hang_<pid>_<time>.dmp from another process: the 32-bit rundll32 running + /// RynthCore.SehTrampoline.dll's RC_DumpProcess (v9+; the runtime's createdump.exe takes no + /// pid any more). Nothing here waits on a lock a suspended thread holds (see the header). + /// While it runs this process is in HIGH priority class: the dumper suspends each thread + /// and reads its context, and on a busy machine that read waits seconds for every + /// low-priority thread (the loader's hook freezes had the same wait, native\Loader\Hooks.c + /// BoostForFreeze), with every thread it already suspended frozen meanwhile. No dump when + /// the helper is missing or older (never the in-process fallback). Never throws. + /// + internal static bool WriteHangDumpOutOfProcess(string reason, out string dumpPath, string prefix = "hang") + { + dumpPath = string.Empty; + try + { + string dir = Path.Combine(LogPaths.LogDirectory, "dumps"); + Directory.CreateDirectory(dir); + long free = FreeBytes(dir); + if (!DumpBudget.SmallDumpAllowed(free)) + { + RynthLog.Error($"CrashDump: not writing the {prefix} dump - {(free < 0 ? "free space unknown" : (free / (1024 * 1024)) + " MB free")} on the dump volume, reason={reason}"); + return false; + } + string? helper = Compatibility.SehTrampoline.DumpHelperPath(); + if (helper == null) + { + RynthLog.Error($"CrashDump: the loaded RynthCore.SehTrampoline.dll has no RC_DumpProcess (older than v9; a client restart loads the new one) - {prefix} dump skipped (a dump written from inside a live client can deadlock it), reason={reason}"); + return false; + } + + dumpPath = Path.Combine(dir, $"{prefix}_{Environment.ProcessId}_{DateTime.Now:yyyyMMdd_HHmmss}.dmp"); + // SysWOW64's rundll32: a 32-bit process, like the DLL. + string rundll = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.SystemX86), "rundll32.exe"); + var psi = new ProcessStartInfo(rundll, HangDumpCommand.Arguments(helper, dumpPath, Environment.ProcessId)) + { + UseShellExecute = false, + CreateNoWindow = true, + }; + + long t0 = Stopwatch.GetTimestamp(); + bool boosted = false; + ProcessPriorityClass before = ProcessPriorityClass.Normal; + int exitCode; + bool exited; + lock (DumpLock) + { + using Process self = Process.GetCurrentProcess(); + try + { + before = self.PriorityClass; + if (before != ProcessPriorityClass.High && before != ProcessPriorityClass.RealTime) + { + self.PriorityClass = ProcessPriorityClass.High; + boosted = true; + } + } + catch { /* no boost: the dump just takes longer */ } + try + { + using Process? dumper = Process.Start(psi); + if (dumper == null) { RynthLog.Error($"CrashDump: the dump helper did not start, reason={reason}"); return false; } + exited = dumper.WaitForExit(DumpToolTimeoutMs); + if (!exited) { try { dumper.Kill(); } catch { } } + exitCode = exited ? dumper.ExitCode : -1; + } + finally + { + if (boosted) { try { self.PriorityClass = before; } catch { } } + } + } + double ms = (Stopwatch.GetTimestamp() - t0) * 1000.0 / Stopwatch.Frequency; + long size = 0; + try { size = File.Exists(dumpPath) ? new FileInfo(dumpPath).Length : 0; } catch { } + if (!exited || exitCode != 0 || size == 0) + { + RynthLog.Error($"CrashDump: dump helper {(exited ? $"exit {exitCode} ({HangDumpCommand.DescribeExit(exitCode)})" : $"still running after {DumpToolTimeoutMs / 1000}s, stopped")} after {ms:0} ms, no {prefix} dump, reason={reason}"); + try { File.Delete(dumpPath); } catch { } + return false; + } + RynthLog.Error($"CrashDump: wrote {dumpPath} ({size / 1024}KB, out of process, {ms:0} ms) reason={reason}"); + return true; + } + catch (Exception ex) + { + RynthLog.Error($"CrashDump: {prefix} dump failed {ex.GetType().Name}: {ex.Message}"); + return false; + } + } + /// Free bytes available to this user on the volume holding ; -1 when unknown. internal static long FreeBytes(string dir) { diff --git a/src/RynthCore.Engine/D3D9/EndSceneHook.cs b/src/RynthCore.Engine/D3D9/EndSceneHook.cs index b2aca30..c408256 100644 --- a/src/RynthCore.Engine/D3D9/EndSceneHook.cs +++ b/src/RynthCore.Engine/D3D9/EndSceneHook.cs @@ -296,12 +296,21 @@ internal static class EndSceneHook } } + // AC's own EndScene (and whatever AC does until the next frame): the hang watchdog's + // step goes back to "outside the engine" first. + private static int CallOriginalEndScene(IntPtr pDevice) + { + MainThreadHangWatchdog.Step = null; + return _originalEndScene!(pDevice); + } + private static int EndSceneDetour(IntPtr pDevice) { // Liveness beacon for MainThreadHangWatchdog — this detour runs on AC's // main/render thread every frame (even with the ImGui backend disabled), // so a stalled beat means the main thread is wedged. Must never throw. try { MainThreadHangWatchdog.MainThreadBeat(); } catch { } + MainThreadHangWatchdog.Step = "EndScene: engine frame"; try { if (!_offscreenFilterDisabled && !DX9Backend.IsRenderingToBackBuffer(pDevice)) @@ -320,7 +329,7 @@ internal static class EndSceneHook // fall back with Decal; without Decal nothing changes. if (DecalD3D9.Enabled || (_skipCount < MaxOffscreenSkipsBeforeFallback && offscreenElapsedMs < OffscreenFallbackDelayMs)) - return _originalEndScene!(pDevice); + return CallOriginalEndScene(pDevice); _offscreenFilterDisabled = true; RynthLog.D3D9($"EndSceneHook: Falling back to unfiltered EndScene after {_skipCount} skipped offscreen pass(es) over {offscreenElapsedMs}ms."); @@ -398,7 +407,7 @@ internal static class EndSceneHook // New hook confirmed live — safe to free the old // trampoline now. MinHook.MH_RemoveHook(oldAddr); - return _originalEndScene!(pDevice); + return CallOriginalEndScene(pDevice); } RynthLog.D3D9("EndSceneHook: Rehook failed — restoring original hook."); @@ -421,7 +430,7 @@ internal static class EndSceneHook } if (_renderCount < WarmupFrames) - return _originalEndScene!(pDevice); + return CallOriginalEndScene(pDevice); _uiActivated = true; RynthLog.D3D9("EndSceneHook: Warmup complete - initializing ImGui."); @@ -450,6 +459,7 @@ internal static class EndSceneHook // The UI hides between characters: nothing is drawn at character select or // on the way out, and it's back the moment login completes (an engine // reload synthesises login for a player already in the world). + MainThreadHangWatchdog.Step = "EndScene: overlay blit and ImGui submit"; try { if (Compatibility.LoginLifecycleHooks.HasObservedLoginComplete) @@ -542,6 +552,6 @@ internal static class EndSceneHook catch { /* never let the cap take EndScene down */ } _videoPatchTimer.Restart(); - return _originalEndScene!(pDevice); + return CallOriginalEndScene(pDevice); } } diff --git a/src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs b/src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs index 36f32f5..b4a191b 100644 --- a/src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs +++ b/src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs @@ -163,10 +163,14 @@ internal static class Nav3DRenderInjector // Video patch: no 3D scene this frame, so no markers or plates over the black. if (VideoPatch.SkipWorldThisFrame) return; _inRender = true; + long cost = ImGuiBackend.UiCost.Start(); // UiCost: outside ui=, listed apart try { ImGuiBackend.DX9Backend.RenderNav3D(dev); } catch { } + ImGuiBackend.UiCost.Stop(ImGuiBackend.UiCost.Nav3D, cost); + cost = ImGuiBackend.UiCost.Start(); try { ImGuiBackend.UnderUiLayer.PresentFallback(dev); } catch { } + ImGuiBackend.UiCost.Stop(ImGuiBackend.UiCost.WorldPresent, cost); _inRender = false; _atEndScene++; } @@ -192,6 +196,7 @@ internal static class Nav3DRenderInjector // This frame's camera, not the one EndScene captured last frame (see RefreshView). try { GameMatrixCapture.RefreshView(); } catch { } + long cost = ImGuiBackend.UiCost.Start(); // UiCost: outside ui=, listed apart try { // At the UI pass AC has set a full-screen viewport; the markers project @@ -201,8 +206,10 @@ internal static class Nav3DRenderInjector catch { } + ImGuiBackend.UiCost.Stop(ImGuiBackend.UiCost.Nav3D, cost); // The world overlays (nameplates, combat text) go here too, over the // markers and under AC's UI. UnderUiLayer presents a list at most once. + cost = ImGuiBackend.UiCost.Start(); try { if (sceneViewport) ImGuiBackend.UnderUiLayer.PresentAtUiPass(dev); @@ -211,6 +218,7 @@ internal static class Nav3DRenderInjector catch { } + ImGuiBackend.UiCost.Stop(ImGuiBackend.UiCost.WorldPresent, cost); _inRender = false; return true; } diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 4d4886c..247e479 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -983,6 +983,9 @@ public static class EntryPoint RynthLog.Info("InitWorker: stand-down complete - this client runs as a Decal client; RynthCore stays idle."); return; } + // Panel layout per character (UI/PanelLayout): before the EndScene hook, so the first + // frame already asks for the right layout (after a hot reload, the character's). + UI.PanelLayout.Initialize(); if (Plugins.EngineSettings.EnablePlugins) { RynthLog.Info("InitWorker DIAG — calling PluginManager.LoadPlugins."); diff --git a/src/RynthCore.Engine/HangDumpCommand.cs b/src/RynthCore.Engine/HangDumpCommand.cs new file mode 100644 index 0000000..51a07fa --- /dev/null +++ b/src/RynthCore.Engine/HangDumpCommand.cs @@ -0,0 +1,36 @@ +// ============================================================================ +// RynthCore.Engine - HangDumpCommand.cs +// The hang watchdog's dump, written from outside the client (CrashDump. +// WriteHangDumpOutOfProcess): the 32-bit rundll32 runs RynthCore.SehTrampoline.dll's +// RC_DumpProcess (native\SehTrampoline\SehTrampoline.c, DumpArgs.h). Its command line +// and what its exit code means. Pure: tools\EngineRobustnessTests checks both. +// ============================================================================ + +using System.Globalization; + +namespace RynthCore.Engine; + +internal static class HangDumpCommand +{ + /// The rundll32 entry, by its plain name (rundll32 tries RC_DumpProcessW first). + public const string Entry = "RC_DumpProcess"; + + /// + /// rundll32's arguments: "<helper dll>",RC_DumpProcess <pid> <dump path>. The + /// path is the rest of the line, unquoted (RC_DumpProcess takes it as it is, spaces included). + /// + public static string Arguments(string helperDll, string dumpPath, int pid) => + $"\"{helperDll}\",{Entry} {pid.ToString(CultureInfo.InvariantCulture)} {dumpPath}"; + + /// What RC_DumpProcess's exit code means. + public static string DescribeExit(int code) => code switch + { + 0 => "written", + 1 => "bad arguments", + 2 => "could not open the client process", + 3 => "could not create the dump file", + 4 => "no dbghelp MiniDumpWriteDump", + 5 => "MiniDumpWriteDump failed", + _ => "rundll32 could not run the helper", + }; +} diff --git a/src/RynthCore.Engine/ImGui/DX9Backend.cs b/src/RynthCore.Engine/ImGui/DX9Backend.cs index 92a2b1d..4b48d45 100644 --- a/src/RynthCore.Engine/ImGui/DX9Backend.cs +++ b/src/RynthCore.Engine/ImGui/DX9Backend.cs @@ -39,6 +39,37 @@ internal static unsafe class DX9Backend return _vtxScratch; } + // Rebased-index scratch (DrawSubmitPlan): one command's indices less its smallest one, reused for + // every command (DrawIndexedPrimitiveUP copies them before it returns). Freed in Shutdown. + private static ushort* _idxScratch; + private static int _idxScratchCapacity; + + private static ushort* EnsureIndexScratch(int needed) + { + if (needed > _idxScratchCapacity) + { + int cap = _idxScratchCapacity == 0 ? 16384 : _idxScratchCapacity; + while (cap < needed) cap *= 2; + if (_idxScratch != null) NativeMemory.Free(_idxScratch); + _idxScratch = (ushort*)NativeMemory.Alloc((nuint)cap, sizeof(ushort)); + _idxScratchCapacity = cap; + } + return _idxScratch; + } + + // ── UiCost counters ── + private static SubmitStats _lastSubmit; + /// The last RenderDrawData / RenderDrawList call's counters (read right after the call). Render thread. + public static SubmitStats LastSubmit => _lastSubmit; + + private static int _fontUploads, _texUploads; + /// Textures made since the last call: the font atlas, and the others (icons, map tiles, pictures). Render thread. + public static void TakeUploads(out int font, out int tex) + { + font = _fontUploads; tex = _texUploads; + _fontUploads = _texUploads = 0; + } + // ── Diagnostics (/rc imgui diag): what the last RenderDrawData did ── private static int _diagLists, _diagVtx, _diagCmds, _diagDraws, _diagSkipped, _diagFailed, _diagLastHr; private static long _diagFrames; @@ -413,6 +444,12 @@ internal static unsafe class DX9Backend _vtxScratch = null; _vtxScratchCapacity = 0; } + if (_idxScratch != null) + { + NativeMemory.Free(_idxScratch); + _idxScratch = null; + _idxScratchCapacity = 0; + } _initialized = false; _coreInitialized = false; } @@ -524,6 +561,7 @@ internal static unsafe class DX9Backend private static void RenderLists(ImDrawList** cmdLists, int cmdListsCount, int totalVtx, Vector2 displayPos, Vector2 displaySize, IntPtr pDevice, bool midFrame) { + _lastSubmit.Clear(); if (cmdListsCount == 0) return; if (displaySize.X <= 0 || displaySize.Y <= 0) return; if (cmdLists == null) return; @@ -629,6 +667,12 @@ internal static unsafe class DX9Backend SetupRenderStateNative(pDevice, displayPos, displaySize); const int ResetRenderStateSentinel = -8; // ImDrawCallback_ResetRenderState + // The texture and scissor rect last set here: an unchanged one isn't set again. + IntPtr boundTex = IntPtr.Zero; + bool texBound = false; + RECT boundScissor = default; + bool scissorBound = false; + ref SubmitStats st = ref _lastSubmit; for (int n = 0; n < cmdListsCount; n++) { @@ -638,6 +682,7 @@ internal static unsafe class DX9Backend int vtxCount = list->VtxBuffer.Size; int cmdCount = list->CmdBuffer.Size; if (vtxCount == 0 || cmdCount == 0) continue; + st.Lists++; ImDrawVert* srcVtx = (ImDrawVert*)list->VtxBuffer.Data; ushort* idxBase = (ushort*)list->IdxBuffer.Data; @@ -696,20 +741,52 @@ internal static unsafe class DX9Backend if (sr.Top < 0) sr.Top = 0; if (sr.Right > (int)displaySize.X) sr.Right = (int)displaySize.X; if (sr.Bottom > (int)displaySize.Y) sr.Bottom = (int)displaySize.Y; - if (sr.Right <= sr.Left || sr.Bottom <= sr.Top) { _diagSkipped++; continue; } - _setScissorRect!(pDevice, &sr); - _setTexture!(pDevice, 0, cmd->TextureId); + if (sr.Right <= sr.Left || sr.Bottom <= sr.Top) { _diagSkipped++; st.Skipped++; continue; } - // DrawIndexedPrimitiveUP has no base-vertex argument, so the - // command's VtxOffset is applied by offsetting the vertex pointer. + // DrawIndexedPrimitiveUP copies NumVertices vertices on every call, so a + // command gets only the vertices its indices reach (DrawSubmitPlan), not the + // whole list (that was V x C vertices a frame: the Loot Editor's 200-330 ms + // submit). It has no base-vertex argument: the command's VtxOffset and its + // smallest index move the vertex pointer, and the indices are rebased to it. uint vtxOffset = cmd->VtxOffset; - if (vtxOffset >= (uint)vtxCount) { _diagSkipped++; continue; } + ushort* cmdIdx = idxBase + cmd->IdxOffset; + if (vtxOffset >= (uint)vtxCount + || cmd->IdxOffset + elemCount > (uint)list->IdxBuffer.Size + || !DrawSubmitPlan.Plan(cmdIdx, (int)elemCount, vtxCount, (int)vtxOffset, out int first, out int numVerts)) + { + _diagSkipped++; st.Skipped++; continue; + } + ushort* drawIdx = cmdIdx; + if (first > 0) + { + drawIdx = EnsureIndexScratch((int)elemCount); + DrawSubmitPlan.Rebase(cmdIdx, drawIdx, (int)elemCount, first); + } + + if (!scissorBound || sr.Left != boundScissor.Left || sr.Top != boundScissor.Top + || sr.Right != boundScissor.Right || sr.Bottom != boundScissor.Bottom) + { + _setScissorRect!(pDevice, &sr); + boundScissor = sr; + scissorBound = true; + } + if (!texBound || cmd->TextureId != boundTex) + { + _setTexture!(pDevice, 0, cmd->TextureId); + if (texBound) st.TexSwitches++; + boundTex = cmd->TextureId; + texBound = true; + } + int hr = _drawIndexedPrimUP!(pDevice, - D3DPT_TRIANGLELIST, 0, (uint)vtxCount - vtxOffset, + D3DPT_TRIANGLELIST, 0, (uint)numVerts, elemCount / 3, - (IntPtr)(idxBase + cmd->IdxOffset), D3DFMT_INDEX16, - (IntPtr)(vtxBuf + vtxOffset), (uint)sizeof(CustomVertex)); + (IntPtr)drawIdx, D3DFMT_INDEX16, + (IntPtr)(vtxBuf + vtxOffset + first), (uint)sizeof(CustomVertex)); _diagDraws++; + st.Draws++; + st.VtxCopied += numVerts; + st.VtxWholeList += vtxCount - vtxOffset; if (hr < 0) { _diagFailed++; _diagLastHr = hr; } } } @@ -927,27 +1004,42 @@ internal static unsafe class DX9Backend return false; } - // Copy with RGBA → BGRA swizzle (ImGui gives RGBA, D3D9 A8R8G8B8 is BGRA in memory) - byte* src = (byte*)pixels; byte* dst = (byte*)locked.pBits; - - for (int y = 0; y < height; y++) + if (ImGuiFonts.TakeBgraPixels(width, height, out IntPtr bgra)) { - byte* srcRow = src + y * width * 4; - byte* dstRow = dst + y * locked.Pitch; - - for (int x = 0; x < width; x++) + // The bake worker made the BGRA rows (ImGuiFonts.BakeWorker): only a row copy here. + try { - int si = x * 4; - int di = x * 4; - dstRow[di + 0] = srcRow[si + 2]; // B ← R - dstRow[di + 1] = srcRow[si + 1]; // G ← G - dstRow[di + 2] = srcRow[si + 0]; // R ← B - dstRow[di + 3] = srcRow[si + 3]; // A ← A + long row = (long)width * 4; + for (int y = 0; y < height; y++) + Buffer.MemoryCopy((byte*)bgra + y * row, dst + (long)y * locked.Pitch, row, row); + } + finally { ImGuiFonts.FreeBgraPixels(bgra); } + } + else + { + // Copy with RGBA → BGRA swizzle (ImGui gives RGBA, D3D9 A8R8G8B8 is BGRA in memory) + byte* src = (byte*)pixels; + + for (int y = 0; y < height; y++) + { + byte* srcRow = src + y * width * 4; + byte* dstRow = dst + y * locked.Pitch; + + for (int x = 0; x < width; x++) + { + int si = x * 4; + int di = x * 4; + dstRow[di + 0] = srcRow[si + 2]; // B ← R + dstRow[di + 1] = srcRow[si + 1]; // G ← G + dstRow[di + 2] = srcRow[si + 0]; // R ← B + dstRow[di + 3] = srcRow[si + 3]; // A ← A + } } } unlockRect(_fontTexture, 0); + _fontUploads++; // UiCost: a font atlas upload this frame // Store texture ID for ImGui io.Fonts.SetTexID(_fontTexture); @@ -1001,6 +1093,7 @@ internal static unsafe class DX9Backend } } unlockRect(tex, 0); + _texUploads++; // UiCost return tex; } @@ -1033,6 +1126,7 @@ internal static unsafe class DX9Backend for (int y = 0; y < rows; y++) // the pitch of a compressed surface is the bytes of one row of blocks blocks.Slice(y * rowBytes, rowBytes).CopyTo(new Span(dst + y * locked.Pitch, rowBytes)); unlockRect(tex, 0); + _texUploads++; // UiCost return tex; } diff --git a/src/RynthCore.Engine/ImGui/DrawSubmitPlan.cs b/src/RynthCore.Engine/ImGui/DrawSubmitPlan.cs new file mode 100644 index 0000000..58dca7e --- /dev/null +++ b/src/RynthCore.Engine/ImGui/DrawSubmitPlan.cs @@ -0,0 +1,70 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/DrawSubmitPlan.cs +// How DX9Backend hands one ImDrawCmd to DrawIndexedPrimitiveUP. Pure logic, +// no engine or D3D types (tools/UiCostTests compiles it). The submit's +// counters (SubmitStats) live in UiCostModel.cs, which stays self-contained. +// +// DrawIndexedPrimitiveUP copies NumVertices vertices out of the caller's +// memory into the runtime's own vertex buffer on EVERY call. The renderer used +// to pass the whole draw list's vertex count for each command, so a window +// with V vertices and C draw commands copied V x C vertices a frame. Every +// PushClipRect starts a new command; the Loot Editor's rule list pushes two +// clip rects per row (name, conditions), so with the editor open the frame's +// vertices went from ~13k to ~30k in one child list split into a command or +// more per row, and the submit copied the list once per command: on the order +// of a million vertices (tens of MB) a frame through the runtime's ring +// buffer. Logged live: submit 200-330 ms for <1 ms of building (and the GPU/ +// driver stalls slowed another client on the PC too). +// +// Now each command gets only the vertices its indices reach: the min..max of +// its indices. When min > 0 the indices are rebased into a scratch copy and +// the vertex pointer moved by min, so MinVertexIndex is always 0 (some D3D9 +// implementations copy from vertex 0 up to MinVertexIndex + NumVertices, +// whatever MinVertexIndex says). A frame now copies about its vertex count. +// ============================================================================ + +namespace RynthCore.Engine.ImGuiBackend; + +internal static unsafe class DrawSubmitPlan +{ + /// + /// The vertices one command uses: the smallest and largest of its + /// indices (count > 0). Linear in count; over a frame that is the frame's index count. + /// + public static void IndexRange(ushort* idx, int count, out int min, out int max) + { + int lo = ushort.MaxValue, hi = 0; + for (int i = 0; i < count; i++) + { + int v = idx[i]; + if (v < lo) lo = v; + if (v > hi) hi = v; + } + min = lo; + max = hi; + } + + /// dst[i] = src[i] - by, for the indices of a command whose smallest index is . + public static void Rebase(ushort* src, ushort* dst, int count, int by) + { + for (int i = 0; i < count; i++) + dst[i] = (ushort)(src[i] - by); + } + + /// + /// What to draw for one command: its first vertex (from the command's VtxOffset) and how many + /// vertices to hand over. False when an index reaches past the list (a broken list: skipped, + /// nothing read out of bounds). is the list's vertex count. + /// + public static bool Plan(ushort* idx, int count, int listVtx, int vtxOffset, out int first, out int numVerts) + { + first = 0; + numVerts = 0; + if (count <= 0 || vtxOffset < 0 || vtxOffset >= listVtx) return false; + IndexRange(idx, count, out int min, out int max); + if (vtxOffset + max >= listVtx) return false; + first = min; + numVerts = max - min + 1; + return true; + } +} diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index c6ff181..47339e2 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -121,107 +121,174 @@ internal static class EngineFrameController return true; } - public static bool Init(IntPtr pDevice) + // ImGui init runs in two parts since 2026-11-01: the first makes the context (handed to the + // plugins at once, as before) and starts the font atlas bake on a worker (ImGuiFonts. + // StartInitialBake); frames build nothing until the bake is done, and the frame that finds it + // done swaps it in, sets up the Win32 backend and uploads the texture. The bake used to run + // here, on AC's thread, for 2.5-5 s of every hot reload (the main-thread hangs of 10-31/11-01). + private enum InitStep { Done, Baking, Failed } + + private static long _initStartedTicks; + + private static InitStep Init(IntPtr pDevice) { if (_imguiInitialized) - return true; + return InitStep.Done; + bool begin = _context == IntPtr.Zero; - if (!EnsureCore(pDevice)) + if (begin) { - _initFailStep = "EnsureCore (game window not found)"; - return false; + if (!EnsureCore(pDevice)) + { + _initFailStep = "EnsureCore (game window not found)"; + return InitStep.Failed; + } + + // Before any context exists: the loaded cimgui.dll must be the exact + // build ImGui.NET wraps, or every struct read below is at wrong offsets. + MainThreadHangWatchdog.Step = "ImGui init: self-test"; + _initStartedTicks = Stopwatch.GetTimestamp(); + Compatibility.MemoryUse.Mark("ImGui init: before the self-test"); + if (!ImGuiSelfTest.Run(EntryPoint.ImGuiNativeHandle)) + return InitStep.Failed; + Compatibility.MemoryUse.Mark("ImGui self-test done"); } - // Before any context exists: the loaded cimgui.dll must be the exact - // build ImGui.NET wraps, or every struct read below is at wrong offsets. - Compatibility.MemoryUse.Mark("ImGui init: before the self-test"); - if (!ImGuiSelfTest.Run(EntryPoint.ImGuiNativeHandle)) - return false; - Compatibility.MemoryUse.Mark("ImGui self-test done"); - IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext(); - if (previousContext != IntPtr.Zero) - RynthLog.Render($"EngineFrameController: Existing ImGui context detected (0x{previousContext:X8}) - isolating RynthCore context."); - - _context = ImGuiNET.ImGui.CreateContext(); - Compatibility.MemoryUse.Mark("ImGui context created"); - bool initSucceeded = false; + if (begin) + { + if (previousContext != IntPtr.Zero) + RynthLog.Render($"EngineFrameController: Existing ImGui context detected (0x{previousContext:X8}) - isolating RynthCore context."); + MainThreadHangWatchdog.Step = "ImGui init: context"; + _context = ImGuiNET.ImGui.CreateContext(); + Compatibility.MemoryUse.Mark("ImGui context created"); + } + InitStep result = InitStep.Failed; try { ImGuiNET.ImGui.SetCurrentContext(_context); ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); - // Pin imgui.ini to a stable absolute path so window positions/sizes - // persist across plugin reloads (RL) and AC restarts. The default - // ImGui behavior writes to the working directory which can differ - // between launches. Allocated once, kept alive for the process lifetime. - try + if (begin) { - string iniPath = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "imgui.ini"); - System.IO.Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir); - IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath); - unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; } - RynthLog.Info($"EngineFrameController: imgui.ini pinned to {iniPath}"); + SetUpContext(io); + MainThreadHangWatchdog.Step = "ImGui init: starting the font bake"; + if (ImGuiFonts.StartInitialBake(_uiScale)) + { + RynthLog.UI("EngineFrameController: the font atlas bakes on a worker; ImGui frames start once it is done."); + result = InitStep.Baking; + return result; + } + // No worker to be had: the old way, on this thread. + MainThreadHangWatchdog.Step = "ImGui init: fonts on the render thread"; + ImGuiFonts.Build(io, _uiScale); } - catch (Exception ex) + else { - RynthLog.Render($"EngineFrameController: failed to pin imgui.ini path - {ex.Message}"); + MainThreadHangWatchdog.Step = "ImGui init: swapping in the baked atlas"; + if (!ImGuiFonts.SwapFinished(io, _uiScale, out string baked)) + { + result = InitStep.Baking; // still baking: no ImGui frame yet + return result; + } + double sinceMs = (Stopwatch.GetTimestamp() - _initStartedTicks) * 1000.0 / Stopwatch.Frequency; + RynthLog.UI($"ImGuiFonts: first atlas {baked} ({sinceMs:0} ms after ImGui init began)."); + Compatibility.MemoryUse.Mark("ImGui fonts swapped in"); } - io.ConfigFlags |= ImGuiConfigFlags.DockingEnable; - // Multi-viewport (ViewportsEnable) is deliberately never enabled: it - // runs many native->managed platform/renderer callbacks per frame on - // AC's thread and creates HWNDs from inside EndScene. Pop-out panels, - // if built, are driven explicitly by the engine instead - // (docs/IMGUI_PARITY_PLAN.md section 4.2). - - // DPI scale for fonts and style metrics. Logged next to Avalonia's - // scale: docked positions are stored in Avalonia logical units, so - // the two must agree for a panel to land in the same place in - // either face (plan section 4.4). - _uiScale = UiScale.ForWindow(_gameHwnd); - RynthLog.UI($"EngineFrameController: ImGui scale {_uiScale:0.##} (Avalonia input scale {UI.AvaloniaOverlay.InputScale:0.##})."); - RynthTheme.Apply(ImGuiNET.ImGui.GetStyle(), _uiScale); - Compatibility.MemoryUse.Mark("ImGui theme applied"); - ImGuiFonts.Build(io, _uiScale); - + MainThreadHangWatchdog.Step = "ImGui init: Win32 backend"; if (!Win32Backend.Init(_gameHwnd)) { _initFailStep = "Win32Backend.Init"; - return false; + return result; } Compatibility.MemoryUse.Mark("Win32 backend ready"); + MainThreadHangWatchdog.Step = "ImGui init: font texture upload"; if (!DX9Backend.InitImGui(pDevice)) { _initFailStep = "DX9Backend.InitImGui"; - return false; + return result; } Compatibility.MemoryUse.Mark("DX9 backend ready (font texture)"); _lastFrameTicks = Stopwatch.GetTimestamp(); _imguiInitialized = true; - initSucceeded = true; + result = InitStep.Done; RynthLog.UI("EngineFrameController: ImGui initialized."); - return true; + return result; } finally { - if (!initSucceeded && _context != IntPtr.Zero) + if (result == InitStep.Failed && _context != IntPtr.Zero) { + // A bake may still be running: no context may be destroyed while it allocates. + ImGuiFonts.WaitForWorkers(); ImGuiNET.ImGui.DestroyContext(_context); _context = IntPtr.Zero; } ImGuiNET.ImGui.SetCurrentContext(previousContext); + MainThreadHangWatchdog.Step = "EndScene: ImGui frame"; } } + /// The new context's ini handling, flags, DPI scale and theme (Init's first part). Context current. + private static void SetUpContext(ImGuiIOPtr io) + { + // Panel layout per character (UI/PanelLayout): the engine loads and saves the + // imgui.ini of the layout in use itself (the character's, or the PC-wide + // default), so Dear ImGui gets no file name: it would load only the one it + // started with and write it from the render thread, not atomically. The + // context starts with the layout already applied, if there is one. + if (UI.PanelLayout.Initialized) + { + unsafe { io.NativePtr->IniFilename = null; } + UI.PanelLayout.OnContextCreated(LoadIniFn); + RynthLog.Info("EngineFrameController: imgui.ini is loaded and saved by the panel layout (UI/PanelLayout)."); + } + // Without it (an engine that didn't get that far), as before: pin imgui.ini to + // a stable absolute path so window positions/sizes persist across plugin + // reloads (RL) and AC restarts. The default ImGui behavior writes to the + // working directory which can differ between launches. Allocated once, + // kept alive for the process lifetime. + else try + { + string iniPath = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "imgui.ini"); + System.IO.Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir); + IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath); + unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; } + RynthLog.Info($"EngineFrameController: imgui.ini pinned to {iniPath}"); + } + catch (Exception ex) + { + RynthLog.Render($"EngineFrameController: failed to pin imgui.ini path - {ex.Message}"); + } + + io.ConfigFlags |= ImGuiConfigFlags.DockingEnable; + // Multi-viewport (ViewportsEnable) is deliberately never enabled: it + // runs many native->managed platform/renderer callbacks per frame on + // AC's thread and creates HWNDs from inside EndScene. Pop-out panels, + // if built, are driven explicitly by the engine instead + // (docs/IMGUI_PARITY_PLAN.md section 4.2). + + // DPI scale for fonts and style metrics. Logged next to Avalonia's + // scale: docked positions are stored in Avalonia logical units, so + // the two must agree for a panel to land in the same place in + // either face (plan section 4.4). + _uiScale = UiScale.ForWindow(_gameHwnd); + RynthLog.UI($"EngineFrameController: ImGui scale {_uiScale:0.##} (Avalonia input scale {UI.AvaloniaOverlay.InputScale:0.##})."); + RynthTheme.Apply(ImGuiNET.ImGui.GetStyle(), _uiScale); + Compatibility.MemoryUse.Mark("ImGui theme applied"); + } + public static void Shutdown() { - if (!_imguiInitialized) + // A context whose first font atlas is still baking (Init's two parts) goes too. + if (!_imguiInitialized && _context == IntPtr.Zero) return; + bool framesRan = _imguiInitialized; IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext(); IntPtr contextToDestroy = _context; @@ -250,6 +317,15 @@ internal static class EngineFrameController // unhooks), so restoring AC's original WndProc this early sends // those destroys to AC's proc, which ignores them, and the orphaned // panel HWND outlives the engine load. + // The windows' places go to the layout's imgui.ini now (with no IniFilename + // DestroyContext doesn't save them; UI/PanelLayout). + try + { + // Not before the first frame (the atlas still baking): nothing moved, nothing to save. + if (UI.PanelLayout.Initialized && framesRan) + UI.PanelLayout.SaveIniOnShutdown(ImGuiNET.ImGui.SaveIniSettingsToMemory()); + } + catch (Exception ex) { RynthLog.UI($"EngineFrameController: imgui.ini save at shutdown threw {ex.GetType().Name}: {ex.Message}"); } ImGuiNET.ImGui.DestroyContext(contextToDestroy); ImGuiFonts.Free(); // the atlas referenced these buffers; the context is gone now @@ -276,6 +352,7 @@ internal static class EngineFrameController { // Resolve game HWND and seed EntryPoint.GameHwnd. Required even // in ImGui-off mode so Avalonia owner-window binding works. + MainThreadHangWatchdog.Step = "EndScene: engine pipeline (layout, prefetches, queues)"; EnsureCore(pDevice); // Settings > Display: borderless windowed + AC window placement. Throttled; reads only @@ -283,6 +360,12 @@ internal static class EngineFrameController try { UI.AcWindowChrome.Tick(_gameHwnd); } catch (Exception ex) { RynthLog.UI($"AcWindowChrome.Tick threw {ex.GetType().Name}: {ex.Message}"); } + // Panel layout per character: switches to the character's layout (or back to the + // PC-wide default) and applies a loaded one, before anything below draws a panel. + // A layout waits for the ImGui context while the ImGui layer is in use. + UI.PanelLayout.Tick(imguiInUse: Plugins.EngineSettings.EnableImGuiBackend && !_imguiInitFailed, + imguiReady: _imguiInitialized, SnapshotIniFn, LoadIniFn); + // Cache the D3D9 device function pointers used by Nav3DRenderInjector, // RenderNav3D, and the always-on render path. This is a strict subset // of what InitImGui needs and is safe to run without ImGui state. @@ -400,8 +483,12 @@ internal static class EngineFrameController bool imguiEnabled = Plugins.EngineSettings.EnableImGuiBackend; bool imguiBuilt = false; long uiTicks = 0; + MainThreadHangWatchdog.Step = "EndScene: ImGui frame"; if (!imguiEnabled) + { _imguiIdle = true; // switched off in game: input state resets when it comes back + UiCost.DiscardFrame(); // no UI frame: what the 3D pass timed isn't kept for one + } else { long t0 = Stopwatch.GetTimestamp(); @@ -421,7 +508,13 @@ internal static class EngineFrameController long t0 = Stopwatch.GetTimestamp(); // Popped-out panels: their own contexts, windows and render targets. if (_imguiInitialized) + { + MainThreadHangWatchdog.Step = "EndScene: pop-out panels"; + // UiCost: what RenderAll spends outside the pop-out windows it times itself. + long c0 = UiCost.Start(), mark = UiCost.Mark; ImGuiPopOuts.RenderAll(pDevice, _uiScale, PanelsLive); + UiCost.StopExclusive(UiCost.PopOuts, c0, mark); + } long ticks = uiTicks + (Stopwatch.GetTimestamp() - t0); if (imguiBuilt) { @@ -431,6 +524,7 @@ internal static class EngineFrameController else { UiFrameStats.Record(ticks); + UiCost.EndFrame(ticks); } } } @@ -599,11 +693,38 @@ internal static class EngineFrameController /// Panel faces show only in the world, like the Avalonia overlay (hidden /// between characters, not closed). Also off as soon as AC leaves the world screen /// (UiFlowHooks, before the logout dispatch catches up) and for good once - /// Client::Cleanup starts. + /// Client::Cleanup starts. And after a login (or a hot reload) not before that + /// character's panel layout is in place (UI/PanelLayout), so nothing draws at the + /// default places first. /// private static bool PanelsLive => Compatibility.LoginLifecycleHooks.HasObservedLoginComplete && Compatibility.UiFlowHooks.InWorldOrUnknown - && !Compatibility.UiFlowHooks.ClientCleanupStarted; + && !Compatibility.UiFlowHooks.ClientCleanupStarted + && UI.PanelLayout.ReadyToDraw; + + // The ImGui windows' saved text, read from and loaded into the main context for UI/PanelLayout + // (render thread, between frames). Cached so the per-frame Tick allocates nothing. + private static readonly Func SnapshotIniFn = SnapshotIni; + private static readonly Action LoadIniFn = LoadIni; + + private static string? SnapshotIni() + { + if (!_imguiInitialized || _context == IntPtr.Zero) return null; + IntPtr previous = ImGuiNET.ImGui.GetCurrentContext(); + ImGuiNET.ImGui.SetCurrentContext(_context); + try { return ImGuiNET.ImGui.SaveIniSettingsToMemory(); } + finally { ImGuiNET.ImGui.SetCurrentContext(previous); } + } + + /// Loads ini text into the main context: Dear ImGui applies it to windows that already exist too. + private static void LoadIni(string text) + { + if (_context == IntPtr.Zero) return; + IntPtr previous = ImGuiNET.ImGui.GetCurrentContext(); + ImGuiNET.ImGui.SetCurrentContext(_context); + try { ImGuiNET.ImGui.LoadIniSettingsFromMemory(text); } + finally { ImGuiNET.ImGui.SetCurrentContext(previous); } + } /// DPI scale the fonts and style were built for (see Init). private static float _uiScale = 1f; @@ -663,19 +784,24 @@ internal static class EngineFrameController { // Initialised as soon as the backend is enabled (not lazily on first // content), so the cimgui self-test result is in the log at startup. - if (!Init(pDevice)) + InitStep step = Init(pDevice); + if (step == InitStep.Failed) { _imguiInitFailed = true; RynthLog.Error($"EngineFrameController: ImGui init FAILED at step '{_initFailStep}' - ImGui frames disabled for this session."); return false; } + if (step == InitStep.Baking) + return false; // the first font atlas is still baking on its worker: no ImGui frame yet } Win32Backend.UpdateClientMetrics(out int clientW, out int clientH); // Monster nameplates: pick the monsters (throttled) before deciding // whether there is a frame to build, so plates alone can ask for one. + long cHud = UiCost.Start(); Hud.MonsterHud.Update(PanelsLive); + UiCost.Stop(UiCost.HudUpdate, cHud); if (!HasImGuiContent()) { @@ -704,6 +830,8 @@ internal static class EngineFrameController } _frameCount++; + // UiCost (ImGui/UiCost.cs): each part of the frame below is timed, by name. + long cSetup = UiCost.Start(); // A panel's text size changed: re-bake the fonts (only the sizes in // use) and replace the font texture, between frames. // The new atlas is baked on a worker (ImGuiFonts.PumpRebuild), once per run of @@ -737,7 +865,10 @@ internal static class EngineFrameController io.DeltaTime = dt > 0f ? dt : 1f / 60f; RynthTheme.RefreshStyle(ref _themeApplied); // a theme change re-colours the base style + UiCost.Stop(UiCost.FrameSetup, cSetup); + long cNew = UiCost.Start(); ImGuiNET.ImGui.NewFrame(); + UiCost.Stop(UiCost.ImGuiNewFrame, cNew); frameStarted = true; // Before any window: a drag from a popped-out Inventory or AC's inventory becomes // a payload the client's drop targets (Mini Remote slots) see this frame. @@ -755,15 +886,17 @@ internal static class EngineFrameController if (Plugins.EngineSettings.EnableImGuiShell) { branch = 1; + long cShell = UiCost.Start(); RynthCoreShell.Render(_frameCount); - PluginManager.RenderAll(); + UiCost.Stop(UiCost.Shell, cShell); + PluginManager.RenderAll(); // times each plugin's Render (UiCost) } else if (PluginOverlayWindowsLive) { branch = 2; // Only the opt-in extra windows (RynthPluginRenderOverlay), never the // plugins' full ImGui UIs. - PluginManager.RenderOverlayAll(); + PluginManager.RenderOverlayAll(); // times each plugin's RenderOverlay (UiCost) } else { @@ -779,29 +912,53 @@ internal static class EngineFrameController // World overlays: built into UnderUiLayer's list, drawn next frame at // AC's 3D->UI transition (under AC's UI and every panel), no input. // Video patch: with no 3D scene only the screen-fixed player plate draws. + // Timed from here, as one part (plates, the player plate, combat text): the HUD's own + // code isn't instrumented. + long cPlates = UiCost.Start(); Hud.MonsterHud.Draw(_uiScale, worldVisible: !D3D9.VideoPatch.SkipWorldThisFrame); + UiCost.Stop(UiCost.MonsterHud, cPlates, cPlates != 0 ? Hud.MonsterHud.PlateCount : -1); // Video patch "all": the "rendering paused" banner (background list, under the panels). + long cPart = UiCost.Start(); VideoPatchBanner.Draw(); + UiCost.Stop(UiCost.VideoBanner, cPart); // Server verdicts, the plugins' section manifests and the servermenu push. Every // frame, bar or not: with the bar hidden (the rail instead) nothing else ticks them, // so Options > Diagnostics listed no servers and no server plugin was told it is active. + cPart = UiCost.Start(); RynthCore.Engine.UI.ServerMenus.Tick(); + UiCost.Stop(UiCost.ServerMenus, cPart); + cPart = UiCost.Start(); if (ImGuiBar.Visible) ImGuiBar.Draw(_uiScale); - ImGuiPanelHost.DrawAll(_uiScale); + UiCost.Stop(UiCost.Bar, cPart); + ImGuiPanelHost.DrawAll(_uiScale); // times each panel by title, and its own upkeep (UiCost) // Settings drawer bodies RynthAi's window didn't draw this frame let their sources go. + cPart = UiCost.Start(); Panels.SettingsDrawerBodies.EndFrame(); + UiCost.Stop(UiCost.DrawerBodies, cPart); + cPart = UiCost.Start(); ImGuiBar.SyncPopOut(_uiScale); + UiCost.Stop(UiCost.Bar, cPart); } if (ImGuiFontTest.Enabled) ImGuiFontTest.Draw(_uiScale); + long cRender = UiCost.Start(); ImGuiNET.ImGui.EndFrame(); frameEnded = true; ImGuiNET.ImGui.Render(); + UiCost.Stop(UiCost.ImGuiRender, cRender); + long cFinish = UiCost.Start(); ImGuiAssertLog.Poll(); _framesBuilt++; _lastDisplaySize = io.DisplaySize; + // Windows moved a while ago (Dear ImGui's dirty timer; no IniFilename, so it asks): + // saved to the panel layout's imgui.ini in the background (UI/PanelLayout). + if (io.WantSaveIniSettings) + { + io.WantSaveIniSettings = false; + UI.PanelLayout.QueueIniSave(ImGuiNET.ImGui.SaveIniSettingsToMemory(), explicitSave: false); + } // io.WantCaptureMouse already applies ImGui's own button-ownership // rule; io.WantTextInput is true only while a text field is edited. @@ -826,6 +983,7 @@ internal static class EngineFrameController if (typing && !Win32Backend.UiCaptureEnabled) _dropImGuiTextFocus = true; ArbitrateTextFocus(io.WantTextInput); + UiCost.Stop(UiCost.FrameFinish, cFinish); return true; } catch (Exception ex) @@ -884,7 +1042,9 @@ internal static class EngineFrameController long t0 = Stopwatch.GetTimestamp(); SubmitImGuiFrame(device); - UiFrameStats.Record(_deferredUiTicks + (Stopwatch.GetTimestamp() - t0)); + long ticks = _deferredUiTicks + (Stopwatch.GetTimestamp() - t0); + UiFrameStats.Record(ticks); + UiCost.EndFrame(ticks); } /// Draws the frame produced. @@ -895,7 +1055,16 @@ internal static class EngineFrameController try { ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData(); + long c0 = UiCost.Start(); DX9Backend.RenderDrawData(drawData, pDevice); + if (c0 != 0) + { + int vertices = 0; + // ImDrawData +12 TotalVtxCount (as LogHeartbeatIfDue). + unsafe { byte* p = (byte*)drawData.NativePtr; if (p != null) vertices = *(int*)(p + 12); } + UiCost.Stop(UiCost.Submit, c0, vertices); + UiCost.SetSubmit(DX9Backend.LastSubmit); // draws, texture switches, vertices copied + } _drawSubmits++; if (!_loggedFirstSubmit) { diff --git a/src/RynthCore.Engine/ImGui/FontPixels.cs b/src/RynthCore.Engine/ImGui/FontPixels.cs new file mode 100644 index 0000000..a0f7578 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/FontPixels.cs @@ -0,0 +1,24 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/FontPixels.cs +// ImGui's font atlas pixels (RGBA32) as D3D9 A8R8G8B8 rows (BGRA in memory). The bake +// worker converts them (ImGuiFonts.BakeWorker), so AC's thread only copies rows into the +// texture (DX9Backend.CreateFontTexture). Pure: tools\EngineRobustnessTests checks it. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static class FontPixels +{ + /// R and B swap in each 32-bit pixel (little-endian RGBA: R in the low byte). + public static void RgbaToBgra(ReadOnlySpan rgba, Span bgra) + { + if (bgra.Length < rgba.Length) throw new ArgumentException("destination too small", nameof(bgra)); + for (int i = 0; i < rgba.Length; i++) + { + uint p = rgba[i]; + bgra[i] = (p & 0xFF00FF00u) | ((p & 0x000000FFu) << 16) | ((p >> 16) & 0x000000FFu); + } + } +} diff --git a/src/RynthCore.Engine/ImGui/ImGuiBar.cs b/src/RynthCore.Engine/ImGui/ImGuiBar.cs index 4c5526e..f3c7fb5 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiBar.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiBar.cs @@ -241,6 +241,20 @@ internal static class ImGuiBar /// True when the ImGui bar should draw (the ImGui layer on, not popped out). public static bool Visible => ResolveFace() != PanelFace.Avalonia && !Floating; + /// + /// The panel store now holds another layout (UI/PanelLayout: another character's, the default, or a + /// reset): the bar's place, rows and popped-out state are read from it again; a popped-out bar's + /// window closes and SyncPopOut opens it at the new layout's spot. AC thread, between frames. + /// + public static void OnLayoutSwitched() + { + Volatile.Write(ref _rowSettings, null); + _floating = null; + _placed = false; + _userMoved = false; + if (ImGuiPopOuts.IsPopped(PopOutTitle)) ImGuiPopOuts.Close(PopOutTitle); + } + /// /// Opens or closes the bar's own window to match . AC /// thread, in the world, with the main context current (after the panels). diff --git a/src/RynthCore.Engine/ImGui/ImGuiFonts.cs b/src/RynthCore.Engine/ImGui/ImGuiFonts.cs index 3a43440..bf1fa42 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiFonts.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiFonts.cs @@ -32,6 +32,13 @@ // Font files are read by Preload() on the engine's init worker, so AC's // render thread only copies bytes into the atlas. The native TTF buffers and // glyph ranges stay alive until Free() (after the context is destroyed). +// +// The first atlas is baked off AC's thread too (2026-11-01, StartInitialBake): on a +// hot reload with every client reloading at once, queueing the fonts, rasterizing +// the atlas, the RGBA->BGRA copy and freeing the ~150 MB of TTF copies took 2.5-5 s +// of AC's main thread in the first ImGui frame (the "[UiCost] frame 3611 ms" lines, +// the main-thread hangs of every reload). The worker now does all of it; AC's thread +// swaps the finished atlas in and copies ready BGRA rows into the texture. // ============================================================================ using System; @@ -105,6 +112,8 @@ internal static unsafe class ImGuiFonts // set per size in use. Get() returns the set for CurrentStep, which the panel // host sets while it draws a panel, so every face's text grows without any // face code changing. Baked (not stretched), so the big text stays sharp. + // The sizes self-drawn windows are drawn at (UI.PanelDrawScale) are baked too: + // a window at 160% draws its text from the 160% set (StepsToBake). private static readonly Dictionary ScaledFonts = new(); /// Text size step of the panel being drawn (0 = normal). Render thread. @@ -167,6 +176,15 @@ internal static unsafe class ImGuiFonts _preloaded = true; } + /// The text size steps any panel uses, and those the self-drawn windows' sizes need. + private static List StepsToBake(float scale) + { + List steps = RynthCore.Engine.UI.PanelTextScale.StepsInUse(); + foreach (int step in RynthCore.Engine.UI.PanelDrawScale.FontStepsInUse(scale)) + if (!steps.Contains(step)) steps.Add(step); + return steps; + } + /// A baked font. Before Build (or if it failed) this is ImGui's default font. public static ImFontPtr Get(UiFont font) { @@ -219,7 +237,7 @@ internal static unsafe class ImGuiFonts Compatibility.MemoryUse.Mark("font files read"); ScaledFonts.Clear(); - AddAll(io.Fonts, scale, RynthCore.Engine.UI.PanelTextScale.StepsInUse(), Fonts, ScaledFonts); + AddAll(io.Fonts, scale, StepsToBake(scale), Fonts, ScaledFonts); if (Fonts[(int)UiFont.Ui11].NativePtr != null) io.NativePtr->FontDefault = Fonts[(int)UiFont.Ui11].NativePtr; @@ -403,8 +421,16 @@ internal static unsafe class ImGuiFonts public int Steps; public double Ms; public string? Error; + // The atlas pixels as D3D9 A8R8G8B8 rows (BGRA in memory), made by the worker + // (NativeMemory); handed on by SwapIn. 0 when the bake failed. + public IntPtr Bgra; + public int Width, Height; } + // The swapped-in atlas's BGRA copy, until DX9Backend uploads it (TakeBgraPixels). Render thread. + private static IntPtr _bgra; + private static int _bgraWidth, _bgraHeight; + private static System.Threading.Thread? _bakeThread; private static Bake? _bakeDone; // set by the worker as it ends private static readonly List FreeThreads = new(); @@ -418,32 +444,15 @@ internal static unsafe class ImGuiFonts { what = ""; if (_bakeThread != null) - { - Bake? done = System.Threading.Volatile.Read(ref _bakeDone); - if (done == null) return false; // still baking: frames go on with the old atlas - _bakeThread.Join(); - _bakeThread = null; - _bakeDone = null; - if (done.Atlas == IntPtr.Zero) - { - // Failed off-thread: the old way, here. - io.Fonts.Clear(); - Build(io, scale); - what = $"off-thread bake failed ({done.Error}); re-baked on the render thread"; - return true; - } - SwapIn(io, done); - what = $"baked off-thread in {done.Ms:0.0} ms ({done.Steps} enlarged size(s) in use)"; - return true; - } + return SwapFinished(io, scale, out what); // false while baking: frames go on with the old atlas if (!TakeRebuildRequest()) return false; PrepareNativeData(); - List steps = RynthCore.Engine.UI.PanelTextScale.StepsInUse(); + List steps = StepsToBake(scale); try { _bakeDone = null; - _bakeThread = EngineThreads.Start("ImGuiFonts.Bake", () => BakeWorker(scale, steps)); + _bakeThread = EngineThreads.Start("ImGuiFonts.Bake", () => BakeWorker(scale, steps, prepare: false)); return false; } catch (Exception ex) @@ -456,27 +465,125 @@ internal static unsafe class ImGuiFonts } } - private static void BakeWorker(float scale, List steps) + /// + /// The first atlas of a context, baked on a worker (see the header): reading the font files if + /// the init worker hasn't, making their native copies, queueing every font, rasterizing, the + /// BGRA copy and freeing the TTF copies all happen there. AC thread, once the scale is known. + /// False when no worker could be started (the caller then calls ). + /// + public static bool StartInitialBake(float scale) + { + if (_bakeThread != null) return true; + List steps = RynthCore.Engine.UI.PanelTextScale.StepsInUse(); + try + { + _bakeDone = null; + _bakeThread = EngineThreads.Start("ImGuiFonts.Bake", () => BakeWorker(scale, steps, prepare: true)); + return true; + } + catch (Exception ex) + { + _bakeThread = null; + RynthLog.UI($"ImGuiFonts: no bake thread for the first atlas ({ex.GetType().Name}: {ex.Message}); baking it on the render thread."); + return false; + } + } + + /// + /// Render thread, with 's context current: swaps a finished bake (the + /// first atlas, or a re-bake) into it. True when the atlas changed (the caller makes its + /// texture); false while none is running or it is still baking. + /// + public static bool SwapFinished(ImGuiIOPtr io, float scale, out string what) + { + what = ""; + if (_bakeThread == null) return false; + Bake? done = System.Threading.Volatile.Read(ref _bakeDone); + if (done == null) return false; + _bakeThread.Join(); + _bakeThread = null; + _bakeDone = null; + if (done.Atlas == IntPtr.Zero) + { + // Failed off-thread: the old way, here. + io.Fonts.Clear(); + Build(io, scale); + what = $"off-thread bake failed ({done.Error}); baked on the render thread"; + return true; + } + SwapIn(io, done); + what = $"baked off-thread in {done.Ms:0.0} ms: {CountBaked()} fonts at scale {scale:0.##}, {done.Steps} enlarged size(s) in use, " + + $"icons {(_phosphor != null ? $"{IconCount()} merged" : "missing")}" + + (_symbolMerges > 0 ? $", Segoe UI Symbol merged into {_symbolMerges}" : ""); + return true; + } + + /// + /// The swapped-in atlas's pixels as A8R8G8B8 rows, made by the bake worker, when they match + /// x : the caller copies them into the texture + /// and frees them with . False (nothing to free) otherwise: the + /// caller converts ImGui's RGBA itself. Either way the copy is no longer held here. Render thread. + /// + public static bool TakeBgraPixels(int width, int height, out IntPtr bgra) + { + bgra = _bgra; + bool match = bgra != IntPtr.Zero && _bgraWidth == width && _bgraHeight == height; + if (bgra != IntPtr.Zero && !match) FreeBgraPixels(bgra); + _bgra = IntPtr.Zero; + _bgraWidth = _bgraHeight = 0; + if (!match) bgra = IntPtr.Zero; + return match; + } + + public static void FreeBgraPixels(IntPtr bgra) + { + if (bgra != IntPtr.Zero) NativeMemory.Free((void*)bgra); + } + + private static void BakeWorker(float scale, List steps, bool prepare) { var bake = new Bake { Steps = steps.Count }; long t0 = Stopwatch.GetTimestamp(); ImFontAtlas* atlas = null; try { + // The first bake makes the native copies of the font files here; a re-bake finds + // them made (PumpRebuild prepares them first). One bake runs at a time, and nothing + // else touches them until it is joined (SwapFinished, WaitForWorkers). + if (prepare) + { + PrepareNativeData(); + Compatibility.MemoryUse.Mark("font files read (bake worker)"); + } atlas = ImGuiNative.ImFontAtlas_ImFontAtlas(); var ptr = new ImFontAtlasPtr(atlas); AddAll(ptr, scale, steps, bake.Base, bake.Scaled); if (bake.Base[(int)UiFont.Ui11].NativePtr == null) ptr.AddFontDefault(); // no Segoe UI: ImGui's built-in font keeps text readable ptr.Build(); - // The RGBA copy the texture is made from, here too: the swap then only uploads it. - ptr.GetTexDataAsRGBA32(out IntPtr _, out int _, out int _); + // The RGBA copy the texture is made from, and its BGRA rows for D3D9, here too: + // the swap then only copies rows into the texture. + ptr.GetTexDataAsRGBA32(out IntPtr rgba, out int w, out int h); + if (rgba != IntPtr.Zero && w > 0 && h > 0) + { + bake.Bgra = (IntPtr)NativeMemory.Alloc((nuint)w * (nuint)h, 4); + FontPixels.RgbaToBgra(new ReadOnlySpan((void*)rgba, w * h), new Span((void*)bake.Bgra, w * h)); + bake.Width = w; + bake.Height = h; + } + // The glyphs are rasterized: the atlas's copies of the font files (~150 MB with + // every size) are never read again (DX9Backend's note), so they go here, not on + // AC's thread. The pixels and TexReady stay. + ptr.ClearInputData(); + if (prepare) Compatibility.MemoryUse.Mark("font atlas baked (bake worker)"); bake.Atlas = (IntPtr)atlas; atlas = null; } catch (Exception ex) { bake.Error = $"{ex.GetType().Name}: {ex.Message}"; + FreeBgraPixels(bake.Bgra); + bake.Bgra = IntPtr.Zero; } finally { @@ -496,6 +603,10 @@ internal static unsafe class ImGuiFonts Array.Copy(bake.Base, Fonts, Fonts.Length); ScaledFonts.Clear(); foreach (KeyValuePair kv in bake.Scaled) ScaledFonts[kv.Key] = kv.Value; + FreeBgraPixels(_bgra); // a copy never uploaded (each swap is uploaded straight after) + _bgra = bake.Bgra; + _bgraWidth = bake.Width; + _bgraHeight = bake.Height; ImGuiPopOuts.ReplaceFontAtlas((IntPtr)old, (IntPtr)fresh); if (old == null || old == fresh) return; IntPtr oldPtr = (IntPtr)old; @@ -538,7 +649,11 @@ internal static unsafe class ImGuiFonts _bakeDone = null; if (pending != null && pending.Atlas != IntPtr.Zero) ImGuiNative.ImFontAtlas_destroy((ImFontAtlas*)pending.Atlas); // baked, never swapped in + if (pending != null) FreeBgraPixels(pending.Bgra); } + FreeBgraPixels(_bgra); + _bgra = IntPtr.Zero; + _bgraWidth = _bgraHeight = 0; foreach (IntPtr p in NativeBuffers) NativeMemory.Free((void*)p); NativeBuffers.Clear(); diff --git a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs index ded38cd..1fdcbc7 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs @@ -118,6 +118,15 @@ internal interface IImGuiPanel /// bool ClickThroughWantsWheel => false; + /// + /// True while the face shows a bare look (the Sense panel's compact view, 2026-10-31): docked, + /// the host draws no header, frame, border, background or resize grip, so only what the face + /// paints shows; with the rest passes clicks to the game. The window + /// keeps its place and size for when the face is framed again. Popped out (an OS window of its + /// own) and embedded copies are framed as usual. Answered by the face's last Draw; keep it cheap. + /// + bool Bare => false; + /// /// Popped out and not hovered or in use: how often the face is redrawn (Hz). /// Its pictures are only pushed when they change; this bounds the cost of @@ -594,10 +603,14 @@ internal static class ImGuiPanelHost /// public static void DrawAll(float uiScale) { + // UiCost: each panel by its title; the rest of DrawAll as the host's upkeep. + long cHost = UiCost.Start(), costMark = UiCost.Mark; + int drawn = 0; _frameScale = uiScale; WheelWanted = false; float placeScale = PlacementScale(); ApplyFaceChanges(placeScale); // plugin windows taking over (or giving back) engine panels + ApplyLayoutSwitch(placeScale); // another character's panel layout (UI/PanelLayout) while (Requests.TryDequeue(out var req)) Apply(req.Title, req.Kind, placeScale); RemoveUnregistered(); @@ -614,9 +627,13 @@ internal static class ImGuiPanelHost if (_resizeTitle == entry.Title) _resizeTitle = null; // hid mid-resize: free the grip continue; } + long cPanel = UiCost.Start(); DrawPanel(entry, uiScale, placeScale, null); + UiCost.StopPanel(entry.Title, cPanel); + drawn++; } DrawSizeNote(); + UiCost.StopExclusive(UiCost.PanelHost, cHost, costMark, cHost != 0 ? drawn : -1); } // ── One way to resize every panel (Tom 2026-10-23) ─────────────────── @@ -680,7 +697,9 @@ internal static class ImGuiPanelHost lock (Sync) Entries.TryGetValue(title, out entry); if (entry == null || !entry.Shown || !entry.Popped) return; _frameScale = uiScale; + long cPanel = UiCost.Start(); DrawPanel(entry, uiScale, PlacementScale(), display); + UiCost.StopPopped(entry.Title, cPanel); } /// A pop-out window was moved or resized by the user: save it. Game thread. @@ -703,6 +722,12 @@ internal static class ImGuiPanelHost _restored = true; // Settings > Display "Remember Open Windows and Positions" (default on). if (!Plugins.EngineSettings.RememberWindowLayout) return; + OpenSavedOpen(); + } + + /// Opens the engine panels the panel store has saved open (ImGui or Both docked face). AC thread. + private static void OpenSavedOpen() + { List titles = new(); // Script windows (dynamic) open when their owner says so, not from the saved state. lock (Sync) @@ -719,6 +744,77 @@ internal static class ImGuiPanelHost } } + // ── Panel layout per character (UI/PanelLayout) ─────────────────────── + + private static volatile bool _layoutSwitched; + + /// + /// The panel store now holds another layout (another character's, the default, or a reset): the + /// open panels take their places from it at the next DrawAll. Any thread. + /// + public static void OnLayoutSwitched() => _layoutSwitched = true; + + /// + /// After a layout switch: each shown panel is placed from the new layout (docked spot and size, popped + /// out or not, and where); an engine panel the layout has saved closed closes, without saving over + /// it; engine panels it has saved open open. Plugin and script windows stay open (their owners + /// decide that) and move. Nothing shown (a hot reload, the first login): only the opening. AC thread. + /// + private static void ApplyLayoutSwitch(float placeScale) + { + if (!_layoutSwitched) return; + _layoutSwitched = false; + bool remember = Plugins.EngineSettings.RememberWindowLayout; + List order; + lock (Sync) order = DrawOrder; + foreach (Entry e in order) + { + if (!e.Shown) continue; + bool has = PanelStateStore.TryGetPanel(e.Title, out PanelStateStore.PanelEntry saved); + if (!e.Dynamic && remember && has && !saved.Open) + { + CloseQuietly(e); + continue; + } + if (e.Popped) + { + ImGuiPopOuts.Close(e.Title); + e.Popped = false; + } + PlaceFromSavedState(e, placeScale); + if (PanelRouter.CanPopOut && !e.Spec.NoPopOut && has && saved.Floating) + StartPopOut(e, placeScale, fromSaved: true); + else if (!has) + Persist(e, open: true, placeScale); // new to this layout: saved here, so it reopens here + } + if (remember) OpenSavedOpen(); // queued; applied by this DrawAll (an open one is skipped) + RynthLog.UI("ImGuiPanelHost: the open panels took their places from the panel layout now in use."); + } + + /// Closes a shown face without saving its placement (the layout it came from isn't in use any more). AC thread. + private static void CloseQuietly(Entry entry) + { + lock (Sync) + { + if (_open.Contains(entry.Title)) + { + var next = new HashSet(_open, StringComparer.OrdinalIgnoreCase); + next.Remove(entry.Title); + System.Threading.Volatile.Write(ref _open, next); + } + } + if (entry.Popped) + { + ImGuiPopOuts.Close(entry.Title); + entry.Popped = false; + } + try { entry.Instance?.OnHidden(); } + catch (Exception ex) { RynthLog.UI($"ImGuiPanelHost: {entry.Title}.OnHidden threw {ex.GetType().Name}: {ex.Message}"); } + entry.Instance = null; + entry.Shown = false; + System.Threading.Interlocked.Decrement(ref _shownCount); + } + /// Client pixels per logical unit (the unit PanelSpec sizes, MinSize and RequestSize use). internal static float PlacementScale() { @@ -1006,7 +1102,10 @@ internal static class ImGuiPanelHost { PanelSpec spec = entry.Spec; bool popped = popDisplay.HasValue; - bool standard = spec.Chrome == PanelChrome.Standard; + // A bare face (IImGuiPanel.Bare): docked, no frame of any kind, only what it paints. + bool bare = false; + if (!popped) try { bare = entry.Instance?.Bare ?? false; } catch { } + bool standard = spec.Chrome == PanelChrome.Standard && !bare; bool both = PanelRouter.ResolveDockedFace(entry.Title) == PanelFace.Both; Vector2 minSize = (entry.Instance?.MinSize ?? spec.MinSize) * placeScale; @@ -1071,10 +1170,10 @@ internal static class ImGuiPanelHost ImGuiNET.ImGui.SetNextWindowSizeConstraints(minSize, new Vector2(float.MaxValue, float.MaxValue)); } - uint background = spec.Background ?? RynthTheme.PanelGlass; + uint background = bare ? 0u : spec.Background ?? RynthTheme.PanelGlass; ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, spec.Rounding); - ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, spec.Chrome == PanelChrome.None ? 0f : 1f); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, spec.Chrome == PanelChrome.None || bare ? 0f : 1f); ImGuiNET.ImGui.PushStyleColor(ImGuiCol.WindowBg, background); ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, spec.BorderColor ?? RynthTheme.PanelBorder); @@ -1113,7 +1212,7 @@ internal static class ImGuiPanelHost // the same way, over the corner the face leaves free. bool inlineGrip = standard && spec.GripInBody; bool manualGrip = (!standard || inlineGrip) && !clickThrough && !popped // popped: the window resizes itself - && !spec.NoResize; + && !spec.NoResize && !bare; // bare: sized while framed Vector2 outerPos = ImGuiNET.ImGui.GetWindowPos(), outerSize = ImGuiNET.ImGui.GetWindowSize(); float gSize = GripSize(entry, uiScale); Vector2 gMin = GripMin(entry, uiScale, outerPos + outerSize); @@ -1271,6 +1370,9 @@ internal static class ImGuiPanelHost /// True while an embedded copy draws: its window moves and size requests are ignored. [ThreadStatic] private static bool _inEmbed; + /// True while an embedded copy of a face draws (inside another panel's section). AC thread. + internal static bool DrawingEmbedded => _inEmbed; + /// True when is registered and may be drawn inside another panel. Any thread. public static bool CanEmbed(string title) => !NotEmbeddable.Contains(title) && HasFace(title); diff --git a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs index 42e62bc..868feab 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs @@ -432,7 +432,10 @@ internal static unsafe class ImGuiPopOuts if (pop.Window == null || pop.Window.Hwnd == IntPtr.Zero) continue; long interval = pop.HotFrames > 0 || pop.Hovered || pop.WantTextInput ? 0 : pop.IdleInterval; if (pop.HotFrames <= 0 && now - pop.LastFrameTicks < Math.Max(interval, FrameInterval)) continue; + // UiCost: the window's own frame, render and present; its panel is timed by the host. + long cPop = UiCost.Start(), costMark = UiCost.Mark; RenderOne(device, pop, uiScale, now); + UiCost.StopPopOutWindow(pop.Title, cPop, costMark); } } finally diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/HealthProbe.cs b/src/RynthCore.Engine/ImGui/MonsterHud/HealthProbe.cs new file mode 100644 index 0000000..f648c62 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/MonsterHud/HealthProbe.cs @@ -0,0 +1,194 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/MonsterHud/HealthProbe.cs +// Fresh health for the monster plates that are NOT the selected / queried +// target (2026-10-31: "only the selected monster's plate keeps updating; the +// others show a number that stops changing while they take damage"). +// +// Why they froze: ACE sends a creature's health (0x01C0 UpdateHealth) only +// to players whose current health-query target it is (Player.HandleAction- +// QueryHealth -> UpdateSelectedTarget; Creature.OnHealthUpdate walks that +// creature's selectedTargets). One target per player: every QueryHealth +// moves the stream. So a plate got one value when it was selected / queried / +// appraised and then nothing, and CleaveHealth estimates only cover the +// player's own weapon hits (no other players, pets, procs or DoTs). +// +// The fix: the HUD asks for them, slowly. At most one probe per interval +// (setting, default 1 s), and each probe is immediately followed by a query +// for the stream's owner (the last target a plugin or the selection asked +// for), so the selected / fight target keeps its live stream. Cost per probe: +// two 0x01BF game actions up, two 0x01C0 replies down (well under 100 bytes). +// +// Who is probed (Pick): plates on screen, not the stream owner, not dead. +// 1. "active" plates (hurt, hit by you, or hitting you) whose last server +// reading is ActiveRefreshSec old or more, the stalest first; +// 2. plates never read by the server, nearest first (one probe each); +// 3. quiet plates whose reading is IdleRefreshSec old or more. +// Nothing due: no traffic. +// +// A probe's reply is the HUD's: PluginManager records it for the plates but +// does not hand it to plugins (IsProbeReply), so a bot never reads another +// player's damage on a monster it isn't fighting as its own hit. +// +// Pick and the ledger are pure (time is passed in); compiled into +// tools/CleaveGhostTests. Engine-owned statics only. +// ============================================================================ + +using System; +using System.Threading; + +namespace RynthCore.Engine.ImGuiBackend.Hud; + +internal static class HealthProbe +{ + /// A plate in the fight is re-read when its last server reading is this old (s). + public const double ActiveRefreshSec = 2.0; + /// A quiet plate (full health, nobody fighting it) is re-read this rarely (s). + public const double IdleRefreshSec = 12.0; + /// A 0x01C0 for a probed id this soon after the probe (ms) is the probe's reply. + public const long ReplyWindowMs = 2000; + + /// The setting's range and default: seconds between two probes. + public const float DefaultIntervalSec = 1.0f, MinIntervalSec = 0.5f, MaxIntervalSec = 5.0f; + + /// + /// One plate. : the server has sent its health at least once; + /// : seconds since that last server reading (estimates don't count). + /// : hurt, hit by the player or hitting the player recently. + /// : its last reading was 0. + /// + public readonly record struct Candidate(uint Id, float Distance, bool Seen, double ServerAgeSec, bool Active, bool Dead = false); + + /// The plate to probe now, or 0 when none is due. is never picked (it is streamed). + public static uint Pick(ReadOnlySpan candidates, uint owner) + { + uint best = 0; + int bestTier = -1; + double bestScore = double.NegativeInfinity; + float bestD = float.MaxValue; + foreach (Candidate c in candidates) + { + if (c.Id == 0 || c.Id == owner || c.Dead) continue; + int tier; + double score; + if (c.Active) + { + if (c.Seen && !(c.ServerAgeSec >= ActiveRefreshSec)) continue; + tier = 2; + score = c.Seen ? c.ServerAgeSec / ActiveRefreshSec : double.MaxValue; + } + else if (!c.Seen) + { + tier = 1; + score = 0; // all equal: the nearest wins + } + else + { + if (!(c.ServerAgeSec >= IdleRefreshSec)) continue; + tier = 0; + score = c.ServerAgeSec / IdleRefreshSec; + } + bool better = tier > bestTier || + (tier == bestTier && (score > bestScore || (score == bestScore && c.Distance < bestD))); + if (!better) continue; + best = c.Id; bestTier = tier; bestScore = score; bestD = c.Distance; + } + return best; + } + + // ── The server's health stream: whose it is, and which replies are the HUD's ── + + private static readonly object Sync = new(); + private static uint _owner; + private static bool _ownerKnown; + private const int MaxPending = 8; + private static readonly uint[] PendingId = new uint[MaxPending]; + private static readonly long[] PendingAt = new long[MaxPending]; + private static readonly bool[] PendingSticky = new bool[MaxPending]; + private static int _pendingNext; + private static long _probes; + + /// Probes sent since the engine started (status line). + public static long ProbeCount => Interlocked.Read(ref _probes); + + /// + /// A health query that is not the HUD's went out for (a plugin's QueryHealth, + /// or the client's own on a selection change): the server streams that id now, and its replies + /// belong to whoever asked. Any thread. + /// + public static void NoteQuery(uint id) + { + lock (Sync) + { + _owner = id; + _ownerKnown = true; + // The stream moved: a sticky probe (sent with no owner to hand back to) no longer streams, + // and the newly queried id's replies are the asker's. + for (int i = 0; i < MaxPending; i++) + if (PendingId[i] == id || PendingSticky[i]) { PendingId[i] = 0; PendingSticky[i] = false; } + } + } + + /// The id the server streams health for (see NoteQuery); false before anything was noted. + public static bool TryGetOwner(out uint owner) + { + lock (Sync) + { + owner = _owner; + return _ownerKnown; + } + } + + /// + /// The HUD probed at . : no owner was + /// queried after it, so the server keeps streaming this id to us: every reply for it is the HUD's until + /// the next NoteQuery (no ReplyWindowMs). + /// + public static void NoteProbe(uint id, long nowMs, bool sticky = false) + { + if (id == 0) return; + lock (Sync) + { + int slot = -1; + for (int i = 0; i < MaxPending; i++) + if (PendingId[i] == id) { slot = i; break; } + if (slot < 0) { slot = _pendingNext; _pendingNext = (_pendingNext + 1) % MaxPending; } + PendingId[slot] = id; + PendingAt[slot] = nowMs; + PendingSticky[slot] = sticky; + _probes++; + } + } + + /// True when a health reply for answers a HUD probe (sent within ReplyWindowMs). + public static bool IsProbeReply(uint id, long nowMs) + { + if (id == 0) return false; + lock (Sync) + { + if (_ownerKnown && id == _owner) return false; // someone else asked for it too + for (int i = 0; i < MaxPending; i++) + if (PendingId[i] == id) + { + if (PendingSticky[i]) return true; + long age = nowMs - PendingAt[i]; + if (age >= 0 && age <= ReplyWindowMs) return true; + PendingId[i] = 0; // expired + return false; + } + return false; + } + } + + /// Logout / character switch: nothing carries over. + public static void Reset() + { + lock (Sync) + { + _owner = 0; + _ownerKnown = false; + Array.Clear(PendingId); + Array.Clear(PendingSticky); + _pendingNext = 0; + } + } +} diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs index 3f871e6..88046b0 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs @@ -288,6 +288,7 @@ internal static class MonsterHud if (track) Snapshot(now, trackMonsters); } if (monsters) ApplyDealtHits(now); + if (monsters && MonsterHudSettings.RefreshOthersHealth) ProbeHealth(now); _hasContent = Plates.Count > 0 || MonsterHudSettings.SelfPlate || CombatText.HasContent; } @@ -316,6 +317,8 @@ internal static class MonsterHud { ClearPlates(); MonsterHudData.Clear(); + HealthProbe.Reset(); + _nextProbeTicks = 0; PlateDebuffs.Clear(); CombatText.Clear(); PlayerPlate.Reset(); @@ -1590,6 +1593,45 @@ internal static class MonsterHud } } + // ── Health for the plates the server isn't streaming (HealthProbe) ── + private static readonly List ProbeCandidates = new(); + private static long _nextProbeTicks; + /// "Hit by you" keeps a plate in the fight this long (s) for the probe's refresh. + private const double ProbeHitMemorySec = 30; + + /// + /// At most one health query per "Refresh others' health" interval for an on-screen plate the server + /// isn't streaming, then one for the stream's owner so the selected / fight target keeps its feed. + /// AC's main thread only (both sends go out back to back, in order); skipped otherwise and in a + /// death / portal / login window. + /// + private static void ProbeHealth(long now) + { + if (now < _nextProbeTicks || Plates.Count == 0) return; + float interval = Math.Clamp(MonsterHudSettings.HealthRefreshSec, HealthProbe.MinIntervalSec, HealthProbe.MaxIntervalSec); + _nextProbeTicks = now + (long)(interval * Stopwatch.Frequency); + if (!CombatActionHooks.HasQueryHealth || AcMainThreadQueue.MustQueue(teardown: false)) return; + + if (!HealthProbe.TryGetOwner(out uint owner)) owner = ClientHelperHooks.GetSelectedItemId(); + double freq = Stopwatch.Frequency; + long hitWindow = (long)(ProbeHitMemorySec * freq); + ProbeCandidates.Clear(); + foreach (Plate p in Plates.Values) + { + if (p.IsLabel || p.Gone || !p.OnScreen || p.Alpha < 0.01f || p.Id == _playerId) continue; + bool has = MonsterHudData.TryGetHealth(p.Id, out HealthObservation h); + bool seen = has && h.ServerTicks != 0; + long lastHit = CombatText.LastHitTicks(p.Id); + bool active = p.IsAttacker || (has && (h.Ratio < 0.999f || h.Estimated)) || + (lastHit != long.MinValue && now - lastHit < hitWindow); + ProbeCandidates.Add(new HealthProbe.Candidate(p.Id, p.Distance, seen, seen ? (now - h.ServerTicks) / freq : 0, + active, Dead: seen && h.Ratio <= 0.001f)); + } + uint id = HealthProbe.Pick(System.Runtime.InteropServices.CollectionsMarshal.AsSpan(ProbeCandidates), owner); + if (id == 0) return; + CombatActionHooks.SendHudHealthProbe(id, owner, Environment.TickCount64); + } + internal static uint FindPlateByName(string name) { uint target = ClientHelperHooks.GetSelectedItemId(); @@ -1696,7 +1738,9 @@ internal static class MonsterHud $"name labels {labels} ({labelsOnScreen} on screen, {portals} portals), {Classes.Count} objects classified; " + $"camera {(GameMatrixCapture.HasCapturedFrame ? "captured" : "not captured")} " + $"(frame lb 0x{GameMatrixCapture.FrameLandblock:X4}, viewport {GameMatrixCapture.ViewportWidth}x{GameMatrixCapture.ViewportHeight}); " + - $"weakness data {(_weakByWcid.Count + _weakByName.Count > 0 ? "loaded" : "none")}.", + $"weakness data {(_weakByWcid.Count + _weakByName.Count > 0 ? "loaded" : "none")}; " + + $"others' health refresh {(MonsterHudSettings.RefreshOthersHealth ? $"on, every {MonsterHudSettings.HealthRefreshSec:0.0#} s" : "off")} " + + $"({HealthProbe.ProbeCount} quer{(HealthProbe.ProbeCount == 1 ? "y" : "ies")} sent).", PlateDebuffs.Describe(), PlayerPlate.Describe() + " " + CombatText.Describe(), AcMouseOver.Describe(), diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudData.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudData.cs index ea86ec6..eb8929b 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudData.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudData.cs @@ -23,8 +23,10 @@ using System.Diagnostics; namespace RynthCore.Engine.ImGuiBackend.Hud; /// Last health observation for one object. : the ratio before it -/// (-1 = first). : worked out from a hit (CleaveHealth), not sent by the server. -internal readonly record struct HealthObservation(float Ratio, uint Current, uint Max, long Ticks, float Prev = -1f, bool Estimated = false); +/// (-1 = first). : worked out from a hit (CleaveHealth), not sent by the server. +/// : when the server last sent this object's health (0 = never; estimates keep it). +internal readonly record struct HealthObservation(float Ratio, uint Current, uint Max, long Ticks, float Prev = -1f, bool Estimated = false, + long ServerTicks = 0); internal static class MonsterHudData { @@ -58,7 +60,8 @@ internal static class MonsterHudData } if (Health.Count >= MaxHealthEntries && !Health.ContainsKey(id)) Health.Clear(); - Health[id] = new HealthObservation(ratio, current, max, now, before, estimated); + long serverTicks = estimated ? (had ? prev.ServerTicks : 0) : now; + Health[id] = new HealthObservation(ratio, current, max, now, before, estimated, serverTicks); } // An estimate never kills (CleaveHealth keeps it above 0) and the server correcting one // isn't a heal: the combat text sees an estimate's successor as a first observation. diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs index 182d88f..e92471b 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs @@ -49,6 +49,14 @@ internal static class MonsterHudSettings public static float HeightLift = 0.0f; // extra metres above the estimated head height /// A left-click on a monster plate selects that monster in game. public static bool ClickToSelect = true; + /// + /// "Refresh others' health" (2026-10-31): the server streams health only for the selected / queried + /// monster, so the HUD asks for the other plates' health itself, one monster per HealthRefreshSec + /// (HealthProbe). Off: only the selected / queried monster's plate is live. + /// + public static bool RefreshOthersHealth = true; + /// Seconds between two of those health queries (HealthProbe's range). + public static float HealthRefreshSec = HealthProbe.DefaultIntervalSec; // Name-only labels over NPCs (vendors in gold) and, optionally, other players. // Counted apart from MaxPlates so they never push a monster plate out. @@ -220,6 +228,10 @@ internal static class MonsterHudSettings case "scale": if (TryF(val, out float s)) Scale = Math.Clamp(s, MinScale, MaxScale); break; case "opacity": if (TryF(val, out float o)) Opacity = Math.Clamp(o, MinOpacity, MaxOpacity); break; case "clickSelect": ClickToSelect = val == "1"; break; + case "refreshOthersHealth": RefreshOthersHealth = val == "1"; break; + case "healthRefreshSec": + if (TryF(val, out float hr)) HealthRefreshSec = Math.Clamp(hr, HealthProbe.MinIntervalSec, HealthProbe.MaxIntervalSec); + break; case "heightLift": if (TryF(val, out float h)) HeightLift = Math.Clamp(h, MinLift, MaxLift); break; case "npcNames": NpcNames = val == "1"; break; case "npcDistance": if (TryF(val, out float nd)) NpcMaxDistance = Math.Clamp(nd, MinNpcDistance, MaxNpcDistanceLimit); break; @@ -339,6 +351,8 @@ internal static class MonsterHudSettings sw.WriteLine(FormattableString.Invariant($"opacity={Opacity:0.##}")); sw.WriteLine(FormattableString.Invariant($"heightLift={HeightLift:0.##}")); sw.WriteLine($"clickSelect={B(ClickToSelect)}"); + sw.WriteLine($"refreshOthersHealth={B(RefreshOthersHealth)}"); + sw.WriteLine(FormattableString.Invariant($"healthRefreshSec={HealthRefreshSec:0.##}")); sw.WriteLine($"npcNames={B(NpcNames)}"); sw.WriteLine(FormattableString.Invariant($"npcDistance={NpcMaxDistance:0.#}")); sw.WriteLine(FormattableString.Invariant($"npcMax={MaxNpcLabels}")); @@ -397,6 +411,7 @@ internal static class MonsterHudSettings Enabled = true; MaxDistance = 35f; MaxPlates = 20; Filter = PlateFilter.All; ShowNames = true; ShowHpNumbers = true; ShowDistance = false; ShowLevel = true; ShowWeakness = true; FadeWithDistance = true; Scale = 1.0f; Opacity = 0.9f; HeightLift = 0f; ClickToSelect = true; + RefreshOthersHealth = true; HealthRefreshSec = HealthProbe.DefaultIntervalSec; ShowDebuffs = true; ShowOthersDebuff = true; NpcNames = true; NpcMaxDistance = 30f; MaxNpcLabels = 15; PlayerNames = false; PlayerBars = false; PortalNames = true; PortalMaxDistance = DefaultPortalDistance; @@ -462,7 +477,8 @@ internal static class MonsterHudSettings $"RynthVision nameplates: monsters {(Enabled ? "ON" : "OFF")} ({(Filter == PlateFilter.Engaged ? "engaged only" : "all monsters")}, " + $"{MaxDistance:0}yd, max {MaxPlates}, scale {Scale:0.##}, opacity {Opacity:0.##}, lift {HeightLift:0.#}m; " + $"names {OnOff(ShowNames)}, hp {OnOff(ShowHpNumbers)}, level {OnOff(ShowLevel)}, weak {OnOff(ShowWeakness)}, " + - $"distance {OnOff(ShowDistance)}, fade {OnOff(FadeWithDistance)}, click to select {OnOff(ClickToSelect)}), debuffs {OnOff(ShowDebuffs)} (others {OnOff(ShowOthersDebuff)}); " + + $"distance {OnOff(ShowDistance)}, fade {OnOff(FadeWithDistance)}, click to select {OnOff(ClickToSelect)}, " + + $"refresh others' health {(RefreshOthersHealth ? $"every {HealthRefreshSec:0.0#} s" : "off")}), debuffs {OnOff(ShowDebuffs)} (others {OnOff(ShowOthersDebuff)}); " + $"NPC names {OnOff(NpcNames)} ({NpcMaxDistance:0}yd, max {MaxNpcLabels}), player names {OnOff(PlayerNames)} (bars {OnOff(PlayerBars)}), " + $"portal names {OnOff(PortalNames)} ({PortalMaxDistance:0}yd); " + $"self {OnOff(SelfPlate)} ({(SelfPlacement == SelfPlacement.Fixed ? "fixed on screen, " + (SelfLocked ? "locked" : "unlocked") : "follows you, " + SelfPosition.ToString().ToLowerInvariant())}, " + diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs index bd0b952..ec4d132 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs @@ -67,6 +67,14 @@ internal static class MonsterHudSettingsUi MonsterHudSettings.MinDistance, MonsterHudSettings.MaxDistanceLimit, "%.0f", w); changed |= SliderI("Max plates", ref MonsterHudSettings.MaxPlates, MonsterHudSettings.MinPlates, MonsterHudSettings.MaxPlatesLimit, w); + changed |= Toggle("Refresh others' health", ref MonsterHudSettings.RefreshOthersHealth, + "The server only keeps the selected (or fought) monster's health up to date. On: the HUD also asks for " + + "the other plates' health, one monster at a time - first the ones in the fight, then any it hasn't seen - " + + "and hands the live feed straight back to your target. Two small queries per refresh. " + + "Off: only your target's plate is live. Chat: /rv plates refresh [on|off], /rv plates refresh ."); + if (MonsterHudSettings.RefreshOthersHealth) + changed |= SliderF("Refresh every (s)", ref MonsterHudSettings.HealthRefreshSec, + HealthProbe.MinIntervalSec, HealthProbe.MaxIntervalSec, "%.1f s", w); Section("On the plate", w); changed |= Toggle("Name", ref MonsterHudSettings.ShowNames, null); diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs index 60cffe3..3d28325 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs @@ -14,7 +14,8 @@ // highlights is laid out by hand (LayoutSpans) so each run can take its own // colour. Drag across lines to copy them (the keyboard stays with the game, // so copy is mouse-driven). Right-click a line to copy it or to make a rule -// from it: move / copy lines like it to a tab, hide them, colour them. A line +// from it: move / copy lines like it to a tab, hide them, colour or highlight +// them (a "Highlight line" rule: a band behind the whole line). A line // with map coordinates in it ("42.1N, 33.6E") also offers "Arrow to" and "Go // to" them, sent to RynthNav (UI/Data/ChatCoords.cs finds them). The // coordinates are also drawn as underlined links: click points RynthNav's @@ -638,6 +639,10 @@ internal sealed class ChatFace : IImGuiPanel Vector2 p = basePos + new Vector2(0, _tops[i]); ChatLine line = _vis[i]; ChatRoute route = line.Route; + // A "Highlight line" rule: a band behind all of the line's rows, under the mention + // tint and the selection. One rect, no allocation; _h[i] already spans every row. + if (route.HighlightArgb is uint band) + dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), RynthTheme.Argb(ChatColorModes.BandArgb(band))); if (route.Mention) dl.AddRectFilled(p, p + new Vector2(wrapW + 6, _h[i]), MentionBg); if (lo >= 0 && i >= lo && i <= hi) @@ -1065,15 +1070,17 @@ internal sealed class ChatFace : IImGuiPanel // ── Rules from a line ──────────────────────────────────────────────── - private void RuleFromLine(ChatRuleAction action, string? tab) + private void RuleFromLine(ChatRuleAction action, string? tab, ChatColorMode colour = ChatColorMode.Line) { var rule = new ChatFilterRule { Pattern = _ctxPattern, Action = action, Tab = tab ?? "" }; if (action == ChatRuleAction.Color) { - rule.ColorMode = ChatColorMode.Line; + rule.ColorMode = colour; ChatModel.AddRule(rule); if (!ImGuiPanelHost.IsOpen("ChatFilters")) PanelRouter.Toggle("ChatFilters"); - Flash("Rule added - pick its colour in Filters"); + Flash(colour == ChatColorMode.Highlight + ? "Rule added: lines like this are highlighted - pick its colour in Filters" + : "Rule added - pick its colour in Filters"); return; } ChatModel.AddRule(rule); @@ -1486,6 +1493,7 @@ internal sealed class ChatFace : IImGuiPanel TabMenu("Also show them in", ChatRuleAction.Copy); if (ImGuiNET.ImGui.MenuItem("Hide them")) RuleFromLine(ChatRuleAction.Hide, null); if (ImGuiNET.ImGui.MenuItem("Colour them…")) RuleFromLine(ChatRuleAction.Color, null); + if (ImGuiNET.ImGui.MenuItem("Highlight them…")) RuleFromLine(ChatRuleAction.Color, null, ChatColorMode.Highlight); ImGuiNET.ImGui.Separator(); if (ImGuiNET.ImGui.MenuItem("Edit rules…") && !ImGuiPanelHost.IsOpen("ChatFilters")) PanelRouter.Toggle("ChatFilters"); diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs index a547f19..115de74 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs @@ -5,6 +5,7 @@ // // [#] [on] [Contains v] [pattern ...................] [up] [down] [delete] // When [Any line v] [Move to v] [Junk v] [Colour line v] [swatch] +// (colour: No colour / Colour line / Colour match / Highlight line) // (a regex error, a timed-out rule, a missing tab, or its hit count) // // The order and what each action does are spelled out in the header lines @@ -84,7 +85,15 @@ internal sealed class ChatFiltersFace : IImGuiPanel "Hide: the line is not shown anywhere (the chat log still has it).", "Colour only: no routing; the rule just colours.", }; - private static readonly string[] ColorLabels = { "No colour", "Colour line", "Colour match" }; + // Indexed by ChatColorMode. + private static readonly string[] ColorLabels = { "No colour", "Colour line", "Colour match", "Highlight line" }; + private static readonly string[] ColorHelp = + { + "No colour: the rule doesn't colour the line.", + "Colour line: the whole line's text in this colour.", + "Colour match: just the text the rule matched, in this colour.", + "Highlight line: a band in this colour behind the whole line; the text keeps its colour.", + }; private static readonly string[] ModeHelp = { "Regex: a case-insensitive regular expression (^ start, $ end, \\d+ a number...).", @@ -116,7 +125,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); Label("Rules run top to bottom (" + PhosphorIcons.ArrowUp + PhosphorIcons.ArrowDown + " to reorder) on each line's text: plain text (any case) or a regex.", Mute); Label("Where it shows: Copy rules add a tab and go on; the first Move or Hide that matches decides.", Mute); - Label("Colour: the first \"Colour line\" wins; \"Colour match\" colours every match (a higher rule wins an overlap).", Mute); + Label("Colour: the first \"Colour line\" wins, and the first \"Highlight line\"; \"Colour match\" colours every match (a higher rule wins an overlap).", Mute); ImGuiNET.ImGui.PopFont(); ImGuiNET.ImGui.Dummy(new Vector2(0, 1)); @@ -346,7 +355,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel if (r.Action != ChatRuleAction.Hide) { - int mode = (int)r.ColorMode; + int mode = Math.Clamp((int)r.ColorMode, 0, ColorLabels.Length - 1); string colText = ColorLabels[mode] + Caret; Vector2 cPos = flow.Place(ButtonWidth(colText)); if (Button("##colmode", colText, cPos, new Vector2(ButtonWidth(colText), rowH), Text, BtnFill)) @@ -354,8 +363,8 @@ internal sealed class ChatFiltersFace : IImGuiPanel { rule.ColorMode = (ChatColorMode)k; ChatModel.FiltersChanged(); - }, 130); - ImGuiNET.ImGui.SetItemTooltip("Colour line: the whole line. Colour match: just the text the rule matched."); + }, 140); + SafeImGui.SetItemTooltip(ColorHelp[mode]); if (r.ColorMode != ChatColorMode.None) { Vector2 sPos = flow.Place(rowH); @@ -629,6 +638,9 @@ internal sealed class ChatFiltersFace : IImGuiPanel } uint color = RynthTheme.Argb(ChatLineColors.Resolve(route.LineArgb, ChatLineColors.KindOf(type, channel, text), channel, type)); _testResult.Add((where + (route.LineArgb != null ? " (this is its colour)" : ""), route.Hidden ? Faded(Mute) : color)); + if (!route.Hidden && route.HighlightArgb is uint band) + _testResult.Add(($"Highlighted: a {ChatModel.FormatColor(band | 0xFF000000)} band behind the line (this colour).", + RynthTheme.Argb(band | 0xFF000000))); // Not hidden: name a standard filter that would hide it (one not in the rules yet). if (!route.Hidden) diff --git a/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicLootTab.cs b/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicLootTab.cs index daa9f9d..d9be3b1 100644 --- a/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicLootTab.cs +++ b/src/RynthCore.Engine/ImGui/Panels/Classic/ClassicLootTab.cs @@ -7,7 +7,9 @@ // UiSources.LootEdit, shared with the Loot Editor): each rule // with its on/off gem, its action (Keep, Keep #, Salvage, // Sell, Read) and summary; move up / down, duplicate, delete, -// add; Save and Reload; RynthAi's last message. +// add; Why? (RynthAi's "Why this loot rule?" window for the +// item selected in the game); Save and Reload; RynthAi's last +// message. // A rule's conditions are written in the Loot Editor (the Editor plate opens it // on this file). Opening another file waits for unsaved changes to be saved or // reloaded (the Loot Editor asks about discarding them; this tab doesn't). @@ -170,6 +172,11 @@ internal sealed class ClassicLootTab : IClassicTab if (Plate("##cl_add", "Add", new Vector2(x, y)) && editable) LootEditCommands.Simple("add", -1); SafeImGui.SetItemTooltip("Add a new rule at the end (write it in the Loot Editor)"); + x += Px(50); + // The selected item, not the selected rule: RynthAi's "Why this loot rule?" window. + if (x + Px(46) <= o.X + w && Plate("##cl_why", "Why?", new Vector2(x, y))) + LootEditorFace.AskLootWhy(); + SafeImGui.SetItemTooltip(LootEditorFace.LootWhyLabel + "\n" + LootEditorFace.LootWhyTip); y += Px(21); } diff --git a/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs b/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs index 4fd68a7..6a458a2 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs @@ -16,6 +16,9 @@ // Monster Detail panel (weaknesses, accuracy, damage, summons, damage taken, // its rule). x removes the monster (confirmed). Gold = set by you, dim = // automatic. +// Under a monster's row, when the plugin sends them (the row's "mstats", +// UI/Data/DamageRowStats.cs, 2026-10-30): how often it evades and resists you +// and you it since login, the full numbers on hover. // Where the server plugin reports difficulty tiers: a tier chip after Reset stats // (DamageView.Tier) - which tier the numbers are for, and a picker; "~" marks an // HP estimated from tier 0's. Hidden elsewhere. @@ -97,6 +100,8 @@ internal sealed class DamageFace : IImGuiPanel public string NameShown = "", NameTip = ""; public string Weapon = "", Offhand = "", Pet = "", WeakTop = "", Sec = "", SecTip = ""; public string Prefer = "Auto"; + /// The line under the row (the plugin's evades and resists since login) and its tooltip; "" for none. + public string Stats = "", StatsTip = ""; public bool CritSet, NonCritSet, WeaponGold, OffhandGold, PetGold, PreferGold; public string[] TierLines = Array.Empty(); /// Priority shown (int.MinValue = rules not loaded), whether it's the monster's own @@ -361,6 +366,11 @@ internal sealed class DamageFace : IImGuiPanel t.Sec = r.SecKill > 0 ? r.SecKill.ToString("0.0", inv) : "—"; t.SecTip = (r.SecKill > 0 ? $"{r.SecKill:0.0} s from engaging to the kill (average of timed kills)." : "No timed kills yet.") + (r.HitRate >= 0 ? $"\nHits: {r.HitRate * 100:0}% of attacks and casts landed." : ""); + if (r.Stats != null) + { + t.Stats = r.Stats.Line(); + t.StatsTip = r.Stats.Tip(); + } t.TierLines = new string[r.Tiers.Count]; for (int i = 0; i < r.Tiers.Count; i++) { @@ -756,29 +766,33 @@ internal sealed class DamageFace : IImGuiPanel } } + // The line under a monster's row: the plugin's evades and resists since login (DamageRowStats). + private const float StatsH = 16; + private void DrawRow(DamageRow r, Vector2 clipMin, Vector2 clipMax) { Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); - if (p.Y + RowH < clipMin.Y || p.Y > clipMax.Y) + RowText t = _text[r]; + float h = RowH + (t.Stats.Length > 0 ? StatsH : 0); + if (p.Y + h < clipMin.Y || p.Y > clipMax.Y) { - ImGuiNET.ImGui.Dummy(new Vector2(TableW, RowH)); // off screen: keep the layout, skip the drawing + ImGuiNET.ImGui.Dummy(new Vector2(TableW, h)); // off screen: keep the layout, skip the drawing return; } - RowText t = _text[r]; var dl = ImGuiNET.ImGui.GetWindowDrawList(); - dl.AddRectFilled(p, p + new Vector2(TableW, RowH), r.IsDefault ? HeaderBg : RowBg); + dl.AddRectFilled(p, p + new Vector2(TableW, h), r.IsDefault ? HeaderBg : RowBg); if (r.Targeted) { // The monster being fought (or selected): teal wash, a bar on the left, an outline. - dl.AddRectFilled(p, p + new Vector2(TableW, RowH), TargetBg); - dl.AddRectFilled(p, p + new Vector2(3, RowH), Teal); - dl.AddRect(p, p + new Vector2(TableW, RowH), Teal); + dl.AddRectFilled(p, p + new Vector2(TableW, h), TargetBg); + dl.AddRectFilled(p, p + new Vector2(3, h), Teal); + dl.AddRect(p, p + new Vector2(TableW, h), Teal); } else if (r.Nearby) { // On the player's landblock: a green wash and bar. - dl.AddRectFilled(p, p + new Vector2(TableW, RowH), NearbyBg); - dl.AddRectFilled(p, p + new Vector2(3, RowH), NearbyBar); + dl.AddRectFilled(p, p + new Vector2(TableW, h), NearbyBg); + dl.AddRectFilled(p, p + new Vector2(3, h), NearbyBar); } ImGuiNET.ImGui.PushID(r.IsDefault ? "default" : r.Key); float ty = p.Y + (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f; @@ -892,8 +906,21 @@ internal sealed class DamageFace : IImGuiPanel } SafeImGui.SetItemTooltip("Remove " + r.Name + " from this list (asks first)."); + if (t.Stats.Length > 0) + { + // Under the monster: its evades and resists both ways since login, the full numbers on hover. + ImFontPtr small = ImGuiFonts.Get(UiFont.Ui10); + var at = new Vector2(p.X + ColX[ColMonster] + 22, p.Y + RowH + (StatsH - small.FontSize) * 0.5f - 2); + dl.PushClipRect(new Vector2(p.X, p.Y + RowH), new Vector2(p.X + TableW, p.Y + h), true); + dl.AddText(small, small.FontSize, at, Dim, t.Stats); + dl.PopClipRect(); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + ColX[ColMonster] + 22, p.Y + RowH)); + ImGuiNET.ImGui.InvisibleButton("##stats", new Vector2(Math.Max(1, TableW - ColX[ColMonster] - 26), StatsH)); + SafeImGui.SetItemTooltip(t.StatsTip); + } + ImGuiNET.ImGui.PopID(); - ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + RowH)); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + h)); ImGuiNET.ImGui.Dummy(new Vector2(TableW, 0)); } @@ -1442,7 +1469,7 @@ internal sealed class DamageFace : IImGuiPanel ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), "Reset ALL learned damage statistics?"); ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); ImGuiNET.ImGui.TextColored(RynthTheme.VecOf(RynthTheme.Text), - "Monster names and your settings (manual HP, weapon/offhand picks, debuffs) are KEPT — only the learned damage, crit, casts-to-kill, kills and HP are cleared. This cannot be undone."); + "Monster names and your settings (manual HP, weapon/offhand picks, debuffs) are KEPT — only the learned damage, crit, casts-to-kill, kills and HP are cleared, and the evades and resists under each monster start over. This cannot be undone."); ImGuiNET.ImGui.PopTextWrapPos(); ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); float w = ImGuiNET.ImGui.GetContentRegionAvail().X; diff --git a/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs b/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs index 256953f..18af241 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs @@ -60,6 +60,10 @@ internal sealed class ItemsFace : IImGuiPanel "An entry whose item is gone but with an unlisted item of the same name in your pack\n" + "(a new stack of kits, a replacement weapon) is pointed at that item instead.\n" + "Does nothing while your inventory is still loading. Also: /ra items clean."); + // The other way: everything in the pack that belongs here and isn't listed yet (answers in chat). + AddSelected("##fill_from_pack", PhosphorIcons.Plus + " Add From Pack", "(weapons, healing kits, lockpicks, pet essences not listed yet)", + () => RynthAiCommands.ApplyRemoteCommand("sendchat", "/ra items fill"), + "Adds every weapon, healing kit, lockpick and pet essence in your pack that isn't listed yet.\nRynthAi says in chat what it added. Also: /ra items fill."); // Weapons Section("Weapons", bw); diff --git a/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs b/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs index f05523f..f9e6834 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs @@ -158,6 +158,11 @@ internal sealed class LootEditorFace : IImGuiPanel public readonly byte[] Bytes = new byte[512]; public string? Shown; public bool Active; + // A text condition (TextPattern): the mode shown, the words in the box, and the pattern they were + // read from (re-read only when the pattern changes, so a mode the player picked stays). + public LootTextMode? Mode; + public string Words = ""; + public string? ParsedFrom; } private readonly Dictionary<(int Cond, int Line), FieldBuffer> _fields = new(); private readonly FieldBuffer _nameField = new(), _keepField = new(); @@ -758,10 +763,26 @@ internal sealed class LootEditorFace : IImGuiPanel ? "A rule for the item selected in the game (click it first): preview, then add it here" : s.Dirty ? "Save or discard your edits first" : "This profile is read-only here"); addW += itemW + 6; + // RynthAi answers in its own "Why this loot rule?" window (an older RynthAi ignores it). + string whyLabel = PhosphorIcons.Info + " " + LootWhyLabel; + float whyW = ButtonWidth(whyLabel) + 6; + if (Button("##loot_why", whyLabel, new Vector2(p.X + addW + 6, p.Y), new Vector2(whyW, h), Text, BtnFill)) + AskLootWhy(); + SafeImGui.SetItemTooltip(LootWhyTip); + addW += whyW + 6; MessageText(new Vector2(p.X + addW + 8, p.Y), p.X + w - grip - 4, h); NextLine(p, h); } + /// The "Why this loot rule?" buttons (here and the Classic Loot tab). + internal const string LootWhyLabel = "Why this loot rule?"; + internal const string LootWhyTip = + "Which rule of the loot profile in use takes the item selected in the game, and why the rules above it\n" + + "didn't (the first condition each failed, and the value it read). RynthAi shows it in a small window.\nAlso: /ra loot why"; + + /// RynthAi's "lootwhy" remote command: /ra loot why window, for the selected item. Any thread. + internal static void AskLootWhy() => RynthAiCommands.ApplyRemoteCommand("lootwhy", "show"); + private void MessageText(Vector2 at, float right, float h) { if (_msg.Length == 0 || (_msgOk && (DateTime.Now - _msgAt).TotalSeconds > 10)) return; @@ -1110,14 +1131,13 @@ internal sealed class LootEditorFace : IImGuiPanel } case "keypattern": { - float kw = w * 0.34f; + float kw = w * 0.30f; IdPicker("##key", c, 1, KeyTable(node.KeyTable), "key", p, kw - 2, h, ro); - if (Field("##pat", FieldFor(i, 0), c.Lines[0], new Vector2(p.X + kw + 2, p.Y), w - kw - 2, "pattern (regex)", ro, out string v, h)) - c.Lines[0] = v; + TextPattern("##pat", c, i, new Vector2(p.X + kw + 2, p.Y), w - kw - 2, h, ro); break; } case "text": - if (Field("##text", FieldFor(i, 0), c.Lines[0], p, w, "pattern (regex)", ro, out string t, h)) c.Lines[0] = t; + TextPattern("##text", c, i, p, w, h, ro); break; default: // "value" if (Field("##value", FieldFor(i, 0), c.Lines[0], p, w, node.Labels.Count > 0 ? node.Labels[0].ToLowerInvariant() : "value", ro, out string n, h)) @@ -1188,6 +1208,62 @@ internal sealed class LootEditorFace : IImGuiPanel SafeImGui.SetItemTooltip(tip); } + /// + /// A text condition's pattern as a mode and plain words (2026-11-01: "people hate regex"): [contains v] + /// [words]. The editor writes the regex (UI.LootPatternText) into the condition, so the profile stays a + /// plain VTank .utl; "regex" shows the pattern itself. A mode the player picks stays while the pattern + /// still reads back as it. + /// + private void TextPattern(string id, LootEditConditionDto c, int cond, Vector2 p, float w, float h, bool ro) + { + FieldBuffer buf = FieldFor(cond, 0); + string pattern = c.Lines[0]; + if (!ReferenceEquals(buf.ParsedFrom, pattern)) + { + var (mode, words) = LootPatternText.Parse(pattern); + LootTextMode keep = buf.Mode ?? mode; + if (keep == LootTextMode.Regex) { buf.Mode = LootTextMode.Regex; buf.Words = pattern; } + else if (pattern.Length == 0) { buf.Mode = keep; buf.Words = ""; } + else { buf.Mode = mode; buf.Words = mode == LootTextMode.Regex ? pattern : words; } + buf.ParsedFrom = pattern; + } + LootTextMode shown = buf.Mode ?? LootTextMode.Contains; + + float mw = Math.Min(120, Math.Max(80, w * 0.36f)); + if (PickerButton(id + "_mode", LootPatternText.Label(shown), p, mw - 2, h, ro)) + { + FieldBuffer target = buf; + LootEditConditionDto dto = c; + _picker.Open(new Vector2(p.X, p.Y + h), LootPatternText.Labels, (int)shown, k => + { + LootTextMode next = LootPatternText.Modes[k]; + LootTextMode was = target.Mode ?? LootTextMode.Contains; + if (next == was || dto.Lines.Count == 0) return; + // Into regex: the pattern as it is. Out of regex: its words when it has a plain shape. + string words = next == LootTextMode.Regex ? dto.Lines[0] + : was == LootTextMode.Regex ? (LootPatternText.Parse(dto.Lines[0]) is var (m2, w2) && m2 != LootTextMode.Regex ? w2 : "") + : target.Words; + dto.Lines[0] = LootPatternText.Build(next, words); + target.Mode = next; + target.Words = words; + target.ParsedFrom = dto.Lines[0]; + target.Shown = null; // the box shows the new words + }, Math.Max(150, mw)); + } + SafeImGui.SetItemTooltip("How the text is matched (case doesn't matter). Pick \"regex\" to type a pattern yourself."); + + if (Field(id, buf, buf.Words, new Vector2(p.X + mw, p.Y), w - mw, LootPatternText.Hint(shown), ro, out string typed, h)) + { + buf.Words = typed; + c.Lines[0] = LootPatternText.Build(shown, typed); + buf.ParsedFrom = c.Lines[0]; + } + if (shown != LootTextMode.Regex) + SafeImGui.SetItemTooltip(c.Lines[0].Length > 0 + ? "Written to the profile as: " + c.Lines[0] + (shown is LootTextMode.Contains or LootTextMode.NotContains ? "\nSeveral words: separate them with commas (either of them)." : "") + : (shown is LootTextMode.Contains or LootTextMode.NotContains ? "Type a word. Several: separate them with commas (either of them)." : "Type the text.")); + } + /// A whole number: "45", "45.0" (a buffed-long value written as a double). private static bool TryWhole(string? raw, out int value) { diff --git a/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs b/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs index 70cd5d8..fc3262f 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs @@ -2,8 +2,9 @@ // RynthCore.Engine - ImGui/Panels/LuaFace.cs // ImGui face of the Lua panel. Two layouts, picked by the payload: // -// RynthLua v2 (ScriptInfos present), tabs "Scripts" | "Editor", and on the -// right "N running · RynthAi: loaded / not loaded": +// RynthLua v2 (ScriptInfos present), tabs "Scripts" | "Editor", "Live reload: +// on/off" (a RynthLua with live reload; /lua livereload), and on the right +// "N running · RynthAi: loaded / not loaded": // Scripts one row per script: running dot, name, description, autostart // (Off / global / this character), Run|Stop, Restart. Click a row // to select it; below, the selected script's state, "Open in @@ -161,13 +162,37 @@ internal sealed class LuaFace : IImGuiPanel if (Button("##tab_editor", EditorTab, new Vector2(p.X + sw + 2, p.Y), new Vector2(ew, h), _editorTab ? Teal : Text, _editorTab ? Selected : BtnFill)) _editorTab = true; + // RynthLua's live reload (a RynthLua that has it says so in the payload): /lua livereload on|off. + float lrW = 0; + if (LuaLiveReload.Label(d.LiveReload) is { } lrLabel) + { + bool on = d.LiveReload == true; + string caption = PhosphorIcons.ArrowsClockwise + " " + lrLabel; + lrW = ButtonWidth(caption) + 4; + if (Button("##lua_live", caption, new Vector2(p.X + sw + ew + 8, p.Y), new Vector2(lrW, h), on ? Teal : Mute, on ? Selected : BtnFill)) + LuaCommands.Chat(LuaLiveReload.ClickArgs(on)); + SafeImGui.SetItemTooltip(LuaLiveReload.Tip(on)); + lrW += 6; + } + // Stop every running script (/lua stop all), while two or more run. + if (d.RunningCount > 1 && d.ScriptInfos is { } running) + { + const string StopAll = PhosphorIcons.Stop + " Stop all"; + float saW = ButtonWidth(StopAll) + 4; + if (Button("##lua_stopall", StopAll, new Vector2(p.X + sw + ew + 8 + lrW, p.Y), new Vector2(saW, h), Text, StopBg)) + foreach (LuaScriptInfo si in running) + if (si.Running) LuaCommands.Send("stopScript", si.Name); + SafeImGui.SetItemTooltip("Stop every running script. Also: /lua stop all"); + lrW += saW + 6; + } + var dl = ImGuiNET.ImGui.GetWindowDrawList(); bool ai = d.RynthAi == true; string run = d.RunningCount == 1 ? "1 running" : $"{d.RunningCount} running"; const string sep = " · "; string aiText = ai ? "RynthAi: loaded" : "RynthAi: not loaded"; float runW = ImGuiNET.ImGui.CalcTextSize(run).X, sepW = ImGuiNET.ImGui.CalcTextSize(sep).X, aiW = ImGuiNET.ImGui.CalcTextSize(aiText).X; - float left = p.X + sw + ew + 10, right = p.X + w; + float left = p.X + sw + ew + 10 + lrW, right = p.X + w; float x = Math.Max(left, right - runW - sepW - aiW); float ty = p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f; dl.PushClipRect(new Vector2(left, p.Y), new Vector2(right, p.Y + h), true); diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs index 0d0b09d..143b3f6 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs @@ -691,6 +691,20 @@ internal sealed partial class MetaFace { var dl = ImGuiNET.ImGui.GetWindowDrawList(); bool canRevert = _editOriginal != null && !MetaRuleEdit.SameContent(_editRule, _editOriginal); + string problem = SaveProblem(); + float problemX = p.X; + if (canRevert) problemX += BtnW(PhosphorIcons.ArrowCounterClockwise + " Revert", 60) + 6; + if (problem.Length > 0 && !_editConfirmDelete) + { + // The editor's status line: why the last change isn't saved (the full text on hover). + string del = PhosphorIcons.Trash + (_editIndex < 0 ? " Discard" : " Delete rule"); + float room = p.X + w - BtnW(del, 70) - 6 - problemX; + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + dl.AddText(new Vector2(problemX, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Red, Fit(problem, Math.Max(20, room))); + ImGuiNET.ImGui.PopFont(); + if (ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(problemX, p.Y), new Vector2(problemX + Math.Max(20, room), p.Y + h))) + ImGuiNET.ImGui.SetTooltip(problem); + } if (canRevert) { string label = PhosphorIcons.ArrowCounterClockwise + " Revert"; @@ -702,7 +716,7 @@ internal sealed partial class MetaFace } ImGuiNET.ImGui.SetItemTooltip("Undo every change since you opened this rule (and save that)"); } - else + else if (problem.Length == 0) { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); dl.AddText(new Vector2(p.X, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Faded(Mute), diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs index 41d3ce3..4f2024b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs @@ -207,15 +207,18 @@ internal sealed partial class MetaFace FilterRow(w); // A note over the list: the editor closed under a meta switch, or the meta can't do anything. - string note = string.Empty; - if (_listNote.Length > 0 && NowMs - _listNoteAt < 8000) note = _listNote; + // A change that wasn't saved comes first, in red, and stays until the next result (2026-11-01). + string note = SaveProblem(); + bool unsaved = note.Length > 0; + if (unsaved) { } + else if (_listNote.Length > 0 && NowMs - _listNoteAt < 8000) note = _listNote; else if (_data.Rules.Count > 0 && !HasRulesIn(_data.CurrentState)) note = $"The current state, {_data.CurrentState}, has no rules: the meta does nothing until something changes the state."; if (note.Length > 0) { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); - ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, unsaved ? Red : Amber); ImGuiNET.ImGui.TextUnformatted(note); ImGuiNET.ImGui.PopStyleColor(); ImGuiNET.ImGui.PopTextWrapPos(); diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs index 5791919..7a29131 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs @@ -102,8 +102,7 @@ internal sealed partial class MetaFace : IImGuiPanel // ── Saving ─────────────────────────────────────────────────────────── private readonly MetaAutosave _autosave = new(); private readonly MetaBackupPlan _backup = new(); - private long _saveSentAt = -1; // ms (TickCount64) of the last rule command, for "Saving..." - private long _saveSentVersion; // the snapshot version then + private readonly MetaSaveWatch _saveWatch = new(); // waits for RynthAi's answer to each change private static long NowMs => Environment.TickCount64; // ── Rule editor ────────────────────────────────────────────────────── @@ -145,6 +144,7 @@ internal sealed partial class MetaFace : IImGuiPanel UiSources.Meta.RequestRefresh(); CodeEditor.SetMetaVocabulary(MetaVocabulary.StructKeywords, MetaVocabulary.ConditionKeywords, MetaVocabulary.ActionKeywords); _backup.NewSession(); // a new editing session: the first save backs the file up again + _saveWatch.Reset(); } public void OnHidden() @@ -271,8 +271,7 @@ internal sealed partial class MetaFace : IImGuiPanel // Saving over another meta keeps that one's old copy as .bak. MetaCommands.Backup(target, MetaBackupPlan.BackupOf(target)); MetaCommands.Simple("save_file", path: target); - _saveSentAt = NowMs; - _saveSentVersion = _seenVersion; + _saveWatch.Sent(NowMs, SeenSaveSeq, MetaCommands.Undelivered); } _saveAs = false; } @@ -324,6 +323,7 @@ internal sealed partial class MetaFace : IImGuiPanel { float m = Math.Max(ImGuiNET.ImGui.CalcTextSize(SavedText).X, ImGuiNET.ImGui.CalcTextSize(SavingText).X); m = Math.Max(m, Math.Max(ImGuiNET.ImGui.CalcTextSize(EditingText).X, ImGuiNET.ImGui.CalcTextSize(NoFileText).X)); + m = Math.Max(m, ImGuiNET.ImGui.CalcTextSize(UnconfirmedText).X); if (editor) m = Math.Max(m, ImGuiNET.ImGui.CalcTextSize(DraftText).X); return m + 6; } @@ -339,10 +339,37 @@ internal sealed partial class MetaFace : IImGuiPanel return _editTyping ? (EditingText, Amber, "Saves when you leave the box (Enter, Tab or click elsewhere).") : (SavingText, Amber, "Saving in a moment..."); - if (_saveSentAt >= 0 && _seenVersion == _saveSentVersion && NowMs - _saveSentAt < 2500) - return (SavingText, Amber, "Saving " + file + "..."); + switch (_saveWatch.State(NowMs, _data.SaveResult, MetaCommands.Undelivered)) + { + case MetaSaveState.Saving: + return (SavingText, Amber, "Saving " + file + "..."); + case MetaSaveState.Failed: + case MetaSaveState.NotSent: + return (NoFileText, Red, SaveProblem()); + case MetaSaveState.Unconfirmed: + return (UnconfirmedText, Amber, SaveProblem()); + } string bak = System.IO.Path.GetFileName(MetaBackupPlan.BackupOf(MetaBackupPlan.WrittenFile(_data.CurrentMetaPath!))); - return (SavedText, Green, $"Every change saves to {file} on its own. The first change after opening this panel keeps the file as it was in {bak}."); + string last = _data.SaveResult is { Seq: > 0, Text.Length: > 0 } r ? $"\nLast: {r.Text}" : ""; + return (SavedText, Green, $"Every change saves to {file} on its own. The first change after opening this panel keeps the file as it was in {bak}.{last}"); + } + + private const string UnconfirmedText = PhosphorIcons.Warning + " Not confirmed"; + + /// The result seq the panel has seen (0: none, or a RynthAi without results). + private long SeenSaveSeq => _data.SaveResult?.Seq ?? 0; + + /// Why the last change isn't saved, for the status line and the indicator's tooltip; empty when it is. + private string SaveProblem() + { + if (string.IsNullOrEmpty(_data.CurrentMetaPath)) return string.Empty; // "Not saved" + its own hint + return _saveWatch.State(NowMs, _data.SaveResult, MetaCommands.Undelivered) switch + { + MetaSaveState.Failed => _data.SaveResult!.Text, + MetaSaveState.NotSent => "Not saved: the change never reached RynthAi (it isn't loaded, or is too old for this panel). Reload RynthAi and make the change again.", + MetaSaveState.Unconfirmed => "RynthAi hasn't confirmed the last change. If this stays, it may not have been saved: check the rule after reopening the meta.", + _ => string.Empty, + }; } /// The save status, right-aligned in (pos, width); hover for details. @@ -360,15 +387,14 @@ internal sealed partial class MetaFace : IImGuiPanel /// /// Every command that changes the meta's rules goes through here: before the first one of this - /// session the file is backed up, and the indicator shows "Saving..." until the next snapshot. - /// (RynthAi writes the file after each such command.) + /// session the file is backed up, and the indicator shows "Saving..." until RynthAi answers + /// (MetaSaveWatch; RynthAi writes the file after each such command and reports the result). /// private void SendEdit(MetaCmd cmd) { if (_backup.Before(_data.CurrentMetaPath) is { } b) MetaCommands.Backup(b.File, b.Backup); MetaCommands.Send(cmd); - _saveSentAt = NowMs; - _saveSentVersion = _seenVersion; + _saveWatch.Sent(NowMs, SeenSaveSeq, MetaCommands.Undelivered); } private void BeginSaveAs() diff --git a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs index bfc3b8d..3ef6080 100644 --- a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs @@ -6,7 +6,7 @@ // Recall / Clear / Save / Dungeon Patrol, the route editor (move / duplicate / // delete / set active / move here on the selection; nearest, reverse, snap to // path, point at selection, pause, simplify; recording and trail -> route), -// a chat waypoint, Save As, the nav file picker, the nav point reach +// a chat waypoint, Save As, the nav file picker (at the top), the nav point reach // (RynthAi's FollowNavMin, the same row as Settings > Navigation), and the // waypoint list (click selects, Ctrl/Shift-click multi-selects, double-click // sets active, right-click edits, X or Delete deletes, => marks the active one). @@ -56,6 +56,7 @@ internal sealed class NavFace : IImGuiPanel { PhosphorIcons.NavigationArrow + " Nearest", PhosphorIcons.ArrowsClockwise + " Reverse", PhosphorIcons.Path + " Snap to Path", PhosphorIcons.MapPin + " Point at Selected", PhosphorIcons.Hourglass + " Add Pause", PhosphorIcons.Scissors + " Simplify", + PhosphorIcons.ArrowCounterClockwise + " Restart", }; private static readonly string[] RowMenu = { "Set Active", "Move Here", "Move Up", "Move Down", "Duplicate", "Delete" }; @@ -110,6 +111,19 @@ internal sealed class NavFace : IImGuiPanel bool typing = false; NavPayload d = _data; bool navActive = d.MacroRunning && d.NavigationEnabled; + Vector2 p; + + // Nav file picker, first (2026-11-01, the owner: "move the nav file selection to the top") + if (_navFiles.Length > 0) + { + p = ImGuiNET.ImGui.GetCursorScreenPos(); + float lw = ImGuiNET.ImGui.CalcTextSize("Nav:").X + 6; + ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "Nav:"); + if (Button("##navfile", _fileLabel, new Vector2(p.X + lw, p.Y), new Vector2(w - lw, 22), Text, BtnFill, leftAlign: true)) + _picker.Open(new Vector2(p.X + lw, p.Y + 22), _navFiles, Array.IndexOf(_navFiles, _data.ActiveNavName), i => + NavCommands.Send(new NavCmd { Cmd = "loadNav", NavName = _navFiles[i] })); + NextLine(p, 26); + } // Active nav + status ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); @@ -118,7 +132,7 @@ internal sealed class NavFace : IImGuiPanel if (d.NavStatusLine.Length > 0) Label(d.NavStatusLine, d.NavIsStuck ? Amber : Green); // Start / Stop - Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + p = ImGuiNET.ImGui.GetCursorScreenPos(); if (Button("##startstop", navActive ? StopNav : StartNav, p, new Vector2(w, 28), Text, navActive ? StopBg : StartBg)) { if (navActive) @@ -258,18 +272,6 @@ internal sealed class NavFace : IImGuiPanel } NextLine(p, 26); - // Nav file picker - if (_navFiles.Length > 0) - { - p = ImGuiNET.ImGui.GetCursorScreenPos(); - float lw = ImGuiNET.ImGui.CalcTextSize("Nav:").X + 6; - ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, "Nav:"); - if (Button("##navfile", _fileLabel, new Vector2(p.X + lw, p.Y), new Vector2(w - lw, 22), Text, BtnFill, leftAlign: true)) - _picker.Open(new Vector2(p.X + lw, p.Y + 22), _navFiles, Array.IndexOf(_navFiles, _data.ActiveNavName), i => - NavCommands.Send(new NavCmd { Cmd = "loadNav", NavName = _navFiles[i] })); - NextLine(p, 26); - } - // Waypoints Separator(w); Label($"Waypoints ({_data.Points.Count})", Mute); @@ -441,6 +443,10 @@ internal sealed class NavFace : IImGuiPanel _picker.Open(at, NavCommands.SimplifyLabels, -1, i => NavCommands.Send(new NavCmd { Cmd = "simplifyRoute", Yards = NavCommands.SimplifyYards[i] }), width: 300); break; + case 6: + // Run the route again from its first point (a finished Once route too); answers in chat. + RynthAiCommands.ApplyRemoteCommand("sendchat", "/ra nav restart"); + break; } // Record | Route from Trail... @@ -456,7 +462,11 @@ internal sealed class NavFace : IImGuiPanel Vector2 tp = new(p.X + half + 4, p.Y); if (Button("##fromtrail", FromTrail, tp, new Vector2(half, 22), Text, BtnFill, enabled: _data.TrailPoints >= 2)) _picker.Open(new Vector2(tp.X, tp.Y + 22), NavCommands.TrailChoices, -1, i => - NavCommands.Send(new NavCmd { Cmd = "trailToRoute", Reverse = i == 1 }), width: 300); + { + // The last choice wipes the trail (/ra navtrail clear); the others make a route of it. + if (i == NavCommands.TrailClearChoice) RynthAiCommands.ApplyRemoteCommand("sendchat", "/ra navtrail clear"); + else NavCommands.Send(new NavCmd { Cmd = "trailToRoute", Reverse = i == 1 }); + }, width: 300); if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) SafeImGui.SetTooltip(_data.TrailPoints >= 2 ? $"Breadcrumb trail: {_data.TrailPoints} crumbs, {_data.TrailYards:0} yd.\nThe new route is unsaved; the loaded nav file is not changed." diff --git a/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs b/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs index 7d8e35e..ec45794 100644 --- a/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs +++ b/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs @@ -210,15 +210,31 @@ internal sealed unsafe class LogFace : IImGuiPanel } } -/// Tracker: the session-stat rows (TrackerSource) over an adjustable-opacity background. +/// +/// Tracker: the session-stat rows (TrackerSource) over an adjustable-opacity background, or text only +/// (TrackerSettings.TextOnly: bare, the rows shadowed, clicks pass through except over them). +/// internal sealed class TrackerFace : IImGuiPanel { private static readonly Vector4 TitleColor = RynthTheme.Vec(0xFFE6B450); private static readonly Vector4 LabelColor = RynthTheme.Vec(0xFF999999); private static readonly uint ResetBg = RynthTheme.Argb(0xFF1A2E40); private static uint ResetBorder => RynthTheme.AccentFill; + // Text only: no background behind it, so brighter than the framed look, each with a shadow. + private static readonly uint BareLabel = RynthTheme.Argb(0xFFCFCFCF); + private static readonly uint BareValue = RynthTheme.Argb(0xFFFFFFFF); + private static readonly uint BareShadow = RynthTheme.Argb(0xD0000000); private int _opacity; + // Text only: the mouse is over what the last frame drew, so the window takes input (to drag it, or + // for the frame button); elsewhere clicks reach the game. A press that began there keeps it. + private bool _hot, _pressHot; + + /// Text only is bare: docked, no frame, title, background or grip (popped out it is framed as usual). + public bool Bare => TrackerSettings.TextOnly; + + public bool ClickThrough => Bare && !_hot && !_pressHot; + public void OnShown() { UiSources.Tracker.Subscribe(); @@ -229,6 +245,90 @@ internal sealed class TrackerFace : IImGuiPanel public void OnHidden() => UiSources.Tracker.Unsubscribe(); public void Draw() + { + if (TrackerSettings.TextOnly && !ImGuiPanelHost.DrawingEmbedded && !ImGuiPopOuts.InPopOutFrame) + { + DrawTextOnly(); + return; + } + _hot = _pressHot = false; + DrawFramed(); + } + + /// + /// Text only: each row's label and value with a 1 px shadow, nothing behind them. The rows are a + /// drag handle; the button at the end of the first row (faint until the mouse is on the rows) + /// brings the frame back. + /// + private void DrawTextOnly() + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos(); + float width = Math.Max(60, ImGuiNET.ImGui.GetContentRegionAvail().X); + Vector2 mouse = ImGuiNET.ImGui.GetIO().MousePos; + bool wasHot = _hot; + + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + float rowH = ImGuiNET.ImGui.GetTextLineHeight() + 1; + float buttonW = rowH + 4; + TrackerSnapshot? snap = UiSources.Tracker.Current?.Value; + string[]? values = snap?.Values; + string[] labels = snap?.Labels ?? TrackerSnapshot.DefaultLabels; + ImFontPtr labelFont = ImGuiNET.ImGui.GetFont(); + float labelSize = ImGuiNET.ImGui.GetFontSize(); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Mono9)); + ImFontPtr valueFont = ImGuiNET.ImGui.GetFont(); + float valueSize = ImGuiNET.ImGui.GetFontSize(); + float y = origin.Y; + for (int i = 0; i < labels.Length; i++) + { + // The first row stops short of the frame button. + float right = origin.X + width - (i == 0 ? buttonW + 2 : 0); + Shadowed(dl, labelFont, labelSize, new Vector2(origin.X, y), BareLabel, labels[i]); + string value = values != null && i < values.Length ? values[i] : "—"; + float w = ImGuiNET.ImGui.CalcTextSize(value).X; + Shadowed(dl, valueFont, valueSize, new Vector2(Math.Max(origin.X, right - w), y), BareValue, value); + y += rowH; + } + ImGuiNET.ImGui.PopFont(); + float height = Math.Max(rowH, y - origin.Y); + + // The rows: a drag handle (the window has no title bar to hold). + ImGuiNET.ImGui.SetCursorScreenPos(origin); + ImGuiNET.ImGui.InvisibleButton("##tracker_textonly_drag", new Vector2(Math.Max(1, width - buttonW - 2), height)); + ImGuiPanelHost.DragWindowWithLastItem(); + if (ImGuiNET.ImGui.IsItemHovered() && !ImGuiNET.ImGui.IsItemActive()) + ImGuiNET.ImGui.SetTooltip("Drag to move the Tracker."); + + // Frame button: faint until the mouse is on the rows. + Vector2 bp = new(origin.X + width - buttonW, origin.Y); + ImGuiNET.ImGui.SetCursorScreenPos(bp); + float alpha = wasHot ? 1f : 0.35f; + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.Alpha, alpha); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(1, 0)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, ResetBg); + if (ImGuiNET.ImGui.Button(PhosphorIcons.SquaresFour + "##tracker_frame", new Vector2(buttonW, rowH))) + TrackerSettings.SetTextOnly(false); + ImGuiNET.ImGui.SetItemTooltip("Show the Tracker's frame and background again."); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.PopStyleVar(2); + ImGuiNET.ImGui.PopFont(); + + // Hot for the next frame: the mouse over the rows or the button. + bool over = mouse.X >= origin.X && mouse.X <= origin.X + width && mouse.Y >= origin.Y && mouse.Y <= origin.Y + height; + _hot = over; + bool down = ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left); + if (!down) _pressHot = false; + else if (over && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) _pressHot = true; + } + + private static void Shadowed(ImDrawListPtr dl, ImFontPtr font, float size, Vector2 p, uint color, string text) + { + dl.AddText(font, size, p + new Vector2(1, 1), BareShadow, text); + dl.AddText(font, size, p, color, text); + } + + private void DrawFramed() { var dl = ImGuiNET.ImGui.GetWindowDrawList(); // Background behind the content only (like the Avalonia StackPanel), so @@ -240,11 +340,12 @@ internal sealed class TrackerFace : IImGuiPanel ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - // Title row: [Tracker] [===slider===] [reset] + // Title row: [Tracker] [===slider===] [text only] [reset] ImGuiNET.ImGui.TextColored(TitleColor, "Tracker"); ImGuiNET.ImGui.SameLine(); float resetW = ImGuiNET.ImGui.CalcTextSize(PhosphorIcons.ArrowCounterClockwise).X + 8; - ImGuiNET.ImGui.SetNextItemWidth(Math.Max(10, ImGuiNET.ImGui.GetContentRegionAvail().X - resetW - 4)); + float textOnlyW = ImGuiNET.ImGui.CalcTextSize(PhosphorIcons.TextAa).X + 8; + ImGuiNET.ImGui.SetNextItemWidth(Math.Max(10, ImGuiNET.ImGui.GetContentRegionAvail().X - resetW - textOnlyW - 8)); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(2, 0)); if (ImGuiNET.ImGui.SliderInt("##opacity", ref _opacity, 0, 100, "")) TrackerSettings.SetBgAlpha((byte)Math.Round(_opacity * 2.55), save: false); @@ -256,6 +357,15 @@ internal sealed class TrackerFace : IImGuiPanel ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, ResetBorder); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, 1)); + bool canBare = !ImGuiPanelHost.DrawingEmbedded && !ImGuiPopOuts.InPopOutFrame; + ImGuiNET.ImGui.BeginDisabled(!canBare); + if (ImGuiNET.ImGui.Button(PhosphorIcons.TextAa + "##textonly")) + TrackerSettings.SetTextOnly(true); + ImGuiNET.ImGui.EndDisabled(); + ImGuiNET.ImGui.SetItemTooltip(canBare + ? "Text only: hide the frame and background, just the numbers (clicks pass through to the game).\nThe button at the end of its first row brings the frame back." + : "Text only works while the Tracker is docked (not popped out)."); + ImGuiNET.ImGui.SameLine(); if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + "##reset")) UiSources.Tracker.RequestReset(); ImGuiNET.ImGui.SetItemTooltip("Reset the session stats"); diff --git a/src/RynthCore.Engine/ImGui/Panels/PluginWindowFace.cs b/src/RynthCore.Engine/ImGui/Panels/PluginWindowFace.cs index 6bab36d..5862201 100644 --- a/src/RynthCore.Engine/ImGui/Panels/PluginWindowFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/PluginWindowFace.cs @@ -15,6 +15,10 @@ // (wantHeight) as its minimum and is fitted to it whenever it changes and the // mouse is up (a frameless window's empty rows would still catch clicks meant // for the game); a text size change scales its width along with its fonts. +// A "scale": "draw" window set bigger than normal (PanelDrawScale) gets the +// fonts baked nearest above its size while the plugin draws (2026-11-01: from +// the normal bake, stretched, its text blurred); the font pushed for its menus +// and tooltips stays at the panel's text size. // docs/PLUGIN_WINDOWS.md. AC's render thread. // ============================================================================ @@ -39,11 +43,12 @@ internal sealed class PluginWindowFace : IImGuiPanel // "fitHeight" (v90): the content height the plugin asked for (logical units; 0 = not known // yet), and the text size factor and width (logical) the window was last fitted at. - private readonly bool _fitHeight; + private readonly bool _fitHeight, _drawScale; private readonly float _minWidth; private float _contentHeight, _fitK, _fitWidth; - public PluginWindowFace(string plugin, string surface, string title, bool fitHeight = false, float minWidth = 0f) + public PluginWindowFace(string plugin, string surface, string title, bool fitHeight = false, float minWidth = 0f, + bool drawScale = false) { _plugin = plugin; _title = title; @@ -51,6 +56,15 @@ internal sealed class PluginWindowFace : IImGuiPanel _idScope = "##pw_" + surface; _fitHeight = fitHeight; _minWidth = minWidth; + _drawScale = drawScale; + } + + /// The font step the plugin draws with: a draw-scale window's own size's (baked), else the text size's. + private int DrawFontStep(int textStep) + { + if (!_drawScale) return textStep; + int pct = PanelDrawScale.Get(_title); + return pct > 0 ? ImGuiFonts.BakedStepNear(PanelDrawScale.FontStep(pct, EngineFrameController.FontScale)) : textStep; } /// A fitHeight window's minimum: its minimum width at its text size, and the content's height. @@ -78,10 +92,13 @@ internal sealed class PluginWindowFace : IImGuiPanel guarded = guarded && ImGuiStackGuard.AtWindowBase(bodyBase); // drawn anywhere else: as before ImGuiNET.ImGui.PushID(_idScope); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + int textStep = ImGuiFonts.CurrentStep; + ImGuiFonts.CurrentStep = DrawFontStep(textStep); ImGuiStackGuard.Mark given = guarded ? ImGuiStackGuard.Take() : default; try { result = PluginManager.RenderEmbed(_plugin, _surface, avail, out want); } finally { + ImGuiFonts.CurrentStep = textStep; ImGuiStackGuard.Mark after = default; StackCheck check = guarded ? ImGuiStackGuard.Check(given, out after) : StackCheck.Balanced; if (check == StackCheck.Balanced) diff --git a/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs b/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs index f719495..e71e44d 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs @@ -14,6 +14,9 @@ // legend. Your own arrow, the compass letters and the coordinates have sizes too. // Outdoors the World Map's picture can be drawn behind it (RadarSettingsStore.ShowWorldMap; the // tiles come from WorldMapTiles through WorldMapTileDrawer, the same code as the World Map). +// The object selected in game is highlighted (RadarSettingsStore.HighlightSelected, RadarSelection): +// a ring in its own colour round its marker and the hover label beside it, or an arrow on the +// edge when it is off the picture. // // Data: UiSources.Radar (RadarView, lookups precomputed). World geometry is // drawn without anti-aliasing (crisp tiling like the Avalonia face's aliased @@ -72,6 +75,8 @@ internal sealed class RadarFace : IImGuiPanel // The round radar (RadarSettingsStore.RoundRadar): this frame's circle, read by the drawing helpers. private static bool _round; private static RoundMask _mask; + // The selected object's marker this frame (RadarSelection.Highlighted), or null; drawn over everything. + private static RadarMarker? _sel; /// Markers move: popped out, redraw smoothly even when idle. public int PopOutIdleHz => 20; @@ -167,6 +172,11 @@ internal sealed class RadarFace : IImGuiPanel dl.AddLine(new Vector2(worldMin.X, centre.Y), new Vector2(worldMax.X, centre.Y), Crosshair); } + // The game's current selection (the global AC's SetSelectedObject writes; one read a frame). + uint selectedId = view != null && RadarSettingsStore.HighlightSelected && Compatibility.SelectedTargetHooks.IsInstalled + ? Compatibility.SelectedTargetHooks.ReadCurrentSelectedId() : 0; + _sel = view != null ? RadarSelection.Highlighted(RadarSettingsStore.HighlightSelected, view.Live.Markers, selectedId) : null; + if (view != null) { ImDrawListFlags saved = dl.Flags; @@ -175,6 +185,7 @@ internal sealed class RadarFace : IImGuiPanel DrawWorld(dl, view, centre, worldMin, worldMax); dl.PopClipRect(); dl.Flags = saved; + DrawSelected(dl, view, centre, worldMin, worldMax, origin, panelMax); DrawOutlinedText(dl, ImGuiFonts.Get(UiFont.UiBold11), view.CoordText, new Vector2((origin.X + panelMax.X) * 0.5f, panelMax.Y), CoordText, alignBottom: true, @@ -306,7 +317,7 @@ internal sealed class RadarFace : IImGuiPanel { foreach (RadarMarker m in live.Markers) { - if (!RadarSettingsStore.ShowKind(m.Kind)) continue; + if (m == _sel || !RadarSettingsStore.ShowKind(m.Kind)) continue; // the selected one: DrawSelected if ((pass == 1) != (RadarKind.IsCreature(m.Kind) || m.Kind is RadarKind.Portal or RadarKind.Door)) continue; Vector2 pp = proj.P(m.X, m.Y); if (_round ? !_mask.Contains(pp) : (pp.X < clipMin.X || pp.X > clipMax.X || pp.Y < clipMin.Y || pp.Y > clipMax.Y)) continue; @@ -323,6 +334,7 @@ internal sealed class RadarFace : IImGuiPanel foreach (RadarMarker m in live.Markers) { if (!markers.NameShown(m.Kind) || !RadarSettingsStore.ShowKind(m.Kind)) continue; + if (m == _sel && RadarSettingsStore.ShowSelectedLabel) continue; // its label has the name Vector2 pp = proj.P(m.X, m.Y); if (pp.X < clipMin.X - 8 || pp.X > clipMax.X || pp.Y < clipMin.Y - 8 || pp.Y > clipMax.Y + 8) continue; if (_round && !_mask.Contains(pp)) continue; @@ -338,6 +350,57 @@ internal sealed class RadarFace : IImGuiPanel dl.AddLine(centre, tip, PlayerCol, 2); } + // ── The selected object ──────────────────────────────────────────────── + // A ring in the selection colour round its marker (the marker drawn over everything, even when its + // kind's box is off), and the hover label beside it; off the picture, an arrow on the edge pointing + // to it with the label next to the arrow. Drawn anti-aliased, after the world. + + private const float ArrowInset = 3f, ArrowLength = 9f, ArrowHalfWidth = 5f; + private readonly TipCache _selTip = new(); + + private void DrawSelected(ImDrawListPtr dl, RadarView view, Vector2 centre, Vector2 clipMin, Vector2 clipMax, + Vector2 panelMin, Vector2 panelMax) + { + RadarMarker? sel = _sel; + if (sel == null) return; + var proj = new Projection(centre, view.Live.Player, RadarSettingsStore.RotateWithPlayer, MathF.Max(0.5f, RadarSettingsStore.Zoom)); + Vector2 pp = proj.P(sel.X, sel.Y); + uint col = RynthTheme.Argb(RadarSettingsStore.SelectedColor); + Vector2 anchor; + float gap; + dl.PushClipRect(clipMin, clipMax, true); + if (RadarSelection.EdgeArrow(centre, pp, clipMin, clipMax, _round ? _mask : null, ArrowInset, out Vector2 tip, out Vector2 dir)) + { + RadarSelection.ArrowCorners(tip, dir, ArrowLength, ArrowHalfWidth, out Vector2 a, out Vector2 b, out Vector2 c); + dl.AddTriangleFilled(a, b, c, col); + dl.AddTriangle(a, b, c, Outline, 1.5f); + anchor = tip - dir * (ArrowLength * 0.5f); + gap = ArrowLength; + } + else + { + float size = RadarSettingsStore.Markers.SizeOf(sel.Kind); + float r = MathF.Max(6.5f, RadarMarkerStyle.Radius(sel.Kind) * size + 3f); + dl.AddCircle(pp, r, Outline, 20, 3.5f); + RadarMarkerStyle.Draw(dl, sel.Kind, pp, KindCols[sel.Kind], size); + dl.AddCircle(pp, r, col, 20, 2f); + anchor = pp; + gap = r + 4f; + } + dl.PopClipRect(); + if (!RadarSettingsStore.ShowSelectedLabel) return; + + // The hover label, as a tooltip-styled box kept inside the panel. + string text = _selTip.Get(view, sel); + var style = ImGuiNET.ImGui.GetStyle(); + Vector2 pad = new Vector2(6f, 4f); + Vector2 box = ImGuiNET.ImGui.CalcTextSize(text) + pad * 2f; + Vector2 at = RadarSelection.LabelPos(anchor, gap, box, panelMin, panelMax); + dl.AddRectFilled(at, at + box, ImGuiNET.ImGui.GetColorU32(ImGuiCol.PopupBg), style.PopupRounding); + dl.AddRect(at, at + box, col, style.PopupRounding, ImDrawFlags.None, 1f); + dl.AddText(at + pad, ImGuiNET.ImGui.GetColorU32(ImGuiCol.Text), text); + } + // ── World map backdrop ───────────────────────────────────────────────── // The radar's world coordinates are yards from the world's south-west corner; the World Map's cells // are 24 yards, so cell = yards / 24 on both axes, and the radar's zoom (px per yard) is 24x that @@ -475,11 +538,7 @@ internal sealed class RadarFace : IImGuiPanel private Vector2 _pressPos; private float _pressTravel; - private byte _tipKind = byte.MaxValue; - private string? _tipLabel; - private int _tipDistance = int.MinValue; - private int _tipPct = -1; - private string _tipText = ""; + private readonly TipCache _hoverTip = new(); private void MarkerInput(ImDrawListPtr dl, RadarView view, Vector2 centre, Vector2 clipMin, Vector2 clipMax, bool clicked) { @@ -517,8 +576,9 @@ internal sealed class RadarFace : IImGuiPanel dl.PushClipRect(clipMin, clipMax, true); dl.AddCircle(hitPos, 6.5f, CoordText, 16, 1.5f); dl.PopClipRect(); + if (hit == _sel && RadarSettingsStore.ShowSelectedLabel) return; // its label is already showing ImGuiNET.ImGui.BeginTooltip(); - ImGuiNET.ImGui.TextUnformatted(TipText(view, hit)); + ImGuiNET.ImGui.TextUnformatted(_hoverTip.Get(view, hit)); ImGuiNET.ImGui.EndTooltip(); } @@ -621,34 +681,44 @@ internal sealed class RadarFace : IImGuiPanel } /// - /// "Name\n12 yd" for the hovered marker, plus " 75%" when the marker has an id and - /// the engine has a health reading for it (MonsterHudData: one locked lookup, hover - /// only). Rebuilt only when the marker, whole yards or whole percent change. + /// "Name\n12 yd" for the hovered (or selected) marker, plus " 75%" when the marker has an id and + /// the engine has a health reading for it (MonsterHudData: one locked lookup, hover and the + /// selected marker only). Rebuilt only when the marker, whole yards or whole percent change; one + /// cache for the hover tooltip, one for the selected object's label, so neither rebuilds the other's. /// - private string TipText(RadarView view, RadarMarker m) + private sealed class TipCache { - RadarPlayer p = view.Live.Player; - float dx = m.X - p.WorldX, dy = m.Y - p.WorldY, dz = m.Z - p.Z; - int d = (int)MathF.Round(MathF.Sqrt(dx * dx + dy * dy + dz * dz)); - int pct = -1; - if (m.Id != 0 && RadarKind.IsCreature(m.Kind) && Hud.MonsterHudData.TryGetHealth(m.Id, out Hud.HealthObservation h)) - pct = (int)MathF.Round(h.Ratio * 100f); - // Markers are rebuilt on every radar poll: key on what the text shows, not the instance. - if (m.Kind == _tipKind && d == _tipDistance && pct == _tipPct - && string.Equals(m.Label, _tipLabel, StringComparison.Ordinal)) + private byte _tipKind = byte.MaxValue; + private string? _tipLabel; + private int _tipDistance = int.MinValue; + private int _tipPct = -1; + private string _tipText = ""; + + public string Get(RadarView view, RadarMarker m) + { + RadarPlayer p = view.Live.Player; + float dx = m.X - p.WorldX, dy = m.Y - p.WorldY, dz = m.Z - p.Z; + int d = (int)MathF.Round(MathF.Sqrt(dx * dx + dy * dy + dz * dz)); + int pct = -1; + if (m.Id != 0 && RadarKind.IsCreature(m.Kind) && Hud.MonsterHudData.TryGetHealth(m.Id, out Hud.HealthObservation h)) + pct = (int)MathF.Round(h.Ratio * 100f); + // Markers are rebuilt on every radar poll: key on what the text shows, not the instance. + if (m.Kind == _tipKind && d == _tipDistance && pct == _tipPct + && string.Equals(m.Label, _tipLabel, StringComparison.Ordinal)) + return _tipText; + _tipKind = m.Kind; + _tipLabel = m.Label; + _tipDistance = d; + _tipPct = pct; + // A label is the object's name; the kind always follows it, so a dot says which show box + // in the settings hides it (a fellow is not a "Player", your kill's corpse not a "Corpse"). + string name = string.IsNullOrEmpty(m.Label) ? RadarKind.Name(m.Kind) + : m.Label + " (" + RadarKind.Name(m.Kind) + ")"; + var inv = System.Globalization.CultureInfo.InvariantCulture; + _tipText = name + "\n" + d.ToString(inv) + " yd" + + (pct >= 0 ? " " + pct.ToString(inv) + "%" : ""); return _tipText; - _tipKind = m.Kind; - _tipLabel = m.Label; - _tipDistance = d; - _tipPct = pct; - // A label is the object's name; the kind always follows it, so a dot says which show box - // in the settings hides it (a fellow is not a "Player", your kill's corpse not a "Corpse"). - string name = string.IsNullOrEmpty(m.Label) ? RadarKind.Name(m.Kind) - : m.Label + " (" + RadarKind.Name(m.Kind) + ")"; - var inv = System.Globalization.CultureInfo.InvariantCulture; - _tipText = name + "\n" + d.ToString(inv) + " yd" - + (pct >= 0 ? " " + pct.ToString(inv) + "%" : ""); - return _tipText; + } } // ── Compass and text ─────────────────────────────────────────────────── @@ -763,6 +833,26 @@ internal sealed class RadarFace : IImGuiPanel changed |= Check("Click a dot to select it", ref RadarSettingsStore.ClickToSelect); if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip("Left-click a dot to select that object in game. Hover a dot for its name and distance."); + changed |= Check("Highlight the selected object", ref RadarSettingsStore.HighlightSelected); + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip("Whatever you have selected in game (a monster, NPC, player, portal, door, corpse or item on the ground)\ngets a ring in this colour round its dot, even when its kind's box is off.\nOff the radar's picture, an arrow on the edge points the way to it."); + ImGuiNET.ImGui.SameLine(); + Vector4 selCol = RynthTheme.Vec(RadarSettingsStore.SelectedColor); + if (ImGuiNET.ImGui.ColorEdit4("##selcol", ref selCol, PickFlags)) + { + RadarSettingsStore.SelectedColor = ToArgb(selCol); + _colorDirty = true; + } + if (ImGuiNET.ImGui.IsItemHovered() && !ImGuiNET.ImGui.IsItemActive()) + ImGuiNET.ImGui.SetTooltip("The selection ring's colour (click to change it)."); + if (RadarSettingsStore.HighlightSelected) + { + ImGuiNET.ImGui.Indent(); + changed |= Check("Show its label", ref RadarSettingsStore.ShowSelectedLabel); + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip("The hover label (name, distance, health) stays beside the selected object while it is selected."); + ImGuiNET.ImGui.Unindent(); + } changed |= Slider("Opacity", ref RadarSettingsStore.Opacity, 0.05f, 1.0f, "%.2f"); changed |= Slider("Zoom", ref RadarSettingsStore.Zoom, 0.5f, 6.0f, "%.1f"); changed |= Check("World map behind the radar (outdoors)", ref RadarSettingsStore.ShowWorldMap); @@ -865,8 +955,6 @@ internal sealed class RadarFace : IImGuiPanel float xName = 232 * scale, xSize = 268 * scale, xText = 350 * scale; MarkerStyleSettings markers = RadarSettingsStore.Markers; MarkerStyleEditor.HeaderRow(xName, xSize, xText); - const ImGuiColorEditFlags pickFlags = ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel - | ImGuiColorEditFlags.AlphaBar | ImGuiColorEditFlags.AlphaPreviewHalf; ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 3)); foreach (var (kind, label) in KindRowsOrder) { @@ -893,7 +981,7 @@ internal sealed class RadarFace : IImGuiPanel if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(KindTips[kind]); ImGuiNET.ImGui.SameLine(190 * scale); Vector4 v = RynthTheme.Vec(RadarSettingsStore.KindColors[kind]); - if (ImGuiNET.ImGui.ColorEdit4("##col", ref v, pickFlags)) + if (ImGuiNET.ImGui.ColorEdit4("##col", ref v, PickFlags)) { RadarSettingsStore.KindColors[kind] = ToArgb(v); _colorDirty = true; @@ -922,7 +1010,7 @@ internal sealed class RadarFace : IImGuiPanel RadarSettingsStore.ResetKindColors(); changed = true; } - if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip("Every kind back to its default colour (show boxes stay as they are)."); + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip("Every kind, and the selection ring, back to its default colour (show boxes stay as they are)."); ImGuiNET.ImGui.SameLine(); if (ImGuiNET.ImGui.SmallButton("Reset sizes and names")) { @@ -935,6 +1023,10 @@ internal sealed class RadarFace : IImGuiPanel private static bool _colorDirty; + // The colour swatches: click to pick, alpha included. + private const ImGuiColorEditFlags PickFlags = ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel + | ImGuiColorEditFlags.AlphaBar | ImGuiColorEditFlags.AlphaPreviewHalf; + private static uint ToArgb(Vector4 v) { static uint B(float f) => (uint)Math.Clamp((int)MathF.Round(f * 255f), 0, 255); diff --git a/src/RynthCore.Engine/ImGui/Panels/RadarSelection.cs b/src/RynthCore.Engine/ImGui/Panels/RadarSelection.cs new file mode 100644 index 0000000..abb1d24 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/RadarSelection.cs @@ -0,0 +1,116 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/RadarSelection.cs +// The object selected in game, highlighted on the radar (2026-10-31, a player's +// request: "Can the hover icon stay over whichever mob/door/etc. you have +// selected?"). RadarFace reads AC's current selection each frame (the global the +// SetSelectedObject hook reads, SelectedTargetHooks.ReadCurrentSelectedId: no new +// hook) and draws a ring in its own colour round that object's marker, with the +// hover label (name, distance, health) beside it. Off the radar's picture, a small +// arrow on the edge points the way to it. +// +// The rules, pure (no ImGui, no AC), so tools\RadarSettingsTests links this file: +// - which marker is the selected one: the marker with the selected object's id; +// none when nothing is selected or the marker has no id (RynthAi builds before +// 2026-10-01 send none); +// - it clears when the selection clears, or the object is no longer one of the +// radar's markers (gone, out of the client's view, an item in a pack); +// - the selected object is shown even when its kind's show box is off (items on +// the ground start hidden, and the player picked this one); +// - where the edge arrow goes, and where the label sits. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Numerics; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal static class RadarSelection +{ + /// + /// The marker of the selected object, or null: nothing selected (id 0), the object isn't one of + /// the markers, or the markers carry no ids. A kind this engine doesn't know (a newer RynthAi's) is + /// never highlighted: it has no shape or colour here. A List, not an interface, so the loop allocates nothing. + /// + public static RadarMarker? Find(List? markers, uint selectedId) + { + if (selectedId == 0 || markers == null) return null; + foreach (RadarMarker m in markers) + if (m.Id == selectedId) + return m.Kind < RadarKind.Count ? m : null; + return null; + } + + /// Whether a marker is highlighted this frame: the setting is on and it is the selected object's. + public static RadarMarker? Highlighted(bool settingOn, List? markers, uint selectedId) => + settingOn ? Find(markers, selectedId) : null; + + /// + /// The edge arrow toward a marker that is off the radar's picture. is the + /// marker's screen point; the picture is the box .., or the + /// circle on the round radar. False when the marker is on the picture (it is + /// drawn where it is) or is at the centre. Otherwise is the arrow's point, + /// px inside the edge on the line from to the marker, + /// and the unit direction it points. + /// + public static bool EdgeArrow(Vector2 centre, Vector2 target, Vector2 min, Vector2 max, RoundMask? round, float inset, + out Vector2 tip, out Vector2 dir) + { + tip = default; + dir = default; + if (round is RoundMask circle) + { + if (circle.Contains(target)) return false; + } + else if (target.X >= min.X && target.X <= max.X && target.Y >= min.Y && target.Y <= max.Y) return false; + + Vector2 d = target - centre; + float len = d.Length(); + if (!(len > 1e-4f) || !float.IsFinite(len)) return false; + dir = d / len; + float t; + if (round is RoundMask c) + t = MathF.Max(0f, c.Radius - inset); + else + { + // Onto the box: the nearer of the two sides the ray meets. + float hx = MathF.Max(0f, MathF.Min(centre.X - min.X, max.X - centre.X) - inset); + float hy = MathF.Max(0f, MathF.Min(centre.Y - min.Y, max.Y - centre.Y) - inset); + float tx = MathF.Abs(dir.X) > 1e-6f ? hx / MathF.Abs(dir.X) : float.MaxValue; + float ty = MathF.Abs(dir.Y) > 1e-6f ? hy / MathF.Abs(dir.Y) : float.MaxValue; + t = MathF.Min(tx, ty); + } + tip = centre + dir * t; + return true; + } + + /// + /// The edge arrow's three corners: the point at , the base + /// px back toward the centre and px to each side. + /// + public static void ArrowCorners(Vector2 tip, Vector2 dir, float length, float halfWidth, + out Vector2 a, out Vector2 b, out Vector2 c) + { + var side = new Vector2(-dir.Y, dir.X); + Vector2 back = tip - dir * length; + a = tip; + b = back + side * halfWidth; + c = back - side * halfWidth; + } + + /// + /// Where the label's box () goes: to the right of a marker at + /// , px clear of it, vertically centred; on the left when + /// it would run past ; then kept inside the bounds as far as it fits. + /// + public static Vector2 LabelPos(Vector2 anchor, float gap, Vector2 size, Vector2 boundsMin, Vector2 boundsMax) + { + float x = anchor.X + gap; + if (x + size.X > boundsMax.X) x = anchor.X - gap - size.X; + float y = anchor.Y - size.Y * 0.5f; + x = MathF.Max(boundsMin.X, MathF.Min(x, boundsMax.X - size.X)); + y = MathF.Max(boundsMin.Y, MathF.Min(y, boundsMax.Y - size.Y)); + return new Vector2(x, y); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs index 0f426c2..356ef0d 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs @@ -562,6 +562,15 @@ internal sealed class RynthNavFace : IImGuiPanel SectionLabel("WHERE YOUR RECALLS LAND"); foreach (string line in st.MineLines) Wrapped(line, Text, iw); } + // Lifestone Recall's landing, learned from the lifestone selected or stood at (/rnav tie lifestone). + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + const string LsLabel = PhosphorIcons.MapPin + " My lifestone is the one selected"; + if (Button("##rc_tiels", LsLabel, p, new Vector2(Math.Min(iw, ButtonWidth(LsLabel) + 8), 22), Text, BtnFill)) + RynthNavCommands.Command("tie lifestone"); + ImGuiNET.ImGui.SetItemTooltip("Select the lifestone you are tied to (or stand at it), then click: routes can use\nLifestone Recall from then on, without casting it once first. Also: /rnav tie lifestone"); + NextLine(p, 26); + } } else Wrapped("Update RynthNav (0.6.1) to see your portal ties here and answer \"which tie was it?\" with a button.", Mute, iw); @@ -858,6 +867,19 @@ internal sealed class RynthNavFace : IImGuiPanel ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); Label(view.Summary.Length > 0 ? view.Summary : RynthNavAtlas.Status.Length > 0 ? RynthNavAtlas.Status : "Loading…", Mute); ImGuiNET.ImGui.PopFont(); + // Recent: forget them (/rnav recent clear). + if (_mode == AtlasMode.Recent && view.Rows.Length > 0) + { + Vector2 cp = ImGuiNET.ImGui.GetCursorScreenPos(); + const string ClearLabel = PhosphorIcons.Eraser + " Forget recent places"; + if (Button("##atl_recent_clear", ClearLabel, cp, new Vector2(ButtonWidth(ClearLabel) + 8, 22), Text, BtnFill)) + { + RynthNavCommands.Command("recent clear"); + PushQuery(); + } + ImGuiNET.ImGui.SetItemTooltip("Empty the Recent list (favorites stay). Also: /rnav recent clear"); + NextLine(cp, 26); + } // List float listH = Math.Max(60, origin.Y + size.Y - 6 - ImGuiNET.ImGui.GetCursorScreenPos().Y - DetailH - 4); diff --git a/src/RynthCore.Engine/ImGui/Panels/SenseFace.cs b/src/RynthCore.Engine/ImGui/Panels/SenseFace.cs index ab7ba65..ac2032e 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SenseFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SenseFace.cs @@ -13,6 +13,21 @@ // gear a chat line and/or the system beep when a new match appears // (both off by default; they work with the panel closed). // +// Compact (2026-10-31, the owner: "we should make a small version of it"; in +// item-counter.lua's spirit): only the match rows, tighter, and docked no +// frame or background (IImGuiPanel.Bare); clicks go through to the game except +// over the rows (ClickThrough, worked out from the last frame's rows, as the +// radar's dots). Each row: arrow, name, distance; the coordinates, then the +// kind, when the window is wide enough (SenseLayout.Compact). After the first +// row, two small buttons are always there (faint until the mouse is on the +// panel; SenseLayout.OtherViews): collapse, and back to the full panel. +// Collapsed: one line, "Sense: N"; a click on it (or the caret beside it) +// opens it to compact. The full panel's add row has the compact and collapse +// buttons. The look is kept in sense.txt +// (view=...) and set by /rc sense compact on|off, collapse on|off. Moving and +// resizing are the full panel's (the window keeps its place and size). Popped +// out, or embedded in the Mini Remote, the frame stays; embedded is always full. +// // Data: SenseStore (the list, sense.txt) and UiSources.Sense (the 2 Hz scan on // the pump thread, snapshots only; UI/Data/SenseData.cs). This face only reads // the published view and the player pose snapshot (for the arrows, per frame) @@ -62,6 +77,7 @@ internal sealed class SenseFace : IImGuiPanel "The distance shows when you and the object are both outdoors (or in surface buildings), or in the same dungeon. " + "Otherwise the row says elsewhere and gives the landblock.\n\n" + "Click a row to select it in game. Gear: a chat line or a beep when a new match appears.\n" + + "The arrows-in button (or /rc sense compact on) shows just the matches, without the frame.\n" + "/rc sense opens and closes this panel."; // ── State ─────────────────────────────────────────────────────────── @@ -72,6 +88,16 @@ internal sealed class SenseFace : IImGuiPanel private bool _openSettings; private bool _flashing; + // Compact / collapsed: the mouse is over what the last frame drew (rows, the line, the + // buttons), so the window takes input; elsewhere it lets clicks through. A press that began + // there keeps it until the button is released. + private bool _hot, _pressHot; + + /// Compact and collapsed are bare: docked, no frame or background. + public bool Bare => SenseStore.Layout != SenseLayoutMode.Full; + + public bool ClickThrough => Bare && !_hot && !_pressHot; + public void OnShown() { SenseStore.EnsureLoadQueued(); @@ -82,6 +108,18 @@ internal sealed class SenseFace : IImGuiPanel public void OnHidden() => UiSources.Sense.Unsubscribe(); public void Draw() + { + SenseLayoutMode layout = SenseStore.Layout; + if (layout != SenseLayoutMode.Full && !ImGuiPanelHost.DrawingEmbedded) + { + DrawSmall(layout); + return; + } + _hot = _pressHot = false; + DrawFull(); + } + + private void DrawFull() { float w = Begin(out Vector2 origin, out Vector2 size); DrawAddRow(w); @@ -113,7 +151,7 @@ internal sealed class SenseFace : IImGuiPanel const float h = 22, iconW = 22; string addLabel = PhosphorIcons.Plus + " Add"; float addW = ButtonWidth(addLabel); - float boxW = Math.Max(60, w - addW - iconW * 2 - 12); + float boxW = Math.Max(60, w - addW - iconW * 4 - 20); bool enter = TextBox("##sense_input", _input, start, boxW, PhosphorIcons.MagnifyingGlass + " Name to watch for (* and ? wildcards)", out _, @@ -124,6 +162,17 @@ internal sealed class SenseFace : IImGuiPanel if (enter || add) AddTerm(); float gx = start.X + boxW + 4 + addW + 4; + // The view switch: compact, then collapsed (one line). + if (IconButton("##sense_compact", PhosphorIcons.ArrowsInLineVertical, new Vector2(gx, start.Y), new Vector2(iconW, h), Text, BtnFill, + enabled: SenseStore.Loaded)) + SenseStore.SetLayout(SenseLayoutMode.Compact); + SafeImGui.SetItemTooltip(SenseLayout.SwitchTip(SenseLayoutMode.Compact)); + gx += iconW + 4; + if (IconButton("##sense_collapse", PhosphorIcons.CaretUp, new Vector2(gx, start.Y), new Vector2(iconW, h), Text, BtnFill, + enabled: SenseStore.Loaded)) + SenseStore.SetLayout(SenseLayoutMode.Collapsed); + SafeImGui.SetItemTooltip(SenseLayout.SwitchTip(SenseLayoutMode.Collapsed)); + gx += iconW + 4; if (IconButton("##sense_gear", PhosphorIcons.Gear, new Vector2(gx, start.Y), new Vector2(iconW, h), Text, BtnFill)) _openSettings = true; ImGuiNET.ImGui.SetItemTooltip("Alerts"); @@ -344,6 +393,218 @@ internal sealed class SenseFace : IImGuiPanel } } + // ── Compact and collapsed (bare) ──────────────────────────────────── + + private static readonly uint Shadow = 0xB0000000; + + /// + /// The bare looks: compact (the match rows only) or collapsed ("Sense: N"). Works out + /// for the next frame's from what it draws. + /// + private void DrawSmall(SenseLayoutMode layout) + { + Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos(); + Vector2 size = ImGuiNET.ImGui.GetContentRegionAvail(); + bool popped = ImGuiPopOuts.InPopOutFrame; + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, Vector2.Zero); + try + { + SenseView view = UiSources.Sense.Current?.Value ?? SenseView.Empty; + Vector2 mouse = ImGuiNET.ImGui.GetIO().MousePos; + bool wasHot = _hot; + float k = MathF.Max(0.5f, ImGuiNET.ImGui.GetFontSize() / 10f); + _flashing = false; + + Vector2 drawnMax = layout == SenseLayoutMode.Collapsed || view.Rows.Length == 0 + ? DrawCollapsedLine(origin, view, collapsed: layout == SenseLayoutMode.Collapsed, k) + : DrawCompactRows(origin, size, view, k); + + // The view switch after the first line, always there (2026-10-31: a control you can + // see, not one that shows on hover): faint until the mouse is on the panel. + float bh = MathF.Round(SenseLayout.CompactRowHeight * k), bw = bh + 2; + Vector2 bp = new(drawnMax.X + 4, origin.Y); + Vector2 buttonsMax = bp + new Vector2(bw * 2 + 2, bh); + if (SenseStore.Loaded) + { + bool lit = wasHot || popped; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRectFilled(bp - new Vector2(2, 0), buttonsMax + new Vector2(2, 0), WithAlpha(ShellBg, lit ? 0.85f : 0.45f), 3); + (SenseLayoutMode first, SenseLayoutMode second) = SenseLayout.OtherViews(layout); + ViewButton("##sense_v1", first, bp, new Vector2(bw, bh), lit); + ViewButton("##sense_v2", second, bp + new Vector2(bw + 2, 0), new Vector2(bw, bh), lit); + } + + // Hot for the next frame: the mouse over what was drawn or the view switch, or (once hot) + // the strip out to the buttons. + bool over = SenseStore.Loaded + ? SenseLayout.TakesMouse(mouse.X, mouse.Y, origin.X, origin.Y, drawnMax.X, drawnMax.Y, bp.X - 2, buttonsMax.X + 2, buttonsMax.Y, wasHot) + : SenseLayout.IsHot(mouse.X, mouse.Y, origin.X, origin.Y, drawnMax.X, drawnMax.Y, buttonsMax.X, buttonsMax.Y, wasHot); + _hot = over; + bool down = ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left); + if (!down) _pressHot = false; + else if (over && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) _pressHot = true; + } + finally + { + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopFont(); + } + ImGuiNET.ImGui.SetCursorScreenPos(origin); + ImGuiNET.ImGui.Dummy(new Vector2(1, 1)); + } + + /// One button of the view switch: to (its own glyph). : full strength. + private static void ViewButton(string id, SenseLayoutMode to, Vector2 pos, Vector2 size, bool lit) + { + string glyph = to switch + { + SenseLayoutMode.Compact => PhosphorIcons.CaretDown, + SenseLayoutMode.Collapsed => PhosphorIcons.CaretUp, + _ => PhosphorIcons.ArrowsOutLineVertical, + }; + if (IconButton(id, glyph, pos, size, lit ? Text : Faded(Text), lit ? BtnFill : WithAlpha(BtnFill, 0.5f), font: UiFont.Ui11)) + SenseStore.SetLayout(to); + SafeImGui.SetItemTooltip(SenseLayout.SwitchTip(to)); + } + + /// "Sense: N" (collapsed, or compact with nothing to show). Click opens a collapsed one. Returns its far corner. + private Vector2 DrawCollapsedLine(Vector2 origin, SenseView view, bool collapsed, float k) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float rowH = MathF.Round(SenseLayout.CompactRowHeight * k); + string text = SenseLayout.CollapsedText(view.Rows.Length); + float tw = ImGuiNET.ImGui.CalcTextSize(text).X; + float iconW = rowH; + Vector2 size = new(iconW + tw + 4, rowH); + ImGuiNET.ImGui.SetCursorScreenPos(origin); + bool clicked = ImGuiNET.ImGui.InvisibleButton("##sense_line", size); + bool hot = ImGuiNET.ImGui.IsItemHovered(); + if (hot) + { + dl.AddRectFilled(origin, origin + size, WithAlpha(ShellBg, 0.7f), 3); + ImGuiNET.ImGui.BeginTooltip(); + ImGuiNET.ImGui.TextUnformatted(view.Status.Length > 0 ? view.Status : "Scanning..."); + ImGuiNET.ImGui.TextUnformatted(collapsed ? "Click to show the matches." : "Nothing matching to show."); + ImGuiNET.ImGui.EndTooltip(); + } + if (clicked && collapsed) SenseStore.SetLayout(SenseLayoutMode.Compact); + + uint col = view.Rows.Length > 0 ? Amber : Faded(Text); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Binoculars, origin + new Vector2(1, 1), new Vector2(iconW, rowH), Shadow); + PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.Binoculars, origin, new Vector2(iconW, rowH), col); + ShadowText(dl, new Vector2(origin.X + iconW + 2, origin.Y + (rowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f), view.Rows.Length > 0 ? Text : Faded(Text), text); + return origin + size; + } + + /// The compact rows: arrow, name, distance, then the coordinates and the kind when they fit. Returns the far corner. + private Vector2 DrawCompactRows(Vector2 origin, Vector2 size, SenseView view, float k) + { + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + SenseRow[] rows = view.Rows; + float rowH = MathF.Max(MathF.Round(SenseLayout.CompactRowHeight * k), MathF.Ceiling(ImGuiNET.ImGui.GetFontSize() + 3)); + (int shown, bool more) = SenseLayout.CompactFit(size.Y, rowH, rows.Length); + SenseCompactColumns cols = SenseLayout.Compact(size.X, k); + float arrowW = SenseLayout.CompactArrowWidth * k, distW = SenseLayout.CompactDistWidth * k, + locW = SenseLayout.CompactLocWidth * k, kindW = SenseLayout.CompactKindWidth * k; + + // The name column is as wide as the longest name shown (up to what the layout allows), + // so the rows end where their text does: past that, clicks reach the game. + float nameW = 0; + for (int i = 0; i < shown; i++) nameW = MathF.Max(nameW, ImGuiNET.ImGui.CalcTextSize(rows[i].Name).X); + nameW = MathF.Min(nameW + 8, cols.NameWidth); + float used = arrowW + nameW + distW + (cols.Location ? locW : 0) + (cols.Kind ? kindW : 0); + + long now = Environment.TickCount64; + uint selected = ClientHelperHooks.GetSelectedItemId(); + float heading = PlayerHeading(out bool haveHeading); + float fontH = ImGuiNET.ImGui.GetFontSize(); + int clicked = -1, hovered = -1; + for (int i = 0; i < shown; i++) + { + SenseRow r = rows[i]; + var p = new Vector2(origin.X, origin.Y + i * rowH); + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.PushID(i); + if (ImGuiNET.ImGui.InvisibleButton("##crow", new Vector2(used, rowH))) clicked = i; + bool hot = ImGuiNET.ImGui.IsItemHovered(); + ImGuiNET.ImGui.PopID(); + if (hot) hovered = i; + + bool isSel = r.Id == selected; + if (hot) dl.AddRectFilled(p, p + new Vector2(used, rowH), WithAlpha(ShellBg, 0.7f), 2); + if (r.FirstSeenMs != 0) + { + long age = now - r.FirstSeenMs; + if (age >= 0 && age < FlashMs) + { + _flashing = true; + float pulse = 0.5f + 0.5f * MathF.Cos(age * 0.0126f); + float a = (1f - age / (float)FlashMs) * (0.2f + 0.35f * pulse); + dl.AddRectFilled(p, p + new Vector2(used, rowH), WithAlpha(Amber, a), 2); + } + } + if (isSel) dl.AddRect(p, p + new Vector2(used, rowH), Teal, 2); + + Vector2 mid = p + new Vector2(arrowW * 0.5f, rowH * 0.5f); + uint kc = KindColor(r.Kind); + if (r.Measured && haveHeading && !float.IsNaN(r.Bearing)) + { + DrawArrow(dl, mid + new Vector2(1, 1), r.Bearing - heading, Shadow); + DrawArrow(dl, mid, r.Bearing - heading, kc); + } + else if (r.Measured) + dl.AddCircleFilled(mid, 2.5f, kc); + else + dl.AddCircle(mid, 3.5f, Faded(Mute), 12, 1.2f); + + float ty = p.Y + (rowH - fontH) * 0.5f; + float x = p.X + arrowW; + ShadowCell(dl, r.Name, x, ty, nameW - 4, r.Measured ? Text : Mute); + x += nameW; + ShadowCell(dl, r.DistanceText, x, ty, distW - 4, r.Measured ? Text : Faded(Text)); + x += distW; + if (cols.Location) { ShadowCell(dl, r.LocationText, x, ty, locW - 4, Mute); x += locW; } + if (cols.Kind) ShadowCell(dl, SenseSource.KindName(r.Kind), x, ty, kindW - 4, kc); + } + int slots = shown; + if (more) + { + // Rows that don't fit (the window keeps the full panel's size): how many, in the last slot. + var p = new Vector2(origin.X, origin.Y + shown * rowH); + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.InvisibleButton("##cmore", new Vector2(used, rowH)); + ImGuiNET.ImGui.SetItemTooltip("More matches than fit: make the panel taller in its full view (/rc sense compact off)."); + ShadowText(dl, new Vector2(p.X + arrowW, p.Y + (rowH - fontH) * 0.5f), Mute, SenseLayout.MoreText(rows.Length - shown)); + slots++; + } + + if (clicked >= 0) + AcMainThreadQueue.EnqueueOverlaySelect(rows[clicked].Id); + if (hovered >= 0) + { + ImGuiNET.ImGui.BeginTooltip(); + ImGuiNET.ImGui.TextUnformatted(rows[hovered].Tooltip); + ImGuiNET.ImGui.EndTooltip(); + } + return origin + new Vector2(used, slots * rowH); + } + + private static void ShadowText(ImDrawListPtr dl, Vector2 at, uint color, string text) + { + if (text.Length == 0) return; + dl.AddText(at + new Vector2(1, 1), Shadow, text); + dl.AddText(at, color, text); + } + + private static void ShadowCell(ImDrawListPtr dl, string text, float x, float y, float width, uint color) + { + if (text.Length == 0 || width <= 0) return; + dl.PushClipRect(new Vector2(x, y - 2), new Vector2(x + width, y + 40), true); + ShadowText(dl, new Vector2(x, y), color, text); + dl.PopClipRect(); + } + private static void Cell(ImDrawListPtr dl, string text, float x, float y, float width, uint color) { if (text.Length == 0 || width <= 0) return; diff --git a/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs b/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs index 6f2ad5e..3b24c45 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs @@ -251,7 +251,19 @@ internal sealed class SettingsRows ImGuiNET.ImGui.TextUnformatted(row.Label); ImGuiNET.ImGui.PopStyleColor(); ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, w * 0.45f)); - if (ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label)) + bool clicked = ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label); + Tooltip(row); + if (row.Confirm != null) + { + // Asks first: the question, then the button's own caption to go ahead, or Cancel. + if (clicked) + { + _confirmText = row.Confirm(); + ImGuiNET.ImGui.OpenPopup("##confirm"); + } + clicked = ConfirmPopup(row.ButtonText ?? row.Label); + } + if (clicked) { // A settings edit is applied to this copy and saved like a typed value (the number // boxes re-sync from the copy next frame); Click, when also set, runs after. @@ -262,7 +274,33 @@ internal sealed class SettingsRows } row.Click?.Invoke(); } - Tooltip(row); + } + + private string _confirmText = string.Empty; + + /// The open confirmation (the row's ID scope): true when the player went ahead. + private bool ConfirmPopup(string caption) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(12, 10)); + bool open = ImGuiNET.ImGui.BeginPopup("##confirm"); + ImGuiNET.ImGui.PopStyleVar(); + ImGuiNET.ImGui.PopStyleColor(2); + if (!open) return false; + bool go = false; + try + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim); + ImGuiNET.ImGui.TextUnformatted(_confirmText); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + if (ImGuiNET.ImGui.Button(caption.TrimEnd('.') + "##confirm_go")) { go = true; ImGuiNET.ImGui.CloseCurrentPopup(); } + ImGuiNET.ImGui.SameLine(0, 8); + if (ImGuiNET.ImGui.Button("Cancel##confirm_no")) ImGuiNET.ImGui.CloseCurrentPopup(); + } + finally { ImGuiNET.ImGui.EndPopup(); } + return go; } private void Changed(SettingRow row, double value) diff --git a/src/RynthCore.Engine/ImGui/UiCost.cs b/src/RynthCore.Engine/ImGui/UiCost.cs new file mode 100644 index 0000000..7b5197c --- /dev/null +++ b/src/RynthCore.Engine/ImGui/UiCost.cs @@ -0,0 +1,216 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/UiCost.cs +// Which part of the UI frame is slow: the breakdown behind the heartbeat's +// ui= (UiFrameStats). The logic is in UiCostModel (tested offline); this is +// the engine side - the slots by name, the settings, the log line, the +// heartbeat field and /rc uicost. +// +// Timed (each one Start/Stop pair around a call, on AC's render thread): +// frame setup (fonts, icon textures, backends' NewFrame), the monster HUD +// update and draw (plates, combat text; from EngineFrameController, the +// HUD's own code is not touched), ImGui NewFrame and EndFrame+Render, the +// shell, each plugin's Render / RenderOverlay callback (by plugin), the bar, +// the server menus, the panel host's upkeep, each docked panel and plugin +// window (by title), each popped-out panel (by title) and its pop-out window +// (its own frame, render and present), the ImGui submit (with its vertex +// count), and outside ui= the Nav3D markers and the world overlays' present +// at AC's 3D->UI pass. +// Counted (no timing): the main submit's draw lists, draw calls, texture +// switches and vertices copied, against what copying each command's whole list +// would have been (DrawSubmitPlan), and the textures uploaded that frame (the +// font atlas, the others). The line ends "| submit: ...; uploads: ...", the +// heartbeat field adds " uisub=draws:N,texsw:N,vtx:copied/whole-list,up:font/tex". +// +// engine.json UiCostLog (default on) and UiCostThresholdMs (default 50): +// Settings > Diagnostics, /rc uicost [on|off||now]. Off = no timing at +// all (each site is one flag check). On, a frame at or over the threshold +// writes ONE "[UiCost] frame ..." line, at most once every 5 s; the +// heartbeat gets " uitop=..." only while its ui p95 is over the threshold. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static class UiCost +{ + private static readonly UiCostModel Model = new(Stopwatch.Frequency); + private static readonly object Sync = new(); + + // Fixed parts of the frame. + internal static readonly int FrameSetup = Model.Register("Frame setup"); + internal static readonly int HudUpdate = Model.Register("Monster HUD update"); + internal static readonly int ImGuiNewFrame = Model.Register("ImGui NewFrame"); + internal static readonly int Shell = Model.Register("Shell"); + internal static readonly int MonsterHud = Model.Register("Monster HUD (plates, combat text)", unit: "plates"); + internal static readonly int VideoBanner = Model.Register("Video patch banner"); + internal static readonly int ServerMenus = Model.Register("Server menus"); + internal static readonly int Bar = Model.Register("Bar"); + internal static readonly int PanelHost = Model.Register("Panel host upkeep", unit: "panels"); + internal static readonly int DrawerBodies = Model.Register("Settings drawer bodies"); + internal static readonly int ImGuiRender = Model.Register("ImGui EndFrame+Render"); + internal static readonly int FrameFinish = Model.Register("Frame finish (ini, input)"); + internal static readonly int PopOuts = Model.Register("Pop-outs upkeep"); + internal static readonly int Submit = Model.Register("ImGui submit", unit: "vtx"); + internal static readonly int Nav3D = Model.Register("Nav3D markers", outside: true); + internal static readonly int WorldPresent = Model.Register("World overlays present", outside: true); + + // Named parts, a slot each the first time the name is seen (render thread only). + private static readonly Dictionary PanelSlots = new(StringComparer.Ordinal); + private static readonly Dictionary Popped = new(StringComparer.Ordinal); + private static readonly Dictionary PopOutWindows = new(StringComparer.Ordinal); + private static readonly Dictionary PluginRender = new(StringComparer.Ordinal); + private static readonly Dictionary PluginOverlay = new(StringComparer.Ordinal); + + private static bool _settingsRead; + + /// Timing on (engine.json UiCostLog). Read once per frame from the settings. + public static bool Enabled => Model.Enabled; + + /// A timestamp for a Stop, or 0 while timing is off. + public static long Start() + { + if (!_settingsRead) RefreshSettings(); + return Model.Start(); + } + + public static void Stop(int slot, long start, int count = -1) => Model.Stop(slot, start, count); + + /// What the slots got this frame so far, for . + public static long Mark => Model.Mark; + + public static void StopExclusive(int slot, long start, long mark, int count = -1) => Model.StopExclusive(slot, start, mark, count); + + /// The main ImGui submit's counters (DX9Backend.LastSubmit right after it), for the line and the heartbeat. + public static void SetSubmit(in SubmitStats stats) + { + if (Model.Enabled) Model.SetSubmit(stats); + } + + /// A docked panel or plugin window, by its title. + public static void StopPanel(string title, long start) + { + if (start == 0) return; + Model.Stop(SlotFor(PanelSlots, title, ""), start); + } + + /// A popped-out panel's drawing, by its title. + public static void StopPopped(string title, long start) + { + if (start == 0) return; + Model.Stop(SlotFor(Popped, title, " (popped out)"), start); + } + + /// A pop-out window's own frame, render and present (its panel's drawing not included). + public static void StopPopOutWindow(string title, long start, long mark) + { + if (start == 0) return; + Model.StopExclusive(SlotFor(PopOutWindows, title, " pop-out window"), start, mark); + } + + /// A plugin's Render callback (the shell branch). + public static void StopPluginRender(string plugin, long start) + { + if (start == 0) return; + Model.Stop(SlotFor(PluginRender, plugin, " (plugin render)"), start); + } + + /// A plugin's RenderOverlay callback (its overlay windows). + public static void StopPluginOverlay(string plugin, long start) + { + if (start == 0) return; + Model.Stop(SlotFor(PluginOverlay, plugin, " (plugin overlay)"), start); + } + + private static int SlotFor(Dictionary map, string name, string suffix) + { + if (map.TryGetValue(name, out int slot)) return slot; + slot = Model.Register(string.IsNullOrEmpty(name) ? "(no name)" + suffix : name + suffix); + map[name] = slot; + return slot; + } + + /// + /// The end of a UI frame, where UiFrameStats records it ( is the same + /// number). Writes the slow-frame line when one is due. Render thread. + /// + public static void EndFrame(long uiTicks) + { + RefreshSettings(); + DX9Backend.TakeUploads(out int fontUploads, out int texUploads); // this frame's (also cleared while off) + if (!Model.Enabled && Model.Mark == 0) return; // off, and nothing left from a frame that was on + Model.AddUploads(fontUploads, texUploads); + string? line; + lock (Sync) line = Model.EndFrame(uiTicks, Stopwatch.GetTimestamp(), logSlow: Model.Enabled); + if (line != null) RynthLog.Info(line); + } + + /// No UI frame this EndScene (the ImGui layer is off): what was timed is dropped. Render thread. + public static void DiscardFrame() + { + if (Model.Mark != 0) Model.DiscardFrame(); + } + + private static void RefreshSettings() + { + _settingsRead = true; + Model.Enabled = Plugins.EngineSettings.UiCostLog; + int ms = Plugins.EngineSettings.UiCostThresholdMs; + if (ms != Model.ThresholdMs) lock (Sync) Model.ThresholdMs = ms; + } + + /// + /// The heartbeat's " uitop=a:avg/max,b:avg/max,c:avg/max" (the window's top 3 by average), only + /// while timing is on and is at or over the threshold; otherwise "". + /// Heartbeat thread. + /// + public static string HeartbeatField(float uiP95Ms) + { + if (!Model.Enabled || uiP95Ms < Model.ThresholdMs) return ""; + lock (Sync) return Model.HeartbeatField(Stopwatch.GetTimestamp(), 3); + } + + /// /rc uicost [on|off|<ms>|now|status]: the reply lines (every form answers). + public static List HandleCommand(string args) + { + string a = (args ?? "").Trim().ToLowerInvariant(); + var lines = new List(); + if (a is "on" or "off") + { + Plugins.EngineSettings.UiCostLog = a == "on"; + RefreshSettings(); + lines.Add(a == "on" + ? $"UI cost timing on: a UI frame of {Model.ThresholdMs} ms or more writes one [UiCost] line to the log (at most every 5 s)." + : "UI cost timing off: nothing is timed or logged. /rc uicost on starts it again."); + return lines; + } + if (a.EndsWith("ms", StringComparison.Ordinal)) a = a.Substring(0, a.Length - 2).Trim(); + if (int.TryParse(a, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int ms)) + { + int v = UiCostModel.ClampThresholdMs(ms); + Plugins.EngineSettings.UiCostThresholdMs = v; + RefreshSettings(); + string clamped = v != ms ? $" (kept to {UiCostModel.MinThresholdMs}-{UiCostModel.MaxThresholdMs})" : ""; + lines.Add($"UI cost threshold {v} ms{clamped}; timing {(Model.Enabled ? "on" : "off - /rc uicost on to log")}."); + return lines; + } + if (a is "now" or "") + { + lock (Sync) lines.AddRange(Model.Describe(Stopwatch.GetTimestamp())); + if (!Model.Enabled) lines.Add("Timing is off, so this shows nothing new: /rc uicost on."); + return lines; + } + if (a == "status") + { + lines.Add($"UI cost timing {(Model.Enabled ? "on" : "off")}, threshold {Model.ThresholdMs} ms, {Model.SlotCount} parts named, " + + $"{Model.FramesSeen} frames timed, {Model.LinesWritten} slow-frame lines logged."); + return lines; + } + lines.Add(Usage); + return lines; + } + + public const string Usage = Compatibility.ChatCommandReplies.UiCostUsage; +} diff --git a/src/RynthCore.Engine/ImGui/UiCostModel.cs b/src/RynthCore.Engine/ImGui/UiCostModel.cs new file mode 100644 index 0000000..e0441ea --- /dev/null +++ b/src/RynthCore.Engine/ImGui/UiCostModel.cs @@ -0,0 +1,649 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/UiCostModel.cs +// The UI frame cost breakdown (ImGui/UiCost.cs): which part of the UI frame +// takes the time. Pure logic, no engine types (tools/UiCostTests compiles it). +// +// Each timed part of a frame is a slot (a docked panel by title, a plugin's +// render callback, the monster HUD, the ImGui submit, ...). Start/Stop add the +// ticks of one call to the slot for this frame; EndFrame folds the frame into +// a rolling window (Buckets x 1 s) and, when the frame's UI time is over the +// threshold and no line was written in the last LogIntervalSeconds, returns +// ONE line naming the frame's biggest parts. Nothing allocates per frame: +// the arrays are fixed, a slot's name is made once, and strings are built only +// for that line and for the summaries (/rc uicost now, the heartbeat field). +// +// "Outside" slots (the Nav3D markers and the world overlays' present at AC's +// 3D->UI pass) cost render time but are not part of the heartbeat's ui=; they +// are listed apart. Whatever the frame spent that no slot covers is "untimed" +// (Dear ImGui's own work between the timed calls, input, ini saves...). +// +// Threads: Register, Start, Stop and EndFrame on AC's render thread; the +// summaries from any thread, with the caller holding one lock around them and +// EndFrame (UiCost does). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Text; +using System.Threading; + +namespace RynthCore.Engine.ImGuiBackend; + +internal sealed class UiCostModel +{ + public const int DefaultThresholdMs = 50; + public const int MinThresholdMs = 5; + public const int MaxThresholdMs = 2000; + public const int MaxSlots = 160; + /// The rolling window: this many 1 s buckets (the summaries cover the last 4-5 s). + public const int Buckets = 5; + public const int LogIntervalSeconds = 5; + /// Parts named in a slow-frame line; the rest are summed as "+N more". + public const int LineTopItems = 8; + + /// A threshold from a setting or a command, kept in range. + public static int ClampThresholdMs(int ms) => Math.Clamp(ms, MinThresholdMs, MaxThresholdMs); + + private static readonly CultureInfo Inv = CultureInfo.InvariantCulture; + + private readonly long _freq; + private readonly long _bucketTicks; + private readonly long _logIntervalTicks; + + // Slots. + private readonly string[] _names = new string[MaxSlots]; + private readonly string?[] _units = new string?[MaxSlots]; + private readonly bool[] _outside = new bool[MaxSlots]; + private int _slotCount; + /// Slot 0: names past MaxSlots share it. + public const int OverflowSlot = 0; + + // This frame. + private readonly long[] _fTicks = new long[MaxSlots]; + private readonly int[] _fCount = new int[MaxSlots]; + private readonly int[] _fCalls = new int[MaxSlots]; + private readonly int[] _touched = new int[MaxSlots]; + private int _touchedCount; + private long _fAll, _fOutside; + // This frame's ImGui submit counters (SubmitStats, end of this file) and texture uploads. + private SubmitStats _fSubmit; + private bool _fHasSubmit; + private int _fFontUploads, _fTexUploads; + + // The window, one row per bucket. + private readonly long[] _bStart = new long[Buckets]; + private readonly long[] _bFrames = new long[Buckets]; + private readonly long[] _bUiSum = new long[Buckets]; + private readonly long[] _bUiMax = new long[Buckets]; + private readonly long[] _bSlow = new long[Buckets]; + private readonly long[] _bUntimedSum = new long[Buckets]; + private readonly long[] _bUntimedMax = new long[Buckets]; + private readonly long[,] _bSum = new long[Buckets, MaxSlots]; + private readonly long[,] _bMax = new long[Buckets, MaxSlots]; + private readonly int[,] _bMaxCount = new int[Buckets, MaxSlots]; + // The bucket's slowest frame, part by part. + private readonly long[,] _bWorst = new long[Buckets, MaxSlots]; + private readonly int[,] _bWorstCount = new int[Buckets, MaxSlots]; + private readonly long[] _bWorstUntimed = new long[Buckets]; + // The bucket's submit counters (each one's largest frame) and uploads (summed). + private readonly SubmitStats[] _bSubmitMax = new SubmitStats[Buckets]; + private readonly bool[] _bHasSubmit = new bool[Buckets]; + private readonly long[] _bFontUploads = new long[Buckets]; + private readonly long[] _bTexUploads = new long[Buckets]; + private int _cur = -1; + + private long _lastLogAt; + private bool _loggedOnce; + private int _thresholdMs = DefaultThresholdMs; + private long _thresholdTicks; + + // Scratch for sorting (render thread for the frame line; under the caller's lock for summaries). + private readonly int[] _order = new int[MaxSlots + 1]; + private readonly long[] _orderTicks = new long[MaxSlots + 1]; + private readonly long[] _winSum = new long[MaxSlots]; + private readonly long[] _winMax = new long[MaxSlots]; + private readonly int[] _winMaxCount = new int[MaxSlots]; + private SubmitStats _winSubmit; + private bool _winHasSubmit; + private long _winFontUploads, _winTexUploads; + + /// Timing on: Start returns a timestamp; off: 0 and every Stop is a no-op. + public bool Enabled; + + /// Frames folded into the window since the start (diagnostics, tests). + public long FramesSeen { get; private set; } + + /// Slow-frame lines returned by EndFrame since the start. + public long LinesWritten { get; private set; } + + public UiCostModel(long ticksPerSecond) + { + _freq = Math.Max(1, ticksPerSecond); + _bucketTicks = _freq; + _logIntervalTicks = _freq * LogIntervalSeconds; + ThresholdMs = DefaultThresholdMs; + Register("(more names)"); + for (int i = 0; i < MaxSlots; i++) _fCount[i] = -1; + } + + /// A frame at or over this many ms is slow (logged, counted). + public int ThresholdMs + { + get => _thresholdMs; + set + { + _thresholdMs = ClampThresholdMs(value); + _thresholdTicks = _thresholdMs * _freq / 1000; + } + } + + public int SlotCount => Volatile.Read(ref _slotCount); + + public string SlotName(int slot) => (uint)slot < (uint)SlotCount ? _names[slot] : "?"; + + /// + /// A new slot. names the count passed to Stop ("plates", "vtx"), null for + /// none; : not part of the frame's UI time (listed apart). Past + /// MaxSlots the overflow slot. Render thread (the summaries read only slots already published). + /// + public int Register(string name, string? unit = null, bool outside = false) + { + int n = _slotCount; + if (n >= MaxSlots) return OverflowSlot; + _names[n] = name; + _units[n] = unit; + _outside[n] = outside; + Volatile.Write(ref _slotCount, n + 1); + return n; + } + + /// A timestamp to pass to Stop, or 0 while timing is off. + public long Start() => Enabled ? Stopwatch.GetTimestamp() : 0; + + /// Adds the time since (from Start) to ; a no-op for 0. + public void Stop(int slot, long start, int count = -1) + { + if (start == 0) return; + Add(slot, Stopwatch.GetTimestamp() - start, count); + } + + /// The ticks every slot got this frame so far: Mark before a part, StopExclusive after it. + public long Mark => _fAll; + + /// + /// As Stop, less what the slots timed inside it got (since ): a part that + /// draws other timed parts (the panel host around its panels, a pop-out window around its panel) + /// keeps only its own time, so nothing is counted twice. + /// + public void StopExclusive(int slot, long start, long mark, int count = -1) + { + if (start == 0) return; + long ticks = Stopwatch.GetTimestamp() - start - (_fAll - mark); + Add(slot, ticks < 0 ? 0 : ticks, count); + } + + /// Adds (and a count, when not negative) to a slot for this frame. + public void Add(int slot, long ticks, int count = -1) + { + if ((uint)slot >= (uint)_slotCount) return; + if (_fCalls[slot]++ == 0) _touched[_touchedCount++] = slot; + _fTicks[slot] += ticks; + if (count >= 0) _fCount[slot] = (_fCount[slot] < 0 ? 0 : _fCount[slot]) + count; + _fAll += ticks; + if (_outside[slot]) _fOutside += ticks; + } + + /// This frame's ImGui submit counters (the main submit; a second call this frame replaces them). + public void SetSubmit(in SubmitStats stats) + { + _fSubmit = stats; + _fHasSubmit = true; + } + + /// Textures made or re-uploaded this frame: the font atlas, and any other (icons, map tiles, pictures). + public void AddUploads(int font, int tex) + { + if (font > 0) _fFontUploads += font; + if (tex > 0) _fTexUploads += tex; + } + + /// + /// Ends the frame: is its UI time (what the heartbeat's ui= records). + /// Folds it into the window and returns the slow-frame line when one is due (over the threshold, + /// none in the last LogIntervalSeconds, logging on), else null. + /// + public string? EndFrame(long uiTicks, long now, bool logSlow) + { + Rotate(now); + int b = _cur; + long inside = _fAll - _fOutside; + long untimed = uiTicks - inside; + if (untimed < 0) untimed = 0; + + FramesSeen++; + _bFrames[b]++; + _bUiSum[b] += uiTicks; + bool worst = uiTicks > _bUiMax[b] || _bFrames[b] == 1; + if (uiTicks > _bUiMax[b]) _bUiMax[b] = uiTicks; + bool slow = uiTicks >= _thresholdTicks; + if (slow) _bSlow[b]++; + _bUntimedSum[b] += untimed; + if (untimed > _bUntimedMax[b]) _bUntimedMax[b] = untimed; + + if (worst) + { + for (int s = 0; s < MaxSlots; s++) { _bWorst[b, s] = 0; _bWorstCount[b, s] = -1; } + _bWorstUntimed[b] = untimed; + } + for (int i = 0; i < _touchedCount; i++) + { + int s = _touched[i]; + long t = _fTicks[s]; + _bSum[b, s] += t; + if (t > _bMax[b, s]) _bMax[b, s] = t; + if (_fCount[s] > _bMaxCount[b, s]) _bMaxCount[b, s] = _fCount[s]; + if (worst) { _bWorst[b, s] = t; _bWorstCount[b, s] = _fCount[s]; } + } + if (_fHasSubmit) { _bSubmitMax[b].MaxWith(_fSubmit); _bHasSubmit[b] = true; } + _bFontUploads[b] += _fFontUploads; + _bTexUploads[b] += _fTexUploads; + + string? line = null; + if (logSlow && slow && (!_loggedOnce || now - _lastLogAt >= _logIntervalTicks)) + { + _loggedOnce = true; + _lastLogAt = now; + LinesWritten++; + line = FormatFrameLine(uiTicks, untimed); + } + + DiscardFrame(); // clears only what this frame touched + return line; + } + + /// Drops what this frame timed without folding it in (no UI frame this EndScene). + public void DiscardFrame() + { + for (int i = 0; i < _touchedCount; i++) + { + int s = _touched[i]; + _fTicks[s] = 0; + _fCalls[s] = 0; + _fCount[s] = -1; + } + _touchedCount = 0; + _fAll = 0; + _fOutside = 0; + _fSubmit = default; + _fHasSubmit = false; + _fFontUploads = _fTexUploads = 0; + } + + private void Rotate(long now) + { + if (_cur < 0) + { + _cur = 0; + ClearBucket(0, now); + return; + } + long age = now - _bStart[_cur]; + if (age < _bucketTicks) return; + long steps = age / _bucketTicks; + if (steps >= Buckets) + { + for (int i = 0; i < Buckets; i++) ClearBucket(i, 0); + _cur = 0; + _bStart[0] = now; + return; + } + long start = _bStart[_cur]; + for (long i = 0; i < steps; i++) + { + start += _bucketTicks; + _cur = (_cur + 1) % Buckets; + ClearBucket(_cur, start); + } + } + + private void ClearBucket(int b, long start) + { + _bStart[b] = start; + _bFrames[b] = _bUiSum[b] = _bUiMax[b] = _bSlow[b] = _bUntimedSum[b] = _bUntimedMax[b] = _bWorstUntimed[b] = 0; + _bSubmitMax[b] = default; + _bHasSubmit[b] = false; + _bFontUploads[b] = _bTexUploads[b] = 0; + for (int s = 0; s < MaxSlots; s++) + { + _bSum[b, s] = 0; _bMax[b, s] = 0; _bMaxCount[b, s] = -1; + _bWorst[b, s] = 0; _bWorstCount[b, s] = -1; + } + } + + // ── Text ─────────────────────────────────────────────────────────────── + + private string Ms(long ticks) => (ticks * 1000.0 / _freq).ToString("0.0", Inv); + + private string WithCount(int slot, int count) => + count >= 0 && _units[slot] is { } unit ? $" ({count.ToString(Inv)} {unit})" : ""; + + /// + /// "[UiCost] frame 187.0 ms (over 50): Radar 120.3, Monster HUD 41.0 (38 plates), ..., untimed 3.2, + /// +4 more 0.9 | 3D pass, not in ui=: Nav3D markers 1.2". Parts under 0.05 ms are left out. + /// + private string FormatFrameLine(long uiTicks, long untimed) + { + var sb = new StringBuilder(256); + sb.Append("[UiCost] frame ").Append(Ms(uiTicks)).Append(" ms (over ").Append(_thresholdMs.ToString(Inv)).Append("): "); + int n = 0; + for (int i = 0; i < _touchedCount; i++) + { + int s = _touched[i]; + if (_outside[s]) continue; + _order[n] = s; _orderTicks[n] = _fTicks[s]; n++; + } + _order[n] = -1; _orderTicks[n] = untimed; n++; + SortDesc(n); + AppendTop(sb, n, LineTopItems, s => _fCount[s]); + AppendSubmit(sb, _fHasSubmit, _fSubmit, _fFontUploads, _fTexUploads); + + int o = 0; + for (int i = 0; i < _touchedCount; i++) + { + int s = _touched[i]; + if (!_outside[s]) continue; + _order[o] = s; _orderTicks[o] = _fTicks[s]; o++; + } + if (o > 0) + { + SortDesc(o); + sb.Append(" | 3D pass, not in ui=: "); + AppendTop(sb, o, LineTopItems, s => _fCount[s]); + } + return sb.ToString(); + } + + /// + /// " | submit: 21 lists, 412 draws, 3 tex switches, 31k vtx copied (whole-list 4.2M); uploads: 1 font, 0 tex". + /// The submit part only when one was recorded, the uploads only when there were any. + /// + private static void AppendSubmit(StringBuilder sb, bool has, in SubmitStats s, long font, long tex) + { + if (has) + { + sb.Append(" | submit: ").Append(s.Lists.ToString(Inv)).Append(" lists, ") + .Append(s.Draws.ToString(Inv)).Append(" draws, ") + .Append(s.TexSwitches.ToString(Inv)).Append(" tex switches, ") + .Append(Compact(s.VtxCopied)).Append(" vtx copied (whole-list ").Append(Compact(s.VtxWholeList)).Append(')'); + if (s.Skipped > 0) sb.Append(", ").Append(s.Skipped.ToString(Inv)).Append(" skipped"); + } + if (font > 0 || tex > 0) + sb.Append(has ? "; uploads: " : " | uploads: ").Append(font.ToString(Inv)).Append(" font, ").Append(tex.ToString(Inv)).Append(" tex"); + } + + /// 950, 31.2k, 4.2M. + public static string Compact(long n) + { + if (n < 1000) return n.ToString(Inv); + if (n < 1_000_000) return (n / 1000.0).ToString("0.#", Inv) + "k"; + return (n / 1_000_000.0).ToString("0.#", Inv) + "M"; + } + + private void AppendTop(StringBuilder sb, int n, int top, Func count) + { + long minTicks = _freq / 20000; // 0.05 ms + int shown = 0, more = 0; + long moreTicks = 0; + for (int i = 0; i < n; i++) + { + int s = _order[i]; + long t = _orderTicks[i]; + if (shown >= top || t < minTicks || t <= 0) + { + if (t > 0) { more++; moreTicks += t; } + continue; + } + if (shown > 0) sb.Append(", "); + if (s < 0) sb.Append("untimed ").Append(Ms(t)); + else sb.Append(_names[s]).Append(' ').Append(Ms(t)).Append(WithCount(s, count(s))); + shown++; + } + if (shown == 0) sb.Append("nothing timed"); + if (more > 0) sb.Append(", +").Append(more.ToString(Inv)).Append(" more ").Append(Ms(moreTicks)); + } + + // Insertion sort of _order/_orderTicks [0, n) by ticks, largest first (n is small). + private void SortDesc(int n) + { + for (int i = 1; i < n; i++) + { + int s = _order[i]; + long t = _orderTicks[i]; + int j = i - 1; + while (j >= 0 && _orderTicks[j] < t) + { + _order[j + 1] = _order[j]; + _orderTicks[j + 1] = _orderTicks[j]; + j--; + } + _order[j + 1] = s; + _orderTicks[j + 1] = t; + } + } + + /// The live buckets at (the window), folded into the _win arrays. + private (long frames, long uiSum, long uiMax, long slow, long untimedSum, long untimedMax, long spanTicks, int worstBucket) FoldWindow(long now) + { + Array.Clear(_winSum); + Array.Clear(_winMax); + for (int s = 0; s < MaxSlots; s++) _winMaxCount[s] = -1; + _winSubmit = default; + _winHasSubmit = false; + _winFontUploads = _winTexUploads = 0; + long frames = 0, uiSum = 0, uiMax = 0, slow = 0, untimedSum = 0, untimedMax = 0, oldest = now; + int worstBucket = -1; + if (_cur < 0) return (0, 0, 0, 0, 0, 0, 0, -1); + long horizon = now - _bucketTicks * Buckets; + int slots = SlotCount; + for (int b = 0; b < Buckets; b++) + { + if (_bFrames[b] == 0 || _bStart[b] < horizon) continue; + if (_bStart[b] < oldest) oldest = _bStart[b]; + frames += _bFrames[b]; + uiSum += _bUiSum[b]; + if (worstBucket < 0 || _bUiMax[b] > uiMax) { uiMax = _bUiMax[b]; worstBucket = b; } + slow += _bSlow[b]; + untimedSum += _bUntimedSum[b]; + if (_bUntimedMax[b] > untimedMax) untimedMax = _bUntimedMax[b]; + if (_bHasSubmit[b]) { _winSubmit.MaxWith(_bSubmitMax[b]); _winHasSubmit = true; } + _winFontUploads += _bFontUploads[b]; + _winTexUploads += _bTexUploads[b]; + for (int s = 0; s < slots; s++) + { + _winSum[s] += _bSum[b, s]; + if (_bMax[b, s] > _winMax[s]) _winMax[s] = _bMax[b, s]; + if (_bMaxCount[b, s] > _winMaxCount[s]) _winMaxCount[s] = _bMaxCount[b, s]; + } + } + return (frames, uiSum, uiMax, slow, untimedSum, untimedMax, now - oldest, worstBucket); + } + + /// + /// The window's biggest parts by average per frame, for the heartbeat: " uitop=Radar:2.1/120.3,..." + /// (avg/max ms, spaces in names as '_'). Empty when the window has no frames. + /// + public string HeartbeatField(long now, int top = 3) + { + var w = FoldWindow(now); + if (w.frames == 0) return ""; + int n = FillWindowOrder(w.untimedSum, includeOutside: false); + var sb = new StringBuilder(" uitop="); + int shown = 0; + for (int i = 0; i < n && shown < top; i++) + { + if (_orderTicks[i] <= 0) break; + int s = _order[i]; + if (shown > 0) sb.Append(','); + string name = s < 0 ? "untimed" : _names[s]; + sb.Append(name.Replace(' ', '_').Replace(',', ';').Replace('=', '-')); + sb.Append(':').Append(Ms(_orderTicks[i] / w.frames)).Append('/').Append(Ms(s < 0 ? w.untimedMax : _winMax[s])); + shown++; + } + if (shown == 0) return ""; + // The window's largest submit: " uisub=draws:412,texsw:3,vtx:31k/4.2M,up:0/0" + // (vtx copied / what whole-list copies would have been; uploads font/other, summed). + if (_winHasSubmit || _winFontUploads > 0 || _winTexUploads > 0) + { + sb.Append(" uisub=draws:").Append(_winSubmit.Draws.ToString(Inv)) + .Append(",texsw:").Append(_winSubmit.TexSwitches.ToString(Inv)) + .Append(",vtx:").Append(Compact(_winSubmit.VtxCopied)).Append('/').Append(Compact(_winSubmit.VtxWholeList)) + .Append(",up:").Append(_winFontUploads.ToString(Inv)).Append('/').Append(_winTexUploads.ToString(Inv)); + } + return sb.ToString(); + } + + private int FillWindowOrder(long untimedSum, bool includeOutside) + { + int n = 0; + int slots = SlotCount; + for (int s = 0; s < slots; s++) + { + if (_winSum[s] <= 0 || _outside[s] != includeOutside) continue; + _order[n] = s; _orderTicks[n] = _winSum[s]; n++; + } + if (!includeOutside && untimedSum > 0) { _order[n] = -1; _orderTicks[n] = untimedSum; n++; } + SortDesc(n); + return n; + } + + /// + /// The breakdown for /rc uicost now: the window's frames, the parts by average per frame (with + /// their worst), the slowest frame part by part, and the 3D pass parts. + /// + public List Describe(long now, int top = 8) + { + var lines = new List(); + var w = FoldWindow(now); + string state = Enabled ? $"timing on, slow frames logged at {_thresholdMs.ToString(Inv)} ms+" : "timing off"; + if (w.frames == 0) + { + lines.Add($"UI cost: no UI frames in the last {Buckets.ToString(Inv)} s ({state})."); + return lines; + } + double span = w.spanTicks / (double)_freq; + lines.Add($"UI cost, last {span.ToString("0.0", Inv)} s: {w.frames.ToString(Inv)} frames, avg {Ms(w.uiSum / w.frames)} ms, " + + $"max {Ms(w.uiMax)} ms, {w.slow.ToString(Inv)} at {_thresholdMs.ToString(Inv)} ms+ ({state})."); + + int n = FillWindowOrder(w.untimedSum, includeOutside: false); + var sb = new StringBuilder("Per frame, avg (max): "); + AppendWindowItems(sb, n, top, w.frames, w.untimedMax); + lines.Add(sb.ToString()); + + if (w.worstBucket >= 0) + { + int b = w.worstBucket; + int m = 0; + int slots = SlotCount; + for (int s = 0; s < slots; s++) + { + if (_outside[s] || _bWorst[b, s] <= 0) continue; + _order[m] = s; _orderTicks[m] = _bWorst[b, s]; m++; + } + _order[m] = -1; _orderTicks[m] = _bWorstUntimed[b]; m++; + SortDesc(m); + var wsb = new StringBuilder("Slowest frame ").Append(Ms(w.uiMax)).Append(" ms: "); + AppendTop(wsb, m, top, s => _bWorstCount[b, s]); + lines.Add(wsb.ToString()); + } + + if (_winHasSubmit || _winFontUploads > 0 || _winTexUploads > 0) + { + var ssb = new StringBuilder("ImGui submit, largest per frame"); + AppendSubmit(ssb, _winHasSubmit, _winSubmit, _winFontUploads, _winTexUploads); + // "... | submit: ..." reads as "ImGui submit, largest per frame: ..." here; uploads are the window's sum. + ssb.Replace(" | submit:", ":").Replace(" | uploads:", ": uploads (window total):").Replace("; uploads:", "; uploads (window total):"); + lines.Add(ssb.ToString()); + } + + int o = FillWindowOrder(0, includeOutside: true); + if (o > 0) + { + var osb = new StringBuilder("3D pass, not in ui=, avg (max): "); + AppendWindowItems(osb, o, top, w.frames, 0); + lines.Add(osb.ToString()); + } + return lines; + } + + private void AppendWindowItems(StringBuilder sb, int n, int top, long frames, long untimedMax) + { + int shown = 0; + for (int i = 0; i < n && shown < top; i++) + { + int s = _order[i]; + long avg = _orderTicks[i] / frames; + if (shown > 0) sb.Append(", "); + if (s < 0) sb.Append("untimed ").Append(Ms(avg)).Append(" (").Append(Ms(untimedMax)).Append(')'); + else + { + sb.Append(_names[s]).Append(' ').Append(Ms(avg)).Append(" (").Append(Ms(_winMax[s])); + if (_winMaxCount[s] >= 0 && _units[s] is { } unit) sb.Append(", ").Append(_winMaxCount[s].ToString(Inv)).Append(' ').Append(unit); + sb.Append(')'); + } + shown++; + } + if (shown == 0) sb.Append("nothing timed"); + else if (n > shown) sb.Append(", +").Append((n - shown).ToString(Inv)).Append(" more"); + } + + /// The window's totals (tests): frames, average and max UI ms, slow frames. + public (long Frames, double AvgMs, double MaxMs, long Slow) WindowTotals(long now) + { + var w = FoldWindow(now); + if (w.frames == 0) return (0, 0, 0, 0); + return (w.frames, w.uiSum * 1000.0 / _freq / w.frames, w.uiMax * 1000.0 / _freq, w.slow); + } + + /// One slot's window total, average per frame and max, in ms (tests). + public (double AvgMs, double MaxMs) SlotWindow(long now, int slot) + { + var w = FoldWindow(now); + if (w.frames == 0 || (uint)slot >= (uint)SlotCount) return (0, 0); + return (_winSum[slot] * 1000.0 / _freq / w.frames, _winMax[slot] * 1000.0 / _freq); + } +} + +/// +/// One ImGui submit's counters (DX9Backend.RenderLists): what the [UiCost] line and the +/// heartbeat print about the submit, so a slow one names its shape. +/// +internal struct SubmitStats +{ + /// Draw lists drawn. + public int Lists; + /// Draw calls made (commands with geometry, not clipped away). + public int Draws; + /// Commands skipped: clipped away or broken. + public int Skipped; + /// SetTexture calls that changed the texture. + public int TexSwitches; + /// Vertices handed to the draw calls (what the runtime copies). + public long VtxCopied; + /// What the same submit would have copied handing each command its whole list (the old renderer). + public long VtxWholeList; + + public void Clear() => this = default; + + /// Folds another submit in (the window keeps each counter's largest). + public void MaxWith(in SubmitStats o) + { + if (o.Lists > Lists) Lists = o.Lists; + if (o.Draws > Draws) Draws = o.Draws; + if (o.Skipped > Skipped) Skipped = o.Skipped; + if (o.TexSwitches > TexSwitches) TexSwitches = o.TexSwitches; + if (o.VtxCopied > VtxCopied) VtxCopied = o.VtxCopied; + if (o.VtxWholeList > VtxWholeList) VtxWholeList = o.VtxWholeList; + } +} diff --git a/src/RynthCore.Engine/MainThreadHangWatchdog.cs b/src/RynthCore.Engine/MainThreadHangWatchdog.cs index 26c0d6c..d1fae1a 100644 --- a/src/RynthCore.Engine/MainThreadHangWatchdog.cs +++ b/src/RynthCore.Engine/MainThreadHangWatchdog.cs @@ -19,6 +19,20 @@ // // This captures the exact wedge location for every client, on every freeze, // with no external debugger and no per-PID coordination. +// +// 2026-11-01 (a client hung for good on a hot reload, 10-31 21:17): +// * The hang dump (after six samples, as before) is written out of process: rundll32 +// runs RynthCore.SehTrampoline.dll's RC_DumpProcess (CrashDump.WriteHangDumpOutOfProcess). It was +// MiniDumpWriteDump on this process: dbghelp suspends every other thread and then +// allocates from the process heap, so a main thread suspended inside RtlAllocateHeap +// (the font atlas build) deadlocked the whole process; on the clients that +// recovered it froze every thread for 8-10 s on top of the reload stall. +// * SuspendThread / GetThreadContext / ResumeThread skip the GC transition: a GC +// starting while this thread held the main thread suspended would otherwise stop +// this thread at the P/Invoke return, and the GC would wait for ever for the main +// thread it can't run. +// * Step: what the engine is doing on AC's main thread (EndScene, ImGui init's +// parts), logged with the hang, so a stall inside the engine names its step. // ============================================================================ using System; @@ -35,14 +49,16 @@ internal static class MainThreadHangWatchdog [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr OpenThread(uint dwDesiredAccess, bool bInheritHandle, uint dwThreadId); - [DllImport("kernel32.dll")] + // No GC transition between suspending the main thread and resuming it (see the header): + // these three are short kernel calls that never call back into managed code. + [DllImport("kernel32.dll"), SuppressGCTransition] private static extern uint SuspendThread(IntPtr hThread); - [DllImport("kernel32.dll")] + [DllImport("kernel32.dll"), SuppressGCTransition] private static extern uint ResumeThread(IntPtr hThread); - [DllImport("kernel32.dll", SetLastError = true)] - private static extern bool GetThreadContext(IntPtr hThread, IntPtr lpContext); + [DllImport("kernel32.dll"), SuppressGCTransition] + private static extern int GetThreadContext(IntPtr hThread, IntPtr lpContext); [DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr hObject); @@ -59,6 +75,13 @@ internal static class MainThreadHangWatchdog // While a wedge lasts, the "still hung" line is repeated this often. private const long StillHungRepeatMs = 20_000; + /// + /// What the engine is doing on AC's main thread, set at a few steps of the EndScene + /// detour and of ImGui init; null = outside the engine (AC's own code). Logged with a + /// hang. A constant string per step (no allocation on AC's thread). + /// + internal static volatile string? Step; + /// "unhandled ACCESS_VIOLATION at acclient.exe+0x18712F" when the current hang is a crash dialog. internal static volatile string? CrashCause; @@ -181,6 +204,7 @@ internal static class MainThreadHangWatchdog hangStartBeat = lastBeat; RynthLog.Info("================================================================"); RynthLog.Error($"==== MAIN THREAD HANG DETECTED tid={tid} build={EntryPoint.BuildStamp} initCount={EntryPoint.InitCount} (stalled {stale}ms) ===="); + RynthLog.Error($" main thread step: {Step ?? "outside the engine (AC's own code)"}"); // A modal dialog (AC's error MessageBox) holds the main thread: say which. string? box = Compatibility.MessageBoxHooks.Describe(); if (box != null) RynthLog.Error($" hang cause: {box}"); @@ -204,9 +228,8 @@ internal static class MainThreadHangWatchdog sample++; RynthLog.Info($" (still hung after {MaxSamplesPerHang} samples — suppressing further samples until recovery)"); lastStillHungLog = Environment.TickCount64; - // Confirmed permanent wedge (~10s+): write one targeted - // minidump for WinDbg post-mortem if the log stack walk - // isn't enough. Once per session. + // Confirmed long wedge (~10s+): one minidump for a post-mortem when + // the log stack walk isn't enough, written out of process. Once per session. TryWriteHangDump(tid, stale); } else if (Environment.TickCount64 - lastStillHungLog >= StillHungRepeatMs) @@ -255,8 +278,9 @@ internal static class MainThreadHangWatchdog RynthLog.Info($" (hang minidump skipped: the full-memory dump {full} already covers this hang)"); return; } - CrashDump.WriteSelfDump( - $"main-thread hang tid={tid} stale={staleMs}ms build={EntryPoint.BuildStamp}", out _); + // Out of process (rundll32 + SehTrampoline), never MiniDumpWriteDump on this process: see the header. + CrashDump.WriteHangDumpOutOfProcess( + $"main-thread hang tid={tid} stale={staleMs}ms step={Step ?? "outside the engine"} build={EntryPoint.BuildStamp}", out _); } catch { /* a diagnostic must never destabilize the host */ } } @@ -384,7 +408,7 @@ internal static class MainThreadHangWatchdog suspendCount = SuspendThread(h); if (suspendCount != 0xFFFFFFFF) { - ctxOk = GetThreadContext(h, ctx); + ctxOk = GetThreadContext(h, ctx) != 0; ResumeThread(h); } @@ -395,7 +419,7 @@ internal static class MainThreadHangWatchdog } uint eip = (uint)Marshal.ReadInt32(ctx, CTX_OFF_EIP); - RynthLog.Info($" sample#{sampleNum} (stale {staleMs}ms) eip=0x{eip:X8} {CrashLogger.ResolveCodeAddr((IntPtr)eip)}"); + RynthLog.Info($" sample#{sampleNum} (stale {staleMs}ms) eip=0x{eip:X8} {CrashLogger.ResolveCodeAddr((IntPtr)eip)} step={Step ?? "outside the engine"}"); if (fullStack) { diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs index 506178f..1e707e0 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettings.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs @@ -45,6 +45,8 @@ internal static class EngineSettings private static bool _borderlessWindowed; // Settings > Display: reopen Rynth panels where they were (default on: panels have always been remembered). private static bool _rememberWindowLayout = true; + // Settings > Display: each character keeps its own panel layout (default on; off = the one shared layout). + private static bool _panelLayoutPerCharacter = true; // Settings > Display: save and restore the AC window's own position and size (default off, opt-in). private static bool _rememberAcWindowPosition; // "LoadAllServerPlugins": hand-set only, written back only when true (PluginManifestGate). @@ -55,6 +57,9 @@ internal static class EngineSettings // leaves the world, for at most _holdReloadInWorldMaxMinutes (ReloadInWorldGate). private static bool _holdReloadInWorld; private static int _holdReloadInWorldMaxMinutes = ReloadInWorldGate.DefaultMaxMinutes; + // Settings > Diagnostics: the UI frame cost breakdown (ImGui/UiCost.cs; default on, 50 ms). + private static bool _uiCostLog = true; + private static int _uiCostThresholdMs = ImGuiBackend.UiCostModel.DefaultThresholdMs; // "IltServerNames" / "IltHosts": what counts as Infinite Leaftide (Compatibility/IltInfo.cs). // null = not in the file: IltDetect's defaults. private static List? _iltServerNames; @@ -468,6 +473,27 @@ internal static class EngineSettings } } + /// "PanelLayoutPerCharacter" in engine.json (default true): in the world each character + /// uses its own panel layout (%LOCALAPPDATA%\RynthCore\layouts\<server>\<character>\ + /// panel_state.txt and imgui.ini, UI/PanelLayout), so clients on one PC don't move each other's + /// panels. Off: every client uses the one PC-wide layout, as before. Set in game in Settings > + /// Display: the client it is set in switches at once, the others as they start. + public static bool PanelLayoutPerCharacter + { + get + { + EnsureLoaded(); + return _panelLayoutPerCharacter; + } + set + { + EnsureLoaded(); + if (_panelLayoutPerCharacter == value) return; + _panelLayoutPerCharacter = value; + Save("PanelLayoutPerCharacter"); + } + } + /// "RememberAcWindowPosition" in engine.json (default false, opt-in): save the Asheron's /// Call window's position and size per character and put it back at the next login. /// Set in game in Settings > Display. @@ -545,6 +571,47 @@ internal static class EngineSettings } } + /// "UiCostLog" in engine.json (default true): time the parts of each UI frame (panels by + /// title, plugin callbacks, the monster HUD, pop-outs, the ImGui submit; ImGui/UiCost.cs) and log one + /// "[UiCost]" line for a frame at or over , at most every 5 s. Off: no + /// timing at all. Only a false is written to the file. Settings > Diagnostics, /rc uicost on|off. + public static bool UiCostLog + { + get + { + EnsureLoaded(); + return _uiCostLog; + } + set + { + EnsureLoaded(); + if (_uiCostLog == value) return; + _uiCostLog = value; + Save("UiCostLog"); + } + } + + /// "UiCostThresholdMs" in engine.json (default 50, valid 5-2000): a UI frame this slow is + /// logged with its breakdown (), and the heartbeat names the top parts while + /// its ui p95 is over it. Clamped; only a non-default value is written. Settings > Diagnostics, + /// /rc uicost <ms>. + public static int UiCostThresholdMs + { + get + { + EnsureLoaded(); + return _uiCostThresholdMs; + } + set + { + EnsureLoaded(); + int v = ImGuiBackend.UiCostModel.ClampThresholdMs(value); + if (_uiCostThresholdMs == v) return; + _uiCostThresholdMs = v; + Save("UiCostThresholdMs"); + } + } + /// "ReportEndpoint" in engine.json: a test URL for "Report a problem" instead of the /// built-in https://aelrynth.com/rynth/report (ProblemReportCore.ResolveEndpoint accepts https, /// or http to this PC; anything else is ignored). Null when the file has none. Edited in the file. @@ -807,6 +874,10 @@ internal static class EngineSettings (rwlEl.ValueKind == JsonValueKind.True || rwlEl.ValueKind == JsonValueKind.False)) _rememberWindowLayout = rwlEl.GetBoolean(); + if (doc.RootElement.TryGetProperty("PanelLayoutPerCharacter", out var plpcEl) && + (plpcEl.ValueKind == JsonValueKind.True || plpcEl.ValueKind == JsonValueKind.False)) + _panelLayoutPerCharacter = plpcEl.GetBoolean(); + if (doc.RootElement.TryGetProperty("RememberAcWindowPosition", out var rapEl) && (rapEl.ValueKind == JsonValueKind.True || rapEl.ValueKind == JsonValueKind.False)) _rememberAcWindowPosition = rapEl.GetBoolean(); @@ -825,6 +896,15 @@ internal static class EngineSettings hrimEl.TryGetInt32(out int hrim)) _holdReloadInWorldMaxMinutes = ReloadInWorldGate.ClampMaxMinutes(hrim); + if (doc.RootElement.TryGetProperty("UiCostLog", out var uclEl) && + (uclEl.ValueKind == JsonValueKind.True || uclEl.ValueKind == JsonValueKind.False)) + _uiCostLog = uclEl.GetBoolean(); + + if (doc.RootElement.TryGetProperty("UiCostThresholdMs", out var uctEl) && + uctEl.ValueKind == JsonValueKind.Number && + uctEl.TryGetInt32(out int uct)) + _uiCostThresholdMs = ImGuiBackend.UiCostModel.ClampThresholdMs(uct); + if (doc.RootElement.TryGetProperty("ReportEndpoint", out var repEl) && repEl.ValueKind == JsonValueKind.String && repEl.GetString() is { Length: > 0 } rep) @@ -911,6 +991,8 @@ internal static class EngineSettings "MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", "AutoIdMode", "EnablePluginOverlayWindows", "LoggingLevel", "LoadAllServerPlugins", "TransitionGate", "HoldReloadInWorld", "HoldReloadInWorldMaxMinutes", + "PanelLayoutPerCharacter", + "UiCostLog", "UiCostThresholdMs", }; // The engine.json keys this client changed this session. Every client keeps the whole settings @@ -980,6 +1062,8 @@ internal static class EngineSettings w.WriteBoolean("BorderlessWindowed", true); if (!_rememberWindowLayout) // default true: leave the file as it was w.WriteBoolean("RememberWindowLayout", false); + if (!_panelLayoutPerCharacter) // default true: leave the file as it was + w.WriteBoolean("PanelLayoutPerCharacter", false); if (_rememberAcWindowPosition) // default false: leave the file as it was w.WriteBoolean("RememberAcWindowPosition", true); if (!_closeOnServerDisconnect) // default true: leave the file as it was @@ -994,6 +1078,10 @@ internal static class EngineSettings w.WriteBoolean("HoldReloadInWorld", true); if (_holdReloadInWorldMaxMinutes != ReloadInWorldGate.DefaultMaxMinutes) // only a non-default value is written w.WriteNumber("HoldReloadInWorldMaxMinutes", _holdReloadInWorldMaxMinutes); + if (!_uiCostLog) // default true: only a false is written + w.WriteBoolean("UiCostLog", false); + if (_uiCostThresholdMs != ImGuiBackend.UiCostModel.DefaultThresholdMs) // only a non-default value is written + w.WriteNumber("UiCostThresholdMs", _uiCostThresholdMs); if (_reportEndpoint != null) // only a hand-set value is written w.WriteString("ReportEndpoint", _reportEndpoint); WriteStringList(w, "IltServerNames", _iltServerNames); // null (not in the file): left out diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index f3c8290..9fb87b5 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -811,7 +811,8 @@ internal struct RynthCoreAPI /// which v77 callbacks can arrive. bit0 RynthPluginOnScreenChanged from the UseNewMode hook, /// bit1 ... from the +0x8C mode poll instead (one tick late), bit2 RynthPluginOnClientCleanup, /// bit3 RynthPluginOnTooltipShow, bit4 RynthPluginOnTooltipHide, bit5 RynthPluginOnDragStart, - /// bit6 RynthPluginOnItemDropped, bit7 Client::Cleanup has started. Any thread. + /// bit6 RynthPluginOnItemDropped, bit7 Client::Cleanup has started, bit8 (2026-10-30, not a hook) + /// the Damage panel draws a RynthPluginGetMonsterDamageJson row's "mstats". Any thread. /// Requires API v77+. public IntPtr GetUiHookFlagsFn; diff --git a/src/RynthCore.Engine/Plugins/PluginManager.UiHooks.cs b/src/RynthCore.Engine/Plugins/PluginManager.UiHooks.cs index ec1dfc8..188a57a 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.UiHooks.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.UiHooks.cs @@ -277,6 +277,9 @@ internal static partial class PluginManager if (UiElementHooks.DragStartLive) flags |= 1u << 5; if (UiElementHooks.DropLive) flags |= 1u << 6; if (UiFlowHooks.ClientCleanupStarted) flags |= 1u << 7; + // Not a hook: the Damage panel draws a row's "mstats" (UI/Data/DamageRowStats.cs, 2026-10-30), so + // RynthAi shows its monster stats there instead of its own window. No API version change. + flags |= 1u << 8; return flags; } } diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index bc9976e..19576f0 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -745,6 +745,8 @@ internal static partial class PluginManager public static void QueueSelectedTargetChange(uint currentTargetId, uint previousTargetId) { ImGuiBackend.Hud.HudFeed.OnSelection(currentTargetId); // debuff target matching + // A selection makes the client query its health: the server's health stream follows it (HealthProbe). + ImGuiBackend.Hud.HealthProbe.NoteQuery(currentTargetId); if (!_initialized || _plugins.Count == 0) return; @@ -924,13 +926,21 @@ internal static partial class PluginManager } } - public static void QueueUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) + /// + /// One health observation. : it is a 0x01C0 UpdateHealth (a QueryHealth + /// reply or the server's stream); one that answers the nameplates' own probe (HealthProbe) is the + /// HUD's alone - plugins never asked for it, and a bot must not read someone else's hit on a monster + /// it isn't fighting as its own. + /// + public static void QueueUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth, bool healthReply = false) { // Monster nameplates keep the last ratio per object (engine-side, plugins or not). ImGuiBackend.Hud.MonsterHudData.RecordHealth(targetId, healthRatio, currentHealth, maxHealth); if (_plugins.Count == 0) return; + if (healthReply && ImGuiBackend.Hud.HealthProbe.IsProbeReply(targetId, Environment.TickCount64)) + return; lock (PendingUpdateHealthLock) { @@ -1212,6 +1222,7 @@ internal static partial class PluginManager if (!plugin.Initialized || plugin.Failed || plugin.Render == null) continue; + long cost = ImGuiBackend.UiCost.Start(); // UiCost: each plugin's Render, by name try { plugin.Render(); @@ -1221,6 +1232,7 @@ internal static partial class PluginManager plugin.Failed = true; RynthLog.Error($"PluginManager: {plugin.DisplayName} Render threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)} - disabled."); } + ImGuiBackend.UiCost.StopPluginRender(plugin.DisplayName, cost); } } @@ -1286,6 +1298,7 @@ internal static partial class PluginManager RynthLog.Plugin($"PluginManager: first RenderOverlay call for {plugin.DisplayName}."); } + long cost = ImGuiBackend.UiCost.Start(); // UiCost: each plugin's RenderOverlay, by name try { overlay(); @@ -1295,6 +1308,7 @@ internal static partial class PluginManager plugin.RenderOverlay = null; RynthLog.Error($"PluginManager: {plugin.DisplayName} RenderOverlay threw {ex.GetType().Name}: {ex.Message} - overlay windows off for this session (plugin keeps running)."); } + ImGuiBackend.UiCost.StopPluginOverlay(plugin.DisplayName, cost); } } diff --git a/src/RynthCore.Engine/UI/AcWindowChrome.cs b/src/RynthCore.Engine/UI/AcWindowChrome.cs index c1753ff..4a55b9f 100644 --- a/src/RynthCore.Engine/UI/AcWindowChrome.cs +++ b/src/RynthCore.Engine/UI/AcWindowChrome.cs @@ -275,23 +275,16 @@ internal static class AcWindowChrome try { + // To the imgui.ini of the panel layout in use (this character's, or the PC-wide default). if (ImGuiNET.ImGui.GetCurrentContext() != IntPtr.Zero) - { - string ini = ImGuiNET.ImGui.SaveIniSettingsToMemory(); - string iniPath = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "imgui.ini"); - UiBackgroundWriter.Enqueue("imgui.ini", () => - { - Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir); - File.WriteAllText(iniPath, ini); - }); - } + PanelLayout.QueueIniSave(ImGuiNET.ImGui.SaveIniSettingsToMemory(), explicitSave: true); } catch (Exception ex) { try { RynthLog.UI($"AcWindowChrome: imgui.ini save failed - {ex.Message}"); } catch { } } - // Rewrites panel_state.txt from the in-memory state (even with Remember Open Windows off). + // Rewrites the layout's panel_state.txt from the in-memory state (even with Remember Open Windows off). UiBackgroundWriter.Enqueue("panel state (save now)", PanelStateStore.Flush); try diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index 9b39002..0924e28 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -20,10 +20,12 @@ // Copy it to a tab as well (it stays where it was), // Hide it everywhere, or // Colour it only, -// and it can colour the whole line or just the matched text. Order: top to -// bottom. Copy rules add up; the first matching Move or Hide decides and -// stops the routing. The first matching line colour wins; matched-text -// colours add up, a higher rule winning where two overlap. +// and it can colour the whole line, just the matched text, or (2026-11-01) +// highlight the line with a band behind it. Order: top to bottom. Copy rules +// add up; the first matching Move or Hide decides and stops the routing. The +// first matching line colour wins, and so does the first matching highlight +// (on its own: a line can have both); matched-text colours add up, a higher +// rule winning where two overlap. // // Threads: rules are evaluated ONLY on the pump (ChatSource) - each new line // once, and every kept line again when the rules change (in 8 ms slices, newest @@ -866,7 +868,8 @@ internal static class ChatModel _ => "move", }, When = f.When.Length > 0 ? f.When : null, - ColorMode = f.ColorMode switch { ChatColorMode.Line => "line", ChatColorMode.Match => "match", _ => null }, + // "highlight" since 2026-11-01; an older RynthCore reads it as no colour (ChatColorModes.Parse). + ColorMode = ChatColorModes.ToJson(f.ColorMode), // Kept while the rule is set to "No colour" too, so switching colour back on // after a relaunch finds the colour that was picked. Color = f.ColorMode != ChatColorMode.None || f.ColorArgb != ChatFilterRule.DefaultColor ? FormatColor(f.ColorArgb) : null, @@ -897,12 +900,7 @@ internal static class ChatModel _ => tab.Length == 0 ? ChatRuleAction.Hide : ChatRuleAction.Move, }, When = f.When ?? "", - ColorMode = (f.ColorMode ?? "").ToLowerInvariant() switch - { - "line" => ChatColorMode.Line, - "match" or "text" => ChatColorMode.Match, - _ => ChatColorMode.None, - }, + ColorMode = ChatColorModes.Parse(f.ColorMode), ColorArgb = ParseColor(f.Color) ?? ChatFilterRule.DefaultColor, // Absent (every file before 2026-10-05): Regex, as those rules always were. Mode = ChatRuleMatching.Parse(f.Mode), @@ -1330,6 +1328,8 @@ internal static class ChatModel // rynthchat_settings.v1.bak, and the next save writes version 2. // "lineColors" (2026-10-08, ChatLineColors) is written only once a colour // is set, so it needs no version bump: a file without it loads as before. + // "colorMode": "highlight" (2026-11-01) needs none either: "colorMode" is a + // string, and a RynthCore without it reads an unknown value as no colour. public const int SettingsVersion = 2; private static readonly object SaveLock = new(); diff --git a/src/RynthCore.Engine/UI/Data/ChatRouting.cs b/src/RynthCore.Engine/UI/Data/ChatRouting.cs index 17e34ec..2eb3b3d 100644 --- a/src/RynthCore.Engine/UI/Data/ChatRouting.cs +++ b/src/RynthCore.Engine/UI/Data/ChatRouting.cs @@ -75,7 +75,7 @@ internal sealed class ChatRoute { public static readonly ChatRoute Default = new(false, true, null, null, null, false); - public ChatRoute(bool hidden, bool inHome, string[]? tabs, uint? lineArgb, ChatSpan[]? spans, bool mention) + public ChatRoute(bool hidden, bool inHome, string[]? tabs, uint? lineArgb, ChatSpan[]? spans, bool mention, uint? highlightArgb = null) { Hidden = hidden; InHome = inHome; @@ -83,6 +83,7 @@ internal sealed class ChatRoute LineArgb = lineArgb; Spans = spans; Mention = mention; + HighlightArgb = highlightArgb; } /// A Hide rule matched: shown nowhere. @@ -97,6 +98,10 @@ internal sealed class ChatRoute public ChatSpan[]? Spans { get; } /// Someone said your name (or a mention word). public bool Mention { get; } + /// A "Highlight line" rule's colour (its swatch, 0xAARRGGBB): a band behind the + /// whole line, drawn at ; null = no band. The text + /// keeps its own colour (LineArgb or the channel's). + public uint? HighlightArgb { get; } public bool ShowsIn(string tab, string channel) { @@ -121,7 +126,52 @@ internal enum ChatRuleAction Color, } -internal enum ChatColorMode { None, Line, Match } +/// +/// What a rule's colour does. Line: the line's text colour. Match: only the matched text. +/// Highlight (2026-11-01): a band in the colour behind the whole line, text in its own colour. +/// New values go at the end: the editor's dropdown is indexed by the value. +/// +internal enum ChatColorMode { None, Line, Match, Highlight } + +/// +/// "colorMode" in rynthchat_settings.json and Export / Import, and the highlight band's colour. +/// Kept apart from ChatModel so tools/ChatFilterTests can check them. +/// +internal static class ChatColorModes +{ + /// The value written to JSON; null (no key) for None, as every file before. + public static string? ToJson(ChatColorMode mode) => mode switch + { + ChatColorMode.Line => "line", + ChatColorMode.Match => "match", + ChatColorMode.Highlight => "highlight", + _ => null, + }; + + /// + /// Any case; "text" is an old spelling of "match". Unknown or absent: None. (A RynthCore + /// from before 2026-11-01 reads "highlight" the same way, as None: the rule loads, routes + /// as before and keeps its colour, it just doesn't colour.) + /// + public static ChatColorMode Parse(string? json) => (json ?? "").Trim().ToLowerInvariant() switch + { + "line" => ChatColorMode.Line, + "match" or "text" => ChatColorMode.Match, + "highlight" or "band" => ChatColorMode.Highlight, + _ => ChatColorMode.None, + }; + + /// How opaque the band is for an opaque swatch (0x66 = 40%). + public const uint BandAlpha = 0x66; + + /// + /// The band drawn for a highlight colour: its RGB at 40% of its own alpha. The editor's + /// swatch is RGB only (always opaque), and at full strength a band in a light colour would + /// drown the text, which keeps its normal (often light) colour; 40% reads on the dark chat + /// with any text colour. An imported translucent colour ("#80RRGGBB") comes out fainter still. + /// + public static uint BandArgb(uint argb) => ((argb >> 24) * BandAlpha / 0xFF) << 24 | (argb & 0x00FFFFFF); +} /// /// One rule. Its fields are edited in place by a rule editor (then @@ -305,7 +355,7 @@ internal sealed class ChatRouter { bool hidden = false, inHome = true, routed = false; List? tabs = null; - uint? lineArgb = null; + uint? lineArgb = null, highlightArgb = null; List<(int Start, int Length, uint Argb)>? spans = null; for (int i = 0; i < _rules.Length; i++) @@ -322,8 +372,11 @@ internal sealed class ChatRouter bool wantsRoute = routes && !routed; bool wantsLine = mode == ChatColorMode.Line && lineArgb == null; bool wantsMatch = mode == ChatColorMode.Match; + // The band works like the line colour, on its own: the first Highlight rule that + // matches picks it, whatever Line / Match rules did (they colour the text on top). + bool wantsHighlight = mode == ChatColorMode.Highlight && highlightArgb == null; // Nothing left for it to decide (the test box still shows that it matches). - if (!wantsRoute && !wantsLine && !wantsMatch && trace == null) continue; + if (!wantsRoute && !wantsLine && !wantsMatch && !wantsHighlight && trace == null) continue; if (!rule.WhenMatches(channel, chatType)) continue; Match m; @@ -369,6 +422,13 @@ internal sealed class ChatRouter } else if (mode == ChatColorMode.Line && trace != null) what!.Append(what.Length > 0 ? ", " : "").Append("(line colour already set above)"); + if (wantsHighlight) + { + highlightArgb = rule.ColorArgb; + what?.Append(what.Length > 0 ? ", " : "").Append("highlights the line"); + } + else if (mode == ChatColorMode.Highlight && trace != null) + what!.Append(what.Length > 0 ? ", " : "").Append("(highlight already set above)"); if (wantsMatch) { int n = 0; @@ -427,9 +487,9 @@ internal sealed class ChatRouter if (mention) trace?.Add(new Step(-1, "mentions you (highlighted)")); } - if (!hidden && inHome && tabs == null && lineArgb == null && spans == null && !mention) + if (!hidden && inHome && tabs == null && lineArgb == null && highlightArgb == null && spans == null && !mention) return ChatRoute.Default; - return new ChatRoute(hidden, inHome, tabs?.ToArray(), lineArgb, Resolve(spans, text.Length), mention); + return new ChatRoute(hidden, inHome, tabs?.ToArray(), lineArgb, Resolve(spans, text.Length), mention, highlightArgb); } private static void AddTab(ref List? tabs, string tab) diff --git a/src/RynthCore.Engine/UI/Data/DamageData.cs b/src/RynthCore.Engine/UI/Data/DamageData.cs index 151df71..781e4d1 100644 --- a/src/RynthCore.Engine/UI/Data/DamageData.cs +++ b/src/RynthCore.Engine/UI/Data/DamageData.cs @@ -61,6 +61,9 @@ internal sealed class DamageRow public List Tiers = new(); /// The synthetic top "Default" line (wcid 0). public bool IsDefault; + /// Evades, resists, attacks and spells both ways since login (the row's optional "mstats", + /// DamageRowStats.cs); null when the plugin sends none. + public DamageRowStats? Stats; } internal sealed class DamageTierStat @@ -303,6 +306,7 @@ internal sealed unsafe class DamageSource : UiSource if (e.TryGetProperty("hitRate", out var hr)) row.HitRate = hr.GetDouble(); if (e.TryGetProperty("targeted", out var tg)) row.Targeted = tg.GetBoolean(); if (e.TryGetProperty("nearby", out var nb)) row.Nearby = nb.GetBoolean(); + row.Stats = DamageRowStats.Parse(e); if (e.TryGetProperty("tiers", out var tarr) && tarr.ValueKind == JsonValueKind.Array) foreach (JsonElement te in tarr.EnumerateArray()) row.Tiers.Add(new DamageTierStat diff --git a/src/RynthCore.Engine/UI/Data/DamageRowStats.cs b/src/RynthCore.Engine/UI/Data/DamageRowStats.cs new file mode 100644 index 0000000..1d36ac3 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/DamageRowStats.cs @@ -0,0 +1,92 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/DamageRowStats.cs +// A Damage panel row's combat numbers since login (or the plugin's reset), as +// the plugin sends them: the optional "mstats" object of a row of +// RynthPluginGetMonsterDamageJson (RynthAi 2026-10-30, a player's request: +// "combat statistics under individual monsters, evades/resists for both the +// player and the monster"). DamageFace draws Line() under the monster's row and +// Tip() over it. A plugin that sends no "mstats" gets no line (as before). +// +// "mstats": { "sw": swings, "ev": evaded, "sp": spells, "rs": resisted, "ne": no effect, +// "at": attacks, "yev": you evaded, "ysp": spells at you, "yrs": you resisted, +// "yne": no effect on you, "k": kills, "dd": damage dealt, "dt": damage taken } +// +// sw = your melee and missile attacks at it (hits + its evades), sp = your spells that +// reached it (landed + resisted + no effect); at / ysp the same from it to you. Missing +// numbers are 0. The engine only words them; the plugin counts. +// +// Pure (System.Text.Json only): tools/DamageRowStatsTests compiles this file as is. +// The plugin sees an engine that draws them through GetUiHookFlags bit 8. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.Json; + +namespace RynthCore.Engine.UI.Data; + +internal sealed record DamageRowStats( + int Swings, int Evaded, int Spells, int Resisted, int NoEffect, + int Attacks, int YouEvaded, int SpellsAtYou, int YouResisted, int NoEffectOnYou, + int Kills, long Dealt, long Taken) +{ + /// The row's "mstats", or null when it has none (or nothing counted in it). + public static DamageRowStats? Parse(JsonElement row) + { + if (row.ValueKind != JsonValueKind.Object || !row.TryGetProperty("mstats", out JsonElement m) || m.ValueKind != JsonValueKind.Object) + return null; + var s = new DamageRowStats(I(m, "sw"), I(m, "ev"), I(m, "sp"), I(m, "rs"), I(m, "ne"), + I(m, "at"), I(m, "yev"), I(m, "ysp"), I(m, "yrs"), I(m, "yne"), I(m, "k"), L(m, "dd"), L(m, "dt")); + return s.IsEmpty ? null : s; + } + + public bool IsEmpty => Swings == 0 && Spells == 0 && Attacks == 0 && SpellsAtYou == 0 && Kills == 0; + + /// "23%" (whole from 10% up), "4.5%" (one decimal below), "-" with nothing to divide by. RynthAi words it the same. + public static string Percent(int part, int whole) + { + if (whole <= 0) return "-"; + double p = Math.Clamp((double)part / whole, 0, 1) * 100; + p = p >= 10 ? Math.Round(p, MidpointRounding.AwayFromZero) : Math.Round(p, 1, MidpointRounding.AwayFromZero); + return p.ToString("0.#", CultureInfo.InvariantCulture) + "%"; + } + + /// + /// The line under the row: "It evades 23% (14/61) · It resists 10% (3/30) · You evade 42% (50/120) · + /// You resist 13% (1/8)", each part only when there is something to divide by; "" for none. + /// + public string Line() + { + var parts = new List(4); + if (Swings > 0) parts.Add($"It evades {Percent(Evaded, Swings)} ({N(Evaded)}/{N(Swings)})"); + if (Spells > 0) parts.Add($"It resists {Percent(Resisted, Spells)} ({N(Resisted)}/{N(Spells)})"); + if (Attacks > 0) parts.Add($"You evade {Percent(YouEvaded, Attacks)} ({N(YouEvaded)}/{N(Attacks)})"); + if (SpellsAtYou > 0) parts.Add($"You resist {Percent(YouResisted, SpellsAtYou)} ({N(YouResisted)}/{N(SpellsAtYou)})"); + return string.Join(" · ", parts); + } + + /// The tooltip: both ways in full. + public string Tip() + { + string noEffect = NoEffect > 0 ? $", {N(NoEffect)} no effect (immune)" : ""; + string noEffectYou = NoEffectOnYou > 0 ? $", {N(NoEffectOnYou)} no effect (immune)" : ""; + return "Since you logged in (or /ra mstats reset):\n" + + $"You at it: {N(Swings)} melee/missile attacks, {N(Swings - Evaded)} hit, it evaded {N(Evaded)} ({Percent(Evaded, Swings)}); " + + $"{N(Spells)} spells reached it, it resisted {N(Resisted)} ({Percent(Resisted, Spells)}){noEffect}; " + + $"{N(Dealt)} damage, {N(Kills)} {(Kills == 1 ? "kill" : "kills")}.\n" + + $"It at you: {N(Attacks)} melee/missile attacks, {N(Attacks - YouEvaded)} hit, you evaded {N(YouEvaded)} ({Percent(YouEvaded, Attacks)}); " + + $"{N(SpellsAtYou)} spells reached you, you resisted {N(YouResisted)} ({Percent(YouResisted, SpellsAtYou)}){noEffectYou}; " + + $"{N(Taken)} damage.\n" + + "The killing blow counts as a hit (melee, missile) or a landed spell (magic)."; + } + + private static string N(long v) => v.ToString("N0", CultureInfo.InvariantCulture); + + private static int I(JsonElement m, string key) + => m.TryGetProperty(key, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long x) + ? (int)Math.Clamp(x, 0, int.MaxValue) : 0; + + private static long L(JsonElement m, string key) + => m.TryGetProperty(key, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long x) ? Math.Max(0, x) : 0; +} diff --git a/src/RynthCore.Engine/UI/Data/LuaData.cs b/src/RynthCore.Engine/UI/Data/LuaData.cs index 295cc7d..c34ba6a 100644 --- a/src/RynthCore.Engine/UI/Data/LuaData.cs +++ b/src/RynthCore.Engine/UI/Data/LuaData.cs @@ -43,6 +43,8 @@ internal sealed class LuaPayload public bool? RynthAi { get; set; } /// A character is logged in (per-character autostart needs one). Null from older plugins. public bool? LoggedIn { get; set; } + /// Live reload: a running script restarts when its file is saved (/lua livereload). Null from a RynthLua without it. + public bool? LiveReload { get; set; } } /// One script in the v2 list (RynthLua's LuaScriptInfo). @@ -140,4 +142,14 @@ internal static unsafe class LuaCommands UiSources.Lua.RequestRefreshAfterPluginTick(); }); } + + /// + /// /lua <args> as if typed (it answers in chat), through RynthLua's remote command ("lua", args), + /// for a setting the panel command doesn't carry (live reload). Pump thread, like Send. + /// + public static void Chat(string args) => UiDataHub.Post("Lua /lua " + args, () => + { + if (PluginManager.SendPluginCommand("RynthLua", "lua", args)) + UiSources.Lua.RequestRefreshAfterPluginTick(); + }); } diff --git a/src/RynthCore.Engine/UI/Data/LuaLiveReload.cs b/src/RynthCore.Engine/UI/Data/LuaLiveReload.cs new file mode 100644 index 0000000..aeb594f --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/LuaLiveReload.cs @@ -0,0 +1,29 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/LuaLiveReload.cs +// The Lua panel's live reload toggle (2026-10-31: the owner asked for buttons, +// not only commands): RynthLua's /lua livereload on|off, shown when its panel +// payload says LiveReload (a RynthLua without live reload sends nothing, and +// the toggle isn't drawn). What it says and the /lua arguments a click sends +// (LuaCommands.Chat). Pure, so tools\ChatCommandReplyTests compiles it in. +// ============================================================================ + +namespace RynthCore.Engine.UI.Data; + +internal static class LuaLiveReload +{ + /// The toggle's caption, or null when this RynthLua has no live reload (the toggle isn't drawn). + public static string? Label(bool? on) => on switch + { + true => "Live reload: on", + false => "Live reload: off", + _ => null, + }; + + /// The /lua arguments a click sends: the other value. + public static string ClickArgs(bool on) => on ? "livereload off" : "livereload on"; + + public static string Tip(bool on) => + (on ? "On: a running script restarts when you save its file (or one it requires). Click to turn it off." + : "Off: saving a script's file doesn't restart it. Click to turn live reload on.") + + "\nAlso: /lua livereload on|off"; +} diff --git a/src/RynthCore.Engine/UI/Data/MetaData.cs b/src/RynthCore.Engine/UI/Data/MetaData.cs index 362df73..4bea706 100644 --- a/src/RynthCore.Engine/UI/Data/MetaData.cs +++ b/src/RynthCore.Engine/UI/Data/MetaData.cs @@ -19,6 +19,7 @@ using System.Runtime.InteropServices; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; +using System.Threading; using RynthCore.Engine.Plugins; namespace RynthCore.Engine.UI.Data; @@ -113,6 +114,9 @@ internal sealed class MetaPayload public string SourceText { get; set; } = string.Empty; /// Null from a plugin that doesn't report apply results yet (it reports to chat). public MetaApplyResult? ApplyResult { get; set; } + /// The last write of the meta file, or the edit that wasn't applied (RynthAi's MetaSaver, + /// 2026-11-01); null from a RynthAi without it. The "Saved" indicator follows this. + public MetaSaveResult? SaveResult { get; set; } /// The Meta Manager; null from a RynthAi without it. public SchedulePayload? Schedule { get; set; } /// Seconds in state and the Watchdog; null from a RynthAi without it. @@ -179,28 +183,47 @@ internal sealed unsafe class MetaSource : UiSource internal static unsafe class MetaCommands { private static delegate* unmanaged[Cdecl] _sendMetaCommand; + private static int _undelivered; static MetaCommands() { PluginManager.PluginsUnloaded += () => _sendMetaCommand = null; } + /// Commands that never reached RynthAi (not loaded, no export, the hub refused the post). + /// The Meta panel compares it before and after an edit: it went up = "Not saved: not sent". + public static int Undelivered => Volatile.Read(ref _undelivered); + /// (and its Rule) must not be changed after this call. public static void Send(MetaCmd cmd) { - UiDataHub.Post("Meta " + cmd.Op, () => + bool posted = UiDataHub.Post("Meta " + cmd.Op, () => { if (_sendMetaCommand == null) _sendMetaCommand = (delegate* unmanaged[Cdecl])PluginExportBinder.Resolve("RynthAi", "RynthPluginSendMetaCommand"); - if (_sendMetaCommand == null) return; + if (_sendMetaCommand == null) + { + // Used to return without a word: the panel showed "Saved" for an edit RynthAi never got. + int n = Interlocked.Increment(ref _undelivered); + if (n <= 5 || n % 50 == 0) + RynthLog.UI($"Meta: '{cmd.Op}' NOT sent: RynthAi isn't loaded or has no RynthPluginSendMetaCommand ({n} not sent so far)."); + return; + } string json = JsonSerializer.Serialize(cmd, MetaJsonContext.Default.MetaCmd); IntPtr ansi = Marshal.StringToHGlobalAnsi(json); try { _sendMetaCommand(ansi); } finally { Marshal.FreeHGlobal(ansi); } + if (IsRuleEdit(cmd.Op)) + RynthLog.UI($"Meta: sent {cmd.Op}{(cmd.Index >= 0 ? " " + (cmd.Index + 1) : "")}{(cmd.Path.Length > 0 ? " " + cmd.Path : "")} to RynthAi."); UiSources.Meta.RequestRefreshAfterPluginTick(); }); + if (!posted) Interlocked.Increment(ref _undelivered); // the hub logged why } + /// The commands that change the meta's rules or file (RynthAi writes the file after each). + public static bool IsRuleEdit(string op) => op is "add_rule" or "update_rule" or "delete_rule" or "move_up" or "move_down" + or "duplicate_rule" or "set_rule_enabled" or "set_source" or "save_file"; + public static void Simple(string op, int index = -1, string value = "", string path = "") => Send(new MetaCmd { Op = op, Index = index, Value = value, Path = path }); diff --git a/src/RynthCore.Engine/UI/Data/MetaEditing.cs b/src/RynthCore.Engine/UI/Data/MetaEditing.cs index d07e71b..65bacaa 100644 --- a/src/RynthCore.Engine/UI/Data/MetaEditing.cs +++ b/src/RynthCore.Engine/UI/Data/MetaEditing.cs @@ -110,6 +110,77 @@ internal sealed class MetaBackupPlan public static string BackupOf(string file) => file + ".bak"; } +/// RynthAi's last write of the meta file, or the edit it didn't apply (the snapshot's "saveResult"). +internal sealed class MetaSaveResult +{ + /// Counts results this plugin session (0 = none yet). + public long Seq { get; set; } + public bool Ok { get; set; } = true; + /// What happened, in a few words ("Saved farm.af (12 rules)", "NOT saved to farm.af: ..."). + public string Text { get; set; } = string.Empty; + public string Path { get; set; } = string.Empty; +} + +/// What the Meta panel's save indicator shows. +internal enum MetaSaveState +{ + /// Every change so far was written (or nothing was changed). + Saved, + /// A change was sent; RynthAi hasn't answered yet. + Saving, + /// RynthAi answered: the write failed, or the edit wasn't applied (the result says why). + Failed, + /// The change never reached RynthAi (not loaded, no export). + NotSent, + /// Sent, but no answer after . + Unconfirmed, +} + +/// +/// The Meta panel's "Saved" indicator (2026-11-01). It used to show "Saving..." for 2.5 s after a +/// change and then "Saved", whatever happened: an edit RynthAi refused, one it couldn't write, one +/// that never reached it all looked saved, and the change was simply gone the next time the meta +/// loaded. Now it waits for RynthAi's answer: the snapshot's with a +/// newer than the one seen when the change was sent. A RynthAi +/// without results (null) keeps the old timer. +/// +internal sealed class MetaSaveWatch +{ + /// How long a change waits for RynthAi's answer before the indicator says it's not confirmed. + public const long ConfirmMs = 4000; + /// The old timer, for a RynthAi that reports no results. + public const long LegacySavingMs = 2500; + + private long _sentAt = -1; + private long _seqAtSend; + private int _undeliveredAtSend; + + /// A change was sent now; is the result seq the panel shows, + /// MetaCommands.Undelivered. + public void Sent(long nowMs, long seenSeq, int undelivered) + { + // A burst of changes waits for the answer to the newest one; a send while still waiting keeps + // the older count, so a command dropped earlier in the burst still shows. + if (_sentAt < 0) _undeliveredAtSend = undelivered; + _sentAt = nowMs; + _seqAtSend = seenSeq; + } + + /// The panel opened or another meta loaded: nothing is pending. + public void Reset() => _sentAt = -1; + + public MetaSaveState State(long nowMs, MetaSaveResult? result, int undelivered) + { + if (_sentAt >= 0 && undelivered > _undeliveredAtSend) return MetaSaveState.NotSent; + if (result == null) + return _sentAt >= 0 && nowMs - _sentAt < LegacySavingMs ? MetaSaveState.Saving : MetaSaveState.Saved; + if (_sentAt >= 0 && result.Seq <= _seqAtSend) + return nowMs - _sentAt < ConfirmMs ? MetaSaveState.Saving : MetaSaveState.Unconfirmed; + if (_sentAt >= 0) _sentAt = -1; // answered + return result.Seq > 0 && !result.Ok ? MetaSaveState.Failed : MetaSaveState.Saved; + } +} + /// Rule edits the editor makes. internal static class MetaRuleEdit { diff --git a/src/RynthCore.Engine/UI/Data/NavData.cs b/src/RynthCore.Engine/UI/Data/NavData.cs index bb3c984..d8ef9ce 100644 --- a/src/RynthCore.Engine/UI/Data/NavData.cs +++ b/src/RynthCore.Engine/UI/Data/NavData.cs @@ -139,8 +139,12 @@ internal static class NavCommands { "Replace route with the trail (walk it again)", "Replace route with a backtrack (walk it back)", + "Clear the trail (start a new one from here)", }; + /// The entry that wipes the trail (/ra navtrail clear) instead of making a route. + public const int TrailClearChoice = 2; + /// Route picker index for the plugin's RouteType (1 Circular, 2 Linear, 3 Follow, else Once). public static int RouteIndex(int routeType) => routeType switch { 1 => 1, 2 => 2, 3 => 3, _ => 0 }; diff --git a/src/RynthCore.Engine/UI/Data/SenseData.cs b/src/RynthCore.Engine/UI/Data/SenseData.cs index b91702a..fb37749 100644 --- a/src/RynthCore.Engine/UI/Data/SenseData.cs +++ b/src/RynthCore.Engine/UI/Data/SenseData.cs @@ -3,12 +3,14 @@ // Sense, our take on Virindi Sense: a watch list of names, and every object // the client knows about, anywhere, whose name matches one. // -// SenseStore the watch list and the alert settings, in +// SenseStore the watch list, the alert settings and the panel's look +// (full, compact, collapsed), in // %LocalAppData%\RynthCore\sense.txt (read and written on -// UiBackgroundWriter, never on AC's render thread). -// SensePattern one term, case-insensitive. Without wildcards the name only -// has to contain it ("drake" finds "Dragon's Isle Drake"); -// with * or ? the whole name must match ("Drake*", "?ire Ant"). +// UiBackgroundWriter, never on AC's render thread; the text +// format is SenseFile in SenseModel.cs). +// SensePattern (SenseModel.cs) one term, case-insensitive. Without wildcards +// the name only has to contain it ("drake" finds "Dragon's Isle +// Drake"); with * or ? the whole name must match ("Drake*"). // SenseSource the scan: on the plugin pump thread at 2 Hz, reading only the // engine's main-thread snapshots (LiveObjectIds, the identity, // position, PWD and attackable snapshots, the player pose), @@ -43,60 +45,15 @@ using RynthCore.Engine.Compatibility; namespace RynthCore.Engine.UI.Data; -/// One watch-list term. Immutable. -internal sealed class SensePattern -{ - public SensePattern(string text, bool enabled) - { - Text = (text ?? string.Empty).Trim(); - Enabled = enabled; - IsGlob = Text.IndexOfAny(Wildcards) >= 0; - } - - private static readonly char[] Wildcards = { '*', '?' }; - - public string Text { get; } - public bool Enabled { get; } - /// True when the term has * or ?: the whole name must match it. - public bool IsGlob { get; } - - public bool Matches(string name) - { - if (Text.Length == 0 || string.IsNullOrEmpty(name)) return false; - return IsGlob ? Glob(name, Text) : name.Contains(Text, StringComparison.OrdinalIgnoreCase); - } - - /// - /// Case-insensitive whole-string match of against - /// (* any run, ? one character). Iterative, backtracking - /// only to the last *; no allocation. - /// - internal static bool Glob(string s, string p) - { - int si = 0, pi = 0, star = -1, mark = 0; - while (si < s.Length) - { - if (pi < p.Length && p[pi] == '*') { star = pi++; mark = si; } - else if (pi < p.Length && (p[pi] == '?' || Same(p[pi], s[si]))) { si++; pi++; } - else if (star >= 0) { pi = star + 1; si = ++mark; } - else return false; - } - while (pi < p.Length && p[pi] == '*') pi++; - return pi == p.Length; - } - - private static bool Same(char a, char b) => a == b || char.ToUpperInvariant(a) == char.ToUpperInvariant(b); -} - /// -/// The watch list and alert settings. Edited on AC's thread (the face, /rc sense), -/// read by the scan on the pump thread: the term list is an immutable array +/// The watch list, alert settings and the panel's look. Edited on AC's thread (the face, +/// /rc sense), read by the scan on the pump thread: the term list is an immutable array /// swapped whole, with a version the scan compares. File I/O on UiBackgroundWriter. /// internal static class SenseStore { - public const int MaxTerms = 40; - public const int MaxTermLength = 64; + public const int MaxTerms = SenseFile.MaxTerms; + public const int MaxTermLength = SenseFile.MaxTermLength; private static readonly object Sync = new(); private static SensePattern[] _terms = Array.Empty(); @@ -105,6 +62,7 @@ internal static class SenseStore private static bool _loadQueued; private static volatile bool _alertChat; private static volatile bool _alertBeep; + private static volatile int _layout; // SenseLayoutMode private static bool _alertSubscribed; /// The current terms (never null; do not modify). Any thread. @@ -121,6 +79,9 @@ internal static class SenseStore /// The system beep when a new match appears (off by default). public static bool AlertBeep => _alertBeep; + /// How the panel looks: full (the default), compact or collapsed. Any thread. + public static SenseLayoutMode Layout => (SenseLayoutMode)_layout; + public static bool AnyEnabled { get @@ -148,44 +109,11 @@ internal static class SenseStore private static void LoadNow() { - var list = new List(); - bool chat = false, beep = false; + SenseFileData data = new(); try { string path = FilePath; - if (File.Exists(path)) - { - foreach (string raw in File.ReadAllLines(path)) - { - string line = raw.Trim(); - if (line.Length == 0 || line.StartsWith('#')) continue; - int eq = line.IndexOf('='); - if (eq <= 0) continue; - string key = line[..eq].Trim(); - string val = line[(eq + 1)..]; - switch (key) - { - case "alertChat": chat = val.Trim() == "1"; break; - case "alertBeep": beep = val.Trim() == "1"; break; - case "term": - { - // term=1|pattern (1 on, 0 off); a bare term=pattern is on. - bool on = true; - string text = val; - int bar = val.IndexOf('|'); - if (bar is 1 && (val[0] == '0' || val[0] == '1')) - { - on = val[0] == '1'; - text = val[2..]; - } - text = Clean(text); - if (text.Length > 0 && list.Count < MaxTerms && IndexOf(list, text) < 0) - list.Add(new SensePattern(text, on)); - break; - } - } - } - } + if (File.Exists(path)) data = SenseFile.Parse(File.ReadAllLines(path)); } catch (Exception ex) { @@ -194,41 +122,29 @@ internal static class SenseStore lock (Sync) { - Volatile.Write(ref _terms, list.ToArray()); - _alertChat = chat; - _alertBeep = beep; + Volatile.Write(ref _terms, data.Terms.ToArray()); + _alertChat = data.AlertChat; + _alertBeep = data.AlertBeep; + _layout = (int)data.Layout; Interlocked.Increment(ref _version); _loaded = true; } SyncAlertSubscription(); } - private static string Clean(string text) - { - text = (text ?? string.Empty).Replace('\r', ' ').Replace('\n', ' ').Trim(); - return text.Length > MaxTermLength ? text[..MaxTermLength] : text; - } - - private static int IndexOf(IReadOnlyList list, string text) - { - for (int i = 0; i < list.Count; i++) - if (string.Equals(list[i].Text, text, StringComparison.OrdinalIgnoreCase)) return i; - return -1; - } - /// /// Adds a term (switched on). An existing term with the same text is switched /// on instead. False when the text is empty, the list is full or not loaded yet. /// public static bool Add(string text, out string message) { - text = Clean(text); + text = SenseFile.Clean(text); if (!_loaded) { message = "The watch list is still loading."; return false; } if (text.Length == 0) { message = "Type a name first."; return false; } lock (Sync) { SensePattern[] cur = _terms; - int at = IndexOf(cur, text); + int at = SenseFile.IndexOf(cur, text); if (at >= 0) { message = cur[at].Enabled ? $"\"{cur[at].Text}\" is already on the list." : $"\"{cur[at].Text}\" switched on."; @@ -277,6 +193,19 @@ internal static class SenseStore Save(); } + /// + /// Sets the panel's look and saves it with the list. False (nothing changes) while the list is + /// still loading: the file would be written before it was read. Any thread. + /// + public static bool SetLayout(SenseLayoutMode mode) + { + if (!_loaded) return false; + if ((int)mode == _layout) return true; + _layout = (int)mode; + Save(); + return true; + } + // Under Sync. private static void Replace(int index, SensePattern pattern) { @@ -322,18 +251,11 @@ internal static class SenseStore { try { - SensePattern[] terms = Terms; - var sb = new StringBuilder(); - sb.AppendLine("# RynthCore Sense watch list - auto-generated, hand-edits OK. /rc sense in game."); - sb.AppendLine("# term=1|name (1 on, 0 off). No * or ?: the name contains it. With * or ?: the whole name matches."); - sb.AppendLine(_alertChat ? "alertChat=1" : "alertChat=0"); - sb.AppendLine(_alertBeep ? "alertBeep=1" : "alertBeep=0"); - foreach (SensePattern t in terms) - sb.Append("term=").Append(t.Enabled ? '1' : '0').Append('|').AppendLine(t.Text); + string text = SenseFile.Format(Terms, _alertChat, _alertBeep, Layout); string path = FilePath; string? dir = Path.GetDirectoryName(path); if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); - File.WriteAllText(path, sb.ToString()); + File.WriteAllText(path, text); } catch (Exception ex) { diff --git a/src/RynthCore.Engine/UI/Data/SenseModel.cs b/src/RynthCore.Engine/UI/Data/SenseModel.cs new file mode 100644 index 0000000..7dc75d2 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/SenseModel.cs @@ -0,0 +1,411 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/SenseModel.cs +// The Sense panel's pure part (no AC, no ImGui, no files), so tools\SenseTests +// can compile it in: +// +// SensePattern one watch-list term (moved here from SenseData.cs). +// SenseLayoutMode how the panel looks: Full (the add row, term chips, status +// and the match rows), Compact (only the match rows, tighter, +// no frame or background, clicks pass through except on the +// rows; item-counter.lua's bare look) and Collapsed (one line, +// "Sense: N", that opens back to Compact on a click). +// SenseFile sense.txt read and written as text: the terms, the alerts +// and the look (view=full|compact|collapsed). +// SenseLayout the compact view's layout decisions (which columns fit, +// row height, which row the mouse is on) and /rc sense's +// look commands (compact on|off, collapse on|off, view ...) +// with their replies. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; + +namespace RynthCore.Engine.UI.Data; + +/// One watch-list term. Immutable. +internal sealed class SensePattern +{ + public SensePattern(string text, bool enabled) + { + Text = (text ?? string.Empty).Trim(); + Enabled = enabled; + IsGlob = Text.IndexOfAny(Wildcards) >= 0; + } + + private static readonly char[] Wildcards = { '*', '?' }; + + public string Text { get; } + public bool Enabled { get; } + /// True when the term has * or ?: the whole name must match it. + public bool IsGlob { get; } + + public bool Matches(string name) + { + if (Text.Length == 0 || string.IsNullOrEmpty(name)) return false; + return IsGlob ? Glob(name, Text) : name.Contains(Text, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Case-insensitive whole-string match of against + /// (* any run, ? one character). Iterative, backtracking + /// only to the last *; no allocation. + /// + internal static bool Glob(string s, string p) + { + int si = 0, pi = 0, star = -1, mark = 0; + while (si < s.Length) + { + if (pi < p.Length && p[pi] == '*') { star = pi++; mark = si; } + else if (pi < p.Length && (p[pi] == '?' || Same(p[pi], s[si]))) { si++; pi++; } + else if (star >= 0) { pi = star + 1; si = ++mark; } + else return false; + } + while (pi < p.Length && p[pi] == '*') pi++; + return pi == p.Length; + } + + private static bool Same(char a, char b) => a == b || char.ToUpperInvariant(a) == char.ToUpperInvariant(b); +} + +/// How the Sense panel looks (sense.txt "view"). +internal enum SenseLayoutMode : byte +{ + /// The whole panel: add row, chips, status, column header, rows. The default. + Full, + /// Only the match rows, tighter; no frame or background; clicks pass through except on the rows. + Compact, + /// One line, "Sense: N"; a click opens it to Compact. + Collapsed, +} + +/// What sense.txt holds. +internal sealed class SenseFileData +{ + public List Terms = new(); + public bool AlertChat; + public bool AlertBeep; + public SenseLayoutMode Layout = SenseLayoutMode.Full; +} + +/// sense.txt as text (the store does the file I/O). Pure. +internal static class SenseFile +{ + public const int MaxTerms = 40; + public const int MaxTermLength = 64; + + /// + /// Reads the lines of sense.txt: "alertChat=1", "alertBeep=0", "view=compact", "term=1|name" + /// (1 on, 0 off; a bare "term=name" is on). Comments (#), blank lines and unknown keys are + /// skipped; a duplicate term (any case), an empty one or one past is + /// dropped; an unknown view is Full. + /// + public static SenseFileData Parse(IEnumerable lines) + { + var data = new SenseFileData(); + foreach (string raw in lines) + { + string line = (raw ?? string.Empty).Trim(); + if (line.Length == 0 || line.StartsWith('#')) continue; + int eq = line.IndexOf('='); + if (eq <= 0) continue; + string key = line[..eq].Trim(); + string val = line[(eq + 1)..]; + switch (key) + { + case "alertChat": data.AlertChat = val.Trim() == "1"; break; + case "alertBeep": data.AlertBeep = val.Trim() == "1"; break; + case "view": + data.Layout = SenseLayout.TryParseLayout(val, out SenseLayoutMode mode) ? mode : SenseLayoutMode.Full; + break; + case "term": + { + bool on = true; + string text = val; + int bar = val.IndexOf('|'); + if (bar is 1 && (val[0] == '0' || val[0] == '1')) + { + on = val[0] == '1'; + text = val[2..]; + } + text = Clean(text); + if (text.Length > 0 && data.Terms.Count < MaxTerms && IndexOf(data.Terms, text) < 0) + data.Terms.Add(new SensePattern(text, on)); + break; + } + } + } + return data; + } + + /// The file's text (what reads back). + public static string Format(IReadOnlyList terms, bool alertChat, bool alertBeep, SenseLayoutMode layout) + { + var sb = new StringBuilder(); + sb.AppendLine("# RynthCore Sense watch list - auto-generated, hand-edits OK. /rc sense in game."); + sb.AppendLine("# term=1|name (1 on, 0 off). No * or ?: the name contains it. With * or ?: the whole name matches."); + sb.AppendLine("# view=full|compact|collapsed (/rc sense compact on|off, /rc sense collapse on|off)."); + sb.AppendLine(alertChat ? "alertChat=1" : "alertChat=0"); + sb.AppendLine(alertBeep ? "alertBeep=1" : "alertBeep=0"); + sb.Append("view=").AppendLine(SenseLayout.LayoutName(layout)); + foreach (SensePattern t in terms) + sb.Append("term=").Append(t.Enabled ? '1' : '0').Append('|').AppendLine(t.Text); + return sb.ToString(); + } + + /// One line, trimmed, at most characters. + public static string Clean(string text) + { + text = (text ?? string.Empty).Replace('\r', ' ').Replace('\n', ' ').Trim(); + return text.Length > MaxTermLength ? text[..MaxTermLength] : text; + } + + /// The index of the term with this text (any case), or -1. + public static int IndexOf(IReadOnlyList list, string text) + { + for (int i = 0; i < list.Count; i++) + if (string.Equals(list[i].Text, text, StringComparison.OrdinalIgnoreCase)) return i; + return -1; + } +} + +/// The compact view's columns at a width (px): arrow, name and distance always. +internal readonly record struct SenseCompactColumns(bool Location, bool Kind, float NameWidth); + +/// What one /rc sense look command did. +internal readonly record struct SenseLayoutAnswer(bool Ok, SenseLayoutMode Next, string Reply); + +/// The compact view's layout and the look commands. Pure. +internal static class SenseLayout +{ + /// Row heights (px at 100%): the full view's rows and the compact view's. + public const float FullRowHeight = 20f, CompactRowHeight = 16f; + + /// Compact column widths (px at 100%). + public const float CompactArrowWidth = 16f, CompactDistWidth = 52f, CompactLocWidth = 104f, CompactKindWidth = 50f; + + /// The name keeps at least this much before the coordinates, then the kind, are shown. + public const float CompactNameRoom = 110f; + + public const string Usage = + "Usage: /rc sense [compact on|off | collapse on|off | view full|compact|collapsed] (alone: opens or closes the Sense panel)"; + + /// + /// Which compact columns fit in px (: the text + /// size factor the widths grow with): the coordinates when the name still keeps + /// , then the kind on the same rule. The name gets what is left. + /// + public static SenseCompactColumns Compact(float width, float scale = 1f) + { + float k = scale > 0 ? scale : 1f; + float fixedW = (CompactArrowWidth + CompactDistWidth) * k; + float room = CompactNameRoom * k; + bool loc = width - fixedW - CompactLocWidth * k >= room; + bool kind = loc && width - fixedW - (CompactLocWidth + CompactKindWidth) * k >= room; + float name = width - fixedW - (loc ? CompactLocWidth * k : 0) - (kind ? CompactKindWidth * k : 0); + return new SenseCompactColumns(loc, kind, Math.Max(24f * k, name)); + } + + /// The collapsed line: "Sense: 3", "Sense: 0". + public static string CollapsedText(int matches) => + "Sense: " + Math.Max(0, matches).ToString(CultureInfo.InvariantCulture); + + /// + /// The match row under the mouse at (rows start at , + /// apart, of them shown); -1 for none. + /// + public static int RowAt(float mouseY, float top, float rowHeight, int rows) + { + if (rows <= 0 || rowHeight <= 0 || mouseY < top) return -1; + int i = (int)((mouseY - top) / rowHeight); + return i < rows ? i : -1; + } + + /// + /// Whether the bare panel takes the mouse (else clicks go to the game): over what it drew, from + /// (, ) to (, ), + /// or, while it was already hot, anywhere in the strip to the right of that out to the buttons' + /// far edge (), so the buttons beside the first line can be reached from any row. + /// + public static bool IsHot(float mx, float my, float x0, float y0, float drawnX1, float drawnY1, float buttonsX1, float buttonsY1, bool wasHot) + { + if (mx < x0 || my < y0) return false; + if (mx < drawnX1 && my < drawnY1) return true; + return wasHot && mx < buttonsX1 && my < Math.Max(drawnY1, buttonsY1); + } + + /// + /// The view switch every look shows (2026-10-31: always there, not only on hover): the two other + /// looks, in the order their buttons stand. Full: compact, collapsed. Compact: collapsed (the + /// caret up), full. Collapsed: compact (the caret down), full. + /// + public static (SenseLayoutMode First, SenseLayoutMode Second) OtherViews(SenseLayoutMode current) => current switch + { + SenseLayoutMode.Compact => (SenseLayoutMode.Collapsed, SenseLayoutMode.Full), + SenseLayoutMode.Collapsed => (SenseLayoutMode.Compact, SenseLayoutMode.Full), + _ => (SenseLayoutMode.Compact, SenseLayoutMode.Collapsed), + }; + + /// What the view switch's button to says (its tooltip) and the command it matches. + public static string SwitchTip(SenseLayoutMode to) => to switch + { + SenseLayoutMode.Compact => "Compact: just the matches, no frame; clicks pass through around them (/rc sense view compact)", + SenseLayoutMode.Collapsed => "Collapse to one line, \"Sense: N\"; click it to show the matches (/rc sense view collapsed)", + _ => "The full Sense panel: add names, alerts, move and resize (/rc sense view full)", + }; + + /// + /// Whether the bare panel takes the mouse: , or over the view switch beside the + /// first line (from ), which is always drawn and so always clickable. + /// + public static bool TakesMouse(float mx, float my, float x0, float y0, float drawnX1, float drawnY1, + float buttonsX0, float buttonsX1, float buttonsY1, bool wasHot) + { + if (IsHot(mx, my, x0, y0, drawnX1, drawnY1, buttonsX1, buttonsY1, wasHot)) return true; + return mx >= buttonsX0 && mx < buttonsX1 && my >= y0 && my < buttonsY1; + } + + /// + /// Compact rows that fit in px: (rows drawn, whether the last slot says + /// "+N more" instead). At least one slot when there are rows. + /// + public static (int Drawn, bool More) CompactFit(float height, float rowHeight, int rows) + { + int slots = RowsThatFit(height, rowHeight, rows); + return slots < rows ? (slots - 1, true) : (slots, false); + } + + /// "+3 more". + public static string MoreText(int hidden) => "+" + Math.Max(0, hidden).ToString(CultureInfo.InvariantCulture) + " more"; + + /// How many rows of fit in (at least one when any). + public static int RowsThatFit(float height, float rowHeight, int rows) + { + if (rows <= 0) return 0; + if (rowHeight <= 0) return rows; + return Math.Clamp((int)(height / rowHeight), 1, rows); + } + + public static string LayoutName(SenseLayoutMode mode) => mode switch + { + SenseLayoutMode.Compact => "compact", + SenseLayoutMode.Collapsed => "collapsed", + _ => "full", + }; + + /// "full", "compact" (or "small", "mini"), "collapsed" (or "collapse"), any case. + public static bool TryParseLayout(string text, out SenseLayoutMode mode) + { + switch ((text ?? string.Empty).Trim().ToLowerInvariant()) + { + case "full": case "normal": mode = SenseLayoutMode.Full; return true; + case "compact": case "small": case "mini": mode = SenseLayoutMode.Compact; return true; + case "collapsed": case "collapse": mode = SenseLayoutMode.Collapsed; return true; + default: mode = SenseLayoutMode.Full; return false; + } + } + + /// True when (after "/rc sense ") is a look command. + public static bool IsLayoutCommand(string args) + { + string first = FirstWord(args, out _); + return first is "compact" or "collapse" or "collapsed" or "view"; + } + + /// + /// The check before /rc sense runs (ChatCommandReplies): nothing (open or close the panel), or a + /// look command takes: compact|collapse [on|off], view [full|compact|collapsed]. + /// + public static bool IsValidArgs(string args) + { + string a = (args ?? string.Empty).Trim(); + if (a.Length == 0) return true; + string word = FirstWord(a, out string rest); + string value = rest.Trim().ToLowerInvariant(); + if (value.Contains(' ')) return false; + return word switch + { + "compact" or "collapse" or "collapsed" => value is "" or "on" or "off", + "view" => value is "" or "full" or "compact" or "collapsed", + _ => false, + }; + } + + /// + /// /rc sense compact on|off, collapse on|off, view full|compact|collapsed, from the look now + /// (). Alone (compact, collapse, view) each says the look now. + /// compact off is Full; collapse on is Collapsed, collapse off opens it to Compact (Full stays + /// Full). : the reply says how to open a closed panel. + /// + public static SenseLayoutAnswer Apply(string args, SenseLayoutMode current, bool panelOpen) + { + string word = FirstWord(args, out string rest); + string value = rest.Trim().ToLowerInvariant(); + SenseLayoutMode next = current; + bool changed; + switch (word) + { + case "compact": + if (value.Length == 0) return Now(current, panelOpen); + if (!TryOnOff(value, out bool compactOn)) return Bad(); + next = compactOn ? (current == SenseLayoutMode.Collapsed ? SenseLayoutMode.Collapsed : SenseLayoutMode.Compact) + : SenseLayoutMode.Full; + break; + case "collapse": + case "collapsed": + if (value.Length == 0) return Now(current, panelOpen); + if (!TryOnOff(value, out bool collapseOn)) return Bad(); + next = collapseOn ? SenseLayoutMode.Collapsed + : current == SenseLayoutMode.Collapsed ? SenseLayoutMode.Compact : current; + break; + case "view": + if (value.Length == 0) return Now(current, panelOpen); + if (value is not ("full" or "compact" or "collapsed") || !TryParseLayout(value, out next)) return Bad(); + break; + default: + return Bad(); + } + changed = next != current; + return new SenseLayoutAnswer(true, next, Describe(next, changed ? "Sense: now the " : "Sense is already in the ", panelOpen)); + } + + /// + /// "<head>compact view (just the matches, ...)." plus, when the panel is closed, how to open it. + /// Heads: "Sense: now the " (changed), "Sense is already in the " (no change), "Sense is in the " (asked). + /// + public static string Describe(SenseLayoutMode mode, string head, bool panelOpen) + { + string what = mode switch + { + SenseLayoutMode.Compact => "compact view (just the matches; clicks pass through around them). /rc sense compact off for the full panel", + SenseLayoutMode.Collapsed => "collapsed view (one line, Sense: N). Click it, or /rc sense collapse off, to show the matches", + _ => "full view. /rc sense compact on for the small one", + }; + return head + what + (panelOpen ? "." : ". The panel is closed: /rc sense opens it."); + } + + private static SenseLayoutAnswer Now(SenseLayoutMode current, bool panelOpen) => + new(true, current, Describe(current, "Sense is in the ", panelOpen)); + + private static SenseLayoutAnswer Bad() => new(false, default, Usage); + + private static bool TryOnOff(string value, out bool on) + { + switch (value) + { + case "on": on = true; return true; + case "off": on = false; return true; + default: on = false; return false; + } + } + + private static string FirstWord(string s, out string rest) + { + s = (s ?? string.Empty).Trim(); + int sp = s.IndexOf(' '); + if (sp < 0) { rest = string.Empty; return s.ToLowerInvariant(); } + rest = s[(sp + 1)..].Trim(); + return s[..sp].ToLowerInvariant(); + } +} diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index c924e6e..4ace2d9 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -78,6 +78,8 @@ internal sealed class RynthAiSettings // Ranges > Combat Targeting. Null until RynthAi sends them; an older RynthAi leaves them alone. public int? TargetSelection { get; set; } public bool? TargetLock { get; set; } + // Fight the monster I select (RynthAi 2026-11-01). Null: a RynthAi without it; it leaves it alone. + public bool? FightSelectedTarget { get; set; } public int TargetNoProgressTimeoutSec { get; set; } public int GiveQueueIntervalMs { get; set; } = 150; // Recharge @@ -493,7 +495,10 @@ internal sealed record SettingRow( Action? Edit = null, // Combo rows whose list changes while the game runs (the Theme picker's saved schemes): // asked each time the row draws, in place of Items. - Func? ItemsNow = null) + Func? ItemsNow = null, + // Button rows that can't be undone: the question a click asks first (asked when it opens); + // Click/Edit run only when the player confirms. + Func? Confirm = null) { public bool IsVisible(RynthAiSettings s) => VisibleWhen == null || VisibleWhen(s); @@ -652,6 +657,15 @@ internal static class SettingsSchema private static SettingRow Button(string label, string buttonText, Action click, string? tip = null) => new(SettingKind.Button, label, tip, ButtonText: buttonText, Click: click); + // A button that runs a RynthAi chat command as if typed (it answers in chat), through RynthAi's + // "sendchat" remote command: a one-shot action that has no setting of its own. + private static SettingRow ChatButton(string label, string buttonText, string command, string? tip = null) => + Button(label, buttonText, () => RynthAiCommands.ApplyRemoteCommand("sendchat", command), tip); + + // A button that asks first (Settings > Display's layout reset): Click runs once the player confirms. + private static SettingRow ConfirmButton(string label, string buttonText, Func confirm, Action click, string? tip = null) => + new(SettingKind.Button, label, tip, ButtonText: buttonText, Click: click, Confirm: confirm); + // A button that edits the settings (the panel saves the result like a typed value). private static SettingRow EditButton(string label, string buttonText, Action edit, string? tip = null) => new(SettingKind.Button, label, tip, ButtonText: buttonText, Edit: edit); @@ -751,6 +765,18 @@ internal static class SettingsSchema Bool("Remember Open Windows and Positions", _ => Plugins.EngineSettings.RememberWindowLayout, (_, v) => Plugins.EngineSettings.RememberWindowLayout = v, "On (default): reopen Rynth panels where you left them.\nOff: do not overwrite the saved panel layout or reopen panels from the last session. Applies to all your clients."), + // Stored in engine.json for every client (EngineSettings); the layouts themselves by UI/PanelLayout. + Bool("Panel Layout Per Character", _ => Plugins.EngineSettings.PanelLayoutPerCharacter, + (_, v) => Plugins.EngineSettings.PanelLayoutPerCharacter = v, + "On (default): each character keeps its own panel places (docked, popped out, the bar, plugin windows),\nso clients on this PC no longer move each other's panels. A new character starts from the default layout.\nOff: every client shares one layout, as before. /rc layout shows the files in use.\nThis client switches at once; your other clients when they start."), + // Whose layout is in use and its folder (/rc layout's first line, short). + Status(_ => PanelLayout.SettingsLine()), + Button("Layout for New Characters", "Use this character's", () => PanelLayout.MakeDefaultFromSettings(), + "Make this character's panel layout the default that new characters start from (/rc layout default).\nCharacters that already have a layout keep their own; the button below puts one back to the default.") + with { VisibleWhen = _ => Plugins.EngineSettings.PanelLayoutPerCharacter }, + ConfirmButton("Reset This Character's Layout", "Reset...", () => PanelLayout.ResetConfirmText(), () => PanelLayout.ResetFromSettings(), + "Put this character's panel layout back to the default for new characters: open panels move to the default's places.\nAsks first. Also: /rc layout reset confirm.") + with { VisibleWhen = _ => Plugins.EngineSettings.PanelLayoutPerCharacter && PanelLayout.CanResetFromSettings }, Bool("Remember Game Window Position", _ => Plugins.EngineSettings.RememberAcWindowPosition, (_, v) => { @@ -1196,6 +1222,12 @@ internal static class SettingsSchema Bool("Target Lock", s => s.TargetLock ?? true, (s, v) => s.TargetLock = v, "On: keeps the target it picked until it dies, leaves range (Disengage Range), or a higher-priority monster shows up.\n" + "Off: switches whenever another monster is clearly better by the Targeting rule."), + Bool("Fight the monster I select", s => s.FightSelectedTarget ?? false, (s, v) => s.FightSelectedTarget = v, + "On: in a fight, a monster YOU select (click it, or pick it on the radar or in a Selection window)\n" + + "is fought first, ahead of Targeting and Priority, until it dies, can't be reached, or you select\n" + + "another monster or deselect. The bot's own selections never count. Ignored (Priority 0) and\n" + + "never-attack monsters are not followed (/ra targetlock still forces them). Out to Disengage Range.\n" + + "/ra fightselected [on|off]"), Spacer(), Section("Corpse Acquisition (Yards)"), Double("Corpse Max (yd)", s => s.CorpseApproachRangeMax, (s, v) => s.CorpseApproachRangeMax = v, 0.5, 50.0, 0.5, CorpseMaxTip), @@ -1327,6 +1359,8 @@ internal static class SettingsSchema "When a buff is due, also recast every other buff with less than this much time left,\nso they land together. Buffs with more time are left alone. Default 1200 (20 minutes).\nAt or below 'Rebuff With', only the expiring buff is recast."), Bool("Cast buffs even when an item gives them", s => s.CastBuffsOverItemBuffs, (s, v) => s.CastBuffsOverItemBuffs = v, "Cast your own buff even when worn gear already gives that buff.\nFor servers with buff augments, where your own cast is stronger or lasts longer.\nOn by default: on retail it costs a few extra casts."), + ChatButton("Buffs Left Out", "List in chat", "/ra buff skipped", + "The buffs RynthAi leaves out because this character can't use them, listed in chat (/ra buff skipped)."), Spacer(), Section("Protections (untick to skip)"), BuffToggles(ProtToggles), @@ -1371,6 +1405,12 @@ internal static class SettingsSchema "When your own corpse (\"Corpse of \") is within loot range, open it and take every\nitem on it, whatever the loot profile and Loot From say. Needs Enable Looting.\n/ra owncorpse says where your last corpse is."), Bool("Travel Back To My Corpse", s => s.TravelToOwnCorpse, (s, v) => s.TravelToOwnCorpse = v, "After a death, walk back to where you died with RynthNav (outdoor deaths only),\nfighting on the way as usual, recover the corpse, then carry on. Needs the macro\nrunning and RynthNav loaded. /ra owncorpse stop cancels."), + ChatButton("Where Is My Corpse", "Say in chat", "/ra owncorpse", + "Where your last corpse is, how far, and whether RynthAi is on its way to it (/ra owncorpse)."), + ChatButton("Go To My Corpse", "Go", "/ra owncorpse go", + "Walk back to your last corpse now with RynthNav and recover it (/ra owncorpse go)."), + ChatButton("Stop Going To My Corpse", "Stop", "/ra owncorpse stop", + "Stop the walk back to your corpse (/ra owncorpse stop)."), Spacer(), Section("Inventory Management"), Bool("Enable Autostack", s => s.EnableAutostack, (s, v) => s.EnableAutostack = v), @@ -1380,6 +1420,8 @@ internal static class SettingsSchema "After the salvage queue empties, move same-name bags together so the server merges them."), Bool("Combine Bags During Salvage", s => s.CombineBagsDuringSalvage, (s, v) => s.CombineBagsDuringSalvage = v, "When salvaging an item, also add any under-full salvage bag of the same material to the salvage panel."), + ChatButton("Tidy Packs Now", "Stack and cram", "/mt autopack", + "One pass now: stack what stacks and move items from the main pack into side packs (/mt autopack).\nAutostack and Autocram above do it on their own while they are on."), Button("Floating HUDs", "Inventory HUDs...", () => RynthAiCommands.ApplyRemoteCommand("huds", "show"), "Opens the floating pack item count HUD / Mini Remote setup (/ra huds).\nThe Item Count panel is separate (/rc itemcount; Inventory's Count button)."), Bool("Salvage Without The Panel", s => s.SalvageWithoutPanel, (s, v) => s.SalvageWithoutPanel = v, @@ -1456,6 +1498,23 @@ internal static class SettingsSchema Note("+log = the category is at Info: its trace lines also go to the normal log. The launcher's Logging page sets Off, Trace or Info."), Note("Exceptions always go to exceptions_.txt with full stack traces (throttled). Settings here are for this PC, not the profile."), Spacer(), + // Stored in engine.json for every client (EngineSettings.UiCostLog, UiCostThresholdMs; ImGui/UiCost.cs). + Section("UI Frame Cost"), + Bool("Time the UI frame's parts", _ => Plugins.EngineSettings.UiCostLog, + (_, v) => Plugins.EngineSettings.UiCostLog = v, + "On (default): every panel, plugin window and overlay is timed as it draws, and a slow UI frame\n" + + "writes one [UiCost] line to the log naming its slowest parts (at most one every 5 s). The heartbeat\n" + + "adds uitop= with the top 3 while UI frames are slow. Costs a few microseconds a frame. Also: /rc uicost on|off."), + Int(" Slow frame (ms)", _ => Plugins.EngineSettings.UiCostThresholdMs, + (_, v) => Plugins.EngineSettings.UiCostThresholdMs = v, + ImGuiBackend.UiCostModel.MinThresholdMs, ImGuiBackend.UiCostModel.MaxThresholdMs, 5, + "A UI frame this long or longer is logged with its breakdown. Default 50. Also: /rc uicost .", + when: _ => Plugins.EngineSettings.UiCostLog), + Button(" Breakdown", "Print to chat", + () => Compatibility.RynthCoreChatCommands.TryHandle("/rc uicost now", Compatibility.ChatCommandOrigin.Player), + "Which parts of the UI frame took the time over the last few seconds, and the slowest frame part by part\n" + + "(/rc uicost now)."), + Spacer(), Section("Server"), new SettingRow(SettingKind.ServerPick, "Server", "Which server this character counts as. Auto detects it (the connect host, the world name the server announces, RynthILT).\n" diff --git a/src/RynthCore.Engine/UI/LootPatternText.cs b/src/RynthCore.Engine/UI/LootPatternText.cs new file mode 100644 index 0000000..ef59be3 --- /dev/null +++ b/src/RynthCore.Engine/UI/LootPatternText.cs @@ -0,0 +1,175 @@ +// ============================================================================ +// RynthCore.Engine - UI/LootPatternText.cs +// The Loot Editor's words for a text condition's pattern (2026-11-01, the +// owner: "People hate regex ... let's add a does not contain"). A VTank text +// condition (String Value Match, name matches) holds a regex; the editor +// shows a mode and plain words instead and writes the regex for them: +// +// contains Sanguine Sanguine +// doesn't contain Sanguine ^(?!.*Sanguine) +// starts with Sanguine ^Sanguine +// ends with Sanguine Sanguine$ +// is exactly Sanguine Robe ^Sanguine Robe$ +// regex (anything) as typed +// +// The words are escaped the way RynthCore.LootSdk's LootItemRules.EscapeText +// does (regex metacharacters, spaces left alone), so a profile stays a plain +// VTank .utl. Reading a pattern back (Parse) gives the mode whose shape it +// has, else Regex. Several words: "Sanguine, Tattered" means either word +// (contains / doesn't contain only). Matching is case-insensitive (RynthAi's +// evaluator), so the words are too. Pure: tools\LootPatternTextTests. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace RynthCore.Engine.UI; + +internal enum LootTextMode { Contains, NotContains, StartsWith, EndsWith, Exactly, Regex } + +internal static class LootPatternText +{ + public static readonly LootTextMode[] Modes = + { LootTextMode.Contains, LootTextMode.NotContains, LootTextMode.StartsWith, LootTextMode.EndsWith, LootTextMode.Exactly, LootTextMode.Regex }; + + public static readonly string[] Labels = { "contains", "doesn't contain", "starts with", "ends with", "is exactly", "regex" }; + + public static string Label(LootTextMode mode) => Labels[(int)mode]; + + /// What the field's hint says in . + public static string Hint(LootTextMode mode) => mode switch + { + LootTextMode.Contains or LootTextMode.NotContains => "word(s), commas for either", + LootTextMode.Regex => "pattern (regex)", + _ => "text", + }; + + /// The regex for in (Regex: the text as typed). + public static string Build(LootTextMode mode, string words) + { + if (mode == LootTextMode.Regex) return words; + string w = words.Trim(); + if (w.Length == 0) return ""; // no words yet: an empty pattern (the editor keeps the mode) + switch (mode) + { + case LootTextMode.Contains: + return Alternatives(w, wrap: false); + case LootTextMode.NotContains: + return w.Length == 0 ? "" : "^(?!.*" + Alternatives(w, wrap: true) + ")"; + case LootTextMode.StartsWith: + return "^" + Escape(w); + case LootTextMode.EndsWith: + return Escape(w) + "$"; + default: // Exactly + return "^" + Escape(w) + "$"; + } + } + + /// + /// The mode and words stands for: the first shape it has (doesn't contain, + /// is exactly, starts with, ends with, contains), with its words unescaped; else Regex and the pattern. + /// An empty pattern is Contains with no words. + /// + public static (LootTextMode Mode, string Words) Parse(string pattern) + { + pattern ??= ""; + if (pattern.Length == 0) return (LootTextMode.Contains, ""); + if (pattern.StartsWith("^(?!.*", StringComparison.Ordinal) && pattern.EndsWith(")", StringComparison.Ordinal)) + { + string inner = pattern.Substring(6, pattern.Length - 7); + if (inner.StartsWith("(", StringComparison.Ordinal) && inner.EndsWith(")", StringComparison.Ordinal) + && TryWords(inner.Substring(1, inner.Length - 2), out string several) && several.Contains(',')) + return (LootTextMode.NotContains, several); + if (TryUnescape(inner, out string one)) return (LootTextMode.NotContains, one); + } + bool start = pattern.StartsWith("^", StringComparison.Ordinal); + bool end = pattern.EndsWith("$", StringComparison.Ordinal) && !pattern.EndsWith("\\$", StringComparison.Ordinal); + string mid = pattern.Substring(start ? 1 : 0, pattern.Length - (start ? 1 : 0) - (end ? 1 : 0)); + if (start || end) + { + if (TryUnescape(mid, out string text) && text.Length > 0) + return (start && end ? LootTextMode.Exactly : start ? LootTextMode.StartsWith : LootTextMode.EndsWith, text); + return (LootTextMode.Regex, pattern); + } + if (TryWords(pattern, out string words)) return (LootTextMode.Contains, words); + return (LootTextMode.Regex, pattern); + } + + // "a, b" -> "a|b" (each escaped); wrap: "(a|b)" when there are several. + private static string Alternatives(string words, bool wrap) + { + var parts = new List(); + foreach (string raw in words.Split(',')) + { + string p = raw.Trim(); + if (p.Length > 0) parts.Add(Escape(p)); + } + if (parts.Count == 0) return ""; + string joined = string.Join("|", parts); + return wrap && parts.Count > 1 ? "(" + joined + ")" : joined; + } + + // "a|b" (each a plain escaped text) -> "a, b". + private static bool TryWords(string pattern, out string words) + { + words = ""; + var parts = new List(); + foreach (string piece in SplitTopLevelBars(pattern)) + { + if (!TryUnescape(piece, out string t) || t.Trim().Length == 0 || t.Contains(',')) return false; + parts.Add(t); + } + if (parts.Count == 0) return false; + words = string.Join(", ", parts); + return true; + } + + // Splits on '|' that isn't escaped. + private static IEnumerable SplitTopLevelBars(string s) + { + var sb = new StringBuilder(); + for (int i = 0; i < s.Length; i++) + { + char ch = s[i]; + if (ch == '\\' && i + 1 < s.Length) { sb.Append(ch).Append(s[++i]); continue; } + if (ch == '|') { yield return sb.ToString(); sb.Clear(); continue; } + sb.Append(ch); + } + yield return sb.ToString(); + } + + private const string Meta = "\\*+?|{}[]()^$.#"; + + /// Text with the regex metacharacters escaped, spaces left alone (as LootSdk's EscapeText). + public static string Escape(string text) + { + var sb = new StringBuilder(text.Length + 8); + foreach (char ch in text) + { + if (Meta.IndexOf(ch) >= 0) sb.Append('\\'); + sb.Append(ch); + } + return sb.ToString(); + } + + /// The plain text is, when it has no unescaped metacharacter. + private static bool TryUnescape(string pattern, out string text) + { + var sb = new StringBuilder(pattern.Length); + for (int i = 0; i < pattern.Length; i++) + { + char ch = pattern[i]; + if (ch == '\\') + { + if (i + 1 >= pattern.Length || Meta.IndexOf(pattern[i + 1]) < 0) { text = ""; return false; } + sb.Append(pattern[++i]); + continue; + } + if (Meta.IndexOf(ch) >= 0) { text = ""; return false; } + sb.Append(ch); + } + text = sb.ToString(); + return true; + } +} diff --git a/src/RynthCore.Engine/UI/PanelDrawScale.cs b/src/RynthCore.Engine/UI/PanelDrawScale.cs index 569c528..04ee41e 100644 --- a/src/RynthCore.Engine/UI/PanelDrawScale.cs +++ b/src/RynthCore.Engine/UI/PanelDrawScale.cs @@ -8,6 +8,12 @@ // font (Tom 2026-10-22: "the shortcut size needs to go a lot smaller"). // Stored for the whole PC in %LOCALAPPDATA%\RynthCore\panel_draw_scale.txt as // "Title=percent" lines; every client looks for a change at most every 2 s. +// +// Sharp when bigger (2026-11-01, Tom: enlarged windows "get blurry"): a window +// drawn over 100% took its text from the normal bake, stretched. Now its fonts +// come from the text size bake just above its size (FontStep; PluginWindowFace +// switches ImGuiFonts.CurrentStep while the plugin draws), shrunk a little at +// most, and ImGuiFonts bakes the sizes the saved ones need with the text sizes. // ============================================================================ using System; @@ -38,6 +44,9 @@ internal static class PanelDrawScale private static readonly Dictionary Scales = new(StringComparer.OrdinalIgnoreCase); private static DateTime _fileTime = DateTime.MinValue; private static long _checkedMs = long.MinValue / 2; + // The font steps last handed to ImGuiFonts' bake ("3,6"; null before the first bake). + private static string? _bakedSteps; + private const int RebuildDelayMs = 250; private static string FilePath => Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "panel_draw_scale.txt"); @@ -61,6 +70,7 @@ internal static class PanelDrawScale Refresh(); if ((Scales.TryGetValue(title, out int cur) ? cur : 0) == percent) return; if (percent == 0) Scales.Remove(title); else Scales[title] = percent; + NoteSteps(); try { string path = FilePath; @@ -90,16 +100,65 @@ internal static class PanelDrawScale if (t == _fileTime) return; _fileTime = t; Scales.Clear(); - if (t == DateTime.MinValue) return; - foreach (string raw in File.ReadAllLines(path)) - { - string line = raw.Trim(); - if (line.Length == 0 || line.StartsWith('#')) continue; - int eq = line.LastIndexOf('='); - if (eq <= 0 || !int.TryParse(line.AsSpan(eq + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out int p)) continue; - if (p >= Min && p <= Max) Scales[line[..eq].Trim()] = p; - } + if (t != DateTime.MinValue) + foreach (string raw in File.ReadAllLines(path)) + { + string line = raw.Trim(); + if (line.Length == 0 || line.StartsWith('#')) continue; + int eq = line.LastIndexOf('='); + if (eq <= 0 || !int.TryParse(line.AsSpan(eq + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out int p)) continue; + if (p >= Min && p <= Max) Scales[line[..eq].Trim()] = p; + } + NoteSteps(); } catch { /* the old values stay */ } } + + /// + /// The text size step a window drawn at takes its fonts from: the smallest + /// bake at least that big (shrinking a bigger bake stays sharp, stretching a smaller one blurs); + /// 0 at or under normal. A percent is of 96-DPI pixels; the fonts are baked at . + /// + public static int FontStep(int percent, float fontScale) + { + if (percent <= 0) return 0; + float want = percent / 100f / Math.Max(0.5f, fontScale); + int last = PanelTextScale.SizeNames.Length - 1; + for (int step = 0; step < last; step++) + if (PanelTextScale.Factor(step) >= want - 0.005f) return step; + return last; + } + + /// The non-zero font steps the saved sizes need; ImGuiFonts bakes them with the text sizes. Any thread. + public static List FontStepsInUse(float fontScale) + { + lock (Sync) + { + Refresh(); + List steps = Steps(fontScale); + _bakedSteps = string.Join(",", steps); + return steps; + } + } + + // Caller holds Sync. + private static List Steps(float fontScale) + { + var steps = new List(); + foreach (int p in Scales.Values) + { + int step = FontStep(p, fontScale); + if (step > 0 && !steps.Contains(step)) steps.Add(step); + } + steps.Sort(); + return steps; + } + + // Caller holds Sync. A size whose font step isn't in the bake: re-bake once the changes stop. + private static void NoteSteps() + { + if (_bakedSteps == null) return; + string now = string.Join(",", Steps(RynthCore.Engine.ImGuiBackend.EngineFrameController.FontScale)); + if (now != _bakedSteps) RynthCore.Engine.ImGuiBackend.ImGuiFonts.RequestRebuild(RebuildDelayMs); + } } diff --git a/src/RynthCore.Engine/UI/PanelLayout.cs b/src/RynthCore.Engine/UI/PanelLayout.cs new file mode 100644 index 0000000..a7a2c3a --- /dev/null +++ b/src/RynthCore.Engine/UI/PanelLayout.cs @@ -0,0 +1,452 @@ +// ============================================================================ +// RynthCore.Engine - UI/PanelLayout.cs +// Panel layout per character (PanelLayoutPolicy.cs has the rules and names): +// which layout's files this client uses, the switch between them, and the +// engine's own saving of imgui.ini. +// +// Switching. Tick (EndScene, AC's render thread, every frame) works out the +// layout the client should use: the PC-wide default until a character is in +// the world, then that character's (SessionStateRegistry's server and name, +// known straight after LoginComplete, which a hot reload marks at engine init). +// A switch then runs in three steps: +// 1. render thread: snapshot the ImGui windows of the layout being left; +// 2. UI writer (UiBackgroundWriter, in order with every other UI save): write +// out the layout being left when it is a character's, seed a new +// character's files from the default, PanelStateStore.SwitchTo the new +// panel_state.txt, read the new imgui.ini; +// 3. render thread, before any panel draws: LoadIniSettingsFromMemory (Dear +// ImGui 1.91.6 applies loaded settings to windows that already exist, +// WindowSettingsHandler_ApplyAll), and the bar and the open panels take +// their places from the new store (ImGuiBar / ImGuiPanelHost.OnLayoutSwitched). +// After a login, panels draw only once step 3 is done for that login +// (ReadyToDraw, EngineFrameController.PanelsLive): never first at the default +// places and then a jump. +// +// imgui.ini. The context's IniFilename stays null (EngineFrameController.Init): +// the engine loads the file of the layout in use (step 3) and saves it when +// Dear ImGui asks (io.WantSaveIniSettings), at a switch and at shutdown, off +// the render thread and atomically, always to the file of the layout the +// context holds. +// +// The default pair is written by clients that use it in the world as before +// (setting off, no character name) and by /rc layout default; not by a switch, +// not at character select with the setting on, and never with the windows of a +// character that logged out (PanelLayoutPolicy.MayAutoSaveIni). +// ============================================================================ + +using System; +using System.IO; +using System.Threading; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI; + +internal static class PanelLayout +{ + private static readonly PanelLayoutSession Session = new(); + private static readonly LatestTextWrites IniWrites = new(PanelLayoutFiles.WriteText); + private static volatile bool _initialized; + + /// A finished step 2, waiting for the render thread. + private sealed record Loaded(LayoutSwitch Switch, LayoutFiles Files, string? IniText, string? Error, Action? After); + private static Loaded? _loaded; // written by the UI writer, read by the render thread + + // Render thread: the layout applied (step 3; one reference, so other threads read it whole) + // and the ImGui windows' text for it. + private static Loaded? _applied; + private static string? _activeIniText; + private static bool _contextHeldCharacter; // the ImGui context has had a character's windows in it + private static LayoutOwner? _placedFor; // the layout the open panels were last placed from + private static bool _placedForSet; + + /// The character whose layout is applied; null = the default (or none yet). + private static LayoutOwner? Active => Volatile.Read(ref _applied)?.Switch.To; + + // The identity Tick last read (SessionStateRegistry's strings), so it isn't rebuilt every frame. + private static string? _idServer, _idCharacter; + private static LayoutOwner? _idOwner; + + /// An /rc layout default or reset waiting for the render thread (one at a time). + private sealed record PendingOp(LayoutCommand Kind, Action Reply); + private static PendingOp? _pendingOp; + private static Action? _resetReply; // render thread: the reset switch's answer + + /// True once the engine runs layouts (Initialize). Until then imgui.ini is Dear ImGui's own, as before. + public static bool Initialized => _initialized; + + private static string LocalRoot => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore"); + + /// The PC-wide default imgui.ini (the file every client used before). + internal static string DefaultIniPath => Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, PanelLayoutPolicy.ImGuiIniFileName); + + private static LayoutFiles FilesFor(LayoutOwner? who) => PanelLayoutPolicy.FilesFor(LocalRoot, DefaultIniPath, who); + + /// Engine init (InitWorker), before the EndScene hook goes in. From here the engine owns imgui.ini. + public static void Initialize() + { + if (_initialized) return; + _initialized = true; + RynthLog.UI($"PanelLayout: per character {(EngineSettings.PanelLayoutPerCharacter ? "on" : "off")}; layouts under {Path.Combine(LocalRoot, PanelLayoutPolicy.LayoutsFolder)}."); + } + + private static bool InWorld => LoginLifecycleHooks.HasObservedLoginComplete; + + private static LayoutOwner? Identity() + { + string server = SessionStateRegistry.LastServerName, character = SessionStateRegistry.LastCharacterName; + if (!ReferenceEquals(server, _idServer) || !ReferenceEquals(character, _idCharacter)) + { + _idServer = server; + _idCharacter = character; + _idOwner = PanelLayoutPolicy.Owner(server, character); + } + return _idOwner; + } + + /// + /// True when panels may draw (EngineFrameController.PanelsLive): after a login, only once that + /// login's layout is in place. Always true before Initialize. Render thread. + /// + public static bool ReadyToDraw => + !_initialized || Session.ReadyToDraw(Environment.TickCount64, InWorld, LoginLifecycleHooks.LoginCompleteAtMs); + + // ── the frame (render thread) ───────────────────────────────────────── + + /// + /// Once a frame, from EndScene (render thread, outside the ImGui frame). : + /// the ImGui layer is on and didn't fail, so a layout waits for its context; : + /// the context exists. / run on it. + /// + public static void Tick(bool imguiInUse, bool imguiReady, Func snapshotIni, Action loadIni) + { + if (!_initialized) return; + try + { + ApplyLoaded(imguiInUse, imguiReady, loadIni); + + if (!Session.InFlight && Volatile.Read(ref _pendingOp) != null && Interlocked.Exchange(ref _pendingOp, null) is { } op) + RunOp(op, imguiReady ? snapshotIni : null); + + LayoutSwitch? sw = Session.Tick(Environment.TickCount64, EngineSettings.PanelLayoutPerCharacter, InWorld, + LoginLifecycleHooks.LoginCompleteAtMs, SessionStateRegistry.LoginRecorded, Identity()); + if (sw is { } s) + StartSwitch(s, s.FlushFrom && imguiReady ? snapshotIni() : null); + if (_resetReply is { } unanswered) + { + // The reset asked for this frame didn't become a switch: the layout in use changed first. + _resetReply = null; + unanswered(PanelLayoutPolicy.FailedReply("reset the panel layout", "the layout in use changed first; try again"), false); + } + } + catch (Exception ex) + { + RynthLog.UI($"PanelLayout: tick threw {ex.GetType().Name}: {ex.Message}"); + } + } + + /// Step 1: the switch goes to the UI writer, with the windows of the layout being left. + private static void StartSwitch(LayoutSwitch sw, string? fromIni) + { + LayoutFiles from = FilesFor(sw.From), to = FilesFor(sw.To); + if (sw.FlushFrom && fromIni != null) IniWrites.Queue(from.ImGuiIni, fromIni); + Action? after = null; + if (sw.Reseed && _resetReply is { } reply && sw.To is { } who) + { + _resetReply = null; + after = error => reply(error == null ? PanelLayoutPolicy.ResetDoneReply(who) + : PanelLayoutPolicy.FailedReply("reset " + PanelLayoutPolicy.Describe(who) + "'s panel layout", error), error == null); + } + UiBackgroundWriter.Enqueue("panel layout switch", () => LoadOnWriter(sw, from, to, after)); + } + + /// Step 2 (UI writer): write out what is left, seed or reseed, switch the store, read the new imgui.ini. + private static void LoadOnWriter(LayoutSwitch sw, LayoutFiles from, LayoutFiles to, Action? after) + { + string? ini = null, error = null; + string seeded = string.Empty; + try + { + if (sw.FlushFrom) IniWrites.Flush(from.ImGuiIni); + } + catch (Exception ex) + { + RynthLog.UI($"PanelLayout: writing out {from.ImGuiIni} failed - {ex.Message}"); + } + try + { + if (sw.To != null) + { + LayoutFiles defaults = FilesFor(null); + if (sw.Reseed) + { + PanelLayoutFiles.CopyOver(defaults, to); + seeded = " (reset from the default)"; + } + else + { + var copied = PanelLayoutFiles.SeedMissing(defaults, to); + if (copied.PanelState || copied.Ini) + seeded = " (new: " + (copied.PanelState && copied.Ini ? "both files" : copied.PanelState ? "panel_state.txt" : "imgui.ini") + + " copied from the default)"; + } + } + } + catch (Exception ex) + { + // The switch still happens: the character's files are made by its first save. + error = ex.Message; + } + // Never throws (it logs a file it can't read and starts empty). + PanelStateStore.SwitchTo(to.PanelState, flushCurrent: sw.FlushFrom); + try { ini = PanelLayoutFiles.ReadText(to.ImGuiIni); } + catch (Exception ex) { error ??= ex.Message; } + + string who = sw.To is { } owner ? PanelLayoutPolicy.Describe(owner) + "'s" : "the PC-wide default"; + if (error == null) RynthLog.UI($"PanelLayout: switched to {who} layout{seeded}: {to.PanelState}, {to.ImGuiIni}."); + else RynthLog.Warn($"PanelLayout: switched to {who} layout ({to.PanelState}), but its files had a problem - {error}."); + Volatile.Write(ref _loaded, new Loaded(sw, to, ini, error, after)); + try { after?.Invoke(error); } catch { } + } + + /// Step 3 (render thread): the loaded layout goes into the ImGui context, the bar and the open panels. + private static void ApplyLoaded(bool imguiInUse, bool imguiReady, Action loadIni) + { + Loaded? l = Volatile.Read(ref _loaded); + if (l == null || ReferenceEquals(l, _applied)) return; + if (imguiInUse && !imguiReady) return; // the context is made this frame: apply on the next + if (imguiReady && !string.IsNullOrEmpty(l.IniText)) + { + try { loadIni(l.IniText); } + catch (Exception ex) { RynthLog.UI($"PanelLayout: loading {l.Files.ImGuiIni} threw {ex.GetType().Name}: {ex.Message}"); } + } + Volatile.Write(ref _applied, l); + _activeIniText = l.IniText; + if (l.Switch.To != null) _contextHeldCharacter = true; + Session.MarkApplied(l.Switch.Gen); + + // A reset places the panels again even though the layout's owner is the same. + if (InWorld && (l.Switch.Reseed || !_placedForSet || !Equals(l.Switch.To, _placedFor))) + { + // At character select nothing draws: the panels are placed when a character comes in. + _placedFor = l.Switch.To; + _placedForSet = true; + ImGuiBackend.ImGuiBar.OnLayoutSwitched(); + ImGuiBackend.ImGuiPanelHost.OnLayoutSwitched(); + } + } + + /// + /// The ImGui context was just made (EngineFrameController.Init, context current, before its first + /// frame): it starts with the windows of the layout in use, if one is applied already. + /// + public static void OnContextCreated(Action loadIni) + { + if (!_initialized || _applied == null || string.IsNullOrEmpty(_activeIniText)) return; + try { loadIni(_activeIniText); } + catch (Exception ex) { RynthLog.UI($"PanelLayout: loading the layout into the new context threw {ex.GetType().Name}: {ex.Message}"); } + } + + // ── saving imgui.ini ────────────────────────────────────────────────── + + /// + /// The ImGui windows' text to save (render thread): Dear ImGui's dirty timer (io.WantSaveIniSettings), + /// or for Save Layout Now. Written in the background, atomically, to + /// the file of the layout the context holds. + /// + public static void QueueIniSave(string text, bool explicitSave) + { + if (!_initialized) + { + // Dear ImGui owns the file (IniFilename pinned): Save Layout Now writes the default, as before. + if (explicitSave) UiBackgroundWriter.Enqueue("imgui.ini", () => PanelLayoutFiles.WriteText(DefaultIniPath, text)); + return; + } + if (!MaySave(explicitSave, out string path)) return; + _activeIniText = text; + IniWrites.Queue(path, text); + UiBackgroundWriter.Enqueue("imgui.ini", () => + { + try { IniWrites.Flush(path); } + catch (Exception ex) { RynthLog.UI($"PanelLayout: saving {path} failed - {ex.Message}"); } + }); + } + + /// The ImGui context is about to go (engine shutdown, a hot reload): its windows are written now. + public static void SaveIniOnShutdown(string text) + { + if (!_initialized || !MaySave(explicitSave: false, out string path)) return; + try + { + IniWrites.Queue(path, text); + IniWrites.Flush(path); + } + catch (Exception ex) + { + RynthLog.UI($"PanelLayout: saving {path} at shutdown failed - {ex.Message}"); + } + } + + private static bool MaySave(bool explicitSave, out string path) + { + path = string.Empty; + // Nothing applied yet: the context holds no file's windows, and saving it would empty one. + if (Volatile.Read(ref _applied) is not { } applied) return false; + if (!explicitSave && !PanelLayoutPolicy.MayAutoSaveIni(applied.Switch.To != null, EngineSettings.PanelLayoutPerCharacter, InWorld, _contextHeldCharacter)) + return false; + path = applied.Files.ImGuiIni; + return true; + } + + // ── /rc layout and Settings ─────────────────────────────────────────── + + /// /rc layout: the layout in use, its files, and the default's. Any thread (racy reads). + public static string[] DescribeLines() + { + LayoutFiles defaults = FilesFor(null); + if (!_initialized) + return PanelLayoutPolicy.StatusLines(null, defaults, DefaultReason.NotRunning, defaults, false); + bool perCharacter = EngineSettings.PanelLayoutPerCharacter; + Loaded? applied = Volatile.Read(ref _applied); + LayoutOwner? active = applied?.Switch.To; + LayoutFiles files = applied?.Files ?? defaults; + DefaultReason why = DefaultReason.None; + if (active == null) + { + if (!perCharacter) why = DefaultReason.SettingOff; + else if (!InWorld) why = DefaultReason.NotInWorld; + else if (!Session.Decided) why = DefaultReason.WaitingForName; + else if (Session.Wanted == null) why = DefaultReason.NoCharacterName; + } + return PanelLayoutPolicy.StatusLines(active, files, why, defaults, perCharacter); + } + + // Settings > Display's line, built again only when what it shows changed (it draws every frame). + private static Loaded? _lineFor; + private static int _lineFlags = -1; + private static string _line = string.Empty; + + /// Settings > Display: whose layout this client uses and where its files are. Render thread. + public static string SettingsLine() + { + bool perCharacter = EngineSettings.PanelLayoutPerCharacter; + Loaded? applied = Volatile.Read(ref _applied); + int flags = (perCharacter ? 1 : 0) | (InWorld ? 2 : 0) | (Session.Decided ? 4 : 0) | (Session.Wanted != null ? 8 : 0) | (_initialized ? 16 : 0); + if (ReferenceEquals(applied, _lineFor) && flags == _lineFlags) return _line; + _lineFor = applied; + _lineFlags = flags; + LayoutFiles defaults = FilesFor(null); + LayoutOwner? active = applied?.Switch.To; + DefaultReason why = DefaultReason.None; + if (!_initialized) why = DefaultReason.NotRunning; + else if (active == null) + { + if (!perCharacter) why = DefaultReason.SettingOff; + else if (!InWorld) why = DefaultReason.NotInWorld; + else if (!Session.Decided) why = DefaultReason.WaitingForName; + else if (Session.Wanted == null) why = DefaultReason.NoCharacterName; + } + _line = PanelLayoutPolicy.SettingsLine(active, applied?.Files ?? defaults, why); + return _line; + } + + /// Settings > Display's reset button: there is a character's own layout to reset. + public static bool CanResetFromSettings => _initialized && Active != null; + + /// Settings > Display's reset confirmation text. + public static string ResetConfirmText() => PanelLayoutPolicy.ResetConfirmText(Active); + + /// Settings > Display "Reset this character's layout" (confirmed): /rc layout reset confirm, answered in chat. + public static void ResetFromSettings() + { + static void Chat(string text, bool ok) => + AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + text, ok ? 1 : 0x1A); + string? problem = Request(LayoutCommand.ResetConfirm, Chat); + if (problem != null) Chat(problem, false); + } + + /// + /// /rc layout default or reset: null when it can run, else why not (with the usage). Reset without + /// confirm only answers what it would do (). Any thread. + /// + public static string? Check(LayoutCommand kind, out string ask) + { + ask = string.Empty; + string verb = kind == LayoutCommand.MakeDefault ? "make a default from this client" : "reset the panel layout"; + LayoutOwner? active = Active; + string? problem = PanelLayoutPolicy.CharacterLayoutProblem(verb, _initialized, EngineSettings.PanelLayoutPerCharacter, + InWorld, active, Session.InFlight); + if (problem == null && kind == LayoutCommand.ResetAsk && active != null) + ask = PanelLayoutPolicy.ResetAskReply(active, FilesFor(null)); + return problem; + } + + /// + /// /rc layout default or reset confirm: queued for the render thread; gets the + /// result (text, ok) from the UI writer when it is done. Null when queued, else why not. Any thread. + /// + public static string? Request(LayoutCommand kind, Action reply) + { + string? problem = Check(kind, out _); + if (problem != null) return problem; + if (Interlocked.CompareExchange(ref _pendingOp, new PendingOp(kind, reply), null) != null) + return PanelLayoutPolicy.BusyReply; + return null; + } + + /// Settings > Display "Layout for New Characters": /rc layout default, answered in chat. + public static void MakeDefaultFromSettings() + { + static void Chat(string text, bool ok) => + AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] " + text, ok ? 1 : 0x1A); + string? problem = Request(LayoutCommand.MakeDefault, Chat); + if (problem != null) Chat(problem, false); + } + + /// Runs a queued /rc layout op (render thread, no switch in flight). + private static void RunOp(PendingOp op, Func? snapshotIni) + { + Loaded? applied = Volatile.Read(ref _applied); + if (applied?.Switch.To is not { } who) + { + // The layout changed between the command and this frame (a logout, the setting). + op.Reply(PanelLayoutPolicy.CharacterLayoutProblem("change the panel layout", true, EngineSettings.PanelLayoutPerCharacter, + InWorld, null, false) ?? PanelLayoutPolicy.FailedReply("change the panel layout", "no character layout is in use"), false); + return; + } + LayoutFiles files = applied.Files; + if (op.Kind == LayoutCommand.ResetConfirm) + { + // The next switch (this frame) copies the default over this character's files and + // places the panels from it; it answers when its files are done. + _resetReply = op.Reply; + Session.WantReseed(); + return; + } + + // Make default: this character's windows as they are now (saved to its own file too), then + // the panel store's text, both written as the default, in order after every save queued so far. + string? ini = snapshotIni?.Invoke(); + if (ini != null) + { + _activeIniText = ini; + IniWrites.Queue(files.ImGuiIni, ini); + } + LayoutFiles defaults = FilesFor(null); + UiBackgroundWriter.Enqueue("panel layout default", () => + { + try + { + IniWrites.Flush(files.ImGuiIni); + PanelLayoutFiles.MakeDefault(files, defaults, PanelStateStore.Snapshot(), ini); + RynthLog.UI($"PanelLayout: {PanelLayoutPolicy.Describe(who)}'s layout is now the default ({defaults.PanelState}, {defaults.ImGuiIni})."); + op.Reply(PanelLayoutPolicy.MakeDefaultDoneReply(who, defaults), true); + } + catch (Exception ex) + { + op.Reply(PanelLayoutPolicy.FailedReply("make the default", ex.Message), false); + } + }); + } +} diff --git a/src/RynthCore.Engine/UI/PanelLayoutFiles.cs b/src/RynthCore.Engine/UI/PanelLayoutFiles.cs new file mode 100644 index 0000000..d2a6653 --- /dev/null +++ b/src/RynthCore.Engine/UI/PanelLayoutFiles.cs @@ -0,0 +1,123 @@ +// ============================================================================ +// RynthCore.Engine - UI/PanelLayoutFiles.cs +// Panel layout per character: the file operations (PanelLayoutPolicy has the +// names and decisions). No engine state and no logging, so +// tools\PanelLayoutTests runs them against a temp folder. +// +// Every write is atomic (a temp file beside the target, then a replace: +// EngineSettingsFile.WriteAtomic), so a client that dies mid-save leaves the +// old file, never half a file. Each client writes only its own character's +// files; the default pair is written only by an explicit "make this the +// default" and, as before, by clients that use it. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.UI; + +internal static class PanelLayoutFiles +{ + private static readonly UTF8Encoding Utf8NoBom = new(false); + + /// The file's text, or null when there is none. + public static string? ReadText(string path) => File.Exists(path) ? File.ReadAllText(path) : null; + + /// Writes to atomically (creating its folder). + public static void WriteText(string path, string text) + { + string? dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + EngineSettingsFile.WriteAtomic(path, Utf8NoBom.GetBytes(text)); + } + + /// + /// A character without a layout yet starts from the default: each of its files that is missing is + /// copied from the default's (PanelLayoutPolicy.SeedPlan). Files it already has are left alone. + /// Returns which were copied. + /// + public static (bool PanelState, bool Ini) SeedMissing(LayoutFiles defaults, LayoutFiles character) + { + var plan = PanelLayoutPolicy.SeedPlan(File.Exists(character.PanelState), File.Exists(character.ImGuiIni), + File.Exists(defaults.PanelState), File.Exists(defaults.ImGuiIni)); + if (plan.PanelState) CopyAtomic(defaults.PanelState, character.PanelState); + if (plan.Ini) CopyAtomic(defaults.ImGuiIni, character.ImGuiIni); + return plan; + } + + /// + /// /rc layout reset: the character's files become copies of the default's. A file the default + /// doesn't have makes the character's empty (as a new character with no default would start), so + /// nothing of the old layout is left. Nothing is deleted. + /// + public static void CopyOver(LayoutFiles defaults, LayoutFiles character) + { + if (File.Exists(defaults.PanelState)) CopyAtomic(defaults.PanelState, character.PanelState); + else WriteText(character.PanelState, string.Empty); + if (File.Exists(defaults.ImGuiIni)) CopyAtomic(defaults.ImGuiIni, character.ImGuiIni); + else WriteText(character.ImGuiIni, string.Empty); + } + + /// + /// /rc layout default: the character's layout becomes the default for new characters. + /// is the panel store's text now; the ImGui + /// windows' (null: the character's imgui.ini as saved, and nothing when it has none). + /// + public static void MakeDefault(LayoutFiles character, LayoutFiles defaults, string panelState, string? ini) + { + WriteText(defaults.PanelState, panelState); + string? text = ini ?? ReadText(character.ImGuiIni); + if (text != null) WriteText(defaults.ImGuiIni, text); + } + + private static void CopyAtomic(string from, string to) + { + string? dir = Path.GetDirectoryName(to); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + EngineSettingsFile.WriteAtomic(to, File.ReadAllBytes(from)); + } +} + +/// +/// The latest text queued for each file, written by whoever flushes it first (the UI writer, a layout +/// switch, shutdown): an older save can never land after a newer one. Writes run one at a time. +/// +internal sealed class LatestTextWrites +{ + private readonly object _slots = new(); + private readonly object _writing = new(); + private readonly Dictionary _pending = new(StringComparer.OrdinalIgnoreCase); + private readonly Action _write; + + public LatestTextWrites(Action write) => _write = write; + + /// Keeps as what gets next (replacing an unwritten one). Any thread; never blocks on a write. + public void Queue(string path, string text) + { + lock (_slots) _pending[path] = text; + } + + /// Writes 's queued text, if any. False when there was nothing to write. Throws what the write throws. + public bool Flush(string path) + { + lock (_writing) + { + string? text; + lock (_slots) + { + if (!_pending.Remove(path, out text)) return false; + } + _write(path, text); + return true; + } + } + + /// True while has text waiting. + public bool HasPending(string path) + { + lock (_slots) return _pending.ContainsKey(path); + } +} diff --git a/src/RynthCore.Engine/UI/PanelLayoutPolicy.cs b/src/RynthCore.Engine/UI/PanelLayoutPolicy.cs new file mode 100644 index 0000000..062e94d --- /dev/null +++ b/src/RynthCore.Engine/UI/PanelLayoutPolicy.cs @@ -0,0 +1,354 @@ +// ============================================================================ +// RynthCore.Engine - UI/PanelLayoutPolicy.cs +// Panel layout per character: the pure part (no AC, no ImGui, no engine +// state), so tools\PanelLayoutTests can compile it in. PanelLayout.cs does the +// threads and the engine's stores; PanelLayoutFiles.cs the file operations. +// +// A layout is the pair of files the engine keeps window places in: +// panel_state.txt docked panels, pop-outs, the bar (place, rows, popped +// out), plugin windows (v89) and script windows (v71); +// imgui.ini the windows plugins draw with ImGui themselves. +// Every client on a PC used to share one pair, so whichever client saved last +// won and the others came back from a reload or a restart with its places. +// Now a client in the world uses its character's own pair: +// %LOCALAPPDATA%\RynthCore\layouts\\\panel_state.txt, imgui.ini +// At character select, while no character name is known, and with the setting +// off (engine.json "PanelLayoutPerCharacter": false) it uses the PC-wide +// default pair, the files every client used before: panel_state.txt beside +// that folder and C:\Games\RynthSuite\RynthAi\imgui.ini. A character without +// a layout yet starts from a copy of the default, so nothing moves the first +// time. The key is the one the engine's other per-character files use: the +// server and character of the launch context (SessionStateRegistry). +// +// Here: who owns a layout and its file names, which layout a client uses, +// what a new character's layout is seeded from, the session bookkeeping that +// decides when to switch and when panels may draw (PanelLayoutSession), and +// /rc layout's parsing and reply texts. +// ============================================================================ + +using System; +using System.Globalization; +using System.IO; +using System.Text; + +namespace RynthCore.Engine.UI; + +/// Whose layout: a character on a server (names as the launch context gives them). +internal sealed record LayoutOwner(string Server, string Character) +{ + // AC names are unique per server ignoring case, and the folders are case-insensitive too. + public bool Equals(LayoutOwner? other) => + other is not null + && string.Equals(Server, other.Server, StringComparison.OrdinalIgnoreCase) + && string.Equals(Character, other.Character, StringComparison.OrdinalIgnoreCase); + + public override int GetHashCode() => + HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(Server), StringComparer.OrdinalIgnoreCase.GetHashCode(Character)); +} + +/// The two files of one layout. +internal readonly record struct LayoutFiles(string PanelState, string ImGuiIni) +{ + public string Folder => Path.GetDirectoryName(PanelState) ?? string.Empty; +} + +/// What /rc layout asks for. +internal enum LayoutCommand { Invalid, Status, MakeDefault, ResetAsk, ResetConfirm } + +/// Why a client in the world uses the PC-wide default (the status line says it). +internal enum DefaultReason { None, SettingOff, NotInWorld, NoCharacterName, WaitingForName, NotRunning } + +internal static class PanelLayoutPolicy +{ + public const string PanelStateFileName = "panel_state.txt"; + public const string ImGuiIniFileName = "imgui.ini"; + public const string LayoutsFolder = "layouts"; + + /// After login, how long a client waits for the character's name before it uses what it has. + public const long IdentityWaitMs = 3000; + + /// A switch that hasn't finished this long after it was asked for no longer keeps panels from drawing. + public const long ApplyGiveUpMs = 5000; + + // ── who, and the file names ──────────────────────────────────────── + + /// The layout's owner, or null while no character name is known. + public static LayoutOwner? Owner(string? server, string? character) + { + string c = (character ?? string.Empty).Trim(); + if (c.Length == 0) return null; + return new LayoutOwner((server ?? string.Empty).Trim(), c); + } + + /// "Name on Server" (just the name when the server isn't known), for replies and the log. + public static string Describe(LayoutOwner who) => + who.Server.Length > 0 ? who.Character + " on " + who.Server : who.Character; + + /// The PC-wide default pair: today's files. + public static LayoutFiles DefaultFiles(string localRoot, string defaultIniPath) => + new(Path.Combine(localRoot, PanelStateFileName), defaultIniPath); + + /// A character's pair: <localRoot>\layouts\<server>\<character>\. + public static LayoutFiles CharacterFiles(string localRoot, LayoutOwner who) + { + string dir = Path.Combine(localRoot, LayoutsFolder, SafeSegment(who.Server), SafeSegment(who.Character)); + return new LayoutFiles(Path.Combine(dir, PanelStateFileName), Path.Combine(dir, ImGuiIniFileName)); + } + + /// The files for ; null = the PC-wide default. + public static LayoutFiles FilesFor(string localRoot, string defaultIniPath, LayoutOwner? who) => + who is null ? DefaultFiles(localRoot, defaultIniPath) : CharacterFiles(localRoot, who); + + private const int MaxSegment = 64; + + private static readonly string[] ReservedNames = + { + "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", + "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", + "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", + }; + + /// + /// as one folder name: characters Windows doesn't allow become '_', no + /// trailing dot or space, not a device name, at most 64 characters; "_" for an empty name. A name + /// that had to change gets "-" and a hash of the original, so two names that clean up alike + /// (a server "A:B" and one "A?B") keep apart. Names that are already safe stay as they are. + /// + public static string SafeSegment(string? name) + { + string original = (name ?? string.Empty).Trim(); + if (original.Length == 0) return "_"; + char[] invalid = Path.GetInvalidFileNameChars(); + var sb = new StringBuilder(original.Length); + foreach (char ch in original) + sb.Append(ch < 32 || Array.IndexOf(invalid, ch) >= 0 ? '_' : ch); + string s = sb.ToString().TrimEnd('.', ' '); + if (s.Length > MaxSegment) s = s.Substring(0, MaxSegment).TrimEnd('.', ' '); + string stem = s.Split('.')[0]; + if (s.Length == 0 || Array.Exists(ReservedNames, r => r.Equals(stem, StringComparison.OrdinalIgnoreCase))) + s = "_" + s; + if (s == original) return s; + uint h = 2166136261; // FNV-1a over the lower-cased original + foreach (char ch in original.ToLowerInvariant()) + h = (h ^ ch) * 16777619; + return s + "-" + h.ToString("x8", CultureInfo.InvariantCulture); + } + + // ── which layout ───────────────────────────────────────────────────── + + /// The layout a client uses: its character's while in the world with the setting on and a + /// name known; otherwise (null) the PC-wide default. + public static LayoutOwner? Choose(bool perCharacter, bool inWorld, LayoutOwner? identity) => + perCharacter && inWorld ? identity : null; + + /// Which of a new character's files are copied from the default: each one the character + /// doesn't have yet and the default has (a missing default file leaves the character's missing too). + public static (bool PanelState, bool Ini) SeedPlan(bool characterPanelState, bool characterIni, bool defaultPanelState, bool defaultIni) => + (!characterPanelState && defaultPanelState, !characterIni && defaultIni); + + /// + /// Whether an automatic save of the ImGui windows (the dirty timer, shutdown) may write the file in + /// use. Always for a character's layout. The default: with the setting off (the shared file, as + /// before), or in the world by a client whose context never held a character's windows (one with + /// no character name, which uses the default as before). Not at character select: the default + /// there is this client's copy from when it loaded it, and writing it back could undo another + /// client's /rc layout default; nor with the windows of a character that just logged out. An + /// explicit save (Save Layout Now) writes whatever is in use. + /// + public static bool MayAutoSaveIni(bool characterLayout, bool perCharacter, bool inWorld, bool contextHeldCharacter) => + characterLayout || !perCharacter || (inWorld && !contextHeldCharacter); + + // ── /rc layout ─────────────────────────────────────────────────────── + + public const string Usage = "Usage: /rc layout [status] | default | reset [confirm]"; + + /// "/rc layout" and its arguments (any case, any spacing). + public static LayoutCommand ParseCommand(string? args) + { + string a = string.Join(' ', (args ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant(); + return a switch + { + "" or "status" => LayoutCommand.Status, + "default" => LayoutCommand.MakeDefault, + "reset" => LayoutCommand.ResetAsk, + "reset confirm" => LayoutCommand.ResetConfirm, + _ => LayoutCommand.Invalid, + }; + } + + public static string ReasonText(DefaultReason why) => why switch + { + DefaultReason.SettingOff => "Panel layout per character is off (Settings > Display)", + DefaultReason.NotInWorld => "no character is in the world", + DefaultReason.NoCharacterName => "no character name is known for this client (it wasn't started by the RynthCore launcher)", + DefaultReason.WaitingForName => "still waiting for the character's name", + DefaultReason.NotRunning => "panel layouts aren't running in this client", + _ => "the layout is still switching", + }; + + /// /rc layout: the layout in use and its files, and the default's. + public static string[] StatusLines(LayoutOwner? inUse, LayoutFiles files, DefaultReason why, LayoutFiles defaults, bool perCharacter) + { + if (inUse is not null) + return new[] + { + $"Panel layout: {Describe(inUse)}'s own: {files.PanelState} and {files.ImGuiIni}.", + $"New characters start from the default ({defaults.PanelState} and {defaults.ImGuiIni}): /rc layout default makes this layout that default, /rc layout reset puts this character back to it.", + }; + if (why == DefaultReason.NotRunning) + return new[] { $"Can't show the panel layout: {ReasonText(why)} (the engine's panels aren't up)." }; + string line = $"Panel layout: the PC-wide default ({ReasonText(why)}): {files.PanelState} and {files.ImGuiIni}."; + return perCharacter + ? new[] { line, "Each character gets its own layout, a copy of this default, when it logs in." } + : new[] { line }; + } + + /// + /// Settings > Display's line under "Panel Layout Per Character": whose layout is in use and the + /// folder its files are in (a character's), or the PC-wide default and why. + /// + public static string SettingsLine(LayoutOwner? inUse, LayoutFiles files, DefaultReason why) + { + if (inUse is not null) + return $"In use: {Describe(inUse)}'s own layout ({files.Folder})."; + if (why == DefaultReason.NotRunning) + return "In use: none (" + ReasonText(why) + ")."; + return $"In use: the PC-wide default ({ReasonText(why)}): {files.PanelState}."; + } + + /// Settings > Display's reset confirmation: what "Reset this character's layout" will do. + public static string ResetConfirmText(LayoutOwner? who) => + who is null + ? "No character's own layout is in use, so there is nothing to reset." + : $"Replace {Describe(who)}'s panel layout with the default for new characters?\nOpen panels move to the default's places. This can't be undone."; + + /// Why /rc layout default or reset can't run (null: it can), with the usage. + public static string? CharacterLayoutProblem(string verb, bool running, bool perCharacter, bool inWorld, LayoutOwner? inUse, bool switching) + { + string why; + if (!running) why = ReasonText(DefaultReason.NotRunning); + else if (!perCharacter) why = ReasonText(DefaultReason.SettingOff); + else if (!inWorld) why = ReasonText(DefaultReason.NotInWorld); + else if (switching) why = "the layout is still switching; try again in a moment"; + else if (inUse is null) why = ReasonText(DefaultReason.NoCharacterName); + else return null; + return $"Can't {verb}: {why}. {Usage}"; + } + + public static string ResetAskReply(LayoutOwner who, LayoutFiles defaults) => + $"This replaces {Describe(who)}'s panel layout with the default for new characters ({defaults.PanelState}): open panels move to the default's places. To go ahead: /rc layout reset confirm."; + + public static string ResetDoneReply(LayoutOwner who) => + $"{Describe(who)}'s panel layout was reset from the default: the panels are in the default's places now."; + + public static string MakeDefaultDoneReply(LayoutOwner who, LayoutFiles defaults) => + $"{Describe(who)}'s panel layout is now the default for new characters ({defaults.PanelState} and {defaults.ImGuiIni}). Characters that already have a layout keep their own."; + + public static string FailedReply(string what, string error) => $"Can't {what}: {error}."; + + public const string BusyReply = "Can't: a panel layout change is already waiting; try again in a moment. " + Usage; +} + +/// A switch to start: write out (when it is a character's), seed or reseed +/// 's files, load them. One at a time, in order with the other UI writes. +internal readonly record struct LayoutSwitch(int Gen, LayoutOwner? From, bool FromKnown, LayoutOwner? To, bool Reseed, long ForLoginMs) +{ + /// The layout switched away from is a character's and is kept (not a reset): its files are written out first. + public bool FlushFrom => FromKnown && From is not null && !Reseed; +} + +/// +/// One client's layout bookkeeping, render thread only: which layout it should use, when to start a +/// switch, and whether panels may draw. A switch is asked for (Tick), done in the background +/// (PanelLayout: files, then the stores), then applied on the render thread (MarkApplied), one at a time. +/// After a login (or the hot reload that marks one), panels draw only once the character's layout is +/// applied, so they never show first at the default places and then jump. +/// +internal sealed class PanelLayoutSession +{ + private int _gen; // the last switch asked for + private LayoutOwner? _target; // ... and the layout it goes to + private bool _asked; // a switch was asked for at least once + private long _askedAtMs; + private long _askedForLogin; // the login (LoginCompleteAtMs) that switch was decided for; 0 = not in the world + private int _appliedGen; + private LayoutOwner? _applied; + private long _readyForLogin; // the login whose layout is applied; 0 = none + private bool _reseedWanted; // /rc layout reset confirm: the next switch copies the default over the character's files + + /// The layout applied last (null = the default). Meaningful once . + public LayoutOwner? AppliedLayout => _applied; + public bool AnyApplied => _appliedGen > 0; + /// A switch was asked for and isn't applied yet. + public bool InFlight => _asked && _appliedGen != _gen; + /// The layout the client should use, as of the last Tick; meaningful while . + public LayoutOwner? Wanted { get; private set; } + /// False only in the world while the character's name isn't settled yet. + public bool Decided { get; private set; } + + /// The next switch reseeds the character's files from the default (a reset). + public void WantReseed() => _reseedWanted = true; + + /// + /// Once a frame. : the login's identity is recorded + /// (SessionStateRegistry); is it (null: no character name). + /// Returns a switch to start, or null. + /// + public LayoutSwitch? Tick(long nowMs, bool perCharacter, bool inWorld, long loginAtMs, bool identityRecorded, LayoutOwner? identity) + { + if (!inWorld) + { + Decided = true; + Wanted = null; + } + // (A login time of 0 in the world: the flag is set, its time not yet; wait for it.) + else if (loginAtMs != 0 && (identityRecorded || nowMs - loginAtMs >= PanelLayoutPolicy.IdentityWaitMs)) + { + Decided = true; + Wanted = PanelLayoutPolicy.Choose(perCharacter, inWorld, identity); + } + else + { + Decided = false; + _reseedWanted = false; // a new login: a reset asked for the old one is dropped + return null; // the name is on its way: no switch, and panels wait (ReadyToDraw) + } + + if (InFlight) return null; // one switch at a time; the next Tick after it is applied looks again + long forLogin = inWorld ? loginAtMs : 0; + bool reseed = _reseedWanted && Wanted is not null && Equals(Wanted, _applied); + _reseedWanted = false; + if (_asked && Equals(Wanted, _target) && !reseed) + { + // Already in use (a relogin to the layout the client had, or the default with the setting off). + if (forLogin != 0) _readyForLogin = forLogin; + return null; + } + var sw = new LayoutSwitch(++_gen, _asked ? _target : null, _asked, Wanted, reseed, forLogin); + _target = Wanted; + _asked = true; + _askedAtMs = nowMs; + _askedForLogin = forLogin; + return sw; + } + + /// Switch is applied on the render thread (its files are in the stores and the ImGui context). + public void MarkApplied(int gen) + { + if (gen != _gen || gen == _appliedGen) return; + _appliedGen = gen; + _applied = _target; + if (_askedForLogin != 0) _readyForLogin = _askedForLogin; + } + + /// + /// True when panels may draw: outside the world always (nothing draws there), in the world once the + /// layout decided for this login is applied. A switch stuck past ApplyGiveUpMs stops holding them. + /// + public bool ReadyToDraw(long nowMs, bool inWorld, long loginAtMs) + { + if (!inWorld) return true; + if (loginAtMs != 0 && _readyForLogin == loginAtMs) return true; + return Decided && InFlight && nowMs - _askedAtMs >= PanelLayoutPolicy.ApplyGiveUpMs; + } +} diff --git a/src/RynthCore.Engine/UI/PanelStateStore.cs b/src/RynthCore.Engine/UI/PanelStateStore.cs index 329325c..c6ed10f 100644 --- a/src/RynthCore.Engine/UI/PanelStateStore.cs +++ b/src/RynthCore.Engine/UI/PanelStateStore.cs @@ -18,13 +18,17 @@ // without a barlayout= row gives the toolbar one row, no icon limit. // // Stored under %LocalAppData%\RynthCore\panel_state.txt — survives reloads -// and out-of-game (the Runtime dir might be wiped during deploy). +// and out-of-game (the Runtime dir might be wiped during deploy). That is the +// PC-wide default; in the world a client uses its character's own copy, +// layouts\\\panel_state.txt (PanelLayout switches the file +// with SwitchTo). Saves are atomic: a temp file, then a replace. // ============================================================================ using System; using System.Collections.Generic; using System.Globalization; using System.IO; +using System.Text; using RynthCore.Engine.Plugins; namespace RynthCore.Engine.UI; @@ -48,8 +52,10 @@ internal static class PanelStateStore private static (double Left, double Top)? _barFloatingPosition; private static int _barRows = BarLayout.DefaultRows, _barMaxPerRow = BarLayout.NoLimit; private static bool _loaded; + private static string? _path; // the file in use (SwitchTo); null = the PC-wide default - private static string FilePath + /// The PC-wide default file: %LocalAppData%\RynthCore\panel_state.txt. + internal static string DefaultPath { get { @@ -58,6 +64,48 @@ internal static class PanelStateStore } } + private static string FilePath => _path ?? DefaultPath; + + /// The file in use now (the default, or the character's). Any thread. + internal static string CurrentPath + { + get { lock (Sync) return FilePath; } + } + + /// + /// Panel layout per character (PanelLayout): from now on the store reads and writes + /// . With the file in use is written + /// out first (a character's layout being left); the default is never written by a switch. + /// Everything in memory is then replaced by 's contents (none: an empty + /// layout). The UI writer's thread, in order with the other saves. + /// + internal static void SwitchTo(string path, bool flushCurrent) + { + lock (Sync) + { + if (flushCurrent && _loaded) Save(); + Panels.Clear(); + _barPosition = null; + _barFloating = false; + _barFloatingPosition = null; + _barRows = BarLayout.DefaultRows; + _barMaxPerRow = BarLayout.NoLimit; + _path = path; + _loaded = false; + Load(); + } + } + + /// The file's text for what is in memory now (/rc layout default writes it as the default). Any thread. + internal static string Snapshot() + { + lock (Sync) + { + Load(); + return Format(); + } + } + public static (double Left, double Top)? BarPosition { get { lock (Sync) { Load(); return _barPosition; } } @@ -276,34 +324,8 @@ internal static class PanelStateStore if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); - using var sw = new StreamWriter(path, append: false); - sw.WriteLine("# RynthCore Avalonia panel state — auto-generated, hand-edits OK."); - if (_barPosition is { } bar) - { - // Always emit the extended form if we have any floating state to - // remember; legacy 2-column form only when no popout has happened. - if (_barFloating || _barFloatingPosition is not null) - { - (double fl, double ft) = _barFloatingPosition ?? (0, 0); - sw.WriteLine(FormattableString.Invariant( - $"bar={bar.Left:0.##},{bar.Top:0.##},{(_barFloating ? "floating" : "docked")},{fl:0.##},{ft:0.##}")); - } - else - { - sw.WriteLine(FormattableString.Invariant($"bar={bar.Left:0.##},{bar.Top:0.##}")); - } - } - - // Only when changed: a file that never had the row reads back the same. - if (_barRows != BarLayout.DefaultRows || _barMaxPerRow != BarLayout.NoLimit) - sw.WriteLine("barlayout=" + BarLayout.Format(_barRows, _barMaxPerRow)); - - foreach (var kv in Panels) - { - PanelEntry e = kv.Value; - sw.WriteLine(FormattableString.Invariant( - $"panel.{kv.Key}={(e.Open ? "open" : "closed")},{e.Left:0.##},{e.Top:0.##},{e.Width:0.##},{e.Height:0.##},{(e.Floating ? "floating" : "docked")},{e.FloatingLeft:0.##},{e.FloatingTop:0.##}")); - } + // Atomic (temp file, then replace): a client that dies mid-save leaves the old file. + EngineSettingsFile.WriteAtomic(path, new UTF8Encoding(false).GetBytes(Format())); } catch (Exception ex) { @@ -311,6 +333,40 @@ internal static class PanelStateStore } } + /// The file's text for what is in memory (under Sync). + private static string Format() + { + var sw = new StringBuilder(); + sw.AppendLine("# RynthCore Avalonia panel state — auto-generated, hand-edits OK."); + if (_barPosition is { } bar) + { + // Always emit the extended form if we have any floating state to + // remember; legacy 2-column form only when no popout has happened. + if (_barFloating || _barFloatingPosition is not null) + { + (double fl, double ft) = _barFloatingPosition ?? (0, 0); + sw.AppendLine(FormattableString.Invariant( + $"bar={bar.Left:0.##},{bar.Top:0.##},{(_barFloating ? "floating" : "docked")},{fl:0.##},{ft:0.##}")); + } + else + { + sw.AppendLine(FormattableString.Invariant($"bar={bar.Left:0.##},{bar.Top:0.##}")); + } + } + + // Only when changed: a file that never had the row reads back the same. + if (_barRows != BarLayout.DefaultRows || _barMaxPerRow != BarLayout.NoLimit) + sw.AppendLine("barlayout=" + BarLayout.Format(_barRows, _barMaxPerRow)); + + foreach (var kv in Panels) + { + PanelEntry e = kv.Value; + sw.AppendLine(FormattableString.Invariant( + $"panel.{kv.Key}={(e.Open ? "open" : "closed")},{e.Left:0.##},{e.Top:0.##},{e.Width:0.##},{e.Height:0.##},{(e.Floating ? "floating" : "docked")},{e.FloatingLeft:0.##},{e.FloatingTop:0.##}")); + } + return sw.ToString(); + } + private static bool TryParseDoubles(string csv, int expected, out double[] values) { string[] parts = csv.Split(','); diff --git a/src/RynthCore.Engine/UI/Panels/RadarSettingsStore.cs b/src/RynthCore.Engine/UI/Panels/RadarSettingsStore.cs index 7c65425..1cbc415 100644 --- a/src/RynthCore.Engine/UI/Panels/RadarSettingsStore.cs +++ b/src/RynthCore.Engine/UI/Panels/RadarSettingsStore.cs @@ -49,6 +49,16 @@ internal static class RadarSettingsStore /// ImGui face: a left-click on a dot selects that object in game. public static bool ClickToSelect = true; + /// ImGui face: the object selected in game gets a ring round its marker (and an edge arrow + /// when it is off the picture). On by default (2026-10-31). + public static bool HighlightSelected = true; + /// ...and the hover label (name, distance, health) beside it. Off by default: the box covers + /// the radar, and the ring alone says which one is selected (2026-10-31). + public static bool ShowSelectedLabel = false; + /// The ring's colour (ARGB): magenta, a hue none of the kinds use by default. + public const uint DefaultSelectedColor = 0xFFFF2ED9; + public static uint SelectedColor = DefaultSelectedColor; + /// ImGui face: the World Map's picture drawn behind the radar while you're outdoors (off by default). public static bool ShowWorldMap; /// How strongly that picture shows (the radar's own Opacity applies on top). @@ -136,7 +146,12 @@ internal static class RadarSettingsStore /// The kind's colour (ARGB); white for a kind this engine doesn't know. public static uint KindColor(byte kind) => kind < KindColors.Length ? KindColors[kind] : 0xFFFFFFFF; - public static void ResetKindColors() => Array.Copy(DefaultKindColors, KindColors, KindColors.Length); + /// Every kind's colour, and the selection ring's, back to the defaults. + public static void ResetKindColors() + { + Array.Copy(DefaultKindColors, KindColors, KindColors.Length); + SelectedColor = DefaultSelectedColor; + } /// Every marker size, name box and text size back to its default (show boxes and colours stay). public static void ResetSizes() @@ -204,6 +219,12 @@ internal static class RadarSettingsStore case "showLifestones": ShowLifestones = val == "1"; break; case "showGroundItems": ShowGroundItems = val == "1"; break; case "clickSelect": ClickToSelect = val == "1"; break; + case "selectHighlight": HighlightSelected = val == "1"; break; + case "selectLabel": ShowSelectedLabel = val == "1"; break; + case "selectedColor": + if (uint.TryParse(val, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint sc)) + SelectedColor = sc; + break; case "worldMap": ShowWorldMap = val == "1"; break; case "worldMapOpacity": if (float.TryParse(val, NumberStyles.Float, CultureInfo.InvariantCulture, out float wo) && float.IsFinite(wo)) @@ -267,6 +288,11 @@ internal static class RadarSettingsStore sw.WriteLine($"showLifestones={(ShowLifestones ? "1" : "0")}"); sw.WriteLine($"showGroundItems={(ShowGroundItems ? "1" : "0")}"); sw.WriteLine($"clickSelect={(ClickToSelect ? "1" : "0")}"); + sw.WriteLine($"selectHighlight={(HighlightSelected ? "1" : "0")}"); + sw.WriteLine($"selectLabel={(ShowSelectedLabel ? "1" : "0")}"); + // Like the kind colours: only when it differs from the default. + if (SelectedColor != DefaultSelectedColor) + sw.WriteLine(FormattableString.Invariant($"selectedColor={SelectedColor:X8}")); sw.WriteLine($"worldMap={(ShowWorldMap ? "1" : "0")}"); sw.WriteLine(FormattableString.Invariant($"worldMapOpacity={WorldMapOpacity:0.##}")); sw.WriteLine(FormattableString.Invariant($"compassSize={CompassSize:0.##}")); diff --git a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs index 882ed0d..3252e08 100644 --- a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs @@ -334,6 +334,8 @@ internal static class SettingsPanel case SettingKind.Spacer: return Spacer(); case SettingKind.Button: + // A button that asks first is the ImGui panel's only (this panel is being retired). + if (row.Confirm != null) return null; return ButtonRow(row.Label, row.ButtonText ?? row.Label, () => { // A settings edit is pushed like a typed value; the tab is rebuilt so the diff --git a/src/RynthCore.Engine/UI/Sections/PluginWindows.cs b/src/RynthCore.Engine/UI/Sections/PluginWindows.cs index 7f9e4b9..fbcd86c 100644 --- a/src/RynthCore.Engine/UI/Sections/PluginWindows.cs +++ b/src/RynthCore.Engine/UI/Sections/PluginWindows.cs @@ -101,7 +101,7 @@ internal static class PluginWindows string sig = WindowPlan.Signature(w); if (Live.TryGetValue(title, out Hosted? h) && h.Signature == sig) continue; SectionWindowDecl decl = w; - Func face = () => new PluginWindowFace(decl.Plugin, decl.Surface, decl.Title, decl.FitHeight, decl.MinWidth); + Func face = () => new PluginWindowFace(decl.Plugin, decl.Surface, decl.Title, decl.FitHeight, decl.MinWidth, decl.DrawScale); if (takeOvers.Contains(title)) { // An engine panel's place: its key, saved place and open state stay; nothing to reopen. diff --git a/src/RynthCore.Engine/UI/TrackerSettings.cs b/src/RynthCore.Engine/UI/TrackerSettings.cs index 170d66d..3c8fbab 100644 --- a/src/RynthCore.Engine/UI/TrackerSettings.cs +++ b/src/RynthCore.Engine/UI/TrackerSettings.cs @@ -1,7 +1,8 @@ // ============================================================================ // RynthCore.Engine - UI/TrackerSettings.cs -// The Tracker panel's background opacity, shared by its ImGui and Avalonia -// faces: %APPDATA%\RynthCore\rynthtracker_settings.json ({"bgAlpha":0-255}). +// The Tracker panel's background opacity and its text-only look, shared by its +// ImGui and Avalonia faces: %APPDATA%\RynthCore\rynthtracker_settings.json +// ({"bgAlpha":0-255,"textOnly":false}). // Loaded on the engine init worker; saves go through UiBackgroundWriter so // the ImGui face never writes a file from AC's thread. // ============================================================================ @@ -15,11 +16,14 @@ namespace RynthCore.Engine.UI; internal static class TrackerSettings { private static volatile int _bgAlpha = 0xCC; // ~80% + private static volatile bool _textOnly; private static volatile bool _loaded; private static readonly object LoadSync = new(); + // RYNTHCORE_TRACKER_SETTINGS: another file (tools\TrackerSettingsTests). private static string SettingsPath => - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthtracker_settings.json"); + Environment.GetEnvironmentVariable("RYNTHCORE_TRACKER_SETTINGS") is { Length: > 0 } over ? over + : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthtracker_settings.json"); /// Background alpha 0-255. public static byte BgAlpha @@ -31,6 +35,20 @@ internal static class TrackerSettings } } + /// + /// Text only (2026-11-01, the owner: "make the window invisible besides the writing"): docked, the + /// panel has no frame, title or background, only its rows (shadowed), and clicks pass through + /// except over them. + /// + public static bool TextOnly + { + get + { + EnsureLoaded(); + return _textOnly; + } + } + /// Sets the alpha now; writes the file in the background. public static void SetBgAlpha(byte alpha, bool save) { @@ -40,6 +58,14 @@ internal static class TrackerSettings UiBackgroundWriter.Enqueue("tracker settings", Save); } + /// Text only on or off, saved in the background. + public static void SetTextOnly(bool on) + { + EnsureLoaded(); + _textOnly = on; + UiBackgroundWriter.Enqueue("tracker settings", Save); + } + public static void EnsureLoaded() { if (_loaded) return; @@ -54,6 +80,8 @@ internal static class TrackerSettings using var doc = JsonDocument.Parse(File.ReadAllText(path)); if (doc.RootElement.TryGetProperty("bgAlpha", out var v)) _bgAlpha = Math.Clamp(v.GetInt32(), 0, 255); + if (doc.RootElement.TryGetProperty("textOnly", out var t) && t.ValueKind is JsonValueKind.True or JsonValueKind.False) + _textOnly = t.GetBoolean(); } } catch { } @@ -61,13 +89,17 @@ internal static class TrackerSettings } } + /// The settings file's text. + internal static string ToJson(int bgAlpha, bool textOnly) => + $"{{\"bgAlpha\":{bgAlpha},\"textOnly\":{(textOnly ? "true" : "false")}}}"; + private static void Save() { try { string path = SettingsPath; Directory.CreateDirectory(Path.GetDirectoryName(path)!); - File.WriteAllText(path, $"{{\"bgAlpha\":{_bgAlpha}}}"); + File.WriteAllText(path, ToJson(_bgAlpha, _textOnly)); } catch { } } diff --git a/src/RynthCore.PluginSdk/UiTypes.cs b/src/RynthCore.PluginSdk/UiTypes.cs index d35b6b2..7aa9e91 100644 --- a/src/RynthCore.PluginSdk/UiTypes.cs +++ b/src/RynthCore.PluginSdk/UiTypes.cs @@ -56,4 +56,10 @@ public enum RynthUiHookFlags : uint ItemDropped = 1u << 6, /// The client's cleanup has started: no more ticks or events. CleanupStarted = 1u << 7, + /// + /// Not a hook (2026-10-30): the engine's Damage panel draws the optional "mstats" of a + /// RynthPluginGetMonsterDamageJson row (evades and resists both ways) under that monster. + /// Engines without it ignore the field. + /// + DamageRowStats = 1u << 8, } diff --git a/tools/ChatCommandReplyTests/ChatCommandReplyTests.csproj b/tools/ChatCommandReplyTests/ChatCommandReplyTests.csproj index 550dec1..ed5a2f3 100644 --- a/tools/ChatCommandReplyTests/ChatCommandReplyTests.csproj +++ b/tools/ChatCommandReplyTests/ChatCommandReplyTests.csproj @@ -23,6 +23,10 @@ + + + + diff --git a/tools/ChatCommandReplyTests/Program.cs b/tools/ChatCommandReplyTests/Program.cs index d888bc8..5319ea4 100644 --- a/tools/ChatCommandReplyTests/Program.cs +++ b/tools/ChatCommandReplyTests/Program.cs @@ -26,6 +26,7 @@ internal static class Program ReplyTexts(); SourceMatchesCatalog(); ChatBurst(); + ControlsRunTheirCommands(); Console.WriteLine(); Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); @@ -98,12 +99,19 @@ internal static class Program ("inventory", "inv", "inv now"), ("inventory", "inventory", "inventory now"), ("sense", "sense", "sense now"), + ("sense", "sense compact on", "sense compact maybe"), + ("sense", "sense collapse off", "sense collapse on off"), + ("sense", "sense view collapsed", "sense view huge"), + ("sense", "sense compact", "sense frob on"), ("characters", "chars", "characters now"), ("itemcount", "itemhud", "itemcount now"), ("resetbar", "barreset", "resetbar now"), ("actionstate", "actions", "actionstate now"), ("unlockactions", "unlock", "unlockactions now"), ("vitals", "hud", "vitals now"), + ("layout", "layout", "layout frob"), + ("layout", "layout reset confirm", "layout reset now"), + ("layout", "layout default", "layout default now"), }; private static void EveryVerbValidAndInvalid() @@ -155,6 +163,7 @@ internal static class Program ("report", "report the map froze", "report", "ProblemReport (alone: opens the panel)"), ("flight", "flight mark here", "flight frob", "FlightRecorder.HandleCommand: its usage"), ("autoid", "autoid limited", "autoid frob", "AutoIdService.HandleCommand: its usage"), + ("uicost", "uicost 80", "uicost frob", "UiCost.HandleCommand: its usage"), ("netmsg", "netmsg log on", "netmsg frob", "ServerMessageStream.HandleCommand: its usage"), ("hotkeys", "hotkeys", "hotkeys frob", "HotkeyCommandParser: unknown verb + usage"), ("settings", "settings Hotkeys", "settings frob", "SettingsCommand: no tab called 'frob' (tabs: ...)"), @@ -372,6 +381,32 @@ internal static class Program Check(spam <= 22, $"a retry loop sending every 5 ms for 1 s: at most 12 + 10 (got {spam})"); } + // ── controls that run a command (2026-10-31: buttons for what commands do) ── + + private static void ControlsRunTheirCommands() + { + Case("the Sense panel's view switch: each button names a /rc sense command that runs"); + foreach (RynthCore.Engine.UI.Data.SenseLayoutMode to in new[] { RynthCore.Engine.UI.Data.SenseLayoutMode.Full, + RynthCore.Engine.UI.Data.SenseLayoutMode.Compact, RynthCore.Engine.UI.Data.SenseLayoutMode.Collapsed }) + { + string tip = RynthCore.Engine.UI.Data.SenseLayout.SwitchTip(to); + Match m = Regex.Match(tip, @"/rc (sense [a-z ]+)\)"); + Check(m.Success, $"the {to} button's tip names its command: {tip}"); + if (!m.Success) continue; + ChatVerbCheck c = ChatCommandReplies.Check(m.Groups[1].Value); + Check(c.Problem == null && c.Verb?.Name == "sense", $"'/rc {m.Groups[1].Value}' runs"); + } + + Case("the Lua panel's live reload toggle"); + Check(RynthCore.Engine.UI.Data.LuaLiveReload.Label(null) == null, "a RynthLua without live reload: no toggle"); + Check(RynthCore.Engine.UI.Data.LuaLiveReload.Label(true) == "Live reload: on" + && RynthCore.Engine.UI.Data.LuaLiveReload.Label(false) == "Live reload: off", "it says the value now"); + Check(RynthCore.Engine.UI.Data.LuaLiveReload.ClickArgs(true) == "livereload off" + && RynthCore.Engine.UI.Data.LuaLiveReload.ClickArgs(false) == "livereload on", "a click sends the other value (/lua livereload on|off)"); + Check(RynthCore.Engine.UI.Data.LuaLiveReload.Tip(true).Contains("/lua livereload on|off", StringComparison.Ordinal) + && RynthCore.Engine.UI.Data.LuaLiveReload.Tip(false).Contains("/lua livereload on|off", StringComparison.Ordinal), "the tip names the command"); + } + private static void Case(string name) { _case = name; diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index 4404381..3f9392a 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -60,6 +60,11 @@ internal static class Program LineColorRetail(); LineColorPrecedence(); LineColorJson(); + HighlightRouting(); + HighlightPrecedence(); + HighlightBand(); + HighlightJson(); + HighlightOldReader(); Console.WriteLine(); Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); @@ -468,6 +473,216 @@ internal static class Program Check(!ChatLineColors.AnySet, "loading a file without it clears them"); } + // ── Highlight line (2026-11-01): a band behind the whole line ────────── + // ChatColorMode.Highlight -> ChatRoute.HighlightArgb (the rule's colour); the face draws + // ChatColorModes.BandArgb of it behind all the line's rows. The first matching Highlight + // rule wins the band, on its own: Line and Match rules still colour the text. + + private const uint HlA = 0xFF3366FF, HlB = 0xFFFF6633, LineC = 0xFF00FF00, MatchC = 0xFFFF00FF; + + private static ChatFilterRule ColourRule(string pattern, ChatColorMode mode, uint argb, + ChatRuleAction action = ChatRuleAction.Color, string when = "", string tab = "") + { + ChatFilterRule r = Rule(pattern, action, when, tab); + r.ColorMode = mode; + r.ColorArgb = argb; + return r; + } + + private static ChatRoute Route(string text, string channel, int type, out List trace, params ChatFilterRule[] rules) + { + trace = new List(); + var router = RetailRouter(rules); + ChatRoute traced = router.Evaluate(text, channel, type, trace); + ChatRoute quiet = router.Evaluate(text, channel, type, null); + // The pump routes without a trace, the test box with one: they must agree. + Check(traced.HighlightArgb == quiet.HighlightArgb && traced.LineArgb == quiet.LineArgb + && traced.Hidden == quiet.Hidden && traced.InHome == quiet.InHome + && (traced.Spans?.Length ?? 0) == (quiet.Spans?.Length ?? 0), $"'{text}': traced and untraced routes agree"); + return traced; + } + + private static bool Says(List trace, int rule, string what) => + trace.Any(s => s.Rule == rule && s.What.Contains(what, StringComparison.Ordinal)); + + private static void HighlightRouting() + { + Case("highlight: the route carries the rule's colour"); + try + { + ResetPresets(); + ChatRoute r = Route("Bob tells you, \"hi\"", "Chat", 3, out var trace, ColourRule("tells you", ChatColorMode.Highlight, HlA)); + Check(r.HighlightArgb == HlA, "a matching Highlight rule sets HighlightArgb to its colour"); + Check(r.LineArgb == null && r.Spans == null, "...and leaves the text colour alone"); + Check(!r.Hidden && r.InHome && r.Tabs == null, "...and the routing alone"); + Check(Says(trace, 0, "highlights the line"), "the test box says it highlights the line"); + + ChatRoute none = Route("Bob says, \"hi\"", "Chat", 2, out var t2, ColourRule("tells you", ChatColorMode.Highlight, HlA)); + Check(ReferenceEquals(none, ChatRoute.Default), "no match: the shared default route (no allocation)"); + Check(t2.Count == 0, "...and nothing in the test box"); + + var off = ColourRule("tells you", ChatColorMode.Highlight, HlA); + off.Enabled = false; + Check(Route("Bob tells you, \"hi\"", "Chat", 3, out _, off).HighlightArgb == null, "a rule that is off doesn't highlight"); + + var combatOnly = ColourRule("evaded", ChatColorMode.Highlight, HlA, when: "chan:Combat"); + Check(Route("You evaded Tusker Guard!", "Combat", 6, out _, combatOnly).HighlightArgb == HlA, "When chan:Combat: a Combat line is highlighted"); + Check(Route("Bob says, \"evaded\"", "Chat", 2, out _, combatOnly).HighlightArgb == null, "...a Chat line isn't"); + + ChatRoute moved = Route("Bob tells you, \"hi\"", "Chat", 3, out var t3, + ColourRule("tells you", ChatColorMode.Highlight, HlA, ChatRuleAction.Move, tab: "Tells")); + Check(moved.HighlightArgb == HlA && !moved.InHome && moved.Tabs is ["Tells"], "a Move rule can highlight: moved and highlighted"); + Check(Says(t3, 0, "moves it to Tells") && Says(t3, 0, "highlights the line"), "...the test box says both"); + + ChatRoute hidden = Route("spam spam", "Chat", 2, out _, + Rule("spam", ChatRuleAction.Hide), ColourRule("spam", ChatColorMode.Highlight, HlA)); + Check(hidden.Hidden && hidden.HighlightArgb == null, "a Hide rule above: hidden, nothing to highlight"); + + Check(!ChatRetailVerdict.IsHidden(RetailRouter(ColourRule("spam", ChatColorMode.Highlight, HlA)), "buy spam now", 3), + "a Highlight rule never hides a line from the retail chat"); + + var mentionRouter = new ChatRouter(new[] { ColourRule("Tester", ChatColorMode.Highlight, HlA) }, + new Regex(@"\bTester\b", RegexOptions.IgnoreCase), self: "", countHits: false); + ChatRoute both = mentionRouter.Evaluate("Bob says, \"Tester come here\"", "Chat", 2, null); + Check(both.Mention && both.HighlightArgb == HlA && both.Spans is { Length: 1 } && both.Spans[0].Argb == ChatRouter.MentionArgb, + "a mention keeps its tint and name colour on a highlighted line"); + } + finally { ResetPresets(); } + } + + private static void HighlightPrecedence() + { + Case("highlight: the first matching Highlight rule wins; Line and Match still colour the text"); + try + { + ResetPresets(); + const string line = "Critical hit! Olthoi Swarm Nymph nicks your head"; + ChatRoute r = Route(line, "Combat", 6, out var trace, + ColourRule("Critical", ChatColorMode.Highlight, HlA), ColourRule("Olthoi", ChatColorMode.Highlight, HlB)); + Check(r.HighlightArgb == HlA, "two Highlight rules: the higher one's colour"); + Check(Says(trace, 1, "(highlight already set above)"), "the test box says the lower one was beaten"); + + ChatRoute nomatch = Route(line, "Combat", 6, out _, + ColourRule("nothing here", ChatColorMode.Highlight, HlA), ColourRule("Olthoi", ChatColorMode.Highlight, HlB)); + Check(nomatch.HighlightArgb == HlB, "the higher one doesn't match: the lower one's colour"); + + ChatRoute lineFirst = Route(line, "Combat", 6, out _, + ColourRule("Critical", ChatColorMode.Line, LineC), ColourRule("Olthoi", ChatColorMode.Highlight, HlA)); + Check(lineFirst.LineArgb == LineC && lineFirst.HighlightArgb == HlA, "Colour line above Highlight: both apply"); + ChatRoute hlFirst = Route(line, "Combat", 6, out _, + ColourRule("Critical", ChatColorMode.Highlight, HlA), ColourRule("Olthoi", ChatColorMode.Line, LineC)); + Check(hlFirst.LineArgb == LineC && hlFirst.HighlightArgb == HlA, "Highlight above Colour line: both apply"); + + ChatRoute lines = Route(line, "Combat", 6, out _, + ColourRule("Critical", ChatColorMode.Line, LineC), ColourRule("Olthoi", ChatColorMode.Line, HlB), + ColourRule("nicks", ChatColorMode.Highlight, HlA)); + Check(lines.LineArgb == LineC && lines.HighlightArgb == HlA, "Colour line unchanged: still the first one wins"); + + ChatRoute match = Route(line, "Combat", 6, out _, + ColourRule("Olthoi", ChatColorMode.Match, MatchC), ColourRule("Critical", ChatColorMode.Highlight, HlA)); + Check(match.HighlightArgb == HlA && match.Spans is { Length: 1 } && match.Spans[0].Argb == MatchC + && line.Substring(match.Spans[0].Start, match.Spans[0].Length) == "Olthoi", "Colour match and Highlight: the match coloured on the band"); + Check(match.LineArgb == null, "...the rest of the text keeps its normal colour"); + + // A Highlight rule takes no part in routing order: a Move below it still decides. + ChatRoute route = Route(line, "Combat", 6, out _, + ColourRule("Critical", ChatColorMode.Highlight, HlA), Rule("Olthoi", ChatRuleAction.Move, tab: "Crits")); + Check(route.HighlightArgb == HlA && route.Tabs is ["Crits"] && !route.InHome, "a Move below a Highlight still moves it"); + } + finally { ResetPresets(); } + } + + private static void HighlightBand() + { + Case("highlight: the band is the swatch colour at 40%"); + Check(ChatColorModes.BandAlpha == 0x66, "40% (0x66) for an opaque colour"); + Check(ChatColorModes.BandArgb(0xFF3366FF) == 0x663366FF, "an opaque swatch: same RGB, alpha 0x66"); + Check(ChatColorModes.BandArgb(0xFFFFFFFF) == 0x66FFFFFF, "white: alpha 0x66"); + Check(ChatColorModes.BandArgb(0x80112233) == 0x33112233, "an imported translucent colour: fainter still (0x80 -> 0x33)"); + Check(ChatColorModes.BandArgb(0x01112233) >> 24 == 0, "a nearly clear colour: nearly no band"); + Check((ChatColorModes.BandArgb(ChatFilterRule.DefaultColor) & 0xFFFFFF) == (ChatFilterRule.DefaultColor & 0xFFFFFF), "the default amber keeps its RGB"); + } + + private static void HighlightJson() + { + Case("highlight: colorMode \"highlight\" in the settings file and Export / Import"); + Check((int)ChatColorMode.None == 0 && (int)ChatColorMode.Line == 1 && (int)ChatColorMode.Match == 2 && (int)ChatColorMode.Highlight == 3, + "the old values keep their numbers (the dropdown is indexed by them)"); + foreach (ChatColorMode m in Enum.GetValues()) + Check(ChatColorModes.Parse(ChatColorModes.ToJson(m)) == m, $"{m} round-trips"); + Check(ChatColorModes.ToJson(ChatColorMode.None) == null, "None writes no colorMode (as before)"); + Check(ChatColorModes.ToJson(ChatColorMode.Line) == "line" && ChatColorModes.ToJson(ChatColorMode.Match) == "match", "line / match written as before"); + Check(ChatColorModes.ToJson(ChatColorMode.Highlight) == "highlight", "Highlight writes \"highlight\""); + Check(ChatColorModes.Parse("HIGHLIGHT") == ChatColorMode.Highlight && ChatColorModes.Parse(" highlight ") == ChatColorMode.Highlight, "any case, spaces"); + Check(ChatColorModes.Parse("text") == ChatColorMode.Match, "\"text\" still reads as match"); + Check(ChatColorModes.Parse(null) == ChatColorMode.None && ChatColorModes.Parse("") == ChatColorMode.None + && ChatColorModes.Parse("sparkle") == ChatColorMode.None, "absent / unknown: None"); + + var opts = RynthChatJsonContext.Default.RynthChatSettingsDto; + RynthChatSettingsDto old = JsonSerializer.Deserialize(OldFile, opts)!; + foreach (RynthChatFilterDto f in old.Filters!) + Check(ChatColorModes.ToJson(ChatColorModes.Parse(f.ColorMode)) == f.ColorMode, $"an old rule's colorMode ({f.ColorMode ?? "none"}) is written back unchanged"); + + old.Filters[2].ColorMode = ChatColorModes.ToJson(ChatColorMode.Highlight); + old.Filters[2].Color = ChatLineColors.FormatColor(HlA); + string saved = JsonSerializer.Serialize(old, opts); + Check(saved.Contains("\"colorMode\":\"highlight\"", StringComparison.Ordinal), "saved as colorMode:highlight"); + RynthChatSettingsDto back = JsonSerializer.Deserialize(saved, opts)!; + Check(ChatColorModes.Parse(back.Filters![2].ColorMode) == ChatColorMode.Highlight, "loads back as Highlight"); + Check(ChatLineColors.ParseColor(back.Filters[2].Color) == HlA, "...with its colour"); + Check(JsonSerializer.Serialize(back, opts) == saved, "load + save is stable"); + + var set = new RynthChatRuleSetDto { Format = RynthChatRuleSetDto.FormatName, Rules = back.Filters, Tabs = back.CustomTabs }; + string exported = JsonSerializer.Serialize(set, RynthChatJsonContext.Default.RynthChatRuleSetDto); + RynthChatRuleSetDto imported = JsonSerializer.Deserialize(exported, RynthChatJsonContext.Default.RynthChatRuleSetDto)!; + Check(ChatColorModes.Parse(imported.Rules![2].ColorMode) == ChatColorMode.Highlight + && ChatLineColors.ParseColor(imported.Rules[2].Color) == HlA, "Export / Import keeps the highlight and its colour"); + RynthChatFilterDto[]? bare = JsonSerializer.Deserialize("[{\"pattern\":\"x\",\"colorMode\":\"highlight\",\"color\":\"#3366FF\"}]", + RynthChatJsonContext.Default.RynthChatFilterDtoArray); + Check(bare != null && ChatColorModes.Parse(bare[0].ColorMode) == ChatColorMode.Highlight, "a bare rule array imports the highlight"); + } + + /// + /// The colorMode reading of RynthCore release/2026.10.31.4 (ChatModel.FromDto), copied as it was: + /// what an older client does with a file that has "highlight" in it. + /// + private static ChatColorMode OldReader(string? colorMode) => (colorMode ?? "").ToLowerInvariant() switch + { + "line" => ChatColorMode.Line, + "match" or "text" => ChatColorMode.Match, + _ => ChatColorMode.None, + }; + + /// The colorMode writing of release/2026.10.31.4 (ChatModel.ToDto), copied as it was. + private static string? OldWriter(ChatColorMode m) => m switch { ChatColorMode.Line => "line", ChatColorMode.Match => "match", _ => null }; + + private static void HighlightOldReader() + { + Case("highlight: an older RynthCore reads a file with \"highlight\" without breaking"); + const string newFile = """ + {"version":2,"customTabs":["Junk"], + "filters":[{"pattern":"tells you","tab":"","enabled":true,"action":"color","colorMode":"highlight","color":"#3366FF"}, + {"pattern":"In portal Space","tab":"Junk","enabled":true,"action":"move","colorMode":"highlight","color":"#FF6633"}, + {"pattern":"fizzled","tab":"","enabled":true,"action":"color","colorMode":"match","color":"#FFD27A"}]} + """; + RynthChatSettingsDto? dto = null; + try { dto = JsonSerializer.Deserialize(newFile, RynthChatJsonContext.Default.RynthChatSettingsDto); } + catch (JsonException) { } + Check(dto?.Filters is { Length: 3 }, "the file reads (colorMode is a string: no JSON error)"); + if (dto?.Filters is not { Length: 3 } f) return; + Check(OldReader(f[0].ColorMode) == ChatColorMode.None, "an old reader takes \"highlight\" as no colour"); + Check(ChatLineColors.ParseColor(f[0].Color) == HlA, "...the rule's colour is still read"); + Check(f[1].Action == "move" && f[1].Tab == "Junk" && OldReader(f[1].ColorMode) == ChatColorMode.None, "...a highlighting Move rule still moves"); + Check(OldReader(f[2].ColorMode) == ChatColorMode.Match, "...the other rules are unaffected"); + // An old client that saves again: the mode is dropped, the colour kept (ToDto writes a + // non-default colour even with no colour mode), so turning it back on finds the colour. + Check(OldWriter(OldReader(f[0].ColorMode)) == null, "an old client's save drops the highlight (no colorMode)"); + Check(ChatColorModes.Parse(OldWriter(OldReader(f[2].ColorMode))) == ChatColorMode.Match, "...and keeps the other modes"); + // And the new reader reads what an old client writes exactly as the old reader did. + foreach (string? s in new[] { null, "", "line", "match", "text", "LINE", "bogus" }) + Check(ChatColorModes.Parse(s) == OldReader(s), $"the new reader agrees with the old on '{s ?? "null"}'"); + } + private static void WhenParsing() { Case("When: the same reading as before"); diff --git a/tools/CleaveGhostTests/CleaveGhostTests.csproj b/tools/CleaveGhostTests/CleaveGhostTests.csproj index d143f75..8306b03 100644 --- a/tools/CleaveGhostTests/CleaveGhostTests.csproj +++ b/tools/CleaveGhostTests/CleaveGhostTests.csproj @@ -8,7 +8,10 @@ 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. + Also (2026-10-31) src\RynthCore.Engine\ImGui\MonsterHud\HealthProbe.cs: which unselected plate the HUD asks + the server's health for next (the server streams only the queried target), and which 0x01C0 replies are the + probe's (kept from plugins) versus the selection's / a plugin's. + All compiled in; no game, no engine. Run: dotnet run -c Release (exit 0 = pass, 1 = fail) --> @@ -22,6 +25,7 @@ + diff --git a/tools/CleaveGhostTests/Program.cs b/tools/CleaveGhostTests/Program.cs index abdbd0d..9720271 100644 --- a/tools/CleaveGhostTests/Program.cs +++ b/tools/CleaveGhostTests/Program.cs @@ -16,6 +16,10 @@ internal static class Program 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); + Run("health probe: fight plates first, then never-read, then old quiet ones; never the stream's owner", ProbeFightFirst); + Run("health probe: the stalest fight plate first, never-read plates nearest first", ProbeStalestAndNearest); + Run("health probe: nothing due (fresh, dead, no id) sends nothing", ProbeNothingDue); + Run("health probe: a probe's replies are the HUD's; the owner's and plugins' are theirs", ProbeReplies); Console.WriteLine($"{_checks} check(s), {_failed} failed."); return _failed == 0 ? 0 : 1; } @@ -109,4 +113,100 @@ internal static class Program ObjectFreshness.Note(0xF74C, 0, 1); Check(ObjectFreshness.AgeMs(0, 2) == -1, "id 0 ignored"); } + + // ── HealthProbe: the unselected plates' health ────────────────────── + + private static void ProbeFightFirst() + { + // 0x10 is the selection (streamed). 0x20 is in the fight, last read 3 s ago; 0x30 never read; + // 0x40 quiet at full health, read 20 s ago. + HealthProbe.Candidate[] c = + [ + new(0x10, 1.0f, true, 5.0, true), + new(0x20, 4.0f, true, 3.0, true), + new(0x30, 2.0f, false, 0, false), + new(0x40, 1.5f, true, 20.0, false), + ]; + Check(HealthProbe.Pick(c, owner: 0x10) == 0x20, "a fight plate the server isn't streaming goes first"); + Check(HealthProbe.Pick(c, owner: 0x20) == 0x10, "the stream's owner is never probed (the selection is, once it isn't the owner)"); + HealthProbe.Candidate[] noFight = [c[2], c[3]]; + Check(HealthProbe.Pick(noFight, owner: 0x10) == 0x30, "then a plate never read"); + HealthProbe.Candidate[] quiet = [c[3]]; + Check(HealthProbe.Pick(quiet, owner: 0x10) == 0x40, "then a quiet plate whose reading is old"); + } + + private static void ProbeStalestAndNearest() + { + HealthProbe.Candidate[] fight = + [ + new(0x20, 1.0f, true, 2.5, true), + new(0x21, 9.0f, true, 6.0, true), + new(0x22, 3.0f, false, 0, true), // hitting you, never read: before any reading + ]; + Check(HealthProbe.Pick(fight, 0) == 0x22, "a fight plate never read beats every read one"); + Check(HealthProbe.Pick(fight[..2], 0) == 0x21, "the stalest fight plate first"); + HealthProbe.Candidate[] unseen = + [ + new(0x30, 7.0f, false, 0, false), + new(0x31, 2.0f, false, 0, false), + new(0x32, 5.0f, false, 0, false), + ]; + Check(HealthProbe.Pick(unseen, 0) == 0x31, "never-read plates: the nearest first"); + } + + private static void ProbeNothingDue() + { + HealthProbe.Candidate[] c = + [ + new(0x20, 1.0f, true, HealthProbe.ActiveRefreshSec - 0.1, true), // fresh fight plate + new(0x40, 1.0f, true, HealthProbe.IdleRefreshSec - 0.1, false), // quiet, read recently + new(0x50, 1.0f, true, 30.0, true, Dead: true), // dead + new(0, 1.0f, false, 0, true), // no id + ]; + Check(HealthProbe.Pick(c, 0) == 0, "nothing due: no query (no traffic)"); + Check(HealthProbe.Pick(ReadOnlySpan.Empty, 0) == 0, "no plates: nothing"); + HealthProbe.Candidate[] nan = [new(0x20, 1.0f, true, double.NaN, true)]; + Check(HealthProbe.Pick(nan, 0) == 0, "a NaN age is never due"); + HealthProbe.Candidate[] due = [new(0x20, 1.0f, true, HealthProbe.ActiveRefreshSec, true)]; + Check(HealthProbe.Pick(due, 0) == 0x20, "a fight plate exactly ActiveRefreshSec old is due"); + } + + private static void ProbeReplies() + { + HealthProbe.Reset(); + Check(!HealthProbe.TryGetOwner(out _), "after a reset the stream's owner is unknown"); + HealthProbe.NoteQuery(0x10); // the selection / a plugin asked for 0x10 + Check(HealthProbe.TryGetOwner(out uint o) && o == 0x10, "the owner is the last queried id"); + + HealthProbe.NoteProbe(0x20, 1000); + Check(HealthProbe.IsProbeReply(0x20, 1150), "the reply to a probe is the HUD's"); + Check(HealthProbe.IsProbeReply(0x20, 1300), "... every path that reports it (window, not consume-once)"); + Check(!HealthProbe.IsProbeReply(0x10, 1150), "the owner's replies go to plugins"); + Check(!HealthProbe.IsProbeReply(0x30, 1150), "an id nobody probed goes to plugins"); + Check(!HealthProbe.IsProbeReply(0x20, 1000 + HealthProbe.ReplyWindowMs + 1), "after the window the id's replies go to plugins again"); + Check(!HealthProbe.IsProbeReply(0x20, 1200), "... and the expired entry is gone"); + + HealthProbe.NoteProbe(0x21, 2000); + HealthProbe.NoteQuery(0x21); // a plugin asked for the same monster right after + Check(!HealthProbe.IsProbeReply(0x21, 2100), "a plugin's own query for a probed id takes its replies back"); + Check(HealthProbe.TryGetOwner(out o) && o == 0x21, "... and owns the stream"); + + // No owner to hand the stream back to: the probed id keeps streaming to us, all of it the HUD's. + HealthProbe.NoteQuery(0); + HealthProbe.NoteProbe(0x22, 3000, sticky: true); + Check(HealthProbe.IsProbeReply(0x22, 3000 + 60_000), "sticky probe: still the HUD's a minute later"); + HealthProbe.NoteQuery(0x10); + Check(!HealthProbe.IsProbeReply(0x22, 3000 + 60_001), "the next query moves the stream: sticky entry gone"); + + for (uint i = 1; i <= 20; i++) HealthProbe.NoteProbe(0x100 + i, 5000); // more than the ledger holds + Check(HealthProbe.IsProbeReply(0x114, 5100), "the newest probes are remembered when the ledger wraps"); + Check(!HealthProbe.IsProbeReply(0x101, 5100), "the oldest are dropped (bounded)"); + HealthProbe.NoteProbe(0, 5000); + Check(!HealthProbe.IsProbeReply(0, 5000), "id 0 never"); + long before = HealthProbe.ProbeCount; + HealthProbe.NoteProbe(0x200, 6000); + Check(HealthProbe.ProbeCount == before + 1, "probes are counted"); + HealthProbe.Reset(); + Check(!HealthProbe.IsProbeReply(0x114, 5100) && !HealthProbe.TryGetOwner(out _), "reset (logout) forgets everything"); + } } diff --git a/tools/DamageRowStatsTests/DamageRowStatsTests.csproj b/tools/DamageRowStatsTests/DamageRowStatsTests.csproj new file mode 100644 index 0000000..d91dc79 --- /dev/null +++ b/tools/DamageRowStatsTests/DamageRowStatsTests.csproj @@ -0,0 +1,23 @@ + + + + + Exe + net10.0 + enable + enable + true + DamageRowStatsTests + + + + + + + diff --git a/tools/DamageRowStatsTests/Program.cs b/tools/DamageRowStatsTests/Program.cs new file mode 100644 index 0000000..3b47335 --- /dev/null +++ b/tools/DamageRowStatsTests/Program.cs @@ -0,0 +1,102 @@ +using System.Text.Json; +using RynthCore.Engine.UI.Data; + +namespace DamageRowStatsTests; + +/// +/// The line under a monster in the Damage panel (DamageRowStats): RynthAi's "mstats" on a +/// RynthPluginGetMonsterDamageJson row, read and worded. The JSON here is the shape RynthAi +/// writes (RynthSuite RynthAiHostTests MonsterStatsTests checks RynthAi's side of it). +/// +internal static class Program +{ + private static int _checks, _failed; + + private static void Check(bool cond, string what) + { + _checks++; + if (cond) return; + _failed++; + Console.WriteLine(" [FAIL] " + what); + } + + private static void Eq(T actual, T expected, string what) + => Check(EqualityComparer.Default.Equals(actual, expected), $"{what}: expected '{expected}', got '{actual}'"); + + private static DamageRowStats? Row(string json) + { + using var doc = JsonDocument.Parse(json); + return DamageRowStats.Parse(doc.RootElement); + } + + private static int Main() + { + Reads(); + Missing(); + Words(); + Percents(); + Console.WriteLine($"DamageRowStatsTests: {_checks} checks, {_failed} failed."); + return _failed == 0 ? 0 : 1; + } + + private const string Full = + "{\"wcid\":7,\"name\":\"Drudge Skulker\",\"mstats\":{\"sw\":61,\"ev\":14,\"sp\":30,\"rs\":3,\"ne\":2," + + "\"at\":120,\"yev\":50,\"ysp\":8,\"yrs\":1,\"yne\":0,\"k\":12,\"dd\":12345,\"dt\":2345}}"; + + private static void Reads() + { + DamageRowStats? s = Row(Full); + Check(s != null, "a row with mstats reads"); + if (s == null) return; + Eq((s.Swings, s.Evaded, s.Spells, s.Resisted, s.NoEffect), (61, 14, 30, 3, 2), "your side"); + Eq((s.Attacks, s.YouEvaded, s.SpellsAtYou, s.YouResisted, s.NoEffectOnYou), (120, 50, 8, 1, 0), "its side"); + Eq((s.Kills, s.Dealt, s.Taken), (12, 12345L, 2345L), "kills and damage"); + + DamageRowStats? part = Row("{\"mstats\":{\"at\":4,\"yev\":3}}"); + Check(part != null && part.Attacks == 4 && part.YouEvaded == 3 && part.Swings == 0 && part.Dealt == 0, "missing numbers are 0"); + DamageRowStats? odd = Row("{\"mstats\":{\"sw\":-5,\"ev\":\"x\",\"sp\":2.5,\"at\":3,\"yev\":1,\"dd\":-9}}"); + Check(odd != null && odd.Swings == 0 && odd.Evaded == 0 && odd.Spells == 0 && odd.Dealt == 0 && odd.Attacks == 3, + "negative, text and fractional numbers read as 0"); + DamageRowStats? big = Row("{\"mstats\":{\"sw\":99999999999,\"ev\":1}}"); + Check(big != null && big.Swings == int.MaxValue, "a count past an int is capped"); + } + + private static void Missing() + { + Check(Row("{\"wcid\":7,\"name\":\"Drudge Skulker\",\"kills\":3}") == null, "an older RynthAi's row (no mstats): no line"); + Check(Row("{\"mstats\":{}}") == null, "nothing counted: no line"); + Check(Row("{\"mstats\":{\"sw\":0,\"at\":0}}") == null, "all zero: no line"); + Check(Row("{\"mstats\":5}") == null, "mstats not an object"); + Check(Row("[1,2]") == null, "not a row"); + Check(Row("{\"mstats\":{\"k\":1}}") != null, "a kill alone is something"); + } + + private static void Words() + { + DamageRowStats s = Row(Full)!; + Eq(s.Line(), "It evades 23% (14/61) · It resists 10% (3/30) · You evade 42% (50/120) · You resist 13% (1/8)", "the line"); + Eq(Row("{\"mstats\":{\"at\":4,\"yev\":3}}")!.Line(), "You evade 75% (3/4)", "only the parts with something to divide by"); + Eq(Row("{\"mstats\":{\"k\":1}}")!.Line(), "", "a kill alone: no rates to show (the row stays one line)"); + Eq(Row("{\"mstats\":{\"sw\":2000,\"ev\":1500}}")!.Line(), "It evades 75% (1,500/2,000)", "thousands"); + + string tip = s.Tip(); + Check(tip.Contains("61 melee/missile attacks, 47 hit, it evaded 14 (23%)"), "tip: your attacks: " + tip); + Check(tip.Contains("30 spells reached it, it resisted 3 (10%), 2 no effect (immune)"), "tip: your spells"); + Check(tip.Contains("12,345 damage, 12 kills"), "tip: damage and kills"); + Check(tip.Contains("120 melee/missile attacks, 70 hit, you evaded 50 (42%)"), "tip: its attacks"); + Check(tip.Contains("8 spells reached you, you resisted 1 (13%); 2,345 damage"), "tip: its spells (no 'no effect' when there is none)"); + Check(Row("{\"mstats\":{\"k\":1,\"sw\":1}}")!.Tip().Contains("1 kill."), "one kill"); + } + + private static void Percents() + { + Eq(DamageRowStats.Percent(0, 0), "-", "nothing to divide by"); + Eq(DamageRowStats.Percent(0, 5), "0%", "none"); + Eq(DamageRowStats.Percent(5, 5), "100%", "all"); + Eq(DamageRowStats.Percent(1, 8), "13%", "whole numbers from 10% (12.5 rounds up)"); + Eq(DamageRowStats.Percent(1, 3), "33%", "a third"); + Eq(DamageRowStats.Percent(2, 3), "67%", "two thirds"); + Eq(DamageRowStats.Percent(9, 200), "4.5%", "one decimal below 10%"); + Eq(DamageRowStats.Percent(7, 3), "100%", "clamped"); + } +} diff --git a/tools/EngineRobustnessTests/EngineRobustnessTests.csproj b/tools/EngineRobustnessTests/EngineRobustnessTests.csproj index 1ca6a10..25a5c88 100644 --- a/tools/EngineRobustnessTests/EngineRobustnessTests.csproj +++ b/tools/EngineRobustnessTests/EngineRobustnessTests.csproj @@ -52,6 +52,8 @@ + + diff --git a/tools/EngineRobustnessTests/Program.cs b/tools/EngineRobustnessTests/Program.cs index 905893c..0ff6401 100644 --- a/tools/EngineRobustnessTests/Program.cs +++ b/tools/EngineRobustnessTests/Program.cs @@ -51,6 +51,7 @@ internal static partial class Program RunPumpGuardTests(); RunShutdownOrderTests(); + RunReloadStallTests(); Console.WriteLine($"{_checks} check(s), {_failed} failed."); return _failed == 0 ? 0 : 1; diff --git a/tools/EngineRobustnessTests/ReloadStallTests.cs b/tools/EngineRobustnessTests/ReloadStallTests.cs new file mode 100644 index 0000000..003a21d --- /dev/null +++ b/tools/EngineRobustnessTests/ReloadStallTests.cs @@ -0,0 +1,65 @@ +using RynthCore.Engine; +using RynthCore.Engine.ImGuiBackend; + +namespace EngineRobustnessTests; + +/// +/// The pure parts of the 2026-11-01 reload stall fix: the font atlas's RGBA->BGRA rows made by +/// the bake worker (FontPixels), and the hang dump's rundll32 command line (HangDumpCommand). +/// +internal static partial class Program +{ + private static void RunReloadStallTests() + { + FontPixelsSwapRedAndBlue(); + HangDumpCommandLine(); + } + + private static void FontPixelsSwapRedAndBlue() + { + _case = "font pixels"; + // Little-endian RGBA words: R is the low byte. A8R8G8B8 in memory is B, G, R, A. + uint[] rgba = { 0xFF0000FFu /* opaque red */, 0x80FF0000u /* half blue */, 0x4000FF00u /* green */, 0x00000000u, 0x12345678u }; + var bgra = new uint[rgba.Length]; + FontPixels.RgbaToBgra(rgba, bgra); + Check(bgra[0] == 0xFFFF0000u, $"red lands in the R byte of A8R8G8B8 (0x{bgra[0]:X8})"); + Check(bgra[1] == 0x800000FFu, $"blue lands in the low byte, alpha kept (0x{bgra[1]:X8})"); + Check(bgra[2] == 0x4000FF00u, "green and alpha stay"); + Check(bgra[3] == 0, "transparent black stays"); + Check(bgra[4] == 0x12785634u, $"R and B swap, G and A stay (0x{bgra[4]:X8})"); + + // The bytes the old per-byte loop wrote: dst = { src[2], src[1], src[0], src[3] }. + var rnd = new System.Random(11); + var src = new uint[4096]; + for (int i = 0; i < src.Length; i++) src[i] = (uint)rnd.Next() ^ ((uint)rnd.Next() << 16); + var dst = new uint[src.Length]; + FontPixels.RgbaToBgra(src, dst); + bool same = true; + for (int i = 0; i < src.Length && same; i++) + { + byte[] s = System.BitConverter.GetBytes(src[i]), d = System.BitConverter.GetBytes(dst[i]); + same = d[0] == s[2] && d[1] == s[1] && d[2] == s[0] && d[3] == s[3]; + } + Check(same, "the same bytes as the per-byte swizzle it replaces, for 4096 random pixels"); + + bool threw = false; + try { FontPixels.RgbaToBgra(new uint[4], new uint[3]); } + catch (System.ArgumentException) { threw = true; } + Check(threw, "a destination smaller than the source is refused"); + } + + private static void HangDumpCommandLine() + { + _case = "hang dump command"; + string a = HangDumpCommand.Arguments(@"C:\Games\RynthCore\Runtime\RynthCore.SehTrampoline.dll", + @"C:\Games\RynthCore\Logs\dumps\hang_17132_20261031_211714.dmp", 17132); + Check(a == "\"C:\\Games\\RynthCore\\Runtime\\RynthCore.SehTrampoline.dll\",RC_DumpProcess 17132 C:\\Games\\RynthCore\\Logs\\dumps\\hang_17132_20261031_211714.dmp", + $"dll quoted, entry, pid, then the path as the rest of the line: {a}"); + string spaced = HangDumpCommand.Arguments(@"C:\a b\x.dll", @"C:\Users\Some One's PC\d.dmp", 42); + Check(spaced.EndsWith(" 42 C:\\Users\\Some One's PC\\d.dmp", System.StringComparison.Ordinal), + "a path with spaces and an apostrophe is passed as it is (DumpArgs.h takes the rest of the line)"); + Check(HangDumpCommand.DescribeExit(0) == "written", "0 = written"); + Check(HangDumpCommand.DescribeExit(5) == "MiniDumpWriteDump failed", "5 = MiniDumpWriteDump failed"); + Check(HangDumpCommand.DescribeExit(-1).Contains("rundll32"), "anything else is rundll32's own failure"); + } +} diff --git a/tools/EngineSettingsTests/EngineSettingsTests.csproj b/tools/EngineSettingsTests/EngineSettingsTests.csproj index 4df08fd..601840d 100644 --- a/tools/EngineSettingsTests/EngineSettingsTests.csproj +++ b/tools/EngineSettingsTests/EngineSettingsTests.csproj @@ -26,6 +26,8 @@ + + diff --git a/tools/EngineSettingsTests/Program.cs b/tools/EngineSettingsTests/Program.cs index f217dfe..c72eebc 100644 --- a/tools/EngineSettingsTests/Program.cs +++ b/tools/EngineSettingsTests/Program.cs @@ -61,6 +61,7 @@ namespace EngineSettingsTests Run(nameof(HoldReloadInWorldOptInAndSaved), HoldReloadInWorldOptInAndSaved); Run(nameof(IltServerNamesEdit), IltServerNamesEdit); Run(nameof(DisplaySettingsDefaultsAndSaved), DisplaySettingsDefaultsAndSaved); + Run(nameof(PanelLayoutPerCharacterDefaultOnAndSaved), PanelLayoutPerCharacterDefaultOnAndSaved); Run(nameof(BorderlessDecisions), BorderlessDecisions); Run(nameof(PlacementDecisions), PlacementDecisions); Run(nameof(PlacementFilesArePerClient), PlacementFilesArePerClient); @@ -121,11 +122,16 @@ namespace EngineSettingsTests case "borderless-off": EngineSettings.BorderlessWindowed = false; break; case "layout-on": EngineSettings.RememberWindowLayout = true; break; case "layout-off": EngineSettings.RememberWindowLayout = false; break; + case "charlayout-on": EngineSettings.PanelLayoutPerCharacter = true; break; + case "charlayout-off": EngineSettings.PanelLayoutPerCharacter = false; break; case "acpos-on": EngineSettings.RememberAcWindowPosition = true; break; case "acpos-off": EngineSettings.RememberAcWindowPosition = false; break; case "hold-on": EngineSettings.HoldReloadInWorld = true; break; case "hold-off": EngineSettings.HoldReloadInWorld = false; break; case "hold-minutes": EngineSettings.HoldReloadInWorldMaxMinutes = int.Parse(args[1]); break; + case "uicost-on": EngineSettings.UiCostLog = true; break; + case "uicost-off": EngineSettings.UiCostLog = false; break; + case "uicost-ms": EngineSettings.UiCostThresholdMs = int.Parse(args[1]); break; case "autoid": if (!RynthCore.Engine.Compatibility.AutoIdPolicy.TryParseMode(args[1], out var aim)) throw new ArgumentException(args[1]); EngineSettings.AutoIdMode = aim; @@ -144,6 +150,7 @@ namespace EngineSettingsTests Console.WriteLine("TransitionGate=" + EngineSettings.TransitionGate); Console.WriteLine("BorderlessWindowed=" + EngineSettings.BorderlessWindowed); Console.WriteLine("RememberWindowLayout=" + EngineSettings.RememberWindowLayout); + Console.WriteLine("PanelLayoutPerCharacter=" + EngineSettings.PanelLayoutPerCharacter); Console.WriteLine("RememberAcWindowPosition=" + EngineSettings.RememberAcWindowPosition); Console.WriteLine("HoldReloadInWorld=" + EngineSettings.HoldReloadInWorld); Console.WriteLine("HoldReloadInWorldMaxMinutes=" + EngineSettings.HoldReloadInWorldMaxMinutes); @@ -399,9 +406,12 @@ namespace EngineSettingsTests (new[] { "insertrel-on" }, "InsertReleasesUi", "true"), (new[] { "borderless-on" }, "BorderlessWindowed", "true"), (new[] { "layout-off" }, "RememberWindowLayout", "false"), + (new[] { "charlayout-off" }, "PanelLayoutPerCharacter", "false"), (new[] { "acpos-on" }, "RememberAcWindowPosition", "true"), (new[] { "hold-on" }, "HoldReloadInWorld", "true"), (new[] { "hold-minutes", "90" }, "HoldReloadInWorldMaxMinutes", "90"), + (new[] { "uicost-off" }, "UiCostLog", "false"), + (new[] { "uicost-ms", "120" }, "UiCostThresholdMs", "120"), (new[] { "ilt-add", "Frosthaven" }, "IltServerNames", null), (new[] { "autoid", "all" }, "AutoIdMode", "\"All\""), (new[] { "tgate-off" }, "TransitionGate", "false"), @@ -665,6 +675,34 @@ namespace EngineSettingsTests } } + // Settings > Display "Panel Layout Per Character" (UI/PanelLayout, 2026-10-30): on by default and + // not written while on; off is saved and read back (every client then shares the default layout, + // as before); a value that is not a boolean reads as on. + private static void PanelLayoutPerCharacterDefaultOnAndSaved() + { + string dir = NewDir("charlayout"); + string path = Path.Combine(dir, "engine.json"); + File.WriteAllText(path, LauncherFile); + Eq(DumpValue(RunChild(path, "dump").Out, "PanelLayoutPerCharacter"), "True", "on by default"); + Eq(RunChild(path, "hook-off", "StartTooltip").Exit, 0, "a save with the default"); + Check(!ReadJson(path).TryGetProperty("PanelLayoutPerCharacter", out _), "the default isn't written to the file"); + + Eq(RunChild(path, "charlayout-off").Exit, 0, "switched off"); + Eq(ReadJson(path).GetProperty("PanelLayoutPerCharacter").GetRawText(), "false", "off is saved"); + Check(ReadJson(path).TryGetProperty("LauncherWindow", out _), "launcher keys kept"); + Eq(DumpValue(RunChild(path, "dump").Out, "PanelLayoutPerCharacter"), "False", "off read back at the next start"); + Eq(RunChild(path, "hook-off", "CheckTooltip").Exit, 0, "another save"); + Eq(ReadJson(path).GetProperty("PanelLayoutPerCharacter").GetRawText(), "false", "off survives other saves"); + Eq(RunChild(path, "charlayout-on").Exit, 0, "back on"); + Check(!ReadJson(path).TryGetProperty("PanelLayoutPerCharacter", out _), "back at the default: dropped from the file"); + + foreach (string bad in new[] { "\"no\"", "0", "null" }) + { + File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"PanelLayoutPerCharacter\": {bad}, \"LoggingLevel\"")); + Eq(DumpValue(RunChild(path, "dump").Out, "PanelLayoutPerCharacter"), "True", $"PanelLayoutPerCharacter={bad}: stays on"); + } + } + // ── AcWindowChromePolicy: borderless windowed ─────────────────────── private const int Windowed = 0x14CF0000 | WsCaption | WsThickFrame | WsSysMenu | WsMinimizeBox | WsMaximizeBox; diff --git a/tools/LoaderFreezeBench/Run-Bench.ps1 b/tools/LoaderFreezeBench/Run-Bench.ps1 new file mode 100644 index 0000000..2cbdec0 --- /dev/null +++ b/tools/LoaderFreezeBench/Run-Bench.ps1 @@ -0,0 +1,25 @@ +# Builds and runs bench.c (x86, MSVC): one MinHook queued apply timed with and without the +# HIGH priority class the loader uses around each freeze, on a quiet machine and with every CPU +# busy above this process's LOWEST threads. Loads the machine for ~30 s at below-normal priority. +# Not part of Run-AllTests (no "Test" in the folder name): it measures, it doesn't pass or fail. +param([string]$MinHook = (Join-Path $PSScriptRoot "..\..\src\RynthCore.Engine\Native\minhook.x86.dll")) +$ErrorActionPreference = "Stop" +$vsPath = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath +$vcVer = (Get-ChildItem "$vsPath\VC\Tools\MSVC" | Sort-Object Name -Descending | Select-Object -First 1).Name +$vcBase = "$vsPath\VC\Tools\MSVC\$vcVer" +$cl = "$vcBase\bin\Hostx86\x86\cl.exe" +$sdkVer = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" | Sort-Object Name -Descending | Select-Object -First 1).Name +$sdkInc = "C:\Program Files (x86)\Windows Kits\10\Include\$sdkVer" +$sdkLib = "C:\Program Files (x86)\Windows Kits\10\Lib\$sdkVer" +$env:INCLUDE = "$vcBase\include;$sdkInc\ucrt;$sdkInc\um;$sdkInc\shared" +$env:LIB = "$vcBase\lib\x86;$sdkLib\ucrt\x86;$sdkLib\um\x86" + +$out = Join-Path $env:TEMP "LoaderFreezeBench" +New-Item -ItemType Directory -Force $out | Out-Null +Push-Location $out +try { + & $cl /nologo /O2 /MT /W4 /wd4100 (Join-Path $PSScriptRoot "bench.c") /Fe:bench.exe + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & .\bench.exe (Resolve-Path $MinHook).Path + exit $LASTEXITCODE +} finally { Pop-Location } diff --git a/tools/LoaderFreezeBench/bench.c b/tools/LoaderFreezeBench/bench.c new file mode 100644 index 0000000..7212de4 --- /dev/null +++ b/tools/LoaderFreezeBench/bench.c @@ -0,0 +1,118 @@ +// ============================================================================ +// tools\LoaderFreezeBench\bench.c - how long one MinHook queued apply (the loader's +// "Hooks: N patch(es) applied in one freeze") takes while this process's LOWEST-priority +// threads can't get a CPU, with and without the HIGH priority class the loader's +// BoostForFreeze (native\Loader\Hooks.c) puts around every freeze. +// +// The burner is a second copy of this program: BELOW_NORMAL class, a normal-priority spinning +// thread per CPU (+2), so it sits above this process's LOWEST threads (BELOW_NORMAL class too) +// but below every normal-priority process (the game clients keep their CPU). It runs ~15 s +// per starved phase. Not a gate test (it measures, it doesn't pass or fail, and it loads the +// machine): run it by hand with Run-Bench.ps1. +// +// 2026-11-01 on the 8-core PC with five clients running (the machine already busy): an apply +// took 0.4-13 s as is unstarved and 12-38 s starved; with the boost 85-110 ms either way. +// ============================================================================ +#include +#include +#include +#include + +typedef int (__stdcall *fn0)(void); +typedef int (__stdcall *fncreate)(void*, void*, void**); +typedef int (__stdcall *fn1)(void*); + +static volatile LONG g_stop; +static HANDLE g_never; + +static DWORD WINAPI Spin(LPVOID p) { (void)p; volatile unsigned x = 0; while (!g_stop) x++; return 0; } +static DWORD WINAPI Idle(LPVOID p) { (void)p; WaitForSingleObject(g_never, INFINITE); return 0; } + +__declspec(noinline) int __stdcall Target(int a) { return a * 3 + 1; } +__declspec(noinline) int __stdcall Detour(int a) { return a; } + +static fn1 g_qen, g_qdis; +static fn0 g_apply; +static int g_enabled; + +static double ApplyOnce(int boost) +{ + (g_enabled ? g_qdis : g_qen)((void*)Target); + LARGE_INTEGER f, t0, t1; + QueryPerformanceFrequency(&f); + QueryPerformanceCounter(&t0); + DWORD before = GetPriorityClass(GetCurrentProcess()); + if (boost) SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); + int st = g_apply(); + QueryPerformanceCounter(&t1); // the freeze is over here: every thread runs again + if (boost) SetPriorityClass(GetCurrentProcess(), before); + g_enabled = !g_enabled; + if (st != 0) printf(" MH_ApplyQueued = %d\n", st); + return (t1.QuadPart - t0.QuadPart) * 1000.0 / f.QuadPart; +} + +static HANDLE StartBurner(int seconds) +{ + char self[MAX_PATH], cmd[MAX_PATH + 32]; + GetModuleFileNameA(NULL, self, MAX_PATH); + _snprintf_s(cmd, sizeof cmd, _TRUNCATE, "\"%s\" burn %d", self, seconds); + STARTUPINFOA si = { sizeof si }; + PROCESS_INFORMATION pi; + if (!CreateProcessA(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) return NULL; + CloseHandle(pi.hThread); + Sleep(1500); // every CPU busy before the first apply + return pi.hProcess; +} + +static void Phase(const char* name, int boost, int trials, int burnSeconds) +{ + HANDLE burner = burnSeconds > 0 ? StartBurner(burnSeconds) : NULL; + if (burnSeconds > 0 && !burner) { printf("%s: could not start the burner\n", name); return; } + for (int i = 0; i < trials; i++) { + if (burner && WaitForSingleObject(burner, 0) == WAIT_OBJECT_0) { printf("%s: burner ended, phase cut short\n", name); break; } + Sleep(300); + printf("%-22s trial %d: %8.1f ms\n", name, i, ApplyOnce(boost)); + fflush(stdout); + } + if (burner) { TerminateProcess(burner, 0); CloseHandle(burner); } +} + +int main(int argc, char** argv) +{ + if (argc >= 3 && strcmp(argv[1], "burn") == 0) { + SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS); + SYSTEM_INFO si; + GetSystemInfo(&si); + for (DWORD i = 0; i < si.dwNumberOfProcessors + 2; i++) CloseHandle(CreateThread(NULL, 0, Spin, NULL, 0, NULL)); + Sleep(atoi(argv[2]) * 1000); + return 0; + } + if (argc < 2) { printf("bench \n"); return 2; } + + SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS); + g_never = CreateEventA(NULL, TRUE, FALSE, NULL); + for (int i = 0; i < 6; i++) { // like AC's d3d9 worker threads: LOWEST, waiting + HANDLE t = CreateThread(NULL, 0, Idle, NULL, 0, NULL); + SetThreadPriority(t, THREAD_PRIORITY_LOWEST); + CloseHandle(t); + } + HMODULE mh = LoadLibraryA(argv[1]); + if (!mh) { printf("could not load %s\n", argv[1]); return 3; } + fn0 init = (fn0)GetProcAddress(mh, "MH_Initialize"); + fncreate create = (fncreate)GetProcAddress(mh, "MH_CreateHook"); + g_qen = (fn1)GetProcAddress(mh, "MH_QueueEnableHook"); + g_qdis = (fn1)GetProcAddress(mh, "MH_QueueDisableHook"); + g_apply = (fn0)GetProcAddress(mh, "MH_ApplyQueued"); + void* orig; + if (!init || !create || !g_qen || !g_qdis || !g_apply || init() != 0 || create((void*)Target, (void*)Detour, &orig) != 0) { + printf("MinHook init/create failed\n"); + return 4; + } + + Phase("not starved, as is", 0, 3, 0); + Phase("not starved, boost", 1, 3, 0); + Phase("starved, boost", 1, 4, 15); + Phase("starved, as is", 0, 2, 15); + g_stop = 1; + return 0; +} diff --git a/tools/LootPatternTextTests/LootPatternTextTests.csproj b/tools/LootPatternTextTests/LootPatternTextTests.csproj new file mode 100644 index 0000000..d9aa403 --- /dev/null +++ b/tools/LootPatternTextTests/LootPatternTextTests.csproj @@ -0,0 +1,23 @@ + + + + + Exe + net10.0 + enable + enable + true + LootPatternTextTests + + + + + + + diff --git a/tools/LootPatternTextTests/Program.cs b/tools/LootPatternTextTests/Program.cs new file mode 100644 index 0000000..d1acce5 --- /dev/null +++ b/tools/LootPatternTextTests/Program.cs @@ -0,0 +1,92 @@ +using System.Text.RegularExpressions; +using RynthCore.Engine.UI; + +namespace LootPatternTextTests; + +// Offline tests for the Loot Editor's text-condition modes. 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}"); } + } + + // RynthAi's evaluator: Regex.IsMatch(value, pattern, IgnoreCase). + private static bool Matches(string pattern, string text) => Regex.IsMatch(text, pattern, RegexOptions.IgnoreCase); + + private static int Main() + { + try + { + Writes(); + WhatTheyMatch(); + ReadBack(); + OtherPatternsAreRegex(); + } + catch (Exception ex) + { + _fails++; + Console.WriteLine($" [FAIL] threw: {ex}"); + } + Console.WriteLine(_fails == 0 ? $"PASS ({_asserts} assertions)" : $"FAIL: {_fails} of {_asserts} assertions failed"); + return _fails == 0 ? 0 : 1; + } + + private static void Writes() + { + Check(LootPatternText.Build(LootTextMode.Contains, "Sanguine") == "Sanguine", "contains: the word"); + Check(LootPatternText.Build(LootTextMode.NotContains, "Sanguine") == "^(?!.*Sanguine)", "doesn't contain: a lookahead"); + Check(LootPatternText.Build(LootTextMode.NotContains, "Sanguine, Tattered") == "^(?!.*(Sanguine|Tattered))", "doesn't contain: several words"); + Check(LootPatternText.Build(LootTextMode.Contains, "Sanguine, Tattered") == "Sanguine|Tattered", "contains: several words"); + Check(LootPatternText.Build(LootTextMode.StartsWith, "Ancient") == "^Ancient", "starts with"); + Check(LootPatternText.Build(LootTextMode.EndsWith, "Robe") == "Robe$", "ends with"); + Check(LootPatternText.Build(LootTextMode.Exactly, "Trade Note (250,000)") == "^Trade Note \\(250,000\\)$", "is exactly: brackets escaped, spaces kept"); + Check(LootPatternText.Build(LootTextMode.Regex, "a.*b") == "a.*b", "regex: as typed"); + Check(LootPatternText.Build(LootTextMode.NotContains, " ") == "", "no words: empty"); + Check(LootPatternText.Build(LootTextMode.StartsWith, "") == "", "no words: empty (not a bare ^)"); + Check(LootPatternText.Escape("a.b*c?") == "a\\.b\\*c\\?", "escape: metacharacters"); + } + + private static void WhatTheyMatch() + { + string not = LootPatternText.Build(LootTextMode.NotContains, "Sanguine"); + Check(!Matches(not, "Sanguine Robe") && !Matches(not, "Robe of the sanguine"), "doesn't contain: any case, anywhere"); + Check(Matches(not, "Frost Robe") && Matches(not, "") , "doesn't contain: other names (and an empty one) pass"); + string notTwo = LootPatternText.Build(LootTextMode.NotContains, "Sanguine, Tattered"); + Check(!Matches(notTwo, "Tattered Cloak") && !Matches(notTwo, "Sanguine Robe") && Matches(notTwo, "Fine Cloak"), "doesn't contain: either word"); + string has = LootPatternText.Build(LootTextMode.Contains, "Sanguine, Tattered"); + Check(Matches(has, "a TATTERED cloak") && !Matches(has, "Fine Cloak"), "contains: either word, any case"); + Check(Matches(LootPatternText.Build(LootTextMode.StartsWith, "Ancient"), "Ancient Sword") && !Matches(LootPatternText.Build(LootTextMode.StartsWith, "Ancient"), "An Ancient Sword"), "starts with"); + Check(Matches(LootPatternText.Build(LootTextMode.EndsWith, "Robe"), "Frost Robe") && !Matches(LootPatternText.Build(LootTextMode.EndsWith, "Robe"), "Robe of Frost"), "ends with"); + string exact = LootPatternText.Build(LootTextMode.Exactly, "Trade Note (250,000)"); + Check(Matches(exact, "Trade Note (250,000)") && !Matches(exact, "Trade Note (250,000) x2") && !Matches(exact, "Trade Note 250,000"), "is exactly: the whole name, brackets literal"); + Check(Matches(LootPatternText.Build(LootTextMode.Contains, "a.b"), "a.b") && !Matches(LootPatternText.Build(LootTextMode.Contains, "a.b"), "axb"), "a dot typed is a dot"); + } + + private static void ReadBack() + { + foreach (var (mode, words) in new[] + { + (LootTextMode.Contains, "Sanguine"), (LootTextMode.NotContains, "Sanguine"), (LootTextMode.NotContains, "Sanguine, Tattered"), + (LootTextMode.Contains, "Sanguine, Tattered"), (LootTextMode.StartsWith, "Ancient"), (LootTextMode.EndsWith, "Robe"), + (LootTextMode.Exactly, "Trade Note (250,000)"), (LootTextMode.Contains, "a.b"), (LootTextMode.Exactly, "Mana Stone"), + }) + { + var (m, w) = LootPatternText.Parse(LootPatternText.Build(mode, words)); + Check(m == mode && w == words, $"round trip {mode} '{words}' -> {m} '{w}'"); + } + Check(LootPatternText.Parse("") == (LootTextMode.Contains, ""), "an empty pattern: contains, no words"); + // LootSdk's ExactPattern (the "Add to loot profile" rules): "^" + EscapeText(name) + "$". + Check(LootPatternText.Parse("^Pyreal$") == (LootTextMode.Exactly, "Pyreal"), "the add-item rules' exact names read as is exactly"); + } + + private static void OtherPatternsAreRegex() + { + foreach (string p in new[] { "a.*b", "^(Robe|Cloak)$", "Sword|", "\\d+", "^$", "^(?!.*Sanguine)Robe" }) + Check(LootPatternText.Parse(p).Mode == LootTextMode.Regex, $"'{p}' is regex"); + Check(LootPatternText.Parse("Robe\\$") == (LootTextMode.Contains, "Robe$"), "an escaped $ is a literal: contains 'Robe$'"); + Check(LootPatternText.Parse("a.*b").Words == "a.*b", "regex: its words are the pattern"); + } +} diff --git a/tools/MetaEditTests/Program.cs b/tools/MetaEditTests/Program.cs index 42afdd7..2d0654a 100644 --- a/tools/MetaEditTests/Program.cs +++ b/tools/MetaEditTests/Program.cs @@ -30,12 +30,57 @@ internal static class Program RowTextLeaves(); RowTextLists(); RowTextActions(); + SaveIndicator(); Console.WriteLine(); Console.WriteLine(_failed == 0 ? $"PASS ({_checks} checks)" : $"FAIL: {_failed} of {_checks} checks"); return _failed == 0 ? 0 : 1; } + // ── The "Saved" indicator waits for RynthAi's answer (2026-11-01) ─────── + + private static void SaveIndicator() + { + Case("save indicator follows RynthAi's result"); + var w = new MetaSaveWatch(); + var loaded = new MetaSaveResult { Seq = 1, Ok = true, Text = "Loaded farm.af" }; + Eq(w.State(0, loaded, 0), MetaSaveState.Saved, "nothing sent: saved"); + + w.Sent(1000, loaded.Seq, 0); + Eq(w.State(1100, loaded, 0), MetaSaveState.Saving, "sent, no answer yet"); + var saved = new MetaSaveResult { Seq = 2, Ok = true, Text = "Saved farm.af (3 rules)" }; + Eq(w.State(1200, saved, 0), MetaSaveState.Saved, "answered: saved"); + Eq(w.State(99999, saved, 0), MetaSaveState.Saved, "and stays saved"); + + w.Sent(2000, saved.Seq, 0); + var failed = new MetaSaveResult { Seq = 3, Ok = false, Text = "NOT saved to farm.af: the file is open in another program." }; + Eq(w.State(2100, failed, 0), MetaSaveState.Failed, "answered: failed"); + Eq(w.State(60000, failed, 0), MetaSaveState.Failed, "a failure stays up until the next result"); + w.Sent(61000, failed.Seq, 0); + Eq(w.State(61100, failed, 0), MetaSaveState.Saving, "the next change waits again"); + Eq(w.State(61200, new MetaSaveResult { Seq = 4, Ok = true }, 0), MetaSaveState.Saved, "and its save clears the failure"); + + w.Sent(70000, 4, 0); + Eq(w.State(70000 + MetaSaveWatch.ConfirmMs - 1, new MetaSaveResult { Seq = 4 }, 0), MetaSaveState.Saving, "still waiting just before the limit"); + Eq(w.State(70000 + MetaSaveWatch.ConfirmMs, new MetaSaveResult { Seq = 4 }, 0), MetaSaveState.Unconfirmed, "no answer: not confirmed (it used to say Saved)"); + + var d = new MetaSaveWatch(); + d.Sent(0, 4, 7); + Eq(d.State(10, new MetaSaveResult { Seq = 4 }, 8), MetaSaveState.NotSent, "the command never reached RynthAi"); + d.Sent(20, 4, 8); // a second change in the same burst + Eq(d.State(30, new MetaSaveResult { Seq = 4 }, 8), MetaSaveState.NotSent, "a dropped command earlier in the burst still shows"); + + var old = new MetaSaveWatch(); + old.Sent(0, 0, 0); + Eq(old.State(100, null, 0), MetaSaveState.Saving, "a RynthAi without results: the old timer"); + Eq(old.State(MetaSaveWatch.LegacySavingMs, null, 0), MetaSaveState.Saved, "then saved, as before"); + + var r = new MetaSaveWatch(); + r.Sent(0, 1, 0); + r.Reset(); + Eq(r.State(MetaSaveWatch.ConfirmMs * 2, new MetaSaveResult { Seq = 1 }, 0), MetaSaveState.Saved, "reopened panel: nothing pending"); + } + // ── New state names ────────────────────────────────────────────────── private static void StateNames() diff --git a/tools/PanelLayoutTests/PanelLayoutTests.csproj b/tools/PanelLayoutTests/PanelLayoutTests.csproj new file mode 100644 index 0000000..5d237ee --- /dev/null +++ b/tools/PanelLayoutTests/PanelLayoutTests.csproj @@ -0,0 +1,34 @@ + + + + + Exe + net10.0 + enable + enable + true + PanelLayoutTests + + + + + + + + + + + + + + diff --git a/tools/PanelLayoutTests/Program.cs b/tools/PanelLayoutTests/Program.cs new file mode 100644 index 0000000..2555c12 --- /dev/null +++ b/tools/PanelLayoutTests/Program.cs @@ -0,0 +1,770 @@ +using System.Diagnostics; +using System.Text; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI; + +namespace RynthCore.Engine +{ + /// Stub of the engine's log (PanelStateStore writes load/save problems to it). + internal static class RynthLog + { + internal static readonly List Lines = new(); + internal static void UI(string msg) { lock (Lines) Lines.Add(msg); } + } +} + +namespace RynthCore.Engine.Plugins +{ + /// Stub of the one engine.json setting PanelStateStore reads. + internal static class EngineSettings + { + public static bool RememberWindowLayout { get; set; } = true; + } +} + +namespace PanelLayoutTests +{ + /// + /// Panel layout per character without AC: the key and file names, seeding a new character from the + /// default, the switch at login and back at logout, a hot reload using the character's files from + /// the first frame (the decision logic), two clients never writing each other's files, the setting + /// off giving today's paths, and the /rc layout replies. + /// + internal static class Program + { + private static int _checks, _failed; + private static string _case = ""; + private static string _root = ""; + + // Placeholders only: no real server or character names. + private const string ServerOne = "Server One", ServerTwo = "ServerTwo"; + private const string CharA = "Character A", CharB = "Character B"; + + private static int Main(string[] args) + { + if (args.Length > 0 && args[0] == "--client") + return Client(args.Skip(1).ToArray()); + + _root = Path.Combine(Path.GetTempPath(), "rynth-panel-layout-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_root); + try + { + Run(KeyAndFileNames); + Run(SettingOffGivesTodaysPaths); + Run(SeedingFromTheDefault); + Run(ResetAndMakeDefaultFiles); + Run(LatestTextWritesKeepTheNewest); + Run(StoreSwitchesItsFile); + Run(SwitchAtLoginAndBackAtLogout); + Run(HotReloadUsesTheCharactersFilesFromTheFirstFrame); + Run(IdentityThatNeverComes); + Run(OneSwitchAtATimeAndReset); + Run(TwoSessionsNeverShareAFile); + Run(TwoClientsNeverWriteEachOthersFiles); + Run(AutoSaveRules); + Run(CommandReplies); + } + finally + { + try { Directory.Delete(_root, true); } catch { } + } + + Console.WriteLine(); + Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); + Console.WriteLine(_failed == 0 ? "ALL PANEL LAYOUT TESTS PASSED." : $"{_failed} FAILED."); + return _failed == 0 && _checks > 0 ? 0 : 1; + } + + private static void Run(Action test) + { + try { test(); } + catch (Exception ex) { _checks++; _failed++; Console.WriteLine($" FAIL [{_case}] threw {ex.GetType().Name}: {ex.Message}"); } + } + + private static string NewDir(string name) + { + string dir = Path.Combine(_root, name); + Directory.CreateDirectory(dir); + return dir; + } + + private static string DefaultIni(string root) => Path.Combine(root, "suite", "RynthAi", "imgui.ini"); + + // ── the key and the file names ─────────────────────────────────────── + + private static void KeyAndFileNames() + { + Case("the key: server and character, the file names"); + Check(PanelLayoutPolicy.Owner(ServerOne, "") == null, "no character name: no owner (the default is used)"); + Check(PanelLayoutPolicy.Owner(ServerOne, " ") == null, "a blank name is no name"); + Check(PanelLayoutPolicy.Owner(null, null) == null, "nothing known: no owner"); + LayoutOwner a = PanelLayoutPolicy.Owner(" " + ServerOne + " ", " " + CharA + " ")!; + Check(a.Server == ServerOne && a.Character == CharA, "names are trimmed"); + Check(a.Equals(PanelLayoutPolicy.Owner(ServerOne.ToUpperInvariant(), CharA.ToLowerInvariant())), "the same character in another case is the same owner"); + Check(a.GetHashCode() == PanelLayoutPolicy.Owner(ServerOne.ToUpperInvariant(), CharA.ToLowerInvariant())!.GetHashCode(), "...with the same hash"); + Check(!a.Equals(PanelLayoutPolicy.Owner(ServerTwo, CharA)), "the same name on another server is another owner"); + Check(!a.Equals(PanelLayoutPolicy.Owner(ServerOne, CharB)), "another character is another owner"); + Eq(PanelLayoutPolicy.Describe(a), CharA + " on " + ServerOne, "described as 'name on server'"); + Eq(PanelLayoutPolicy.Describe(PanelLayoutPolicy.Owner("", CharA)!), CharA, "no server: just the name"); + + string root = @"C:\Users\Someone\AppData\Local\RynthCore"; + LayoutFiles f = PanelLayoutPolicy.CharacterFiles(root, a); + Eq(f.PanelState, Path.Combine(root, "layouts", ServerOne, CharA, "panel_state.txt"), "panel_state.txt in layouts\\\\"); + Eq(f.ImGuiIni, Path.Combine(root, "layouts", ServerOne, CharA, "imgui.ini"), "imgui.ini beside it"); + Eq(f.Folder, Path.Combine(root, "layouts", ServerOne, CharA), "the layout's folder"); + Eq(PanelLayoutPolicy.CharacterFiles(root, PanelLayoutPolicy.Owner("", CharA)!).PanelState, + Path.Combine(root, "layouts", "_", CharA, "panel_state.txt"), "no server: the '_' folder"); + Check(PanelLayoutPolicy.CharacterFiles(root, a).Folder != PanelLayoutPolicy.CharacterFiles(root, PanelLayoutPolicy.Owner(ServerTwo, CharA)!).Folder, + "the same name on two servers: two folders"); + + Case("safe file names"); + Eq(PanelLayoutPolicy.SafeSegment(CharA), CharA, "a plain name (letters, a space) stays as it is"); + Eq(PanelLayoutPolicy.SafeSegment("Some-Name'Here"), "Some-Name'Here", "hyphens and apostrophes are fine"); + Eq(PanelLayoutPolicy.SafeSegment(""), "_", "empty: '_'"); + Eq(PanelLayoutPolicy.SafeSegment(null), "_", "null: '_'"); + string colon = PanelLayoutPolicy.SafeSegment("A:B"), question = PanelLayoutPolicy.SafeSegment("A?B"); + Check(colon.StartsWith("A_B-", StringComparison.Ordinal) && question.StartsWith("A_B-", StringComparison.Ordinal), $"invalid characters become '_' ({colon}, {question})"); + Check(colon != question, "two names that clean up alike stay apart (a hash of the original)"); + Eq(PanelLayoutPolicy.SafeSegment("A:B"), colon, "the same name always gives the same folder"); + foreach (string bad in new[] { "a/b", "a\\b", "a*b", "a|b", "a", "a\"b", "tab\there", "dots..." , "space ", "CON", "nul", "com1.txt" }) + { + string s = PanelLayoutPolicy.SafeSegment(bad); + Check(s.Length > 0 && s.IndexOfAny(Path.GetInvalidFileNameChars()) < 0, $"'{bad}' -> '{s}' has no invalid characters"); + Check(!s.EndsWith('.') && !s.EndsWith(' '), $"'{bad}' -> '{s}' doesn't end with a dot or space"); + string stem = s.Split('.')[0].Split('-')[0]; + Check(!new[] { "CON", "NUL", "COM1" }.Contains(stem, StringComparer.OrdinalIgnoreCase), $"'{bad}' -> '{s}' isn't a device name"); + string dir = Path.Combine(_root, "names", s); + Directory.CreateDirectory(dir); + Check(Directory.Exists(dir), $"'{s}' can be made as a folder"); + } + string longName = new string('x', 200); + Check(PanelLayoutPolicy.SafeSegment(longName).Length <= 64 + 9, "a very long name is cut (plus its hash)"); + } + + private static void SettingOffGivesTodaysPaths() + { + Case("the setting off: today's files"); + string root = @"C:\Users\Someone\AppData\Local\RynthCore"; + string ini = @"C:\Games\RynthSuite\RynthAi\imgui.ini"; + LayoutOwner who = PanelLayoutPolicy.Owner(ServerOne, CharA)!; + LayoutFiles today = PanelLayoutPolicy.DefaultFiles(root, ini); + Eq(today.PanelState, Path.Combine(root, "panel_state.txt"), "the default panel_state.txt is the file every client used"); + Eq(today.ImGuiIni, ini, "the default imgui.ini is the file every client used"); + Check(PanelLayoutPolicy.Choose(perCharacter: false, inWorld: true, who) == null, "setting off, in the world: the default"); + Eq(PanelLayoutPolicy.FilesFor(root, ini, PanelLayoutPolicy.Choose(false, true, who)), today, "setting off: today's two files"); + Check(PanelLayoutPolicy.Choose(true, inWorld: false, who) == null, "setting on, at character select: the default"); + Check(PanelLayoutPolicy.Choose(true, true, null) == null, "setting on, in the world, no character name: the default"); + Eq(PanelLayoutPolicy.Choose(true, true, who), who, "setting on, in the world with a name: the character's"); + Eq(PanelLayoutPolicy.FilesFor(root, ini, who), PanelLayoutPolicy.CharacterFiles(root, who), "...and its files"); + + string expected = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "panel_state.txt"); + Eq(PanelStateStore.DefaultPath, expected, "PanelStateStore's default is today's %LOCALAPPDATA%\\RynthCore\\panel_state.txt (path only, not opened)"); + + Case("the setting off: a session never leaves the default"); + var s = new PanelLayoutSession(); + LayoutSwitch? first = s.Tick(0, perCharacter: false, inWorld: false, 0, false, null); + Check(first is { To: null }, "first frame: the default"); + s.MarkApplied(first!.Value.Gen); + Check(s.Tick(10, false, inWorld: true, 10, identityRecorded: true, who) == null, "login with the setting off: no switch"); + Check(s.ReadyToDraw(11, true, 10), "and the panels draw at once (the default is in place)"); + Check(s.Tick(20, false, inWorld: false, 0, true, who) == null, "logout: still nothing to switch"); + } + + // ── seeding a new character from the default ───────────────────────── + + private static void SeedingFromTheDefault() + { + Case("seed plan"); + Eq(PanelLayoutPolicy.SeedPlan(false, false, true, true), (true, true), "nothing yet, default has both: copy both"); + Eq(PanelLayoutPolicy.SeedPlan(true, true, true, true), (false, false), "the character has both: copy nothing"); + Eq(PanelLayoutPolicy.SeedPlan(true, false, true, true), (false, true), "only the ini missing: copy the ini"); + Eq(PanelLayoutPolicy.SeedPlan(false, true, true, true), (true, false), "only panel_state missing: copy it"); + Eq(PanelLayoutPolicy.SeedPlan(false, false, false, false), (false, false), "no default (a fresh install): nothing to copy"); + Eq(PanelLayoutPolicy.SeedPlan(false, false, true, false), (true, false), "the default has no ini: only panel_state"); + + Case("seeding files"); + string root = NewDir("seed"); + LayoutFiles defaults = PanelLayoutPolicy.DefaultFiles(root, DefaultIni(root)); + PanelLayoutFiles.WriteText(defaults.PanelState, "# default\r\npanel.Chat=open,10,20,300,200,docked,0,0\r\n"); + PanelLayoutFiles.WriteText(defaults.ImGuiIni, "[Window][Plugin Window##x]\nPos=5,6\nSize=100,100\n"); + LayoutFiles a = PanelLayoutPolicy.CharacterFiles(root, PanelLayoutPolicy.Owner(ServerOne, CharA)!); + Eq(PanelLayoutFiles.SeedMissing(defaults, a), (true, true), "a new character: both copied"); + Eq(File.ReadAllText(a.PanelState), File.ReadAllText(defaults.PanelState), "panel_state.txt is the default's (nothing moves the first time)"); + Eq(File.ReadAllText(a.ImGuiIni), File.ReadAllText(defaults.ImGuiIni), "imgui.ini is the default's"); + File.WriteAllText(a.PanelState, "# mine\r\n"); + Eq(PanelLayoutFiles.SeedMissing(defaults, a), (false, false), "seeded once: the next login copies nothing"); + Eq(File.ReadAllText(a.PanelState), "# mine\r\n", "the character's own places are kept"); + File.Delete(a.ImGuiIni); + Eq(PanelLayoutFiles.SeedMissing(defaults, a), (false, true), "one file gone: only that one is copied"); + Eq(File.ReadAllText(a.PanelState), "# mine\r\n", "...and the other is kept"); + + string bare = NewDir("seed-nodefault"); + LayoutFiles noDefaults = PanelLayoutPolicy.DefaultFiles(bare, DefaultIni(bare)); + LayoutFiles b = PanelLayoutPolicy.CharacterFiles(bare, PanelLayoutPolicy.Owner(ServerOne, CharB)!); + Eq(PanelLayoutFiles.SeedMissing(noDefaults, b), (false, false), "no default yet: nothing copied"); + Check(!File.Exists(b.PanelState) && !File.Exists(b.ImGuiIni), "...and nothing made up"); + Check(!File.Exists(noDefaults.PanelState) && !File.Exists(noDefaults.ImGuiIni), "the default is never written by seeding"); + NoTempFiles(root); + } + + private static void ResetAndMakeDefaultFiles() + { + Case("reset: the default copied over the character's"); + string root = NewDir("reset"); + LayoutFiles defaults = PanelLayoutPolicy.DefaultFiles(root, DefaultIni(root)); + LayoutFiles a = PanelLayoutPolicy.CharacterFiles(root, PanelLayoutPolicy.Owner(ServerOne, CharA)!); + PanelLayoutFiles.WriteText(defaults.PanelState, "# default\r\n"); + PanelLayoutFiles.WriteText(defaults.ImGuiIni, "[Window][D]\n"); + PanelLayoutFiles.WriteText(a.PanelState, "# old A\r\n"); + PanelLayoutFiles.WriteText(a.ImGuiIni, "[Window][OldA]\n"); + PanelLayoutFiles.CopyOver(defaults, a); + Eq(File.ReadAllText(a.PanelState), "# default\r\n", "panel_state.txt is the default's"); + Eq(File.ReadAllText(a.ImGuiIni), "[Window][D]\n", "imgui.ini is the default's"); + File.Delete(defaults.ImGuiIni); + PanelLayoutFiles.WriteText(a.ImGuiIni, "[Window][OldA]\n"); + PanelLayoutFiles.CopyOver(defaults, a); + Eq(File.ReadAllText(a.ImGuiIni), "", "the default has no imgui.ini: the character's is emptied, not kept"); + + Case("make default: the character's layout written as the default"); + PanelLayoutFiles.WriteText(a.ImGuiIni, "[Window][A]\n"); + PanelLayoutFiles.MakeDefault(a, defaults, "# from A\r\n", "[Window][A now]\n"); + Eq(File.ReadAllText(defaults.PanelState), "# from A\r\n", "the default panel_state.txt is the store's text"); + Eq(File.ReadAllText(defaults.ImGuiIni), "[Window][A now]\n", "the default imgui.ini is the context's windows"); + PanelLayoutFiles.MakeDefault(a, defaults, "# from A again\r\n", null); + Eq(File.ReadAllText(defaults.ImGuiIni), "[Window][A]\n", "no context (ImGui off): the character's imgui.ini as saved"); + Eq(File.ReadAllText(a.PanelState), "# default\r\n", "the character's own files are not changed by it"); + NoTempFiles(root); + } + + private static void LatestTextWritesKeepTheNewest() + { + Case("imgui.ini saves: the newest text wins, never an older one after it"); + var written = new List<(string, string)>(); + var w = new LatestTextWrites((p, t) => written.Add((p, t))); + Check(!w.Flush("x"), "nothing queued: nothing written"); + w.Queue("x", "one"); + w.Queue("x", "two"); + Check(w.HasPending("x"), "queued"); + Check(w.Flush("x"), "flushed"); + Check(written.Count == 1 && written[0] == ("x", "two"), "only the newest is written, once"); + Check(!w.Flush("x"), "a later flush (the writer's queued job after shutdown wrote it) writes nothing"); + w.Queue("x", "three"); + w.Queue("y", "other"); + w.Flush("y"); + Check(written[^1] == ("y", "other") && w.HasPending("x"), "files are separate"); + + string root = NewDir("latest"); + string path = Path.Combine(root, "a", "imgui.ini"); + var real = new LatestTextWrites(PanelLayoutFiles.WriteText); + var threads = new List(); + for (int t = 0; t < 4; t++) + { + int id = t; + var th = new Thread(() => { for (int i = 0; i < 50; i++) { real.Queue(path, $"t{id} i{i}"); real.Flush(path); } }); + threads.Add(th); + th.Start(); + } + foreach (var th in threads) th.Join(); + real.Queue(path, "last"); + real.Flush(path); + Eq(File.ReadAllText(path), "last", "concurrent saves: the file holds the last one, whole"); + NoTempFiles(root); + } + + private static void StoreSwitchesItsFile() + { + Case("PanelStateStore: switching its file, atomic saves"); + string root = NewDir("store"); + string def = Path.Combine(root, "panel_state.txt"); + File.WriteAllText(def, "# default\r\nbar=1,2\r\npanel.Chat=open,10,20,300,200,docked,0,0\r\n"); + byte[] defBytes = File.ReadAllBytes(def); + PanelStateStore.SwitchTo(def, flushCurrent: false); + Eq(PanelStateStore.CurrentPath, def, "the store reads the file it was switched to"); + Check(PanelStateStore.TryGetPanel("Chat", out var chat) && chat.Left == 10, "its panels are read"); + + string a = Path.Combine(root, "layouts", "s", "a", "panel_state.txt"); + Directory.CreateDirectory(Path.GetDirectoryName(a)!); + File.WriteAllText(a, "# A\r\npanel.Radar=open,500,40,200,200,docked,0,0\r\nbarlayout=2,0\r\n"); + PanelStateStore.SwitchTo(a, flushCurrent: false); + Check(!PanelStateStore.TryGetPanel("Chat", out _), "nothing of the old layout is left in memory"); + Check(PanelStateStore.TryGetPanel("Radar", out var radar) && radar.Left == 500, "the new layout's panels"); + Eq(PanelStateStore.BarRows, (2, 0), "the new layout's bar rows"); + Check(PanelStateStore.BarPosition == null, "no bar row: no bar position (not the old one)"); + Eq(File.ReadAllBytes(def), defBytes, "switching away from the default never writes it"); + + PanelStateStore.SetPanel("Radar", new PanelStateStore.PanelEntry(true, 600, 50, 200, 200)); + Check(File.ReadAllText(a).Contains("panel.Radar=open,600,50", StringComparison.Ordinal), "a save goes to the character's file"); + Eq(File.ReadAllBytes(def), defBytes, "...and not the default"); + Check(PanelStateStore.Snapshot().Contains("panel.Radar=open,600,50", StringComparison.Ordinal), "Snapshot is the text of what is in memory"); + NoTempFiles(root); + + string b = Path.Combine(root, "layouts", "s", "b", "panel_state.txt"); + PanelStateStore.SwitchTo(b, flushCurrent: true); + Check(!File.Exists(b), "a character without a file starts empty (no file made by reading)"); + Check(!PanelStateStore.TryGetPanel("Radar", out _), "and empty in memory"); + PanelStateStore.SetBarPosition(7, 8); + Check(File.Exists(b) && File.ReadAllText(b).Contains("bar=7,8", StringComparison.Ordinal), "its first save makes it"); + Check(!File.ReadAllText(a).Contains("bar=7,8", StringComparison.Ordinal), "the other character's file isn't touched"); + + Case("PanelStateStore: Remember Open Windows off"); + RynthCore.Engine.Plugins.EngineSettings.RememberWindowLayout = false; + try + { + string before = File.ReadAllText(b); + PanelStateStore.SetBarPosition(9, 9); + Eq(File.ReadAllText(b), before, "off: a change isn't saved"); + PanelStateStore.SwitchTo(a, flushCurrent: true); + Eq(File.ReadAllText(b), before, "off: a switch doesn't write the file it leaves either"); + PanelStateStore.Flush(); + Check(File.ReadAllText(a).Contains("panel.Radar", StringComparison.Ordinal), "Save Layout Now still writes (the file in use)"); + } + finally + { + RynthCore.Engine.Plugins.EngineSettings.RememberWindowLayout = true; + } + NoTempFiles(root); + } + + // ── the session: when to switch, when panels may draw ─────────────── + + private static readonly LayoutOwner WhoA = PanelLayoutPolicy.Owner(ServerOne, CharA)!; + private static readonly LayoutOwner WhoB = PanelLayoutPolicy.Owner(ServerOne, CharB)!; + + private static void SwitchAtLoginAndBackAtLogout() + { + Case("the switch at login and back at logout"); + var s = new PanelLayoutSession(); + LayoutSwitch? sw = s.Tick(0, true, inWorld: false, 0, false, null); + Check(sw is { To: null, FromKnown: false } && !sw.Value.FlushFrom, "first frame at character select: the default, nothing written out"); + Check(s.ReadyToDraw(1, false, 0), "nothing draws at character select anyway: never held"); + Check(s.Tick(5, true, false, 0, false, null) == null, "while it loads: no second switch"); + s.MarkApplied(sw!.Value.Gen); + Check(s.Tick(10, true, false, 0, false, null) == null, "the default in place: nothing to do"); + + const long login = 1000; + Check(s.Tick(1000, true, inWorld: true, login, identityRecorded: false, null) == null, "login, the name not recorded yet: no switch"); + Check(!s.ReadyToDraw(1000, true, login), "...and panels wait"); + sw = s.Tick(1016, true, true, login, identityRecorded: true, WhoA); + Check(sw is { } x1 && Equals(x1.To, WhoA) && x1.From == null && x1.FromKnown && !x1.FlushFrom, + "the name is in: switch to the character's layout; the default is not written out"); + Check(!s.ReadyToDraw(1020, true, login), "panels still wait while it loads"); + s.MarkApplied(sw!.Value.Gen); + Check(s.ReadyToDraw(1040, true, login), "applied: panels draw, in the character's places"); + Eq(s.AppliedLayout, WhoA, "the character's layout is the one in use"); + Check(s.Tick(1050, true, true, login, true, WhoA) == null, "in the world: nothing more to switch"); + + sw = s.Tick(5000, true, inWorld: false, 0, true, WhoA); + Check(sw is { } x2 && x2.To == null && Equals(x2.From, WhoA) && x2.FlushFrom, + "logout: back to the default, the character's files written out first"); + Check(s.ReadyToDraw(5001, false, 0), "character select: not held"); + s.MarkApplied(sw!.Value.Gen); + + const long relogin = 9000; + sw = s.Tick(9000, true, true, relogin, identityRecorded: true, WhoA); + Check(sw is { } x3 && Equals(x3.To, WhoA) && x3.From == null && !x3.FlushFrom, "logging back in: the character's layout again"); + Check(!s.ReadyToDraw(9001, true, relogin), "...held until it is in place"); + s.MarkApplied(sw!.Value.Gen); + Check(s.ReadyToDraw(9002, true, relogin), "...then drawn"); + + Case("the setting changed in the world: switch, without hiding the panels"); + sw = s.Tick(9100, perCharacter: false, true, relogin, true, WhoA); + Check(sw is { } x4 && x4.To == null && x4.FlushFrom, "off: to the default (the character's written out)"); + Check(s.ReadyToDraw(9101, true, relogin), "the panels keep drawing while it loads"); + s.MarkApplied(sw!.Value.Gen); + sw = s.Tick(9200, perCharacter: true, true, relogin, true, WhoA); + Check(sw is { } x5 && Equals(x5.To, WhoA) && !x5.FlushFrom, "on again: to the character's (the default not written)"); + s.MarkApplied(sw!.Value.Gen); + } + + private static void HotReloadUsesTheCharactersFilesFromTheFirstFrame() + { + Case("hot reload in the world: the character's files from the first frame"); + // The new engine marks the login at init (MarkAlreadyComplete) and records the name; its + // session is new. Simulated frame by frame: drawing is allowed only with the character's + // layout applied, never with the default while in the world. + foreach (bool frameBeforeLoginMark in new[] { false, true }) + { + var s = new PanelLayoutSession(); + long login = 50_000; + LayoutOwner? applied = null; + bool anyApplied = false, drewWithDefault = false, drewWithCharacter = false; + LayoutSwitch? inFlight = null; + int switchesToCharacter = 0; + for (long t = 49_990; t < 50_200; t += 16) + { + bool inWorld = !frameBeforeLoginMark || t >= login; + bool recorded = inWorld && t >= login + 16; // the name lands a frame after the mark + // A switch asked for one frame is loaded by the writer and applied the next. + if (inFlight is { } done) + { + s.MarkApplied(done.Gen); + applied = done.To; + anyApplied = true; + inFlight = null; + } + LayoutSwitch? sw = s.Tick(t, true, inWorld, inWorld ? login : 0, recorded, recorded ? WhoA : null); + if (sw is { } x) + { + inFlight = x; + if (Equals(x.To, WhoA)) switchesToCharacter++; + } + if (inWorld && s.ReadyToDraw(t, true, login)) + { + if (!anyApplied || applied == null) drewWithDefault = true; + else if (Equals(applied, WhoA)) drewWithCharacter = true; + } + } + string how = frameBeforeLoginMark ? " (a frame ran before the login was marked)" : ""; + Check(!drewWithDefault, "panels never drew with the default layout in the world" + how); + Check(drewWithCharacter, "panels drew with the character's layout" + how); + Eq(switchesToCharacter, 1, "one switch to the character" + how); + } + + Case("hot reload: the first switch goes straight to the character"); + var direct = new PanelLayoutSession(); + Check(direct.Tick(100, true, true, 100, identityRecorded: false, null) == null, "login marked, name not yet: no switch to the default first"); + LayoutSwitch? first = direct.Tick(116, true, true, 100, true, WhoA); + Check(first is { } f && Equals(f.To, WhoA) && !f.FromKnown && !f.FlushFrom, "the first switch is the character's, nothing written out"); + Check(!direct.ReadyToDraw(117, true, 100), "no frame draws before it is applied"); + direct.MarkApplied(first!.Value.Gen); + Check(direct.ReadyToDraw(132, true, 100), "applied: the first frame that draws uses it"); + + Case("a login time not set yet in the world: wait for it"); + var early = new PanelLayoutSession(); + Check(early.Tick(10_000, true, inWorld: true, loginAtMs: 0, identityRecorded: true, WhoA) == null, "the flag without its time: no decision"); + Check(!early.ReadyToDraw(10_000, true, 0), "...and no drawing"); + } + + private static void IdentityThatNeverComes() + { + Case("a name that never comes: the default after the wait"); + var s = new PanelLayoutSession(); + s.MarkApplied(s.Tick(0, true, false, 0, false, null)!.Value.Gen); + const long login = 2000; + Check(s.Tick(2000 + PanelLayoutPolicy.IdentityWaitMs - 1, true, true, login, false, null) == null, "just before the wait ends: still waiting"); + Check(!s.ReadyToDraw(2000 + PanelLayoutPolicy.IdentityWaitMs - 1, true, login), "...not drawn"); + Check(s.Tick(2000 + PanelLayoutPolicy.IdentityWaitMs, true, true, login, false, null) == null, "the wait over, no name: the default already in use, no switch"); + Check(s.ReadyToDraw(2000 + PanelLayoutPolicy.IdentityWaitMs, true, login), "...and the panels draw with it"); + + var t = new PanelLayoutSession(); + t.MarkApplied(t.Tick(0, true, false, 0, false, null)!.Value.Gen); + LayoutSwitch? late = t.Tick(login + PanelLayoutPolicy.IdentityWaitMs, true, true, login, false, WhoB); + Check(late is { } l && Equals(l.To, WhoB), "the wait over, a name known but never recorded: that name's layout"); + } + + private static void OneSwitchAtATimeAndReset() + { + Case("one switch at a time"); + var s = new PanelLayoutSession(); + LayoutSwitch first = s.Tick(0, true, false, 0, false, null)!.Value; + Check(s.InFlight, "in flight"); + Check(s.Tick(1, true, true, 1, true, WhoA) == null, "the login during it: no second switch yet"); + Check(!s.ReadyToDraw(2, true, 1), "...and nothing draws (the default isn't the login's layout)"); + s.MarkApplied(first.Gen); + Check(!s.ReadyToDraw(3, true, 1), "the default applied: still not the login's layout"); + LayoutSwitch next = s.Tick(4, true, true, 1, true, WhoA)!.Value; + Check(Equals(next.To, WhoA) && next.Gen == first.Gen + 1, "after it: the character's"); + s.MarkApplied(first.Gen); + Check(s.InFlight, "an old switch marked again doesn't count"); + s.MarkApplied(next.Gen); + Check(!s.InFlight && s.ReadyToDraw(5, true, 1), "done"); + + Case("a stuck switch stops holding the panels"); + var stuck = new PanelLayoutSession(); + stuck.Tick(10, true, true, 10, true, WhoA); + Check(!stuck.ReadyToDraw(10 + PanelLayoutPolicy.ApplyGiveUpMs - 1, true, 10), "held while it may still come"); + Check(stuck.ReadyToDraw(10 + PanelLayoutPolicy.ApplyGiveUpMs, true, 10), "drawn after the give-up time"); + + Case("reset: the character's files reseeded from the default"); + s.WantReseed(); + LayoutSwitch? reset = s.Tick(6, true, true, 1, true, WhoA); + Check(reset is { } r && r.Reseed && Equals(r.To, WhoA) && Equals(r.From, WhoA) && !r.FlushFrom, + "a reseed switch to the same character, its current files not written out (they're being replaced)"); + Check(s.ReadyToDraw(7, true, 1), "the panels keep drawing while it loads"); + s.MarkApplied(reset!.Value.Gen); + Check(s.Tick(8, true, true, 1, true, WhoA) == null, "once: no second reset"); + var none = new PanelLayoutSession(); + none.MarkApplied(none.Tick(0, true, false, 0, false, null)!.Value.Gen); + none.WantReseed(); + Check(none.Tick(1, true, false, 0, false, null) == null, "no character layout in use: a reset does nothing"); + } + + private static void TwoSessionsNeverShareAFile() + { + Case("two clients' sessions: the files each one writes are its own"); + string root = @"C:\Users\Someone\AppData\Local\RynthCore"; + string ini = @"C:\Games\RynthSuite\RynthAi\imgui.ini"; + LayoutFiles defaults = PanelLayoutPolicy.DefaultFiles(root, ini); + var written = new Dictionary> { [WhoA] = new(), [WhoB] = new() }; + foreach (LayoutOwner who in new[] { WhoA, WhoB }) + { + var s = new PanelLayoutSession(); + long t = 0; + void Step(bool inWorld, long login) + { + LayoutSwitch? sw = s.Tick(t += 16, true, inWorld, login, true, who); + if (sw is not { } x) return; + // What a switch writes: the layout left (when FlushFrom) and the one it goes to (seeding). + if (x.FlushFrom) { LayoutFiles f = PanelLayoutPolicy.FilesFor(root, ini, x.From); written[who].Add(f.PanelState); written[who].Add(f.ImGuiIni); } + if (x.To != null) { LayoutFiles f = PanelLayoutPolicy.FilesFor(root, ini, x.To); written[who].Add(f.PanelState); written[who].Add(f.ImGuiIni); } + s.MarkApplied(x.Gen); + // In the world the saves go to the layout in use. + if (inWorld && s.AppliedLayout is { } inUse) { LayoutFiles f = PanelLayoutPolicy.FilesFor(root, ini, inUse); written[who].Add(f.PanelState); written[who].Add(f.ImGuiIni); } + } + Step(false, 0); Step(true, 100); Step(true, 100); Step(false, 0); Step(true, 900); Step(true, 900); + } + Check(written[WhoA].Count > 0 && written[WhoB].Count > 0, "both wrote their layouts"); + Check(!written[WhoA].Overlaps(written[WhoB]), "client A and client B never write the same file"); + Check(!written[WhoA].Contains(defaults.PanelState) && !written[WhoA].Contains(defaults.ImGuiIni) + && !written[WhoB].Contains(defaults.PanelState) && !written[WhoB].Contains(defaults.ImGuiIni), + "neither writes the default (in the world, at a switch or a logout)"); + } + + // Two clients at once: child processes of this test, each a client of one character. + private static void TwoClientsNeverWriteEachOthersFiles() + { + Case("two clients at once, two characters: each writes only its own files"); + string root = NewDir("clients"); + string ini = DefaultIni(root); + LayoutFiles defaults = PanelLayoutPolicy.DefaultFiles(root, ini); + PanelLayoutFiles.WriteText(defaults.PanelState, "# default\r\npanel.Shared=open,1,2,300,200,docked,0,0\r\n"); + PanelLayoutFiles.WriteText(defaults.ImGuiIni, "[Window][Shared]\nPos=1,2\n"); + byte[] defPanel = File.ReadAllBytes(defaults.PanelState), defIni = File.ReadAllBytes(defaults.ImGuiIni); + + var clients = new[] { (ServerOne, CharA), (ServerOne, CharB), (ServerTwo, CharA) }; + var procs = new List(); + foreach (var (server, character) in clients) + { + string self = Environment.ProcessPath!; + var psi = new ProcessStartInfo(self) { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false }; + // Run as "dotnet PanelLayoutTests.dll": the child is the same dll. + if (Path.GetFileNameWithoutExtension(self).Equals("dotnet", StringComparison.OrdinalIgnoreCase)) + psi.ArgumentList.Add(typeof(Program).Assembly.Location); + foreach (string a in new[] { "--client", root, ini, server, character, "150" }) psi.ArgumentList.Add(a); + procs.Add(Process.Start(psi)!); + } + for (int i = 0; i < procs.Count; i++) + { + string output = procs[i].StandardOutput.ReadToEnd() + procs[i].StandardError.ReadToEnd(); + procs[i].WaitForExit(); + Check(procs[i].ExitCode == 0, $"client {i + 1} ran ({output.Trim()})"); + } + + Eq(File.ReadAllBytes(defaults.PanelState), defPanel, "the default panel_state.txt is unchanged"); + Eq(File.ReadAllBytes(defaults.ImGuiIni), defIni, "the default imgui.ini is unchanged"); + foreach (var (server, character) in clients) + { + LayoutOwner who = PanelLayoutPolicy.Owner(server, character)!; + LayoutFiles f = PanelLayoutPolicy.CharacterFiles(root, who); + string panel = File.Exists(f.PanelState) ? File.ReadAllText(f.PanelState) : ""; + string iniText = File.Exists(f.ImGuiIni) ? File.ReadAllText(f.ImGuiIni) : ""; + string mark = Marker(server, character); + Check(panel.Contains("panel." + mark + "=", StringComparison.Ordinal), $"{PanelLayoutPolicy.Describe(who)}: its own panels are in its file"); + Check(panel.Contains("panel.Shared=", StringComparison.Ordinal), $"{PanelLayoutPolicy.Describe(who)}: seeded from the default"); + Check(panel.Contains("panel.Last=open,149,", StringComparison.Ordinal), $"{PanelLayoutPolicy.Describe(who)}: the last save is the one on disk"); + Check(iniText.Contains("[Window][" + mark + "]", StringComparison.Ordinal) && iniText.Contains("Pos=149,149", StringComparison.Ordinal), + $"{PanelLayoutPolicy.Describe(who)}: its imgui.ini holds its own last save"); + foreach (var (os, oc) in clients) + { + if (os == server && oc == character) continue; + string other = Marker(os, oc); + Check(!panel.Contains(other, StringComparison.Ordinal) && !iniText.Contains(other, StringComparison.Ordinal), + $"{PanelLayoutPolicy.Describe(who)}'s files have nothing of {os}/{oc}"); + } + } + NoTempFiles(root); + } + + private static string Marker(string server, string character) => ("M_" + server + "_" + character).Replace(' ', '_'); + + /// A client (child process): character select on the default, a login to its character, saves, a logout. + private static int Client(string[] a) + { + try + { + string root = a[0], ini = a[1], server = a[2], character = a[3]; + int saves = int.Parse(a[4]); + LayoutFiles defaults = PanelLayoutPolicy.DefaultFiles(root, ini); + PanelStateStore.SwitchTo(defaults.PanelState, flushCurrent: false); // character select: the default + LayoutOwner who = PanelLayoutPolicy.Owner(server, character)!; + LayoutFiles mine = PanelLayoutPolicy.CharacterFiles(root, who); + // The login: seed, switch (the default is never written out). + PanelLayoutFiles.SeedMissing(defaults, mine); + PanelStateStore.SwitchTo(mine.PanelState, flushCurrent: false); + var iniWrites = new LatestTextWrites(PanelLayoutFiles.WriteText); + string mark = Marker(server, character); + for (int i = 0; i < saves; i++) + { + PanelStateStore.SetPanel(mark, new PanelStateStore.PanelEntry(true, i, i, 200, 100)); + PanelStateStore.SetPanel("Last", new PanelStateStore.PanelEntry(true, i, i, 200, 100)); + PanelStateStore.SetBarPosition(i, i); + iniWrites.Queue(mine.ImGuiIni, $"[Window][{mark}]\nPos={i},{i}\nSize=100,100\n"); + iniWrites.Flush(mine.ImGuiIni); + } + // The logout: the character's written out, back to the default (not written). + PanelStateStore.SwitchTo(defaults.PanelState, flushCurrent: true); + Console.WriteLine("client ok"); + return 0; + } + catch (Exception ex) + { + Console.WriteLine($"client threw {ex.GetType().Name}: {ex.Message}"); + return 2; + } + } + + // ── saving rules and the commands ───────────────────────────────── + + private static void AutoSaveRules() + { + Case("automatic imgui.ini saves"); + Check(PanelLayoutPolicy.MayAutoSaveIni(characterLayout: true, perCharacter: true, inWorld: true, contextHeldCharacter: true), "a character's layout: always saved"); + Check(PanelLayoutPolicy.MayAutoSaveIni(true, true, inWorld: false, contextHeldCharacter: true), "...also at a logout's last save"); + Check(PanelLayoutPolicy.MayAutoSaveIni(false, perCharacter: false, inWorld: true, contextHeldCharacter: true), "the setting off: the shared default is saved, as before"); + Check(PanelLayoutPolicy.MayAutoSaveIni(false, perCharacter: false, inWorld: false, contextHeldCharacter: false), "the setting off, at character select: saved, as before"); + Check(PanelLayoutPolicy.MayAutoSaveIni(false, true, inWorld: true, contextHeldCharacter: false), "in the world with no character name (the default in use): saved, as before"); + Check(!PanelLayoutPolicy.MayAutoSaveIni(false, true, inWorld: false, contextHeldCharacter: false), + "character select with the setting on: the default isn't written (it could undo another client's /rc layout default)"); + Check(!PanelLayoutPolicy.MayAutoSaveIni(false, true, inWorld: false, contextHeldCharacter: true), "the default after a character logged out: not saved (its windows would leak into it)"); + Check(!PanelLayoutPolicy.MayAutoSaveIni(false, true, inWorld: true, contextHeldCharacter: true), "the default in the world after a character's layout was used: not saved"); + } + + private static void CommandReplies() + { + Case("/rc layout: parsing"); + Eq(PanelLayoutPolicy.ParseCommand(""), LayoutCommand.Status, "alone: the status"); + Eq(PanelLayoutPolicy.ParseCommand(null), LayoutCommand.Status, "null: the status"); + Eq(PanelLayoutPolicy.ParseCommand(" STATUS "), LayoutCommand.Status, "status, any case"); + Eq(PanelLayoutPolicy.ParseCommand("default"), LayoutCommand.MakeDefault, "default"); + Eq(PanelLayoutPolicy.ParseCommand("reset"), LayoutCommand.ResetAsk, "reset alone asks"); + Eq(PanelLayoutPolicy.ParseCommand("reset Confirm"), LayoutCommand.ResetConfirm, "reset confirm, any spacing and case"); + foreach (string bad in new[] { "frob", "default now", "reset now", "confirm", "reset confirm please" }) + Eq(PanelLayoutPolicy.ParseCommand(bad), LayoutCommand.Invalid, $"'{bad}' is not a form"); + + Case("/rc layout: the check before it runs (ChatCommandReplies)"); + foreach (string ok in new[] { "layout", "layout status", "layout default", "layout reset", "layout reset confirm", "LAYOUT Reset confirm" }) + { + ChatVerbCheck c = ChatCommandReplies.Check(ok); + Check(c.Problem == null && c.Verb?.Name == "layout", $"'/rc {ok}' runs"); + } + foreach (string bad in new[] { "layout frob", "layout default now", "layout reset please" }) + { + ChatVerbCheck c = ChatCommandReplies.Check(bad); + Check(c.Verb?.Name == "layout" && c.Problem == PanelLayoutPolicy.Usage, $"'/rc {bad}' answers with the usage"); + } + Eq(ChatCommandReplies.Usage("layout"), PanelLayoutPolicy.Usage, "the catalog's usage is the policy's"); + Check(ChatCommandReplies.CommandList().Contains("layout", StringComparison.Ordinal), "/rc lists layout"); + Check(ChatCommandReplies.KindOfLine(PanelLayoutPolicy.Usage) == ChatReplyKind.Fail, "the usage is a failure (red)"); + + Case("/rc layout: the status"); + string root = @"C:\L", ini = @"C:\G\imgui.ini"; + LayoutFiles defaults = PanelLayoutPolicy.DefaultFiles(root, ini); + LayoutFiles mine = PanelLayoutPolicy.CharacterFiles(root, WhoA); + string[] own = PanelLayoutPolicy.StatusLines(WhoA, mine, DefaultReason.None, defaults, true); + Check(own[0].Contains(PanelLayoutPolicy.Describe(WhoA), StringComparison.Ordinal) && own[0].Contains(mine.PanelState, StringComparison.Ordinal) + && own[0].Contains(mine.ImGuiIni, StringComparison.Ordinal), "a character's: whose, and both files"); + Check(own.Length == 2 && own[1].Contains(defaults.PanelState, StringComparison.Ordinal) && own[1].Contains("/rc layout default", StringComparison.Ordinal) + && own[1].Contains("/rc layout reset", StringComparison.Ordinal), "...and the default's files and the two commands"); + Check(ChatCommandReplies.KindOfLines(own) == ChatReplyKind.Ok, "a state, not a failure"); + foreach (DefaultReason why in new[] { DefaultReason.SettingOff, DefaultReason.NotInWorld, DefaultReason.NoCharacterName, DefaultReason.WaitingForName }) + { + string[] d = PanelLayoutPolicy.StatusLines(null, defaults, why, defaults, perCharacter: why != DefaultReason.SettingOff); + Check(d[0].StartsWith("Panel layout: the PC-wide default (", StringComparison.Ordinal) && d[0].Contains(PanelLayoutPolicy.ReasonText(why), StringComparison.Ordinal) + && d[0].Contains(defaults.PanelState, StringComparison.Ordinal) && d[0].Contains(defaults.ImGuiIni, StringComparison.Ordinal), + $"the default ({why}): why, and both files"); + Check(ChatCommandReplies.KindOfLines(d) == ChatReplyKind.Ok, $"the default ({why}): a state"); + } + string[] off = PanelLayoutPolicy.StatusLines(null, defaults, DefaultReason.NotRunning, defaults, false); + Check(off.Length == 1 && ChatCommandReplies.KindOfLine(off[0]) == ChatReplyKind.Fail, "not running: a failure, says why"); + + Case("/rc layout default and reset: why they can't run"); + Check(PanelLayoutPolicy.CharacterLayoutProblem("x", true, true, true, WhoA, false) == null, "a character's layout in use: they run"); + (bool running, bool per, bool inWorld, LayoutOwner? inUse, bool switching, string want)[] cases = + { + (false, true, true, WhoA, false, PanelLayoutPolicy.ReasonText(DefaultReason.NotRunning)), + (true, false, true, WhoA, false, PanelLayoutPolicy.ReasonText(DefaultReason.SettingOff)), + (true, true, false, null, false, PanelLayoutPolicy.ReasonText(DefaultReason.NotInWorld)), + (true, true, true, WhoA, true, "still switching"), + (true, true, true, null, false, PanelLayoutPolicy.ReasonText(DefaultReason.NoCharacterName)), + }; + foreach (var c in cases) + { + string? p = PanelLayoutPolicy.CharacterLayoutProblem("make a default from this client", c.running, c.per, c.inWorld, c.inUse, c.switching); + Check(p != null && p.StartsWith("Can't make a default from this client: ", StringComparison.Ordinal) && p.Contains(c.want, StringComparison.Ordinal) + && p.EndsWith(PanelLayoutPolicy.Usage, StringComparison.Ordinal), $"why not ({c.want}), with the usage: {p}"); + Check(ChatCommandReplies.KindOfLine(p ?? "") == ChatReplyKind.Fail, $"a failure (red): {c.want}"); + } + + Case("/rc layout default and reset: the answers"); + string ask = PanelLayoutPolicy.ResetAskReply(WhoA, defaults); + Check(ask.Contains(PanelLayoutPolicy.Describe(WhoA), StringComparison.Ordinal) && ask.Contains("/rc layout reset confirm", StringComparison.Ordinal) + && ask.Contains(defaults.PanelState, StringComparison.Ordinal), "reset asks first: whose, from which file, and the confirm"); + Check(ChatCommandReplies.KindOfLine(ask) == ChatReplyKind.Ok, "...as a state (nothing failed)"); + string done = PanelLayoutPolicy.ResetDoneReply(WhoA); + Check(done.StartsWith(PanelLayoutPolicy.Describe(WhoA), StringComparison.Ordinal) && ChatCommandReplies.KindOfLine(done) == ChatReplyKind.Ok, "reset done"); + string made = PanelLayoutPolicy.MakeDefaultDoneReply(WhoA, defaults); + Check(made.Contains(defaults.PanelState, StringComparison.Ordinal) && made.Contains(defaults.ImGuiIni, StringComparison.Ordinal) + && ChatCommandReplies.KindOfLine(made) == ChatReplyKind.Ok, "make default done: the default's files"); + string failed = PanelLayoutPolicy.FailedReply("make the default", "access denied"); + Eq(failed, "Can't make the default: access denied.", "a failed file job says what and why"); + Check(ChatCommandReplies.KindOfLine(failed) == ChatReplyKind.Fail, "...as a failure"); + Check(ChatCommandReplies.KindOfLine(PanelLayoutPolicy.BusyReply) == ChatReplyKind.Fail && PanelLayoutPolicy.BusyReply.EndsWith(PanelLayoutPolicy.Usage, StringComparison.Ordinal), + "busy: a failure, with the usage"); + + Case("Settings > Display: the layout in use and the reset button"); + string line = PanelLayoutPolicy.SettingsLine(WhoA, mine, DefaultReason.None); + Check(line.StartsWith("In use: ", StringComparison.Ordinal) && line.Contains(PanelLayoutPolicy.Describe(WhoA), StringComparison.Ordinal) + && line.Contains(mine.Folder, StringComparison.Ordinal), $"a character's: whose, and its folder ({line})"); + Check(!line.Contains(defaults.PanelState, StringComparison.Ordinal), "...not the default's file"); + foreach (DefaultReason why in new[] { DefaultReason.SettingOff, DefaultReason.NotInWorld, DefaultReason.NoCharacterName, DefaultReason.WaitingForName }) + { + string d = PanelLayoutPolicy.SettingsLine(null, defaults, why); + Check(d.StartsWith("In use: the PC-wide default (", StringComparison.Ordinal) && d.Contains(PanelLayoutPolicy.ReasonText(why), StringComparison.Ordinal) + && d.Contains(defaults.PanelState, StringComparison.Ordinal), $"the default ({why}): why, and its file"); + } + Check(PanelLayoutPolicy.SettingsLine(null, defaults, DefaultReason.NotRunning).Contains(PanelLayoutPolicy.ReasonText(DefaultReason.NotRunning), StringComparison.Ordinal), + "not running: says so"); + string confirm = PanelLayoutPolicy.ResetConfirmText(WhoA); + Check(confirm.Contains(PanelLayoutPolicy.Describe(WhoA), StringComparison.Ordinal) && confirm.EndsWith("can't be undone.", StringComparison.Ordinal), + "the reset asks first: whose layout, and that it can't be undone"); + Check(PanelLayoutPolicy.ResetConfirmText(null).Contains("nothing to reset", StringComparison.Ordinal), "no character's layout: nothing to reset"); + // The button runs /rc layout reset confirm, the form the command takes. + Eq(PanelLayoutPolicy.ParseCommand("reset confirm"), LayoutCommand.ResetConfirm, "the button's command is reset confirm"); + } + + // ── helpers ──────────────────────────────────────────────────────── + + private static void NoTempFiles(string dir) + { + string[] left = Directory.GetFiles(dir, "*.tmp", SearchOption.AllDirectories); + Check(left.Length == 0, "no temp file left behind" + (left.Length > 0 ? ": " + string.Join(", ", left) : "")); + } + + 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 Eq(T actual, T expected, string what) => + Check(EqualityComparer.Default.Equals(actual, expected), $"{what}: expected '{Show(expected)}', got '{Show(actual)}'"); + + private static void Eq(byte[] actual, byte[] expected, string what) => + Check(actual.AsSpan().SequenceEqual(expected), what); + + private static string Show(T v) => v switch + { + null => "null", + string s => s, + _ => v.ToString() ?? "", + }; + } +} diff --git a/tools/PlateSizingTests/PlateSizingTests.csproj b/tools/PlateSizingTests/PlateSizingTests.csproj index cfe73d5..744eb8a 100644 --- a/tools/PlateSizingTests/PlateSizingTests.csproj +++ b/tools/PlateSizingTests/PlateSizingTests.csproj @@ -15,6 +15,8 @@ monster plates' and your plate's "Debuff icon size" default 100 %, an older file loads 100 %, they clamp to 50-200, round-trip on their own (apart from the text sizes), reset with the sizes, the chat form parses; the row's lengths at 100 % are the old expressions exactly at every scale, and its height and width grow with it. + Also "Refresh others' health" (2026-10-31; src\RynthCore.Engine\ImGui\MonsterHud\HealthProbe.cs compiled in for its + range): on at 1 s by default and from an older file, round-trips, the interval clamps, reset restores it. Run: dotnet run -c Release (exit 0 = pass, 1 = fail) --> @@ -28,6 +30,7 @@ + diff --git a/tools/PlateSizingTests/Program.cs b/tools/PlateSizingTests/Program.cs index a3841ae..f7d70a6 100644 --- a/tools/PlateSizingTests/Program.cs +++ b/tools/PlateSizingTests/Program.cs @@ -56,6 +56,9 @@ namespace PlateSizingTests DebuffRowScalesWithTheSetting(); DebuffRowWidthAndCover(); + HealthRefreshDefaultsOn(); + HealthRefreshRoundTripAndClamp(); + Console.WriteLine(); Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); Console.WriteLine(_failed == 0 ? "ALL PLATE SIZING TESTS PASSED." : $"{_failed} FAILED."); @@ -583,6 +586,48 @@ namespace PlateSizingTests // ── harness ───────────────────────────────────────────────────────── + // ── refresh others' health (HealthProbe) ──────────────────────────── + + private static void HealthRefreshDefaultsOn() + { + Case("refresh others' health: on at 1 s by default, and after loading a file from before it"); + S.ResetToDefaults(); + Check(S.RefreshOthersHealth, "on by default"); + Check(S.HealthRefreshSec == HealthProbe.DefaultIntervalSec && HealthProbe.DefaultIntervalSec == 1f, "1 s by default"); + Check(HealthProbe.MinIntervalSec <= 1f && 1f <= HealthProbe.MaxIntervalSec, "the range holds the default"); + string[] old = Written().Where(l => !l.StartsWith("refreshOthersHealth=", StringComparison.Ordinal) && + !l.StartsWith("healthRefreshSec=", StringComparison.Ordinal)).ToArray(); + Check(old.Length == Written().Length - 2, "the old file lacks exactly the two keys"); + S.RefreshOthersHealth = false; S.HealthRefreshSec = 4f; + S.ResetToDefaults(); + S.ApplyLines(old); + Check(S.RefreshOthersHealth && S.HealthRefreshSec == 1f, "on at 1 s after loading the old file"); + Check(S.Describe().Contains("refresh others' health every 1.0 s"), "status line: " + S.Describe()); + } + + private static void HealthRefreshRoundTripAndClamp() + { + Case("refresh others' health: off and an interval round-trip, the interval clamps, reset restores"); + S.ResetToDefaults(); + S.RefreshOthersHealth = false; S.HealthRefreshSec = 2.5f; + string[] lines = Written(); + Check(lines.Contains("refreshOthersHealth=0") && lines.Contains("healthRefreshSec=2.5"), "refreshOthersHealth=0, healthRefreshSec=2.5 written"); + S.ResetToDefaults(); + S.ApplyLines(lines); + Check(!S.RefreshOthersHealth && S.HealthRefreshSec == 2.5f, "off, 2.5 s after reload"); + Check(lines.SequenceEqual(Written()), "identical text after a reload"); + Check(S.Describe().Contains("refresh others' health off"), "status line says off"); + S.ApplyLines(new[] { "healthRefreshSec=0.01" }); + Check(S.HealthRefreshSec == HealthProbe.MinIntervalSec, $"0.01 floored at {HealthProbe.MinIntervalSec}"); + S.ApplyLines(new[] { "healthRefreshSec=60" }); + Check(S.HealthRefreshSec == HealthProbe.MaxIntervalSec, $"60 capped at {HealthProbe.MaxIntervalSec}"); + S.ApplyLines(new[] { "healthRefreshSec=abc", "healthRefreshSec=" }); + Check(S.HealthRefreshSec == HealthProbe.MaxIntervalSec, "junk leaves it alone"); + S.ResetToDefaults(); + Check(S.RefreshOthersHealth && S.HealthRefreshSec == 1f, "reset: on at 1 s"); + S.ResetToDefaults(); + } + private static void Case(string name) { _case = name; diff --git a/tools/RadarSettingsTests/Program.cs b/tools/RadarSettingsTests/Program.cs index 3a519b2..0b8c2e8 100644 --- a/tools/RadarSettingsTests/Program.cs +++ b/tools/RadarSettingsTests/Program.cs @@ -40,6 +40,7 @@ namespace RadarSettingsTests Run("CorpsesOffHidesYourCorpses", CorpsesOffHidesYourCorpses); Run("UnknownKindsHidden", UnknownKindsHidden); Run("SnapshotFiltersPerBox", SnapshotFiltersPerBox); + Run("SelectionDefaults", SelectionDefaults); // before FileRoundTrip: the store loads once, there Run("FileRoundTrip", () => FileRoundTrip(root)); Run("NameAndSizeDefaults", NameAndSizeDefaults); Run("NameAndSizeFileRoundTrip", () => NameAndSizeFileRoundTrip(root)); @@ -47,6 +48,10 @@ namespace RadarSettingsTests Run("WorldMapBackdropSettings", () => WorldMapBackdropSettings(root)); Run("RoundRadarAndClipping", () => RoundRadarAndClipping(root)); Run("ClickThroughWheelZoom", () => ClickThroughWheelZoom(root)); + Run("SelectionSettingsSave", () => SelectionSettingsSave(root)); + Run("WhichMarkerIsSelected", WhichMarkerIsSelected); + Run("SelectionEdgeArrow", SelectionEdgeArrow); + Run("SelectionLabelPlacement", SelectionLabelPlacement); } finally { @@ -144,11 +149,21 @@ namespace RadarSettingsTests var lines = new List { "# test" }; for (int k = 0; k < RadarKind.Count; k++) lines.Add($"{FileKeys[k]}={(k % 2 == 0 ? 0 : 1)}"); // even kinds off + // The selected-object highlight's three keys (the store loads once per process: here). + lines.Add("selectHighlight=0"); + lines.Add("selectLabel=0"); + lines.Add("selectedColor=FF112233"); 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]}"); + Check(!RadarSettingsStore.HighlightSelected, "loaded selectHighlight=0"); + Check(!RadarSettingsStore.ShowSelectedLabel, "loaded selectLabel=0"); + Check(RadarSettingsStore.SelectedColor == 0xFF112233, $"loaded selectedColor ({RadarSettingsStore.SelectedColor:X8})"); + RadarSettingsStore.HighlightSelected = true; + RadarSettingsStore.ShowSelectedLabel = true; + RadarSettingsStore.SelectedColor = RadarSettingsStore.DefaultSelectedColor; string saved = Path.Combine(root, "saved.txt"); Environment.SetEnvironmentVariable("RYNTHCORE_RADAR_SETTINGS", saved); @@ -343,6 +358,156 @@ namespace RadarSettingsTests Check(n >= 3 && Math.Abs(Area(outP, n) - circle / 2) < circle * 0.01f, $"half the circle ({Area(outP, n)} of {circle / 2})"); } + // ── The selected-object highlight (2026-10-31) ────────────────────── + + // The ring starts on, its label off (the box covered the radar); the ring's colour is none of the kinds' default colours. + private static void SelectionDefaults() + { + Check(RadarSettingsStore.HighlightSelected, "highlight the selected object: on by default"); + Check(!RadarSettingsStore.ShowSelectedLabel, "show its label: off by default"); + Check(RadarSettingsStore.SelectedColor == RadarSettingsStore.DefaultSelectedColor, "ring colour default"); + Check(Array.IndexOf(RadarSettingsStore.DefaultKindColors, RadarSettingsStore.DefaultSelectedColor) < 0, + "the ring's default colour is no kind's default colour"); + } + + // The switches save under their keys; the colour only when it isn't the default; Reset colours resets it. + private static void SelectionSettingsSave(string root) + { + string saved = Path.Combine(root, "selection.txt"); + Environment.SetEnvironmentVariable("RYNTHCORE_RADAR_SETTINGS", saved); + RadarSettingsStore.HighlightSelected = true; + RadarSettingsStore.ShowSelectedLabel = true; + RadarSettingsStore.SelectedColor = RadarSettingsStore.DefaultSelectedColor; + RadarSettingsStore.Save(); + string text = File.ReadAllText(saved).Replace("\r\n", "\n"); + Check(text.Contains("selectHighlight=1\n"), "saved selectHighlight=1"); + Check(text.Contains("selectLabel=1\n"), "saved selectLabel=1"); + Check(!text.Contains("selectedColor="), "the default colour is not written"); + + RadarSettingsStore.HighlightSelected = false; + RadarSettingsStore.ShowSelectedLabel = false; + RadarSettingsStore.SelectedColor = 0x80ABCDEF; + RadarSettingsStore.Save(); + text = File.ReadAllText(saved).Replace("\r\n", "\n"); + Check(text.Contains("selectHighlight=0\n"), "saved selectHighlight=0"); + Check(text.Contains("selectLabel=0\n"), "saved selectLabel=0"); + Check(text.Contains("selectedColor=80ABCDEF\n"), "saved selectedColor=80ABCDEF"); + + RadarSettingsStore.ResetKindColors(); + Check(RadarSettingsStore.SelectedColor == RadarSettingsStore.DefaultSelectedColor, "Reset colours resets the ring's colour"); + RadarSettingsStore.HighlightSelected = true; + RadarSettingsStore.ShowSelectedLabel = true; + } + + private static RadarMarker Mk(byte kind, uint id, float x = 0, float y = 0) => + new() { Kind = kind, Id = id, X = x, Y = y, Label = "m" + id }; + + // The selected marker is the one with the selected object's id; it clears with the selection, when + // the object leaves the markers, or when the setting is off; a hidden kind is still found. + private static void WhichMarkerIsSelected() + { + var markers = new List + { + Mk(RadarKind.Monster, 0x80000001), Mk(RadarKind.Portal, 0x70000002), Mk(RadarKind.Corpse, 0x80000003), + Mk(RadarKind.Door, 0x70000004), Mk(RadarKind.GroundItem, 0x80000005), + }; + Check(RadarSelection.Find(markers, 0x70000002) == markers[1], "the portal's id finds the portal"); + Check(RadarSelection.Find(markers, 0x80000003) == markers[2], "the corpse's id finds the corpse"); + Check(RadarSelection.Find(markers, 0) == null, "nothing selected: none"); + Check(RadarSelection.Find(markers, 0x12345678) == null, "an object with no marker (in a pack, gone): none"); + Check(RadarSelection.Find(null, 0x80000001) == null, "no snapshot yet: none"); + + // Old RynthAi builds send no ids: a marker with id 0 is never the selection. + var noIds = new List { Mk(RadarKind.Monster, 0), Mk(RadarKind.Npc, 0) }; + Check(RadarSelection.Find(noIds, 0) == null && RadarSelection.Find(noIds, 0x80000001) == null, "markers without ids never match"); + // A kind this engine doesn't know (a newer RynthAi's): never highlighted (no shape or colour for it). + Check(RadarSelection.Find(new List { Mk(12, 0x80000009) }, 0x80000009) == null, "an unknown kind: none"); + + // The setting off: nothing is highlighted. + Check(RadarSelection.Highlighted(false, markers, 0x80000001) == null, "setting off: none"); + Check(RadarSelection.Highlighted(true, markers, 0x80000001) == markers[0], "setting on: the monster"); + + // It follows the selection, and clears when the selection clears. + Check(RadarSelection.Highlighted(true, markers, 0x70000004) == markers[3], "selection moves to the door"); + Check(RadarSelection.Highlighted(true, markers, 0) == null, "selection cleared: none"); + + // It follows the object as it moves: the next snapshot's marker (a new instance) is found by id. + var next = new List { Mk(RadarKind.Monster, 0x80000001, 25, -10) }; + RadarMarker? moved = RadarSelection.Highlighted(true, next, 0x80000001); + Check(moved != null && moved.X == 25 && moved.Y == -10, "the moved monster's new marker"); + // ...and the object leaving the radar's markers clears it, though it is still selected. + Check(RadarSelection.Highlighted(true, new List(), 0x80000001) == null, "left the markers: none"); + + // A kind whose box is off is still highlighted when it is the selection (items on the ground start hidden). + RadarSettingsStore.ShowGroundItems = false; + Check(RadarSelection.Highlighted(true, markers, 0x80000005) == markers[4], "a hidden kind's selected item is still found"); + RadarSettingsStore.ShowGroundItems = true; + } + + private static bool Near(System.Numerics.Vector2 a, System.Numerics.Vector2 b, float tol = 0.01f) => + Math.Abs(a.X - b.X) <= tol && Math.Abs(a.Y - b.Y) <= tol; + + // The arrow sits inset inside the picture's edge, on the line from the centre toward the marker. + private static void SelectionEdgeArrow() + { + var min = new System.Numerics.Vector2(0, 0); + var max = new System.Numerics.Vector2(200, 200); + var c = new System.Numerics.Vector2(100, 100); + System.Numerics.Vector2 tip, dir; + + Check(!RadarSelection.EdgeArrow(c, new(150, 40), min, max, null, 3, out _, out _), "on the picture: no arrow"); + Check(!RadarSelection.EdgeArrow(c, max, min, max, null, 3, out _, out _), "on the picture's corner: no arrow"); + Check(!RadarSelection.EdgeArrow(c, c, min, max, null, 3, out _, out _), "at the centre: no arrow"); + Check(!RadarSelection.EdgeArrow(c, new(float.NaN, 5), min, max, null, 3, out _, out _), "a NaN position: no arrow"); + + Check(RadarSelection.EdgeArrow(c, new(100, -50), min, max, null, 3, out tip, out dir) + && Near(tip, new(100, 3)) && Near(dir, new(0, -1)), $"straight up: top edge ({tip}, {dir})"); + Check(RadarSelection.EdgeArrow(c, new(400, 100), min, max, null, 3, out tip, out dir) + && Near(tip, new(197, 100)) && Near(dir, new(1, 0)), $"right: right edge ({tip})"); + Check(RadarSelection.EdgeArrow(c, new(-1000, -1000), min, max, null, 3, out tip, out _) + && Near(tip, new(3, 3)), $"up-left far away: the corner ({tip})"); + Check(RadarSelection.EdgeArrow(c, new(300, 150), min, max, null, 3, out tip, out _) + && Near(tip, new(197, 124.25f)), $"right and a little down: the right edge, a quarter down ({tip})"); + // Off-centre panel, wider than tall: the nearer side wins. + var wMin = new System.Numerics.Vector2(10, 20); + var wMax = new System.Numerics.Vector2(410, 120); + Check(RadarSelection.EdgeArrow(new(210, 70), new(410, 270), wMin, wMax, null, 0, out tip, out _) + && Near(tip, new(260, 120)), $"wide panel, diagonal: the bottom edge ({tip})"); + + // The arrow's corners: point at the tip, base back toward the centre, inside the picture. + RadarSelection.EdgeArrow(c, new(100, -50), min, max, null, 3, out tip, out dir); + RadarSelection.ArrowCorners(tip, dir, 9, 5, out var a, out var b, out var cc); + Check(Near(a, tip), "the arrow points at the tip"); + Check(Near((b + cc) * 0.5f, new(100, 12)) && Math.Abs((b - cc).Length() - 10) < 0.01f, $"its base 9 px in, 10 px wide ({b}, {cc})"); + bool inside = true; + foreach (var p in new[] { a, b, cc }) + if (p.X < min.X || p.Y < min.Y || p.X > max.X || p.Y > max.Y) inside = false; + Check(inside, "the whole arrow is inside the picture"); + + // Round: on the circle (less the inset), along the line; inside the circle no arrow. + var round = new RoundMask(c, 100); + Check(!RadarSelection.EdgeArrow(c, new(170, 170), min, max, round, 3, out _, out _), "round: inside the circle, no arrow"); + Check(RadarSelection.EdgeArrow(c, new(180, 180), min, max, round, 3, out tip, out _) + && Math.Abs((tip - c).Length() - 97) < 0.01f && Math.Abs(tip.X - tip.Y) < 0.01f, + $"round: in the box's corner but off the circle: on the circle, diagonal ({tip})"); + Check(RadarSelection.EdgeArrow(c, new(100, 500), min, max, round, 3, out tip, out dir) + && Near(tip, new(100, 197)) && Near(dir, new(0, 1)), $"round: straight down ({tip})"); + } + + // The label goes to the right of the marker, or the left at the right edge, and stays inside the panel. + private static void SelectionLabelPlacement() + { + var min = new System.Numerics.Vector2(0, 0); + var max = new System.Numerics.Vector2(300, 300); + var size = new System.Numerics.Vector2(80, 30); + Check(Near(RadarSelection.LabelPos(new(100, 100), 10, size, min, max), new(110, 85)), "right of the marker, centred"); + Check(Near(RadarSelection.LabelPos(new(250, 100), 10, size, min, max), new(160, 85)), "at the right edge: on the left"); + Check(Near(RadarSelection.LabelPos(new(100, 5), 10, size, min, max), new(110, 0)), "at the top: kept inside"); + Check(Near(RadarSelection.LabelPos(new(100, 295), 10, size, min, max), new(110, 270)), "at the bottom: kept inside"); + Check(Near(RadarSelection.LabelPos(new(40, 100), 50, new(200, 30), min, max), new(90, 85)), "a wide label still fits on the right"); + Check(Near(RadarSelection.LabelPos(new(150, 150), 10, new(400, 400), min, max), min), "bigger than the panel: its top-left corner"); + } + private static float Area(System.Numerics.Vector2[] p, int n) { float a = 0; diff --git a/tools/RadarSettingsTests/RadarSettingsTests.csproj b/tools/RadarSettingsTests/RadarSettingsTests.csproj index 571fe7b..a0b45ff 100644 --- a/tools/RadarSettingsTests/RadarSettingsTests.csproj +++ b/tools/RadarSettingsTests/RadarSettingsTests.csproj @@ -7,7 +7,8 @@ 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 + round-trip through the settings file. The selected-object highlight (RadarSelection.cs): which + marker is the selected one, when it clears, the edge arrow and label maths, and its settings. Uses RYNTHCORE_RADAR_SETTINGS (temp files); never touches %LOCALAPPDATA%\RynthCore. Run: dotnet run -c Release (exit 0 = pass, 1 = fail) --> @@ -26,6 +27,7 @@ + diff --git a/tools/SelfPlateTests/SelfPlateTests.csproj b/tools/SelfPlateTests/SelfPlateTests.csproj index 67b8eeb..6479db2 100644 --- a/tools/SelfPlateTests/SelfPlateTests.csproj +++ b/tools/SelfPlateTests/SelfPlateTests.csproj @@ -28,6 +28,7 @@ + diff --git a/tools/SenseTests/Program.cs b/tools/SenseTests/Program.cs new file mode 100644 index 0000000..e42fce5 --- /dev/null +++ b/tools/SenseTests/Program.cs @@ -0,0 +1,248 @@ +using RynthCore.Engine.UI.Data; + +namespace SenseTests; + +/// +/// The Sense panel's pure part (UI/Data/SenseModel.cs): the compact view's layout, the look +/// commands and their replies, and sense.txt. +/// +internal static class Program +{ + private static int _checks, _failed; + + private static int Main() + { + CompactColumns(); + RowsAndSlots(); + MouseOnTheBarePanel(); + ViewSwitch(); + CollapsedLine(); + LookCommands(); + CommandArguments(); + FileRoundTrip(); + OlderAndBadFiles(); + TermRules(); + Matching(); + + 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(float a, float b) => Math.Abs(a - b) < 0.01f; + + // ── layout ───────────────────────────────────────────────────────── + + private static void CompactColumns() + { + // Arrow 16 + distance 52 always; the coordinates (104) when the name keeps 110, then the kind (50). + SenseCompactColumns narrow = SenseLayout.Compact(200); + Check(!narrow.Location && !narrow.Kind && Near(narrow.NameWidth, 132), $"200 px: arrow, name, distance only (name {narrow.NameWidth})"); + SenseCompactColumns justLoc = SenseLayout.Compact(281); + Check(!justLoc.Location, "281 px: one short of the coordinates"); + SenseCompactColumns loc = SenseLayout.Compact(282); + Check(loc.Location && !loc.Kind && Near(loc.NameWidth, 110), $"282 px: the coordinates come in, the name keeps 110 (got {loc.NameWidth})"); + SenseCompactColumns notKind = SenseLayout.Compact(331); + Check(notKind.Location && !notKind.Kind && Near(notKind.NameWidth, 159), "331 px: coordinates, no kind yet"); + SenseCompactColumns all = SenseLayout.Compact(332); + Check(all.Location && all.Kind && Near(all.NameWidth, 110), $"332 px: coordinates and kind (name {all.NameWidth})"); + SenseCompactColumns big = SenseLayout.Compact(564, scale: 2f); + Check(big.Location && !big.Kind, "the widths grow with the text size: 564 px at 200% is 282 at 100%"); + SenseCompactColumns tiny = SenseLayout.Compact(50); + Check(!tiny.Location && !tiny.Kind && Near(tiny.NameWidth, 24), "a very narrow window keeps a sliver of name"); + Check(SenseLayout.CompactRowHeight < SenseLayout.FullRowHeight, "compact rows are tighter than the full view's"); + } + + private static void RowsAndSlots() + { + Check(SenseLayout.CompactFit(160, 16, 5) == (5, false), "five rows in a 160 px window: all of them"); + Check(SenseLayout.CompactFit(160, 16, 12) == (9, true), "twelve rows in ten slots: nine and a +N more line"); + Check(SenseLayout.CompactFit(10, 16, 3) == (0, true), "a window shorter than a row: just the +N more line"); + Check(SenseLayout.CompactFit(100, 16, 0) == (0, false), "no rows: nothing"); + Check(SenseLayout.MoreText(3) == "+3 more" && SenseLayout.MoreText(-1) == "+0 more", "the more line's text"); + Check(SenseLayout.RowsThatFit(160, 16, 12) == 10 && SenseLayout.RowsThatFit(160, 0, 4) == 4, "rows that fit"); + + Check(SenseLayout.RowAt(105, 100, 16, 3) == 0, "the first row"); + Check(SenseLayout.RowAt(131.9f, 100, 16, 3) == 1, "the second row's last pixel"); + Check(SenseLayout.RowAt(148, 100, 16, 3) == -1, "just below the last row: none"); + Check(SenseLayout.RowAt(99, 100, 16, 3) == -1 && SenseLayout.RowAt(105, 100, 16, 0) == -1, "above, or no rows: none"); + } + + private static void MouseOnTheBarePanel() + { + // Drew (0,0)-(200,48); the buttons beside the first line end at x 240, y 16. + Check(SenseLayout.IsHot(100, 20, 0, 0, 200, 48, 240, 16, wasHot: false), "over a row: the panel takes the mouse"); + Check(!SenseLayout.IsHot(210, 10, 0, 0, 200, 48, 240, 16, wasHot: false), "right of the rows, coming from the game: clicks go through"); + Check(SenseLayout.IsHot(210, 10, 0, 0, 200, 48, 240, 16, wasHot: true), "from a row to the buttons: still the panel's"); + Check(SenseLayout.IsHot(210, 40, 0, 0, 200, 48, 240, 16, wasHot: true), "the strip beside the rows, from the last row toward the buttons"); + Check(!SenseLayout.IsHot(210, 50, 0, 0, 200, 48, 240, 16, wasHot: true), "below the rows: the game's"); + Check(!SenseLayout.IsHot(250, 10, 0, 0, 200, 48, 240, 16, wasHot: true), "past the buttons: the game's"); + Check(!SenseLayout.IsHot(-1, 10, 0, 0, 200, 48, 240, 16, wasHot: true), "left of the panel: the game's"); + Check(!SenseLayout.IsHot(100, 60, 0, 0, 200, 48, 240, 16, wasHot: false), "the empty rest of the window: the game's"); + + // The view switch is always drawn (204..240 beside the first line), so it always takes the mouse. + Check(SenseLayout.TakesMouse(210, 10, 0, 0, 200, 48, 204, 240, 16, wasHot: false), "on the view switch, coming from the game: the panel's"); + Check(!SenseLayout.TakesMouse(202, 10, 0, 0, 200, 48, 204, 240, 16, wasHot: false), "the gap before the switch, coming from the game: the game's"); + Check(!SenseLayout.TakesMouse(210, 20, 0, 0, 200, 48, 204, 240, 16, wasHot: false), "under the switch, coming from the game: the game's"); + Check(!SenseLayout.TakesMouse(241, 10, 0, 0, 200, 48, 204, 240, 16, wasHot: false), "past the switch: the game's"); + Check(SenseLayout.TakesMouse(100, 20, 0, 0, 200, 48, 204, 240, 16, wasHot: false), "over a row: still the panel's"); + Check(SenseLayout.TakesMouse(210, 40, 0, 0, 200, 48, 204, 240, 16, wasHot: true), "the strip toward the switch once hot: still the panel's"); + Check(!SenseLayout.TakesMouse(210, -1, 0, 0, 200, 48, 204, 240, 16, wasHot: false), "above the panel: the game's"); + } + + private static void ViewSwitch() + { + // Every look offers the two others, so the full / compact / collapsed switch is always one click away. + foreach (SenseLayoutMode mode in new[] { SenseLayoutMode.Full, SenseLayoutMode.Compact, SenseLayoutMode.Collapsed }) + { + (SenseLayoutMode a, SenseLayoutMode b) = SenseLayout.OtherViews(mode); + Check(a != mode && b != mode && a != b, $"{SenseLayout.LayoutName(mode)}: the switch offers the other two looks"); + } + Check(SenseLayout.OtherViews(SenseLayoutMode.Full) == (SenseLayoutMode.Compact, SenseLayoutMode.Collapsed), "full: compact, then collapsed"); + Check(SenseLayout.OtherViews(SenseLayoutMode.Compact) == (SenseLayoutMode.Collapsed, SenseLayoutMode.Full), "compact: collapse first (the caret up), then full"); + Check(SenseLayout.OtherViews(SenseLayoutMode.Collapsed) == (SenseLayoutMode.Compact, SenseLayoutMode.Full), "collapsed: open to compact first (the caret down), then full"); + // Each button's tooltip names the command that does the same, and that command is valid. + foreach (SenseLayoutMode to in new[] { SenseLayoutMode.Full, SenseLayoutMode.Compact, SenseLayoutMode.Collapsed }) + { + string tip = SenseLayout.SwitchTip(to); + string cmd = "view " + SenseLayout.LayoutName(to); + Check(tip.Contains("/rc sense " + cmd), $"the {SenseLayout.LayoutName(to)} button's tip names /rc sense {cmd}"); + Check(SenseLayout.IsValidArgs(cmd) && SenseLayout.Apply(cmd, SenseLayoutMode.Full, true).Next == to, $"/rc sense {cmd} is the button's look"); + } + } + + private static void CollapsedLine() + { + Check(SenseLayout.CollapsedText(3) == "Sense: 3", "collapsed: Sense: N"); + Check(SenseLayout.CollapsedText(0) == "Sense: 0" && SenseLayout.CollapsedText(-2) == "Sense: 0", "none (never negative)"); + } + + // ── commands ─────────────────────────────────────────────────────── + + private static void LookCommands() + { + var (full, compact, collapsed) = (SenseLayoutMode.Full, SenseLayoutMode.Compact, SenseLayoutMode.Collapsed); + + SenseLayoutAnswer a = SenseLayout.Apply("compact on", full, panelOpen: true); + Check(a.Ok && a.Next == compact && a.Reply.StartsWith("Sense: now the compact view", StringComparison.Ordinal) && a.Reply.EndsWith("panel.", StringComparison.Ordinal), + "compact on from full: compact, and says so: " + a.Reply); + a = SenseLayout.Apply("compact on", compact, true); + Check(a.Ok && a.Next == compact && a.Reply.StartsWith("Sense is already in the compact view", StringComparison.Ordinal), "compact on twice: already: " + a.Reply); + a = SenseLayout.Apply("compact on", collapsed, true); + Check(a.Ok && a.Next == collapsed && a.Reply.StartsWith("Sense is already in the collapsed view", StringComparison.Ordinal), "compact on while collapsed: stays collapsed (it is the small look)"); + Check(SenseLayout.Apply("compact off", compact, true).Next == full && SenseLayout.Apply("compact off", collapsed, true).Next == full, + "compact off: the full panel, from compact or collapsed"); + a = SenseLayout.Apply("compact off", compact, true); + Check(a.Reply.StartsWith("Sense: now the full view", StringComparison.Ordinal), "compact off says the full view: " + a.Reply); + + Check(SenseLayout.Apply("collapse on", full, true).Next == collapsed, "collapse on from full: collapsed"); + Check(SenseLayout.Apply("collapse on", compact, true).Next == collapsed, "collapse on from compact: collapsed"); + Check(SenseLayout.Apply("collapse off", collapsed, true).Next == compact, "collapse off: the matches (compact)"); + a = SenseLayout.Apply("collapse off", full, true); + Check(a.Ok && a.Next == full && a.Reply.StartsWith("Sense is already in the full view", StringComparison.Ordinal), "collapse off on the full panel: stays full"); + Check(SenseLayout.Apply("collapsed on", full, true).Next == collapsed, "collapsed is collapse's other spelling"); + + Check(SenseLayout.Apply("view full", collapsed, true).Next == full, "view full"); + Check(SenseLayout.Apply("VIEW Compact", full, true).Next == compact, "any case"); + Check(SenseLayout.Apply("view collapsed", compact, true).Next == collapsed, "view collapsed"); + + foreach (string ask in new[] { "compact", "collapse", "view" }) + { + a = SenseLayout.Apply(ask, compact, true); + Check(a.Ok && a.Next == compact && a.Reply.StartsWith("Sense is in the compact view", StringComparison.Ordinal), $"'{ask}' alone: the look now ({a.Reply})"); + } + + a = SenseLayout.Apply("compact on", full, panelOpen: false); + Check(a.Reply.EndsWith("The panel is closed: /rc sense opens it.", StringComparison.Ordinal), "a closed panel: the reply says how to open it"); + + foreach (string bad in new[] { "compact maybe", "view huge", "frob", "collapse yes", "" }) + { + a = SenseLayout.Apply(bad, compact, true); + Check(!a.Ok && a.Reply == SenseLayout.Usage, $"'{bad}': the usage"); + } + Check(SenseLayout.Usage.StartsWith("Usage: /rc sense", StringComparison.Ordinal), "the usage line"); + } + + private static void CommandArguments() + { + foreach (string ok in new[] { "", "compact", "compact on", "compact off", "collapse on", "COLLAPSED off", "view", "view full", "view compact", "view collapsed" }) + Check(SenseLayout.IsValidArgs(ok), $"'/rc sense {ok}' runs"); + foreach (string bad in new[] { "now", "compact maybe", "compact on off", "view huge", "view full now", "frob on" }) + Check(!SenseLayout.IsValidArgs(bad), $"'/rc sense {bad}' gets the usage"); + Check(SenseLayout.IsLayoutCommand("compact on") && SenseLayout.IsLayoutCommand("view") && !SenseLayout.IsLayoutCommand("frob"), "look commands"); + } + + // ── sense.txt ────────────────────────────────────────────────────── + + private static string[] Lines(string text) => text.Replace("\r\n", "\n").Split('\n'); + + private static void FileRoundTrip() + { + var terms = new List { new("Drake", true), new("Mattekar*", false), new("?ire Ant", true) }; + foreach (SenseLayoutMode mode in Enum.GetValues()) + { + string text = SenseFile.Format(terms, alertChat: true, alertBeep: false, mode); + SenseFileData back = SenseFile.Parse(Lines(text)); + Check(back.Layout == mode, $"the look {mode} comes back"); + Check(back.AlertChat && !back.AlertBeep, "the alerts come back"); + Check(back.Terms.Count == 3 && back.Terms[0].Text == "Drake" && back.Terms[0].Enabled + && back.Terms[1].Text == "Mattekar*" && !back.Terms[1].Enabled && back.Terms[1].IsGlob + && back.Terms[2].Text == "?ire Ant", "the terms come back, in order, on and off"); + } + string compact = SenseFile.Format(terms, false, true, SenseLayoutMode.Compact); + Check(compact.Contains("\nview=compact", StringComparison.Ordinal), "written as view=compact"); + Check(SenseFile.Format(terms, false, false, SenseLayoutMode.Full).Contains("view=full", StringComparison.Ordinal), "and view=full"); + Check(SenseFile.Format(terms, false, false, SenseLayoutMode.Collapsed).Contains("view=collapsed", StringComparison.Ordinal), "and view=collapsed"); + } + + private static void OlderAndBadFiles() + { + // A file from before the look: no view line. + SenseFileData old = SenseFile.Parse(new[] + { + "# RynthCore Sense watch list - auto-generated, hand-edits OK. /rc sense in game.", + "alertChat=0", "alertBeep=1", "term=1|Drake", "term=0|Mattekar", + }); + Check(old.Layout == SenseLayoutMode.Full && old.AlertBeep && old.Terms.Count == 2, "an older file: the full panel, as before"); + Check(SenseFile.Parse(new[] { "view=huge" }).Layout == SenseLayoutMode.Full, "an unknown look: full"); + Check(SenseFile.Parse(new[] { "view= Compact " }).Layout == SenseLayoutMode.Compact, "the look by hand, any case and spaces"); + Check(SenseFile.Parse(new[] { "view=compact", "view=collapsed" }).Layout == SenseLayoutMode.Collapsed, "the last view line wins"); + Check(SenseFile.Parse(Array.Empty()).Layout == SenseLayoutMode.Full, "no file: full"); + SenseFileData junk = SenseFile.Parse(new[] { "", " ", "# view=compact", "nonsense", "=x", "unknown=1", "view" }); + Check(junk.Layout == SenseLayoutMode.Full && junk.Terms.Count == 0 && !junk.AlertChat, "comments, blanks and junk are skipped"); + } + + private static void TermRules() + { + var lines = new List { "term=drake", "term=1|DRAKE", "term=0|", "term=1| Golem ", "term=2|odd" }; + SenseFileData d = SenseFile.Parse(lines); + Check(d.Terms.Count == 3, $"a duplicate (any case) and an empty term are dropped ({d.Terms.Count})"); + Check(d.Terms[0].Text == "drake" && d.Terms[0].Enabled, "a bare term=name is on"); + Check(d.Terms[1].Text == "Golem", "trimmed"); + Check(d.Terms[2].Text == "2|odd" && d.Terms[2].Enabled, "only 0| and 1| are flags"); + + var many = new List(); + for (int i = 0; i < 45; i++) many.Add("term=1|name" + i); + Check(SenseFile.Parse(many).Terms.Count == SenseFile.MaxTerms, "at most 40 terms"); + string longName = new('x', 100); + Check(SenseFile.Parse(new[] { "term=1|" + longName }).Terms[0].Text.Length == SenseFile.MaxTermLength, "a long term is cut to 64"); + Check(SenseFile.Clean(" a\r\nb ") == "a b", "one line"); + Check(SenseFile.IndexOf(new List { new("Drake", true) }, "dRaKe") == 0, "found by any case"); + } + + private static void Matching() + { + Check(new SensePattern("drake", true).Matches("Dragon's Isle Drake"), "contains, any case"); + Check(new SensePattern("Drake*", true).Matches("Drake Hatchling") && !new SensePattern("Drake*", true).Matches("Isle Drake"), + "with * the whole name must match"); + Check(new SensePattern("?ire Ant", true).Matches("Fire Ant") && !new SensePattern("?ire Ant", true).Matches("Fire Ants"), "? is one letter"); + Check(!new SensePattern("", true).Matches("Anything") && !new SensePattern("x", true).Matches(""), "empty never matches"); + } +} diff --git a/tools/SenseTests/SenseTests.csproj b/tools/SenseTests/SenseTests.csproj new file mode 100644 index 0000000..064d624 --- /dev/null +++ b/tools/SenseTests/SenseTests.csproj @@ -0,0 +1,26 @@ + + + + + Exe + net10.0 + enable + enable + true + SenseTests + + + + + + + diff --git a/tools/TrackerSettingsTests/Program.cs b/tools/TrackerSettingsTests/Program.cs new file mode 100644 index 0000000..fcd36ac --- /dev/null +++ b/tools/TrackerSettingsTests/Program.cs @@ -0,0 +1,88 @@ +using System.Text.Json; +using RynthCore.Engine.UI; + +namespace RynthCore.Engine.UI +{ + /// Stub of the engine's background writer: runs the write at once. + internal static class UiBackgroundWriter + { + public static void Enqueue(string label, Action work) => work(); + } +} + +namespace TrackerSettingsTests +{ + // Offline tests for the Tracker's settings file. See the csproj. TrackerSettings loads once per + // process, so the order matters: an old-style file first, then saves. + 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 int Main() + { + string root = Path.Combine(Path.GetTempPath(), "rynth-tracker-settings-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + string file = Path.Combine(root, "rynthtracker_settings.json"); + Environment.SetEnvironmentVariable("RYNTHCORE_TRACKER_SETTINGS", file); + try + { + // ToJson: what Save writes, both keys, parseable. + using (var doc = JsonDocument.Parse(TrackerSettings.ToJson(51, true))) + { + Check(doc.RootElement.GetProperty("bgAlpha").GetInt32() == 51, "ToJson writes bgAlpha"); + Check(doc.RootElement.GetProperty("textOnly").GetBoolean(), "ToJson writes textOnly true"); + } + using (var doc = JsonDocument.Parse(TrackerSettings.ToJson(255, false))) + Check(!doc.RootElement.GetProperty("textOnly").GetBoolean(), "ToJson writes textOnly false"); + + // A file from before Text only (bgAlpha alone): its opacity kept, Text only off. + File.WriteAllText(file, "{\"bgAlpha\":100}"); + Check(TrackerSettings.BgAlpha == 100, "an old file's opacity is read"); + Check(!TrackerSettings.TextOnly, "an old file (no textOnly) leaves Text only off"); + + // Text only on: saved with the opacity. + TrackerSettings.SetTextOnly(true); + Check(TrackerSettings.TextOnly, "Text only is on at once"); + using (var doc = JsonDocument.Parse(File.ReadAllText(file))) + { + Check(doc.RootElement.GetProperty("textOnly").GetBoolean(), "Text only on is saved"); + Check(doc.RootElement.GetProperty("bgAlpha").GetInt32() == 100, "saving Text only keeps the opacity"); + } + + // The opacity slider's save keeps Text only. + TrackerSettings.SetBgAlpha(40, save: true); + using (var doc = JsonDocument.Parse(File.ReadAllText(file))) + { + Check(doc.RootElement.GetProperty("bgAlpha").GetInt32() == 40, "the opacity is saved"); + Check(doc.RootElement.GetProperty("textOnly").GetBoolean(), "saving the opacity keeps Text only"); + } + + // Off again. + TrackerSettings.SetTextOnly(false); + Check(!TrackerSettings.TextOnly, "Text only is off at once"); + using (var doc = JsonDocument.Parse(File.ReadAllText(file))) + Check(!doc.RootElement.GetProperty("textOnly").GetBoolean(), "Text only off is saved"); + } + catch (Exception ex) + { + _fails++; + Console.WriteLine($" [FAIL] threw: {ex}"); + } + finally + { + Environment.SetEnvironmentVariable("RYNTHCORE_TRACKER_SETTINGS", null); + try { Directory.Delete(root, recursive: true); } catch { } + } + + Console.WriteLine(_fails == 0 + ? $"PASS ({_asserts} assertions)" + : $"FAIL: {_fails} of {_asserts} assertions failed"); + return _fails == 0 ? 0 : 1; + } + } +} diff --git a/tools/TrackerSettingsTests/TrackerSettingsTests.csproj b/tools/TrackerSettingsTests/TrackerSettingsTests.csproj new file mode 100644 index 0000000..d24abd9 --- /dev/null +++ b/tools/TrackerSettingsTests/TrackerSettingsTests.csproj @@ -0,0 +1,23 @@ + + + + + Exe + net10.0 + enable + enable + true + TrackerSettingsTests + + + + + + + diff --git a/tools/UiCostTests/Program.cs b/tools/UiCostTests/Program.cs new file mode 100644 index 0000000..0c8ebcc --- /dev/null +++ b/tools/UiCostTests/Program.cs @@ -0,0 +1,498 @@ +using System.Diagnostics; +using RynthCore.Engine.ImGuiBackend; + +namespace UiCostTests; + +// Offline tests for the UI frame cost breakdown. See the csproj. +internal static class Program +{ + private static int _fails, _asserts; + + // Logic tests run on a microsecond clock: 1 tick = 1 us, so Ms(1.5) = 1500 ticks. + private const long Us = 1_000_000; + private static long Ms(double ms) => (long)Math.Round(ms * 1000); + private static long Sec(double s) => (long)Math.Round(s * Us); + + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + + private static void Eq(T actual, T expected, string msg) => + Check(EqualityComparer.Default.Equals(actual, expected), $"{msg}: expected '{expected}', got '{actual}'"); + + private static int Main() + { + Run("FrameLineFormat", FrameLineFormat); + Run("ThresholdAndRateLimit", ThresholdAndRateLimit); + Run("ThresholdClamp", ThresholdClamp); + Run("RollingWindow", RollingWindow); + Run("HeartbeatTopThree", HeartbeatTopThree); + Run("DescribeNow", DescribeNow); + Run("ExclusiveTiming", ExclusiveTiming); + Run("OverflowSlot", OverflowSlot); + Run("TimingOff", TimingOff); + Run("DiscardFrame", DiscardFrame); + Run("Overhead", Overhead); + Run("DrawPlanRange", DrawPlanRange); + Run("DrawPlanLootEditorShape", DrawPlanLootEditorShape); + Run("SubmitCountersInLine", SubmitCountersInLine); + Run("SubmitCountersInHeartbeatAndDescribe", SubmitCountersInHeartbeatAndDescribe); + 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}\n{ex.StackTrace}"); } + } + + private static UiCostModel NewModel() => new(Us) { Enabled = true }; + + private static void FrameLineFormat() + { + var m = NewModel(); + int radar = m.Register("Radar"); + int hud = m.Register("Monster HUD", unit: "plates"); + int chat = m.Register("Chat"); + int tiny = m.Register("Tiny"); + int nav = m.Register("Nav3D markers", outside: true); + m.Add(chat, Ms(4.0)); + m.Add(radar, Ms(100.0)); + m.Add(radar, Ms(20.3)); // two calls in one frame add up + m.Add(hud, Ms(41.0), 38); + m.Add(tiny, Ms(0.01)); + m.Add(nav, Ms(1.2)); + string? line = m.EndFrame(Ms(187.0), Sec(10), logSlow: true); + Check(line != null, "a 187 ms frame over 50 writes a line"); + if (line == null) return; + Console.WriteLine(" " + line); + Check(line.StartsWith("[UiCost] frame 187.0 ms (over 50): Radar 120.3, Monster HUD 41.0 (38 plates), untimed 21.7, Chat 4.0", StringComparison.Ordinal), + "parts largest first, with counts and the untimed rest: " + line); + Check(line.Contains(", +1 more 0.0", StringComparison.Ordinal), "a part under 0.05 ms is summed as +1 more"); + Check(line.EndsWith(" | 3D pass, not in ui=: Nav3D markers 1.2", StringComparison.Ordinal), "the 3D pass part listed apart, not in untimed"); + Check(!line.Contains("Tiny", StringComparison.Ordinal), "the tiny part isn't named"); + + // The next frame starts clean. + m.Add(chat, Ms(60)); + string? next = m.EndFrame(Ms(60), Sec(20), logSlow: true); + Check(next != null && !next.Contains("Radar", StringComparison.Ordinal) && next.Contains("Chat 60.0", StringComparison.Ordinal), + "a frame's parts don't carry into the next: " + next); + + // More than LineTopItems parts: the rest are summed. + var many = NewModel(); + for (int i = 0; i < 12; i++) many.Add(many.Register("P" + i), Ms(10 + i)); + string? l2 = many.EndFrame(Ms(500), Sec(1), logSlow: true); + Check(l2 != null && l2.Contains("P11 21.0, P10 20.0", StringComparison.Ordinal), "largest first among many: " + l2); + // Shown: untimed (314) + P11..P5 = 8 parts; P4..P0 (14+13+12+11+10 = 60) summed. + Check(l2 != null && l2.Contains(", +5 more 60.0", StringComparison.Ordinal), "past the top 8 the rest are summed: " + l2); + } + + private static void ThresholdAndRateLimit() + { + var m = NewModel(); + int p = m.Register("Panel"); + string? Frame(double ms, double atSec, bool log = true) + { + m.Add(p, Ms(ms * 0.9)); + return m.EndFrame(Ms(ms), Sec(atSec), log); + } + Check(Frame(60, 0) != null, "the first slow frame is logged"); + Check(Frame(70, 1) == null, "another 1 s later is not (rate limit)"); + Check(Frame(500, 4.99) == null, "nor 4.99 s later"); + Check(Frame(60, 5.0) != null, "5 s after the last line: logged again"); + Check(Frame(49.9, 20) == null, "under the threshold: not logged"); + Check(Frame(50, 21) != null, "exactly at the threshold: logged"); + Check(Frame(60, 40, log: false) == null, "logging off: nothing"); + Check(Frame(60, 41) != null, "logging back on, 20 s after the last line: logged"); + Eq(m.LinesWritten, 4L, "lines written"); + m.ThresholdMs = 100; + Check(Frame(99, 60) == null, "threshold raised to 100: a 99 ms frame isn't slow"); + Check(Frame(100, 61) != null, "...a 100 ms frame is"); + var t = m.WindowTotals(Sec(61)); + Eq(t.Slow, 1L, "slow frames counted in the window at the current threshold"); + } + + private static void ThresholdClamp() + { + Eq(UiCostModel.ClampThresholdMs(1), UiCostModel.MinThresholdMs, "below the range"); + Eq(UiCostModel.ClampThresholdMs(99999), UiCostModel.MaxThresholdMs, "above the range"); + Eq(UiCostModel.ClampThresholdMs(75), 75, "in range"); + var m = NewModel(); + Eq(m.ThresholdMs, UiCostModel.DefaultThresholdMs, "default threshold"); + Eq(UiCostModel.DefaultThresholdMs, 50, "the default is 50 ms"); + m.ThresholdMs = 0; + Eq(m.ThresholdMs, UiCostModel.MinThresholdMs, "a 0 threshold is clamped"); + } + + private static void RollingWindow() + { + var m = NewModel(); + int radar = m.Register("Radar"); + // A frame every 100 ms for 10 s; at t = 2.0 s a 100 ms radar spike. + for (int i = 0; i < 100; i++) + { + double t = i * 0.1; + bool spike = i == 20; + m.Add(radar, Ms(spike ? 100 : 2)); + m.EndFrame(Ms(spike ? 150 : 5), Sec(t), logSlow: false); + if (i == 30) + { + var early = m.SlotWindow(Sec(3.05), radar); + Check(Math.Abs(early.MaxMs - 100) < 0.001, $"at 3 s the window still has the spike (max {early.MaxMs})"); + } + } + var w = m.WindowTotals(Sec(9.95)); + Eq(w.Frames, 50L, "the window holds the last 5 one-second buckets (5.0-9.9 s)"); + Check(Math.Abs(w.AvgMs - 5) < 0.001, $"avg ui 5 ms ({w.AvgMs})"); + Check(Math.Abs(w.MaxMs - 5) < 0.001, $"the spike at 2 s has left the window ({w.MaxMs})"); + var r = m.SlotWindow(Sec(9.95), radar); + Check(Math.Abs(r.AvgMs - 2) < 0.001 && Math.Abs(r.MaxMs - 2) < 0.001, $"radar avg/max 2/2 ({r.AvgMs}/{r.MaxMs})"); + + // Nothing for 10 s: the window is empty, and the first frame after the gap starts a new one. + Eq(m.WindowTotals(Sec(20)).Frames, 0L, "after a 10 s gap the window is empty"); + m.Add(radar, Ms(7)); + m.EndFrame(Ms(8), Sec(20), logSlow: false); + var after = m.WindowTotals(Sec(20.1)); + Eq(after.Frames, 1L, "one frame after the gap"); + Check(Math.Abs(after.MaxMs - 8) < 0.001, "...and only it"); + Eq(m.FramesSeen, 101L, "every frame was folded in"); + + // A gap of 2 buckets: the buckets in between are empty, older ones still count. + var g = NewModel(); + int s = g.Register("S"); + g.Add(s, Ms(1)); g.EndFrame(Ms(1), Sec(0), false); + g.Add(s, Ms(3)); g.EndFrame(Ms(3), Sec(2.5), false); + var gw = g.WindowTotals(Sec(2.6)); + Eq(gw.Frames, 2L, "frames 2.5 s apart are both in the window"); + Check(Math.Abs(gw.AvgMs - 2) < 0.001, $"avg of 1 and 3 ({gw.AvgMs})"); + } + + private static void HeartbeatTopThree() + { + var m = NewModel(); + int a = m.Register("Monster HUD (plates, combat text)", unit: "plates"); + int b = m.Register("Radar"); + int c = m.Register("Chat"); + int d = m.Register("Bar"); + for (int i = 0; i < 10; i++) + { + m.Add(c, Ms(1)); + m.Add(a, Ms(i == 5 ? 41 : 5), 38); + m.Add(d, Ms(0.5)); + m.Add(b, Ms(3)); + m.EndFrame(Ms(i == 5 ? 46 : 10), Sec(i * 0.1), logSlow: false); + } + string f = m.HeartbeatField(Sec(1.0)); + Console.WriteLine(" hb:" + f); + // a: avg (9*5+41)/10 = 8.6, max 41; b 3/3; c 1/1; untimed 0.5/0.5; d 0.5/0.5. + Eq(f, " uitop=Monster_HUD_(plates;_combat_text):8.6/41.0,Radar:3.0/3.0,Chat:1.0/1.0", "top 3 by average, avg/max, no spaces"); + Check(f.LastIndexOf(' ') == 0, "only the leading space"); + Eq(NewModel().HeartbeatField(Sec(1)), "", "no frames: no field"); + } + + private static void DescribeNow() + { + var m = NewModel(); + int radar = m.Register("Radar"); + int hud = m.Register("Monster HUD", unit: "plates"); + int nav = m.Register("Nav3D markers", outside: true); + for (int i = 0; i < 20; i++) + { + bool slow = i == 7; + m.Add(radar, Ms(slow ? 120 : 1)); + m.Add(hud, Ms(slow ? 41 : 2.1), slow ? 38 : 10); + m.Add(nav, Ms(0.5)); + m.EndFrame(Ms(slow ? 187 : 4), Sec(i * 0.05), logSlow: true); + } + List lines = m.Describe(Sec(1.0)); + foreach (string l in lines) Console.WriteLine(" " + l); + Check(lines.Count == 4, $"summary, per-frame, slowest frame, 3D pass lines ({lines.Count})"); + if (lines.Count < 4) return; + Check(lines[0].StartsWith("UI cost, last ", StringComparison.Ordinal) && lines[0].Contains("20 frames", StringComparison.Ordinal) + && lines[0].Contains("max 187.0 ms", StringComparison.Ordinal) && lines[0].Contains("1 at 50 ms+", StringComparison.Ordinal), "summary: " + lines[0]); + Check(lines[1].StartsWith("Per frame, avg (max): Radar ", StringComparison.Ordinal), "radar first by average: " + lines[1]); + Check(lines[1].Contains("Monster HUD 4.0 (41.0, 38 plates)", StringComparison.Ordinal), "hud avg, max and the most plates: " + lines[1]); + Eq(lines[2], "Slowest frame 187.0 ms: Radar 120.0, Monster HUD 41.0 (38 plates), untimed 26.0", "the slowest frame part by part"); + Check(lines[3].StartsWith("3D pass, not in ui=, avg (max): Nav3D markers 0.5 (0.5)", StringComparison.Ordinal), "3D pass: " + lines[3]); + + var empty = NewModel(); + List none = empty.Describe(Sec(1)); + Check(none.Count == 1 && none[0].StartsWith("UI cost: no UI frames", StringComparison.Ordinal), "no frames: one line saying so"); + empty.Enabled = false; + Check(empty.Describe(Sec(1))[0].Contains("timing off", StringComparison.Ordinal), "says when timing is off"); + } + + private static void ExclusiveTiming() + { + long f = Stopwatch.Frequency; + var m = new UiCostModel(f) { Enabled = true }; + int host = m.Register("Panel host upkeep"); + int panel = m.Register("Inventory"); + long start = Stopwatch.GetTimestamp() - f / 10; // the host part began 100 ms ago + long mark = m.Mark; + m.Add(panel, f * 60 / 1000); // a panel inside it took 60 ms + m.StopExclusive(host, start, mark); + m.EndFrame(f / 10, Stopwatch.GetTimestamp(), logSlow: false); + var h = m.SlotWindow(Stopwatch.GetTimestamp(), host); + var p = m.SlotWindow(Stopwatch.GetTimestamp(), panel); + Check(h.AvgMs >= 39.9 && h.AvgMs < 45, $"the host keeps only its own 40 ms ({h.AvgMs:0.00})"); + Check(Math.Abs(p.AvgMs - 60) < 0.01, $"the panel keeps its 60 ms ({p.AvgMs:0.00})"); + + // Stop with a real Start. + int q = m.Register("Q"); + long s = m.Start(); + Check(s != 0, "Start gives a timestamp while timing is on"); + Thread.Sleep(5); + m.Stop(q, s); + m.EndFrame(f / 100, Stopwatch.GetTimestamp(), logSlow: false); + Check(m.SlotWindow(Stopwatch.GetTimestamp(), q).MaxMs >= 4, "a 5 ms sleep is timed"); + } + + private static void OverflowSlot() + { + var m = NewModel(); + int last = -1; + for (int i = 0; i < UiCostModel.MaxSlots + 40; i++) last = m.Register("N" + i); + Eq(last, UiCostModel.OverflowSlot, "past MaxSlots a name gets the overflow slot"); + Eq(m.SlotCount, UiCostModel.MaxSlots, "slot count stops at MaxSlots"); + m.Add(last, Ms(70)); + string? line = m.EndFrame(Ms(80), Sec(1), true); + Check(line != null && line.Contains("(more names) 70.0", StringComparison.Ordinal), "the overflow slot is named: " + line); + m.Add(9999, Ms(5)); // out of range: ignored + m.Add(-1, Ms(5)); + Eq(m.Mark, 0L, "an out-of-range slot adds nothing"); + } + + private static void TimingOff() + { + var m = new UiCostModel(Stopwatch.Frequency) { Enabled = false }; + int p = m.Register("P"); + long s = m.Start(); + Eq(s, 0L, "Start is 0 while timing is off"); + m.Stop(p, s); + m.StopExclusive(p, s, 0); + Eq(m.Mark, 0L, "Stop with 0 adds nothing"); + } + + private static void DiscardFrame() + { + var m = NewModel(); + int nav = m.Register("Nav3D markers", outside: true); + int p = m.Register("P"); + m.Add(nav, Ms(30)); + m.Add(p, Ms(30)); + m.DiscardFrame(); + Eq(m.Mark, 0L, "discarded"); + string? line = m.EndFrame(Ms(60), Sec(1), true); + Check(line != null && !line.Contains("Nav3D", StringComparison.Ordinal) && line.Contains("untimed 60.0", StringComparison.Ordinal), + "a discarded frame's parts don't reach the next frame: " + line); + } + + // The per-frame cost of the breakdown: Parts Start/Stop pairs and an EndFrame (as UiCost does each + // frame), against the same frame with timing off (each Start a flag check, each Stop a 0 check). + private static void Overhead() + { + const int Parts = 40, Frames = 200_000; + var on = new UiCostModel(Stopwatch.Frequency) { Enabled = true }; + var off = new UiCostModel(Stopwatch.Frequency) { Enabled = false }; + int[] slotsOn = new int[Parts], slotsOff = new int[Parts]; + for (int i = 0; i < Parts; i++) { slotsOn[i] = on.Register("Part " + i); slotsOff[i] = off.Register("Part " + i); } + + static double Bench(UiCostModel m, int[] slots, bool endFrame, int frames) + { + long t0 = Stopwatch.GetTimestamp(); + for (int f = 0; f < frames; f++) + { + for (int i = 0; i < slots.Length; i++) + { + long s = m.Start(); + m.Stop(slots[i], s); + } + if (m.Enabled) + { + var st = new SubmitStats { Lists = 20, Draws = 400, TexSwitches = 3, VtxCopied = 30_000, VtxWholeList = 900_000 }; + m.SetSubmit(st); + m.AddUploads(0, f % 1000 == 0 ? 1 : 0); + } + if (endFrame) m.EndFrame(Stopwatch.Frequency / 100, Stopwatch.GetTimestamp(), logSlow: false); + } + return (Stopwatch.GetTimestamp() - t0) * 1e9 / Stopwatch.Frequency / frames; + } + + Bench(on, slotsOn, true, 20_000); // warm up (JIT) + Bench(off, slotsOff, false, 20_000); + long gc0 = GC.GetAllocatedBytesForCurrentThread(); + double onNs = Bench(on, slotsOn, true, Frames); + long allocated = GC.GetAllocatedBytesForCurrentThread() - gc0; + double offNs = Bench(off, slotsOff, false, Frames); + Console.WriteLine($" {Parts} timed parts a frame: on {onNs / 1000.0:0.00} us/frame, off {offNs:0.0} ns/frame, " + + $"{allocated / (double)Frames:0.0} bytes allocated a frame (on); one Start/Stop pair {(onNs / Parts):0} ns."); + Check(onNs < 100_000, $"on: under 0.1 ms a frame ({onNs:0} ns)"); + Check(offNs < 2_000, $"off: under 2 us a frame ({offNs:0} ns)"); + Check(allocated / (double)Frames < 1.0, $"no allocation per frame ({allocated} bytes over {Frames} frames)"); + } + + // ── DrawSubmitPlan: which vertices one draw command hands to DrawIndexedPrimitiveUP ── + + private static unsafe void DrawPlanRange() + { + ushort[] idx = { 104, 105, 106, 104, 106, 107 }; // one quad, vertices 104..107 + fixed (ushort* p = idx) + { + DrawSubmitPlan.IndexRange(p, idx.Length, out int min, out int max); + Eq(min, 104, "smallest index"); + Eq(max, 107, "largest index"); + + Check(DrawSubmitPlan.Plan(p, idx.Length, listVtx: 500, vtxOffset: 0, out int first, out int num), "a quad inside the list is drawn"); + Eq(first, 104, "first vertex = smallest index"); + Eq(num, 4, "4 vertices handed over, not the list's 500"); + + ushort[] rebased = new ushort[idx.Length]; + fixed (ushort* r = rebased) DrawSubmitPlan.Rebase(p, r, idx.Length, first); + Eq(string.Join(",", rebased), "0,1,2,0,2,3", "indices rebased to the first vertex"); + + // VtxOffset (lists past 64k vertices): the indices are relative to it. + Check(DrawSubmitPlan.Plan(p, idx.Length, listVtx: 70_000, vtxOffset: 65_536, out first, out num) && first == 104 && num == 4, + "with a VtxOffset the range is relative to it"); + Check(!DrawSubmitPlan.Plan(p, idx.Length, listVtx: 65_600, vtxOffset: 65_536, out _, out _), + "an index past the list's end (offset + 107 >= 65600) is refused"); + Check(!DrawSubmitPlan.Plan(p, idx.Length, listVtx: 107, vtxOffset: 0, out _, out _), "index 107 in a 107-vertex list is refused"); + Check(DrawSubmitPlan.Plan(p, idx.Length, listVtx: 108, vtxOffset: 0, out _, out num) && num == 4, "...in a 108-vertex list it is drawn"); + Check(!DrawSubmitPlan.Plan(p, 0, 500, 0, out _, out _), "no indices: nothing to draw"); + Check(!DrawSubmitPlan.Plan(p, idx.Length, 500, 500, out _, out _), "a VtxOffset at the list's end is refused"); + } + ushort[] zero = { 0, 1, 2 }; + fixed (ushort* z = zero) + Check(DrawSubmitPlan.Plan(z, 3, 3, 0, out int f0, out int n0) && f0 == 0 && n0 == 3, "starting at vertex 0: no rebase needed (first 0)"); + ushort[] one = { 9, 9, 9 }; + fixed (ushort* o = one) + Check(DrawSubmitPlan.Plan(o, 3, 10, 0, out int f1, out int n1) && f1 == 9 && n1 == 1, "a degenerate command: one vertex"); + } + + // The Loot Editor's rule list as ImGui builds it: per visible row a command in the child's clip + // (row background, 5 icon buttons, the badge: ~450 vertices), then one per PushClipRect (name ~80, + // conditions ~240). Vertices are appended in order, each command's indices reach only its own. + private static unsafe void DrawPlanLootEditorShape() + { + const int Rows = 25; + int[] cmdVtx = { 448, 80, 240 }; // quads: multiples of 4 + var idx = new List(); + var cmds = new List<(int off, int count)>(); + int v = 0; + for (int r = 0; r < Rows; r++) + foreach (int cv in cmdVtx) + { + int off = idx.Count; + for (int q = 0; q < cv / 4; q++) + { + int b = v + q * 4; + idx.AddRange(new[] { (ushort)b, (ushort)(b + 1), (ushort)(b + 2), (ushort)b, (ushort)(b + 2), (ushort)(b + 3) }); + } + cmds.Add((off, idx.Count - off)); + v += cv; + } + int listVtx = v; + long copied = 0, wholeList = 0; + ushort[] arr = idx.ToArray(); + fixed (ushort* p = arr) + foreach (var (off, count) in cmds) + { + Check(DrawSubmitPlan.Plan(p + off, count, listVtx, 0, out _, out int num), "every command is drawable"); + copied += num; + wholeList += listVtx; + } + const int Stride = 28; // DX9Backend.CustomVertex: xyzrhw, colour, uv + Console.WriteLine($" {Rows} rows, {listVtx} vertices, {cmds.Count} commands: copied {copied} vertices ({copied * Stride / 1024.0:0} KB) " + + $"vs whole-list {wholeList} ({wholeList * Stride / 1048576.0:0.0} MB) a frame, {wholeList / (double)copied:0}x less"); + Eq(copied, (long)listVtx, "each vertex is copied once a frame"); + Eq(wholeList, (long)listVtx * cmds.Count, "the old policy copied the list once per command"); + + // The memcpy alone (a lower bound: the D3D9 runtime copies into its own ring buffer, which also + // stalls on the GPU when it wraps), printed, not checked. + byte[] src = new byte[listVtx * Stride], dst = new byte[listVtx * Stride]; + long t0 = Stopwatch.GetTimestamp(); + for (int c = 0; c < cmds.Count; c++) Buffer.BlockCopy(src, 0, dst, 0, src.Length); + double oldMs = (Stopwatch.GetTimestamp() - t0) * 1000.0 / Stopwatch.Frequency; + t0 = Stopwatch.GetTimestamp(); + Buffer.BlockCopy(src, 0, dst, 0, src.Length); + double newMs = (Stopwatch.GetTimestamp() - t0) * 1000.0 / Stopwatch.Frequency; + Console.WriteLine($" memcpy of that volume in system RAM: whole-list {oldMs:0.00} ms, per-command range {newMs:0.000} ms"); + } + + private static void SubmitCountersInLine() + { + var m = NewModel(); + int sub = m.Register("ImGui submit", unit: "vtx"); + int nav = m.Register("Nav3D markers", outside: true); + m.Add(sub, Ms(300), 29344); + m.Add(nav, Ms(1)); + m.SetSubmit(new SubmitStats { Lists = 21, Draws = 412, TexSwitches = 3, VtxCopied = 31_100, VtxWholeList = 4_200_000, Skipped = 2 }); + m.AddUploads(1, 2); + string? line = m.EndFrame(Ms(301), Sec(1), true); + Console.WriteLine(" " + line); + Check(line != null && line.Contains("ImGui submit 300.0 (29344 vtx), untimed 1.0 | submit: 21 lists, 412 draws, 3 tex switches, " + + "31.1k vtx copied (whole-list 4.2M), 2 skipped; uploads: 1 font, 2 tex | 3D pass, not in ui=: Nav3D markers 1.0", + StringComparison.Ordinal), "submit counters and uploads after the parts, before the 3D pass: " + line); + + // The next frame starts clean: no submit recorded, no uploads -> no section. + m.Add(sub, Ms(60), 100); + string? next = m.EndFrame(Ms(60), Sec(10), true); + Check(next != null && !next.Contains("| submit", StringComparison.Ordinal) && !next.Contains("uploads", StringComparison.Ordinal), + "a frame's counters don't carry into the next: " + next); + + // Uploads alone. + m.Add(sub, Ms(60)); + m.AddUploads(1, 0); + string? up = m.EndFrame(Ms(60), Sec(20), true); + Check(up != null && up.Contains(" | uploads: 1 font, 0 tex", StringComparison.Ordinal), "uploads without a submit: " + up); + + // Discarded with the frame. + m.SetSubmit(new SubmitStats { Lists = 1, Draws = 1 }); + m.AddUploads(5, 5); + m.DiscardFrame(); + m.Add(sub, Ms(60)); + string? d = m.EndFrame(Ms(60), Sec(30), true); + Check(d != null && !d.Contains("| submit", StringComparison.Ordinal) && !d.Contains("uploads", StringComparison.Ordinal), "discarded counters are gone: " + d); + + Eq(UiCostModel.Compact(950), "950", "compact under 1000"); + Eq(UiCostModel.Compact(31_150), "31.2k", "compact thousands"); + Eq(UiCostModel.Compact(4_200_000), "4.2M", "compact millions"); + Eq(UiCostModel.Compact(31_000), "31k", "compact without a trailing .0"); + } + + private static void SubmitCountersInHeartbeatAndDescribe() + { + var m = NewModel(); + int sub = m.Register("ImGui submit", unit: "vtx"); + for (int i = 0; i < 10; i++) + { + m.Add(sub, Ms(i == 4 ? 300 : 20), 20_000); + m.SetSubmit(new SubmitStats { Lists = 18, Draws = i == 4 ? 412 : 120, TexSwitches = i == 4 ? 3 : 1, VtxCopied = i == 4 ? 31_000 : 13_000, VtxWholeList = i == 4 ? 4_200_000 : 400_000 }); + if (i == 2) m.AddUploads(1, 0); + if (i == 6) m.AddUploads(0, 3); + m.EndFrame(Ms(i == 4 ? 301 : 21), Sec(i * 0.1), logSlow: false); + } + string f = m.HeartbeatField(Sec(1.0)); + Console.WriteLine(" hb:" + f); + Check(f.EndsWith(" uisub=draws:412,texsw:3,vtx:31k/4.2M,up:1/3", StringComparison.Ordinal), + "the window's largest submit and its summed uploads: " + f); + Check(f.StartsWith(" uitop=ImGui_submit:", StringComparison.Ordinal), "uitop first: " + f); + + List lines = m.Describe(Sec(1.0)); + foreach (string l in lines) Console.WriteLine(" " + l); + Check(lines.Exists(l => l == "ImGui submit, largest per frame: 18 lists, 412 draws, 3 tex switches, 31k vtx copied (whole-list 4.2M); uploads (window total): 1 font, 3 tex"), + "/rc uicost now names the submit's largest counters"); + + // Without a submit recorded the heartbeat field is as before. + var plain = NewModel(); + int p = plain.Register("Radar"); + plain.Add(p, Ms(5)); + plain.EndFrame(Ms(5), Sec(0), false); + Eq(plain.HeartbeatField(Sec(0.5)), " uitop=Radar:5.0/5.0", "no submit: no uisub"); + } +} diff --git a/tools/UiCostTests/UiCostTests.csproj b/tools/UiCostTests/UiCostTests.csproj new file mode 100644 index 0000000..90e2397 --- /dev/null +++ b/tools/UiCostTests/UiCostTests.csproj @@ -0,0 +1,32 @@ + + + + + Exe + net10.0 + enable + enable + true + UiCostTests + true + + + + + + + + diff --git a/tools/VendorRateTests/Program.cs b/tools/VendorRateTests/Program.cs new file mode 100644 index 0000000..b54cab2 --- /dev/null +++ b/tools/VendorRateTests/Program.cs @@ -0,0 +1,97 @@ +using RynthCore.Engine.Compatibility; + +namespace VendorRateTests; + +/// VendorTrade's profile rate check (VendorRatePolicy). See the csproj. +internal static class Program +{ + private static int _checks, _failed; + + private static int Main() + { + // A free storage vendor: BuyPrice 0, SellPrice 0. This is the case that used to turn trading off. + Check(VendorRatePolicy.LooksSane(0f), "rate 0 (free storage vendor)"); + Check(VendorRatePolicy.LooksSane(-0f), "rate -0 (compares equal to 0)"); + + // Ordinary vendors and promissory-note rates. + foreach (float r in new[] { 0.001f, 0.1f, 0.5f, 0.75f, 1f, 1.15f, 2.5f, 10f, 999.9f }) + Check(VendorRatePolicy.LooksSane(r), $"rate {r}"); + + // Misreads stay rejected. + foreach (float r in new[] { -0.001f, -1f, float.NaN, float.PositiveInfinity, float.NegativeInfinity, + VendorRatePolicy.MaxRate, 1e6f, float.MaxValue, float.MinValue }) + Check(!VendorRatePolicy.LooksSane(r), $"rate {r} rejected"); + + Pricing(); + WiringPinned(); + + Console.WriteLine(_failed == 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks} checks failed)"); + return _failed == 0 ? 0 : 1; + } + + private static void Eq(long got, long want, string what) => Check(got == want, $"{what}: got {got}, want {want}"); + + private const uint Note = VendorRatePolicy.ItemTypePromissoryNote; + private const uint Misc = 0x00000080; + + // A 0 rate is free (the vault's GetSellCost/GetBuyCost return 0); any rate above 0 keeps ACE's 1 floor. + private static void Pricing() + { + Check(VendorRatePolicy.IsFreeVendor(0f, 0f), "buy=0 sell=0 is a free vendor"); + Check(!VendorRatePolicy.IsFreeVendor(0f, 1.15f), "buy=0 sell=1.15 is not a free vendor"); + Check(!VendorRatePolicy.IsFreeVendor(0.5f, 0f), "buy=0.5 sell=0 is not a free vendor"); + + Eq(VendorRatePolicy.PlayerPaysForStack(0f, Misc, 0), 0, "rate 0, value 0: cost"); + Eq(VendorRatePolicy.PlayerPaysForStack(0f, Misc, 1), 0, "rate 0, value 1: cost"); + Eq(VendorRatePolicy.PlayerPaysForStack(0f, Misc, 250_000), 0, "rate 0, value 250000: cost"); + Eq(VendorRatePolicy.PlayerPaysForStack(0f, Note, 250_000), 0, "rate 0, a note: cost"); + Eq(VendorRatePolicy.VendorPaysForStack(0f, Misc, 1), 0, "rate 0, value 1: payout"); + Eq(VendorRatePolicy.VendorPaysForStack(0f, Misc, 250_000), 0, "rate 0, value 250000: payout"); + Eq(VendorRatePolicy.VendorPaysForStack(0f, Note, 250_000), 0, "rate 0, a note: payout"); + + // The floor stays for every rate above 0 (stock ACE). + Eq(VendorRatePolicy.PlayerPaysForStack(0.001f, Misc, 1), 1, "rate 0.001, value 1: cost floors at 1"); + Eq(VendorRatePolicy.VendorPaysForStack(0.001f, Misc, 1), 1, "rate 0.001, value 1: payout floors at 1"); + Eq(VendorRatePolicy.PlayerPaysForStack(0.5f, Misc, 0), 1, "rate 0.5, value 0: cost floors at 1"); + Eq(VendorRatePolicy.PlayerPaysForStack(1.15f, Misc, 100), 115, "rate 1.15, value 100: cost"); + Eq(VendorRatePolicy.VendorPaysForStack(0.75f, Misc, 100), 75, "rate 0.75, value 100: payout"); + Eq(VendorRatePolicy.PlayerPaysForStack(2f, Note, 100), 115, "a note costs 1.15x whatever the rate"); + Eq(VendorRatePolicy.VendorPaysForStack(0.5f, Note, 100), 100, "a note pays 1.0x whatever the rate"); + } + + // VendorTrade.cs must route through VendorRatePolicy, or the checks above test code the engine doesn't run. + private static void WiringPinned() + { + string? src = FindUp(Path.Combine("src", "RynthCore.Engine", "Compatibility", "VendorTrade.cs")); + Check(src != null, "found src\\RynthCore.Engine\\Compatibility\\VendorTrade.cs walking up from " + AppContext.BaseDirectory); + if (src == null) return; + string text = File.ReadAllText(src); + foreach (string needle in new[] + { + "snap.ProfileRead = RateLooksSane(snap.BuyRate) && RateLooksSane(snap.SellRate);", + "RateLooksSane(float rate) => VendorRatePolicy.LooksSane(rate);", + "VendorRatePolicy.PlayerPaysForStack(sellRate, itemType, stackValue);", + "VendorRatePolicy.VendorPaysForStack(buyRate, itemType, value);", + "VendorRatePolicy.IsFreeVendor(snap.BuyRate, snap.SellRate)", + }) + Check(text.Contains(needle, StringComparison.Ordinal), "VendorTrade.cs contains: " + needle); + } + + private static string? FindUp(string relative) + { + for (DirectoryInfo? d = new(AppContext.BaseDirectory); d != null; d = d.Parent) + { + string p = Path.Combine(d.FullName, relative); + if (File.Exists(p)) return p; + } + return null; + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) { Console.WriteLine("ok " + what); return; } + _failed++; + Console.WriteLine("FAIL " + what); + } +} diff --git a/tools/VendorRateTests/VendorRateTests.csproj b/tools/VendorRateTests/VendorRateTests.csproj new file mode 100644 index 0000000..ee94d9b --- /dev/null +++ b/tools/VendorRateTests/VendorRateTests.csproj @@ -0,0 +1,24 @@ + + + + + Exe + net10.0 + enable + enable + true + VendorRateTests + + + + + + +