Snapshot for release 2026.10.11.1 (internal 4eca83a)

This commit is contained in:
Tom Bohar 2026-10-11 15:00:53 -04:00
commit 08b80eed86
94 changed files with 11103 additions and 567 deletions

View file

@ -134,7 +134,7 @@ Write-Host " Decal bridge in the installer: $((Get-Item $bridgeStaged).VersionI
Copy-Item (Join-Path $ScriptDir "Output\RynthCore-Setup.exe") "$rel\RynthCore-Setup.exe"
Copy-Item (Join-Path $ScriptDir "staging\plugins\RynthAi\RynthCore.Plugin.RynthAi.dll") "$rel\plugins\"
$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision", "RynthLua", "RynthOracle", "RynthInventory"
$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision", "RynthLua", "RynthOracle", "RynthInventory", "RynthSort", "RynthILT"
foreach ($name in $suitePlugins) {
Step "Building $name"
$proj = Join-Path $RynthSuiteRoot "Plugins\RynthCore.Plugin.$name\RynthCore.Plugin.$name.csproj"
@ -180,6 +180,8 @@ Extract this zip into C:\Games - it creates:
C:\Games\RynthSuite\RynthLua\ RynthLua plugin (Lua scripting; was part of RynthAi)
C:\Games\RynthSuite\RynthOracle\ RynthOracle plugin (quests, character, titles; based on Oracle of Dereth by Advis Eveldan)
C:\Games\RynthSuite\RynthInventory\ RynthInventory plugin (search every character's items)
C:\Games\RynthSuite\RynthSort\ RynthSort plugin (keeps your packs sorted; replaces the RynthSort Lua script)
C:\Games\RynthSuite\RynthILT\ RynthILT plugin (Infinite Leaftide only: the Bounties window's tracker)
C:\Games\RynthCore\NavData\ RynthNav's portals and Atlas
Then, in the RynthCore launcher's Plugins tab, add the full path of each
@ -266,6 +268,8 @@ $pluginDescriptions = @{
RynthLua = "Lua scripting for metas and your own scripts."
RynthOracle = "Quests, character, titles and leaderboards."
RynthInventory = "Search every character's items."
RynthSort = "Keeps your packs sorted: new loot goes to the pack its rule names."
RynthILT = "Infinite Leaftide only: tracks your ACECustom bounties for the Bounties window."
}
# Plugin manifests (embedded in each DLL by the SDK's build targets): each plugin's minEngineApi
# goes into its feed entry, and the core entry says its engine's API ("engineApi"), so launchers

View file

@ -81,12 +81,17 @@ Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Flags: nowait runasorigina
[UninstallRun]
; Decal + RynthCore (experimental): remove the Decal bridge's registration, only
; what the launcher added (see docs/DECAL_BRIDGE_PLAN.md). Every release ships the bridge
; what RynthCore added (see docs/DECAL_BRIDGE_PLAN.md). Every release ships the bridge
; ({app}\DecalBridge, staged by Build-Installer.ps1), so this always runs; with nothing
; registered it changes nothing. Runs before the files are removed. It removes both entries
; the installer writes (see RegisterDecalBridge in [Code]): the per-user one, and the
; machine-wide one - directly when the uninstaller is elevated, otherwise after Windows'
; administrator prompt, which appears only when a machine-wide entry exists.
; registered it changes nothing. Runs before the files are removed. It removes:
; - our entry from any per-user (VirtualStore) copy of Decal's filter list;
; - a per-user copy an earlier RynthCore created (decal-bridge-registration.json says so),
; whatever is in it now: our entries and the HKLM filters it mirrored (HKLM keeps the
; originals). It is exported first to %APPDATA%\RynthCore\decal-backup-<date>.reg. If the
; copy holds entries that are neither ours nor in HKLM, they belong to someone else: the
; copy stays and the uninstall log (launcher.log) says why;
; - this install's machine-wide entry - directly when the uninstaller is elevated, otherwise
; after Windows' administrator prompt, which appears only when that entry exists.
Filename: "{app}\RynthCore.exe"; Parameters: "--decal-bridge-unregister"; Flags: runhidden waituntilterminated; RunOnceId: "RynthCoreDecalBridgeUnregister"
[Code]
@ -104,33 +109,40 @@ begin
end;
(* -------------------------------------------------------------------------------------
Decal + RynthCore (experimental): register the RynthCore Decal bridge on every install
AND every update (the launcher's updater runs this installer with /SILENT), in BOTH
places a Decal client can read its filter list from:
Decal + RynthCore (experimental), strictly opt-in (since 2026-10-10): on install and on
every update (the launcher's updater runs this installer with /SILENT), the RynthCore
Decal bridge is registered ONLY when the installing user has a Decal + RynthCore account
(%APPDATA%\RynthCore\decal-accounts.json, which the launcher deletes when no account uses
the mode). Otherwise nothing Decal-related is touched; the launcher cleans up after
itself when no account uses the mode any more.
1. Machine-wide: HKLM\SOFTWARE\WOW6432Node\Decal\NetworkFilters\{5B3E0D57-...}
(32-bit view). An elevated AC (RynthCore or AC run as administrator), or any AC when
UAC or its registry virtualization is off, reads ONLY this key - the per-user entry
is invisible to it (a player's Decal + RynthCore client never loaded the bridge,
2026-10-03). A non-elevated AC without a per-user copy reads it too.
2. Per-user: this user's VirtualStore copy of that key, ONLY if the copy already exists.
A non-elevated AC is virtualized and, once a copy exists, reads nothing but the copy.
A missing copy is never created: it would hide every HKLM filter added later from
this user's non-elevated clients.
Where it goes:
1. Machine-wide, always: HKLM\SOFTWARE\WOW6432Node\Decal\NetworkFilters\{5B3E0D57-...}
(32-bit view), Decal's own list. Every client reads it unless a per-user copy hides it.
2. Per-user: NEVER a new per-user (VirtualStore) copy of that key. acclient.exe is a
legacy 32-bit program; when HKCU\Software\Classes\VirtualStore\MACHINE\SOFTWARE\
WOW6432Node\Decal\NetworkFilters exists, a non-elevated AC reads nothing but that copy,
so every filter installed for all users afterwards is hidden from Decal (a player's
new plugins and UtilityBelt's newer service vanished, 2026-10). Launchers before
2026-10-10 created such a copy; --decal-bridge-install-user now removes a copy an
earlier RynthCore created (backed up first to %APPDATA%\RynthCore\decal-backup-<date>.reg;
kept when it holds someone else's entries), and only adds our entry to a copy that
exists anyway (Decal can make one itself). The launcher's Recovery Actions > Repair
Decal removes any such copy after a backup.
Both entries are harmless while no account uses Decal + RynthCore: every Decal client
loads the bridge, which stays idle (no hooks, no threads) unless the RynthCore loader is
in the same client. Uninstall removes both ([UninstallRun] --decal-bridge-unregister).
The machine-wide entry is harmless: Decal clients load the bridge, which stays idle (no
hooks, no threads) unless the RynthCore loader is in the same client. Uninstall removes
what RynthCore added ([UninstallRun] --decal-bridge-unregister, see above).
Rights. This installer runs with the lowest privileges (PrivilegesRequired=lowest; the
updater starts it without elevation). Writing HKLM needs administrator rights, so:
updater starts it without elevation). Writing HKLM needs administrator rights, so, for a
user with a Decal + RynthCore account and only when the machine-wide entry is missing or
points at another folder:
- Setup already elevated (installed "for all users", or started by an elevated
launcher): written directly, no prompt.
- Not elevated: Windows' administrator prompt is shown ONCE - only when Decal is
installed, the machine-wide entry is missing or points at another folder, and this
user has a Decal + RynthCore account (decal-accounts.json). Saying no is harmless:
the launcher checks before every Decal + RynthCore launch and repairs it (writing it
directly when it runs elevated, the case that needs it).
- Not elevated: Windows' administrator prompt is shown once. Saying no is harmless for
Decal: the launcher asks again before the next Decal + RynthCore launch (interactive
launches only), and Decal + RynthCore can't be used until it is registered.
The commands are RynthCore.exe's own (Program.cs): --decal-bridge-register-machine and
--decal-bridge-install-user, so the installer and the launcher write identical entries.
------------------------------------------------------------------------------------- *)
@ -170,6 +182,11 @@ var
Code: Integer;
begin
if not DecalInstalled then Exit;
if not UsesDecalBridge then
begin
Log('Decal bridge: no Decal + RynthCore account for this user - nothing registered (opt-in only).');
Exit;
end;
if not FileExists(BridgeDir + '\RynthCore.DecalBridge.dll') then Exit;
Exe := ExpandConstant('{app}\RynthCore.exe');
Params := '--decal-bridge-register-machine "' + BridgeDir + '"';
@ -182,18 +199,24 @@ begin
else
Log('Decal bridge: machine-wide registration exit code ' + IntToStr(Code));
end
else if UsesDecalBridge then
else
begin
if not ShellExec('runas', Exe, Params, ExpandConstant('{app}'), SW_HIDE, ewWaitUntilTerminated, Code) then
Log('Decal bridge: elevated machine-wide registration not done (declined or failed): ' + SysErrorMessage(Code))
else
Log('Decal bridge: elevated machine-wide registration exit code ' + IntToStr(Code));
end
else
Log('Decal bridge: machine-wide entry missing; not elevated and no Decal + RynthCore account - left to the launcher.');
end;
end;
if not MachineBridgeEntryCurrent then
begin
{ No per-user fallback: Decal + RynthCore waits for the machine-wide entry (the launcher
asks again before the next interactive Decal + RynthCore launch). }
Log('Decal bridge: not registered machine-wide - per-user step skipped.');
Exit;
end;
{ Per-user half, as the user who started Setup (the same user unless Setup was elevated
with other credentials). }
with other credentials): removes an earlier RynthCore's per-user copy (backed up first),
adds our entry to a per-user copy that exists anyway. Never creates one. }
if not ExecAsOriginalUser(Exe, '--decal-bridge-install-user "' + BridgeDir + '"', ExpandConstant('{app}'),
SW_HIDE, ewWaitUntilTerminated, Code) then
Log('Decal bridge: per-user step did not start: ' + SysErrorMessage(Code));

View file

@ -13,21 +13,42 @@
// reload, so a reload gives its memory back.
//
// Either way the loader owns the reload event, the file watcher, the address-space
// guard and a MinHook facade (Hooks.c): every hook is installed once, through a
// permanent stub, and a reload only re-points the stub.
// guard, the reload cap (MaxHotReloads per client) and a MinHook facade (Hooks.c):
// every hook is installed once, through a permanent stub, and a reload only re-points
// the stub. For the managed engine it also sets up CoreCLR's crash dumps (Logs\dumps).
// ============================================================================
#include "Loader.h"
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#define ENGINE_DLL_NAME "RynthCore.Engine.dll"
#define ENGINE_INIT_EXPORT "RynthCoreEngineInit"
#define ENGINE_SHUTDOWN_EXPORT "RynthCoreShutdown"
#define ENGINE_REFUSED_EXPORT "RynthCoreReloadRefused"
#define ENGINE_MAXRELOADS_EXPORT "RynthCoreMaxHotReloads"
#define ENGINE_CAPPED_EXPORT "RynthCoreReloadCapped"
#ifndef LOG_DIR // the offline tests (tools\Loader*Tests) log into their own folder
#define LOG_DIR "C:\\Games\\RynthCore\\Logs"
#define LOG_PARENT "C:\\Games\\RynthCore"
#endif
#define STAGING_SUBDIR ".engine_loads"
// Hot reloads one client takes before it refuses the rest (until it restarts). The engine
// says the real number (engine.json MaxHotReloads, RynthCoreMaxHotReloads export); this is
// for an engine without the export. After 4+ reloads in one process, clients died with
// CoreCLR fatal error 0x80131506 at coreclr+0x256E19 (2026-10-08..10, gens 5-6 or the 4th
// reload itself) although every generation unloaded and address space stayed flat: treated
// as a CoreCLR limit on repeated collectible loads, so the loader stops short of it.
#define DEFAULT_MAX_HOT_RELOADS 3
// CoreCLR's own crash dump (createdump.exe, DOTNET_DbgEnableMiniDump): clr_<pid>_<time>.dmp
// in Logs\dumps, newest DUMP_KEEP kept. With the heap (type 2) only while the volume keeps
// DUMP_HEAP_MIN_FREE_MB free (a heap dump of a client is ~1 GB); else a normal one (stacks).
#define DUMP_SUBDIR "dumps"
#define DUMP_PREFIX "clr_"
#define DUMP_KEEP 3
#define DUMP_HEAP_MIN_FREE_MB 3072
#define MIN_RELOAD_INTERVAL_MS 1500
// A managed engine gives its memory back on reload, so the guard only has to keep
// room for one more generation; the NativeAOT engine leaks every generation.
@ -36,6 +57,8 @@
typedef unsigned int (__stdcall *engine_u32_fn)(void* param);
typedef unsigned int (__stdcall *engine_refused_fn)(int freeMb);
typedef int (__stdcall *engine_max_reloads_fn)(void);
typedef unsigned int (__stdcall *engine_capped_fn)(int reloads, int cap);
static volatile LONG g_initialized;
static char g_loaderDir[MAX_PATH];
@ -71,7 +94,9 @@ void LoaderLog(const char* level, const char* fmt, ...)
char path[MAX_PATH];
_snprintf_s(path, sizeof path, _TRUNCATE, LOG_DIR "\\RynthCore.%lu.log", GetCurrentProcessId());
EnterCriticalSection(&g_logLock);
CreateDirectoryA("C:\\Games\\RynthCore", NULL);
#ifdef LOG_PARENT
CreateDirectoryA(LOG_PARENT, NULL);
#endif
CreateDirectoryA(LOG_DIR, NULL);
for (int attempt = 0; attempt < 4; attempt++) {
HANDLE h = CreateFileA(path, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
@ -250,6 +275,93 @@ static int StageEngine(int generation, char* stagedPath, size_t cap, HANDLE* gua
return 1;
}
// ---------------------------------------------------------------------------
// CoreCLR crash dumps
// ---------------------------------------------------------------------------
typedef struct DumpFile {
FILETIME written;
char name[MAX_PATH];
} DumpFile;
static int CompareNewestFirst(const void* a, const void* b)
{
return CompareFileTime(&((const DumpFile*)b)->written, &((const DumpFile*)a)->written);
}
// Deletes all but the newest `keep` clr_*.dmp in `dir` (other dumps, e.g. the engine's
// hang_*.dmp, are left alone). Returns how many it deleted. Init thread only.
static int PruneCrashDumps(const char* dir, int keep)
{
static DumpFile files[512];
char pattern[MAX_PATH];
_snprintf_s(pattern, sizeof pattern, _TRUNCATE, "%s\\" DUMP_PREFIX "*.dmp", dir);
WIN32_FIND_DATAA fd;
HANDLE f = FindFirstFileA(pattern, &fd);
if (f == INVALID_HANDLE_VALUE) return 0;
int count = 0;
do {
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
files[count].written = fd.ftLastWriteTime;
strcpy_s(files[count].name, sizeof files[count].name, fd.cFileName);
count++;
} while (count < (int)(sizeof files / sizeof files[0]) && FindNextFileA(f, &fd));
FindClose(f);
qsort(files, (size_t)count, sizeof files[0], CompareNewestFirst);
int deleted = 0;
for (int i = keep < 0 ? 0 : keep; i < count; i++) {
char p[MAX_PATH];
_snprintf_s(p, sizeof p, _TRUNCATE, "%s\\%s", dir, files[i].name);
if (DeleteFileA(p)) deleted++; // fails for a dump still being written: fine
}
return deleted;
}
// The DOTNET_DbgMiniDumpType for a volume with `freeBytes` free: 2 (MiniDumpWithPrivateReadWrite
// Memory: the GC heap and every private page, what a CoreCLR fatal error needs) when there is
// room, else 1 (normal: threads and stacks, a few MB). Never 4 (full): it adds the mapped
// images, which the debugger reads from disk anyway, for a larger file.
static int CrashDumpType(unsigned long long freeBytes)
{
return freeBytes >= (unsigned long long)DUMP_HEAP_MIN_FREE_MB * 1024 * 1024 ? 2 : 1;
}
// Before CoreCLR starts (it reads these once, in coreclr_initialize): a fatal runtime error
// (FailFast, 0x80131506...) runs createdump.exe from the runtime folder and writes
// <dumpDir>\clr_<pid>_<time>.dmp. Those never reach WER, so before this they left nothing.
// Returns the dump type set, or 0 when the environment already configures it (a test or a
// developer's own choice, including DOTNET_DbgEnableMiniDump=0 to turn it off).
static int ConfigureCrashDumps(const char* dumpDir, const char* runtimeDir)
{
char existing[64];
if (GetEnvironmentVariableA("DOTNET_DbgEnableMiniDump", existing, sizeof existing) > 0 ||
GetEnvironmentVariableA("COMPlus_DbgEnableMiniDump", existing, sizeof existing) > 0) {
LoaderLog("INF", "CrashDumps: DbgEnableMiniDump=%s is already set in the environment; left as it is.", existing);
return 0;
}
CreateDirectoryA(dumpDir, NULL);
int pruned = PruneCrashDumps(dumpDir, DUMP_KEEP);
ULARGE_INTEGER freeBytes;
if (!GetDiskFreeSpaceExA(dumpDir, &freeBytes, NULL, NULL)) freeBytes.QuadPart = 0;
int type = CrashDumpType(freeBytes.QuadPart);
// %t is createdump's own specifier (time of the dump); the pid is filled in here.
char name[MAX_PATH];
_snprintf_s(name, sizeof name, _TRUNCATE, "%s\\" DUMP_PREFIX "%lu_%%t.dmp", dumpDir, GetCurrentProcessId());
SetEnvironmentVariableA("DOTNET_DbgEnableMiniDump", "1");
SetEnvironmentVariableA("DOTNET_DbgMiniDumpType", type == 2 ? "2" : "1");
SetEnvironmentVariableA("DOTNET_DbgMiniDumpName", name);
LoaderLog("INF", "CrashDumps: a CoreCLR fatal error writes %s (type %d, %s; %llu MB free; newest %d kept, %d older deleted).",
name, type, type == 2 ? "with heap" : "stacks only, low disk", freeBytes.QuadPart / (1024 * 1024), DUMP_KEEP, pruned);
char createdump[MAX_PATH];
_snprintf_s(createdump, sizeof createdump, _TRUNCATE, "%s\\createdump.exe", runtimeDir);
if (GetFileAttributesA(createdump) == INVALID_FILE_ATTRIBUTES)
LoaderLog("WRN", "CrashDumps: %s is missing, so a CoreCLR crash still leaves no dump. "
"Run scripts\\Publish-EngineCoreClr.ps1 (full, not -EngineOnly) to put it back.", createdump);
return type;
}
// ---------------------------------------------------------------------------
// Engine calls, whichever host
// ---------------------------------------------------------------------------
@ -260,6 +372,20 @@ static void* EngineExport(const char* name)
return g_engineModule ? (void*)GetProcAddress(g_engineModule, name) : NULL;
}
// 1 = a client that has done `reloadsDone` hot reloads takes no more; `cap` < 0 = no cap.
static int ReloadCapReached(int reloadsDone, int cap)
{
return cap >= 0 && reloadsDone >= cap;
}
// The current engine's MaxHotReloads (engine.json), or the default for an engine without
// the export.
static int CurrentReloadCap(void)
{
engine_max_reloads_fn f = (engine_max_reloads_fn)EngineExport(ENGINE_MAXRELOADS_EXPORT);
return f ? f() : DEFAULT_MAX_HOT_RELOADS;
}
static unsigned int LoadAndInitEngine(void)
{
g_initCount++;
@ -334,6 +460,10 @@ static void Reload(void)
long freeAfter = LoaderFreeAddressSpaceMb(&largest);
LoaderLog(rc == 0 ? "INF" : "ERR", "Reload: %s (gen %d, %ld MB free, %+ld MB vs before the reload).",
rc == 0 ? "complete" : "re-init FAILED", g_initCount, freeAfter, freeAfter - freeBefore);
int cap = CurrentReloadCap();
if (ReloadCapReached(g_initCount - 1, cap))
LoaderLog("INF", "Reload: hot reload %d of %d (engine.json MaxHotReloads); this client takes no more, "
"a newer engine needs a client restart.", g_initCount - 1, cap);
}
// ---------------------------------------------------------------------------
@ -352,6 +482,21 @@ static DWORD WINAPI ReloadWatcher(LPVOID unused)
continue;
}
// The reload cap: nothing is shut down, unloaded or staged, so the client keeps running
// on this generation and its staged file stays as it is (the next client start cleans
// it up once this process is gone, CleanStaleStagingFiles).
int reloadsDone = g_initCount - 1;
int cap = CurrentReloadCap();
if (ReloadCapReached(reloadsDone, cap)) {
LoaderLog("WRN", "ReloadWatcher: reload REFUSED - this client has hot reloaded %d time(s), the cap "
"(engine.json MaxHotReloads) is %d. Staying on engine gen %d; restart the client to load the "
"new engine. (Repeated hot reloads in one client ended in CoreCLR fatal error 0x80131506.)",
reloadsDone, cap, g_initCount);
engine_capped_fn capped = (engine_capped_fn)EngineExport(ENGINE_CAPPED_EXPORT);
if (capped) capped(reloadsDone, cap);
continue;
}
long minFree = g_engineIsManaged ? MIN_FREE_MB_CLR : MIN_FREE_MB_AOT;
long freeMb = LoaderFreeAddressSpaceMb(NULL);
if (freeMb < minFree) {
@ -440,6 +585,10 @@ unsigned int __stdcall RynthCoreInit(void* param)
return 6;
}
if (managed) {
char dumpDir[MAX_PATH], runtimeDir[MAX_PATH];
_snprintf_s(dumpDir, sizeof dumpDir, _TRUNCATE, LOG_DIR "\\" DUMP_SUBDIR);
_snprintf_s(runtimeDir, sizeof runtimeDir, _TRUNCATE, "%s\\dotnet", g_loaderDir);
ConfigureCrashDumps(dumpDir, runtimeDir);
int rc = ClrStart(g_loaderDir);
if (rc != 0) {
LoaderLog("ERR", "FATAL: CoreCLR did not start (rc=%d)", rc);
@ -462,6 +611,9 @@ unsigned int __stdcall RynthCoreInit(void* param)
t = CreateThread(NULL, 0, FileWatcher, NULL, 0, NULL);
if (t) CloseHandle(t);
LoaderLog("INF", "Reload watcher armed on '%s'; file watcher on '%s' (poll 1 s).", eventName, g_enginePath);
int cap = CurrentReloadCap();
if (cap < 0) LoaderLog("INF", "Hot reloads: no cap (engine.json MaxHotReloads %d).", cap);
else LoaderLog("INF", "Hot reloads: at most %d in this client (engine.json MaxHotReloads); after that a new engine needs a restart.", cap);
return 0;
}

View file

@ -2,7 +2,7 @@
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define LOADER_VERSION "2.0"
#define LOADER_VERSION "2.1"
// Loader.c
void LoaderLog(const char* level, const char* fmt, ...);

View file

@ -99,10 +99,29 @@ if (-not $EngineOnly) {
New-Item -ItemType Directory -Force -Path $dotnet | Out-Null
Copy-Item "$rt\native\*" $dotnet -Force
Copy-Item "$rt\lib\net10.0\*.dll" $dotnet -Force
# Diagnostics-only natives the host never loads.
Remove-Item "$dotnet\createdump.exe", "$dotnet\mscordaccore_*.dll", "$dotnet\msquic.dll" -Force -ErrorAction SilentlyContinue
# msquic is never loaded. createdump.exe and the DAC (mscordaccore_*) stay: the loader
# turns on CoreCLR's crash dumps (Logs\dumps\clr_<pid>_<time>.dmp), which run
# createdump.exe from this folder, and a debugger reads the dump with the DAC.
Remove-Item "$dotnet\msquic.dll" -Force -ErrorAction SilentlyContinue
Write-Host "App-local runtime $ver -> $dotnet"
}
elseif (-not (Test-Path "$dotnet\createdump.exe")) {
# Runtimes laid out before 2026-10-11 had createdump.exe and the DAC deleted, so a
# CoreCLR fatal error (0x80131506) left no dump. Put them back from the runtime pack
# whose coreclr.dll is this one (same file version), never from another version.
$have = (Get-Item "$dotnet\coreclr.dll").VersionInfo.FileVersion
$pack = Join-Path $env:USERPROFILE ".nuget\packages\microsoft.netcore.app.runtime.win-x86"
$match = Get-ChildItem $pack -Directory -ErrorAction SilentlyContinue | Where-Object Name -like "10.*" |
ForEach-Object { "$($_.FullName)\runtimes\win-x86\native" } |
Where-Object { (Test-Path "$_\createdump.exe") -and (Get-Item "$_\coreclr.dll").VersionInfo.FileVersion -eq $have } |
Select-Object -First 1
if ($match) {
Copy-Item "$match\createdump.exe" $dotnet -Force
Get-ChildItem $match -Filter "mscordaccore_*.dll" | Copy-Item -Destination $dotnet -Force
Write-Host "Put createdump.exe and the DAC back into $dotnet (CoreCLR crash dumps)."
}
else { Write-Warning "createdump.exe is missing from $dotnet and no runtime pack matches coreclr $have; a CoreCLR crash will leave no dump." }
}
}
# Engine + dependencies. The canonical RynthCore.Engine.dll goes last: the loader's file

View file

@ -21,6 +21,11 @@ $repo = Split-Path $PSScriptRoot -Parent
$testClient = "$repo\tools\TestClient\bin\TestClient.exe"
$alcRoots = "$repo\tools\AlcRoots\bin\Release\net10.0\win-x86\AlcRoots.exe"
# The loader refuses hot reloads past engine.json MaxHotReloads (default 3, 2026-10-11): a soak
# of more reloads needs "MaxHotReloads": -1 in the -Settings file.
if ($Reloads -gt 3 -and -not ((Test-Path $Settings) -and (Select-String -Path $Settings -Pattern '"MaxHotReloads"' -Quiet))) {
Write-Warning "-Reloads $Reloads is over the default cap of 3 hot reloads per client: add ""MaxHotReloads"": -1 to $Settings, or reloads past the 3rd are refused."
}
$env:RYNTHCORE_ENGINE_SETTINGS = $Settings
$env:RYNTHCORE_TEST_CLIENT = "Test-ClrReload" # the loader logs "TestClient: ..." (monitors skip test clients)
# Panel layout (panel_state.txt) lives in %LOCALAPPDATA%\RynthCore and is shared with real

View file

@ -40,6 +40,11 @@ if (Test-Path $pidFile) {
}
}
# The loader refuses hot reloads past engine.json MaxHotReloads (default 3, 2026-10-11): a soak
# of more reloads needs "MaxHotReloads": -1 in the -Settings file.
if ($Reloads -gt 3 -and -not ((Test-Path $Settings) -and (Select-String -Path $Settings -Pattern '"MaxHotReloads"' -Quiet))) {
Write-Warning "-Reloads $Reloads is over the default cap of 3 hot reloads per client: add ""MaxHotReloads"": -1 to $Settings, or reloads past the 3rd are refused."
}
$env:RYNTHCORE_ENGINE_SETTINGS = $Settings
$env:RYNTHCORE_TEST_CLIENT = "Test-ClrWorld" # the loader logs "TestClient: ..." (monitors skip test clients)
# Panel layout (panel_state.txt) lives in %LOCALAPPDATA%\RynthCore and is shared with real

View file

@ -9,7 +9,7 @@ namespace RynthCore.App.Avalonia;
/// <summary>
/// Small code-built dialogs for the Decal bridge: the "Check Decal bridge" report (with
/// Repair / Copy) and the yes/no before the one administrator step.
/// Repair / Copy), the yes/no before an administrator step or Repair Decal, and plain messages.
/// </summary>
internal static class DecalBridgeDialog
{
@ -33,6 +33,18 @@ internal static class DecalBridgeDialog
return result == true;
}
/// <summary>A message with one OK button (selectable text, so paths can be copied).</summary>
public static async Task InfoAsync(Window owner, string title, string message)
{
var dialog = NewWindow(title, 620);
var ok = new Button { Content = "OK", IsDefault = true, IsCancel = true };
ok.Click += (_, _) => dialog.Close(true);
dialog.Content = Layout(title,
new SelectableTextBlock { Text = message, TextWrapping = TextWrapping.Wrap, Foreground = Text },
ok);
await dialog.ShowDialog<bool?>(owner);
}
/// <summary>
/// Shows the check's report. With <paramref name="offerRepair"/>, a Repair button; returns
/// true when the person pressed it.

View file

@ -422,6 +422,8 @@
ToolTip.Tip="Drags the in-game RynthCore overlay bar back to the top-left corner. Use this if the bar was moved off-screen and can no longer be reached. Applies to every running RynthCore client." />
<Button x:Name="CheckDecalBridgeButton" Content="Check Decal bridge" Margin="0,0,8,8"
ToolTip.Tip="For Decal + RynthCore (experimental): checks whether a client started now will load the RynthCore Decal bridge - where Decal reads its plugin list on this PC, whether the bridge is listed and enabled there, Decal's version and its .NET part. Changes nothing unless you press Repair." />
<Button x:Name="RepairDecalButton" Content="Repair Decal" Margin="0,0,8,8"
ToolTip.Tip="For Decal plugins that don't show up: Windows can make Decal read an old per-user copy of its settings (left by an earlier RynthCore, or by Decal itself), which hides plugins installed since. This backs that copy up to a .reg file in %APPDATA%\RynthCore and removes it, after asking. Close Asheron's Call first." />
</WrapPanel>
<TextBlock Text="Manual inject targets the first detected acclient.exe session. Reset Overlay Bar signals all running RynthCore clients via the dispatch file."
TextWrapping="Wrap"

View file

@ -153,7 +153,11 @@ internal partial class MainWindow : Window
_updateTimer.Tick += async (_, _) => await CheckForUpdatesAsync();
_updateTimer.Start();
_ = CheckForUpdatesAsync();
Opened += async (_, _) => await AskAboutUsageStatsOnceAsync();
Opened += async (_, _) =>
{
await AskAboutUsageStatsOnceAsync();
await CleanUpDecalBridgeIfUnusedAsync(atStartup: true);
};
}
private void WireEvents()
@ -179,6 +183,7 @@ internal partial class MainWindow : Window
RefreshSessionsButton.Click += (_, _) => RefreshSessionState();
ResetOverlayBarButton.Click += (_, _) => ResetOverlayBar();
CheckDecalBridgeButton.Click += async (_, _) => await CheckDecalBridgeAsync();
RepairDecalButton.Click += async (_, _) => await RepairDecalAsync();
AddPluginDllButton.Click += async (_, _) => await AddPluginDllAsync();
CheckUpdatesButton.Click += async (_, _) => await CheckForUpdatesAsync();
UpdateCardActionButton.Click += async (_, _) => await OnUpdateCardActionAsync();
@ -775,7 +780,7 @@ internal partial class MainWindow : Window
_settings.SelectedAccountProfileId = _settings.AccountProfiles.FirstOrDefault()?.Id ?? string.Empty;
SaveSettings();
if (removed.InjectionMode == InjectionMode.DecalBridge)
UnregisterDecalBridgeIfUnused();
_ = CleanUpDecalBridgeIfUnusedAsync(atStartup: false);
RefreshLists();
AccountProfilesList.SelectedIndex = Math.Min(index, _settings.AccountProfiles.Count - 1);
RefreshSummary();
@ -1077,9 +1082,8 @@ internal partial class MainWindow : Window
global::Avalonia.Controls.ToolTip.SetTip(bridgeItem,
"EXPERIMENTAL. Decal and RynthCore in the same client: Decal's plugins and RynthCore's " +
"in-game UI run side by side. RynthCore gets chat from Decal through the RynthCore Decal " +
"bridge, which this launcher adds to Decal's filter list before the launch: for your Windows " +
"user, or (when AC runs as administrator on this PC) once for all users after a Windows " +
"administrator prompt. Recovery Actions > Check Decal bridge shows whether it will load. Run one bot per client (VTank or the RynthAi macro, not both). To stop using it, " +
"bridge, which this launcher adds to Decal's filter list for all users when you pick this mode " +
"(once; Windows asks for administrator permission). Recovery Actions > Check Decal bridge shows whether it will load. Run one bot per client (VTank or the RynthAi macro, not both). To stop using it, " +
"set the account back to RynthCore or Decal: once no account uses it, the launcher takes the " +
"bridge out of Decal's list again (uninstalling RynthCore does too).");
@ -1111,45 +1115,126 @@ internal partial class MainWindow : Window
SaveSettings();
AppendActivity(mode == InjectionMode.DecalBridge
? $"{account.DisplayName}: injection method set to Decal + RynthCore (experimental). " +
"The Decal bridge is registered for your Windows user at this account's next launch."
"Adding the RynthCore Decal bridge to Decal's filter list for all users (once; Windows may ask for administrator permission)."
: $"{account.DisplayName}: injection method set to {mode}.");
if (wasBridge)
UnregisterDecalBridgeIfUnused();
if (mode == InjectionMode.DecalBridge)
_ = EnableDecalBridgeAsync();
else if (wasBridge)
_ = CleanUpDecalBridgeIfUnusedAsync(atStartup: false);
}
};
return dropdown;
}
// One Decal registry job at a time (start-up cleanup, a mode change, Repair Decal, a launch).
private readonly SemaphoreSlim _decalBridgeGate = new(1, 1);
/// <summary>
/// The last "Decal + RynthCore" account was switched to another mode: take the Decal bridge
/// out of Decal's filter list for this Windows user again (registration is opt-in and only
/// lasts while an account uses it). Running clients keep what they loaded; the next
/// "Decal + RynthCore" launch registers again.
/// No account uses "Decal + RynthCore" (at start, after a mode change or a deleted account):
/// take the RynthCore Decal bridge out of Decal's filter list again (registration is opt-in
/// and only lasts while an account uses it).
/// - Per-user (no prompt): our entry in a per-user copy of Decal's filter list, and a copy
/// an earlier RynthCore created (backed up first). Only when there is something to remove.
/// - Machine-wide, this install's entry only: asks first, then Windows' administrator prompt
/// (unless the launcher runs elevated). Only when the entry exists; at start, never again
/// after the player said "leave it" (<see cref="AppSettings.DecalFilterRemovalDeclined"/>).
/// Running clients keep what they loaded.
/// </summary>
private void UnregisterDecalBridgeIfUnused()
private async Task CleanUpDecalBridgeIfUnusedAsync(bool atStartup)
{
if (_settings.AccountProfiles.Any(a => a.InjectionMode == InjectionMode.DecalBridge))
return;
await _decalBridgeGate.WaitAsync();
try
{
DecalBridgeRegistration.Status status = DecalBridgeRegistration.GetStatus();
if (status.RegisteredMachineWide)
AppendActivity("No account uses Decal + RynthCore any more. The Decal bridge's entry for all users stays (removing it needs administrator rights; uninstalling RynthCore removes it). " +
"It stays idle in Decal clients without RynthCore.");
if (!status.RegisteredPerUser)
if (_settings.AccountProfiles.Any(a => a.InjectionMode == InjectionMode.DecalBridge))
return;
bool ok = DecalBridgeRegistration.Unregister(out string report);
LauncherDiag.Info($"DECALBRIDGE: no Decal + RynthCore account left - unregister: {report}");
AppendActivity(ok
? $"No account uses Decal + RynthCore any more - Decal bridge removed from Decal's filter list. {report}"
: $"No account uses Decal + RynthCore any more, but removing the Decal bridge did not finish: {report}");
if (DecalBridgeRegistration.PerUserCleanupNeeded())
{
bool ok = DecalBridgeRegistration.Unregister(out string report);
LauncherDiag.Info($"DECALBRIDGE: no Decal + RynthCore account - per-user cleanup: {report}");
AppendActivity(ok
? $"No account uses Decal + RynthCore - Decal bridge taken out of your per-user Decal settings: {report}"
: $"No account uses Decal + RynthCore, but taking the Decal bridge out of your per-user Decal settings did not finish: {report}");
}
string dir = DecalBridgeRegistration.DefaultBridgeDirectory;
if (!DecalBridgeRegistration.MachineEntryIsOurs(dir))
return;
if (atStartup && _settings.DecalFilterRemovalDeclined)
{
LauncherDiag.Info("DECALBRIDGE: no Decal + RynthCore account, machine-wide entry left (the player chose to keep it); not asking at start.");
return;
}
var outcome = DecalBridgeRegistration.UnregisterMachineWide(out string mReport, dir);
LauncherDiag.Info($"DECALBRIDGE: no Decal + RynthCore account - unregister machine-wide: {outcome}: {mReport}");
if (outcome == DecalBridgeRegistration.Outcome.NeedsAdmin)
{
bool yes = await DecalBridgeDialog.AskAsync(this,
"Decal + RynthCore is not in use",
"No account uses Decal + RynthCore any more, but the RynthCore Decal bridge is still in Decal's plugin list for all users on this PC. " +
"It does nothing without RynthCore, but you can take it out now. Windows will ask for administrator permission.\n\n" +
"If you leave it, the launcher won't ask again when it starts. Uninstalling RynthCore also takes it out.",
"Take it out (asks for administrator)", "Leave it");
if (!yes)
{
RememberDecalFilterRemovalDeclined(true);
AppendActivity("No account uses Decal + RynthCore. The Decal bridge stays in Decal's list for all users (idle without RynthCore); the launcher won't ask again at start.");
return;
}
string? self = Environment.ProcessPath;
if (self == null)
{
AppendActivity("Decal bridge: can't find the launcher's own exe for the administrator step.");
return;
}
outcome = DecalBridgeRegistration.RunElevated(self, $"--decal-bridge-unregister-machine \"{dir}\"", out mReport);
LauncherDiag.Info($"DECALBRIDGE: elevated unregister machine-wide: {outcome}: {mReport}");
if (outcome == DecalBridgeRegistration.Outcome.NeedsAdmin)
{
RememberDecalFilterRemovalDeclined(true);
AppendActivity("Decal bridge: not taken out (cancelled at the Windows administrator prompt). It stays idle without RynthCore; the launcher won't ask again at start.");
return;
}
}
if (outcome == DecalBridgeRegistration.Outcome.Registered && !DecalBridgeRegistration.MachineEntryIsOurs(dir))
{
RememberDecalFilterRemovalDeclined(false);
AppendActivity("No account uses Decal + RynthCore any more - the Decal bridge is out of Decal's list for all users.");
}
else
{
AppendActivity($"No account uses Decal + RynthCore, but taking the Decal bridge out of Decal's list for all users did not finish: {mReport}");
}
}
catch (Exception ex)
{
LauncherDiag.Info($"DECALBRIDGE: unregister failed ({ex.GetType().Name}: {ex.Message})");
LauncherDiag.Info($"DECALBRIDGE: cleanup failed ({ex.GetType().Name}: {ex.Message})");
AppendActivity($"Removing the Decal bridge failed: {ex.Message}");
}
finally
{
_decalBridgeGate.Release();
}
}
private void RememberDecalFilterRemovalDeclined(bool declined)
{
if (_settings.DecalFilterRemovalDeclined == declined)
return;
_settings.DecalFilterRemovalDeclined = declined;
SaveSettings();
}
/// <summary>An account was just set to Decal + RynthCore: register now (the one prompt, if needed).</summary>
private async Task EnableDecalBridgeAsync()
{
bool ok = await EnsureDecalBridgeAsync(DecalBridgeAcClientPath, interactive: true);
if (ok)
AppendActivity("Decal bridge ready: Decal + RynthCore accounts can launch.");
}
// ── Decal bridge: register where this PC's client reads, check, explain ─────────────
@ -1158,13 +1243,27 @@ internal partial class MainWindow : Window
DecalLocator.TryGetDecalAcClientPath() ?? AcClientPathTextBox.Text?.Trim() ?? string.Empty;
/// <summary>
/// Registers the Decal bridge where a client started now will read Decal's filter list
/// (DecalBridgeRegistration.RegisterForClients) and checks the result. When that place is
/// the machine-wide list (AC runs with administrator rights on this PC), asks first and runs
/// the one elevated step. False = a Decal + RynthCore client would not load the bridge.
/// Automatic launches never prompt: they log the reason and stay blocked.
/// Registers the Decal bridge in Decal's filter list for all users
/// (DecalBridgeRegistration.RegisterForClients) and checks the result. When this launcher may
/// not write that list, asks first and runs the one elevated step
/// (--decal-bridge-register-machine), then registers again to finish the per-user side. There
/// is no per-user fallback: declined or failed = Decal + RynthCore can't be used until it is
/// registered for all users. False = a Decal + RynthCore client would not load the bridge.
/// Only interactive callers (the player picked the mode, launched, or pressed Repair) prompt;
/// automatic launches log the reason and stay blocked.
/// </summary>
private async Task<bool> EnsureDecalBridgeAsync(string acClientPath, bool interactive)
{
await _decalBridgeGate.WaitAsync();
try { return await EnsureDecalBridgeCoreAsync(acClientPath, interactive); }
finally { _decalBridgeGate.Release(); }
}
private const string DecalBridgeNotRegisteredText =
"Decal + RynthCore can't be used until the RynthCore Decal bridge is in Decal's list for all users. " +
"To add it, launch a Decal + RynthCore account (or use Recovery Actions > Check Decal bridge > Repair) and say yes to Windows' administrator prompt.";
private async Task<bool> EnsureDecalBridgeCoreAsync(string acClientPath, bool interactive)
{
string dir = DecalBridgeRegistration.DefaultBridgeDirectory;
var outcome = DecalBridgeRegistration.RegisterForClients(dir, acClientPath, EngineJsonStore.Path, out string report, out DecalBridgeCheck.Result? check);
@ -1173,6 +1272,7 @@ internal partial class MainWindow : Window
LauncherDiag.Info($"DECALBRIDGE: check after register:{Environment.NewLine}{check.ToReport()}");
if (outcome == DecalBridgeRegistration.Outcome.Registered)
{
RememberDecalFilterRemovalDeclined(false);
AppendActivity(report);
return true;
}
@ -1181,34 +1281,48 @@ internal partial class MainWindow : Window
{
AppendActivity(report);
if (!interactive)
{
AppendActivity(DecalBridgeNotRegisteredText);
return false;
}
bool yes = await DecalBridgeDialog.AskAsync(this,
"Decal + RynthCore: one administrator step",
"On this PC, Asheron's Call reads Decal's plugin list for all users, not just for you" +
(check != null && check.ClientReason.Length > 0 ? $" ({check.ClientReason})" : "") + ".\n\n" +
"RynthCore has to add its Decal bridge to that list once, so Decal loads it next to your other Decal plugins. " +
"Windows will now ask for administrator permission. Nothing else changes; switching every account away from " +
"Decal + RynthCore, or uninstalling RynthCore, takes the entry out again.",
"Decal + RynthCore needs the RynthCore Decal bridge in Decal's plugin list for all users on this PC, " +
"so Decal loads it next to your other Decal plugins (it does nothing in clients without RynthCore).\n\n" +
"Adding it needs administrator permission once; Windows will ask now. Nothing else in Decal changes. " +
"Switching every account away from Decal + RynthCore, or uninstalling RynthCore, takes the entry out again.",
"Add it (asks for administrator)", "Cancel");
if (!yes)
{
AppendActivity("Decal bridge: the administrator step was cancelled.");
AppendActivity("Decal bridge: not added (cancelled). " + DecalBridgeNotRegisteredText);
return false;
}
string? self = Environment.ProcessPath;
if (self == null)
{
AppendActivity("Decal bridge: can't find the launcher's own exe for the administrator step.");
AppendActivity("Decal bridge: can't find the launcher's own exe for the administrator step. " + DecalBridgeNotRegisteredText);
return false;
}
var elevated = DecalBridgeRegistration.RunElevated(self, $"--decal-bridge-register-machine \"{dir}\"", out string eReport);
LauncherDiag.Info($"DECALBRIDGE: elevated register: {elevated}: {eReport}");
if (elevated != DecalBridgeRegistration.Outcome.Registered)
{
AppendActivity($"Decal bridge: not added ({eReport}) " + DecalBridgeNotRegisteredText);
return false;
}
AppendActivity("Decal bridge: " + eReport);
check = RealDecalCheckHost.Check(dir, acClientPath, EngineJsonStore.Path);
LauncherDiag.Info($"DECALBRIDGE: check after the administrator step:{Environment.NewLine}{check.ToReport()}");
AppendActivity(check.Summary);
if (!check.Blocking)
// Again, without rights: the machine-wide entry is there now, so this only finishes the
// per-user side and checks.
outcome = DecalBridgeRegistration.RegisterForClients(dir, acClientPath, EngineJsonStore.Path, out report, out check);
LauncherDiag.Info($"DECALBRIDGE: register after the administrator step: {outcome}: {report}");
if (check != null)
LauncherDiag.Info($"DECALBRIDGE: check after the administrator step:{Environment.NewLine}{check.ToReport()}");
AppendActivity(report);
if (outcome == DecalBridgeRegistration.Outcome.Registered)
{
RememberDecalFilterRemovalDeclined(false);
return true;
}
}
else
{
@ -1220,6 +1334,68 @@ internal partial class MainWindow : Window
return false;
}
/// <summary>
/// Recovery Actions > Repair Decal: Decal is reading an old per-user copy of its settings
/// (Windows' UAC virtualization; made by an earlier RynthCore or by Decal itself), which hides
/// plugins and filters installed for all users since. Asks, backs the copy up to a .reg file in
/// %APPDATA%\RynthCore, removes it, re-registers the bridge for all users when an account uses
/// Decal + RynthCore, and reports what it did.
/// </summary>
private async Task RepairDecalAsync()
{
DecalBridgeRegistration.RepairResult result;
await _decalBridgeGate.WaitAsync();
try
{
List<string> keys = DecalBridgeRegistration.FindVirtualStoreDecalKeys();
LauncherDiag.Info($"DECALBRIDGE: Repair Decal: per-user copies found: {(keys.Count == 0 ? "none" : string.Join(", ", keys))}");
if (keys.Count == 0)
{
AppendActivity("Repair Decal: nothing to repair - Decal has no per-user copy of its settings and already reads the settings for all users.");
await DecalBridgeDialog.InfoAsync(this, "Repair Decal",
"Nothing to repair: Decal has no per-user copy of its settings, so it already sees every installed plugin.");
return;
}
bool yes = await DecalBridgeDialog.AskAsync(this, "Repair Decal",
"Decal is reading an old per-user copy of its settings; this removes it so Decal sees all installed plugins. A backup is saved first.\n\n" +
"Close every Asheron's Call client first. Settings you changed in Decal while that copy was in use go back to the ones for all users " +
"(the backup has them).\n\nWill be removed:\n" + string.Join("\n", keys),
"Back up and remove", "Cancel");
if (!yes)
{
AppendActivity("Repair Decal: cancelled; nothing changed.");
return;
}
result = DecalBridgeRegistration.RepairDecal();
LauncherDiag.Info($"DECALBRIDGE: Repair Decal: ok={result.Ok}: {result.Report}");
AppendActivity("Repair Decal: " + result.Report);
}
catch (Exception ex)
{
LauncherDiag.Info($"DECALBRIDGE: Repair Decal failed ({ex.GetType().Name}: {ex.Message})");
AppendActivity($"Repair Decal failed: {ex.Message}");
return;
}
finally
{
_decalBridgeGate.Release();
}
string bridgeLine = string.Empty;
if (result.Removed.Count > 0 && _settings.AccountProfiles.Any(a => a.InjectionMode == InjectionMode.DecalBridge))
{
bool ok = await EnsureDecalBridgeAsync(DecalBridgeAcClientPath, interactive: true);
bridgeLine = ok
? "\n\nThe RynthCore Decal bridge is registered for all users again (an account uses Decal + RynthCore)."
: "\n\nThe RynthCore Decal bridge is NOT registered for all users (see the Activity tab); Decal + RynthCore can't be used until it is.";
}
string text = result.Ok
? "Done. Removed:\n" + string.Join("\n", result.Removed) + $"\n\nBackup: {result.BackupPath}\n(double-click it to put the keys back)"
: "Repair Decal did not finish. " + result.Report;
text += bridgeLine;
await DecalBridgeDialog.InfoAsync(this, "Repair Decal", text);
}
/// <summary>Recovery Actions > Check Decal bridge: the read-only check, with a Repair button when it fails.</summary>
private async Task CheckDecalBridgeAsync()
{

View file

@ -10,32 +10,39 @@ internal static class Program
public static int Main(string[] args)
{
// The uninstaller removes the Decal bridge registration (docs/DECAL_BRIDGE_PLAN.md):
// no window, just the per-user registry entries this launcher added.
// no window. Per-user: our entry in a per-user copy of Decal's filter list, and a copy an
// earlier RynthCore created (backed up to %APPDATA%\RynthCore\decal-backup-<date>.reg first;
// kept, with the reason logged, when it holds entries that aren't ours or in HKLM).
if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-unregister", StringComparison.OrdinalIgnoreCase)))
{
bool ok = RynthCore.App.DecalBridgeRegistration.Unregister(out string report);
LauncherDiag.Info($"DECALBRIDGE: unregister (command line): {report}");
// A machine-wide entry (added with administrator rights when AC runs elevated on this
// PC) goes too: the uninstaller removes the DLL it points at. Ask for the rights only
// when there is one.
if (RynthCore.App.DecalBridgeRegistration.MachineEntryIsOurs())
// The machine-wide entry for THIS install goes too: the uninstaller removes the DLL it
// points at. Ask for the rights only when there is one (another install's entry stays).
string dir = RynthCore.App.DecalBridgeRegistration.DefaultBridgeDirectory;
if (RynthCore.App.DecalBridgeRegistration.MachineEntryIsOurs(dir))
{
var outcome = RynthCore.App.DecalBridgeRegistration.UnregisterMachineWide(out string mReport);
var outcome = RynthCore.App.DecalBridgeRegistration.UnregisterMachineWide(out string mReport, dir);
if (outcome == RynthCore.App.DecalBridgeRegistration.Outcome.NeedsAdmin && Environment.ProcessPath is string self)
outcome = RynthCore.App.DecalBridgeRegistration.RunElevated(self, "--decal-bridge-unregister-machine", out mReport);
outcome = RynthCore.App.DecalBridgeRegistration.RunElevated(self, $"--decal-bridge-unregister-machine \"{dir}\"", out mReport);
LauncherDiag.Info($"DECALBRIDGE: unregister machine-wide (command line): {mReport}");
ok &= outcome == RynthCore.App.DecalBridgeRegistration.Outcome.Registered;
}
return ok ? 0 : 1;
}
if (Array.Exists(args, a => string.Equals(a, "--decal-bridge-unregister-machine", StringComparison.OrdinalIgnoreCase)))
// --decal-bridge-unregister-machine ["<bridge folder>"]: the elevated step of the above and
// of the launcher's "no account uses Decal + RynthCore any more". With a folder, only an
// entry for that folder (or a dangling one) is removed.
int um = Array.FindIndex(args, a => string.Equals(a, "--decal-bridge-unregister-machine", StringComparison.OrdinalIgnoreCase));
if (um >= 0)
{
var outcome = RynthCore.App.DecalBridgeRegistration.UnregisterMachineWide(out string report);
string? onlyFor = um + 1 < args.Length && !args[um + 1].StartsWith("--", StringComparison.Ordinal) ? args[um + 1] : null;
var outcome = RynthCore.App.DecalBridgeRegistration.UnregisterMachineWide(out string report, onlyFor);
LauncherDiag.Info($"DECALBRIDGE: unregister machine-wide (elevated step): {report}");
return outcome == RynthCore.App.DecalBridgeRegistration.Outcome.Registered ? 0 : 1;
}
// The launcher's elevated step for "AC reads Decal's filter list for all users"
// (MainWindow.EnsureDecalBridgeAsync): --decal-bridge-register-machine "<bridge folder>".
// The launcher's (and the installer's) elevated step: the bridge into Decal's filter list
// for all users (MainWindow.EnsureDecalBridgeAsync): --decal-bridge-register-machine "<bridge folder>".
int rm = Array.FindIndex(args, a => string.Equals(a, "--decal-bridge-register-machine", StringComparison.OrdinalIgnoreCase));
if (rm >= 0)
{
@ -44,8 +51,10 @@ internal static class Program
LauncherDiag.Info($"DECALBRIDGE: register machine-wide (elevated step): {report}");
return outcome == RynthCore.App.DecalBridgeRegistration.Outcome.Registered ? 0 : 1;
}
// The installer's per-user half (installer\RynthCore.iss, as the installing user, every
// install and update): our entry into an EXISTING per-user copy of Decal's filter list.
// The installer's per-user half (installer\RynthCore.iss, as the installing user, on install
// and update, only for a user with a Decal + RynthCore account): an earlier RynthCore's
// per-user copy of Decal's filter list removed (after a backup), our entry into a per-user
// copy that exists anyway. Never creates one.
int iu = Array.FindIndex(args, a => string.Equals(a, "--decal-bridge-install-user", StringComparison.OrdinalIgnoreCase));
if (iu >= 0)
{

View file

@ -25,6 +25,8 @@
<PackageReference Include="Avalonia.Desktop" Version="11.2.3" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.3" />
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.2.3" />
<!-- Avalonia pulls Tmds.DBus.Protocol 0.20.0 (GHSA-xrw6-gwf8-vvr9; D-Bus is Linux-only, but pin the fixed version). -->
<PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" />
</ItemGroup>
<ItemGroup>

View file

@ -34,6 +34,12 @@ internal sealed class AppSettings
/// True once the launcher has explained usage statistics and asked (shown once).
public bool UsageStatsAsked { get; set; }
/// The player said "leave it" (or no at Windows' prompt) when the launcher offered to take
/// the RynthCore Decal bridge out of Decal's list for all users because no account uses
/// Decal + RynthCore any more. The launcher then doesn't ask again at start (switching the
/// last account away still asks). Cleared when the bridge is registered again.
public bool DecalFilterRemovalDeclined { get; set; }
/// When true, the launcher kills any RynthCore-mode acclient.exe it
/// launched that hasn't reached IsLoggedIn within
/// <see cref="StuckClientTimeoutSeconds"/>. Catches stuck char-select,

View file

@ -179,15 +179,15 @@ internal static class DecalBridgeCheck
}
/// <summary>
/// What the installer (and every update) writes, so a client finds the bridge whatever
/// its rights (installer\RynthCore.iss: <see cref="DecalBridgeRegistration.RegisterMachineWide"/>
/// Where a registration goes (the launcher's, and the installer's for a user with a
/// Decal + RynthCore account: installer\RynthCore.iss, <see cref="DecalBridgeRegistration.RegisterMachineWide"/>
/// elevated, <see cref="DecalBridgeRegistration.InstallPerUser"/> as the installing user):
/// - Machine: always (when Decal is installed). Elevated and unvirtualized clients read
/// only HKLM; a virtualized client without a per-user copy reads HKLM too.
/// - PerUser: only into a per-user copy that ALREADY exists. A virtualized client then
/// reads that copy and nothing else, so the HKLM entry is hidden from it. Creating a
/// copy that doesn't exist would be harmful: it would hide every HKLM filter added later
/// (a Decal plugin installed for all users) from this user's non-elevated clients.
/// reads that copy and nothing else, so the HKLM entry is hidden from it. A copy is never
/// created: it would hide every HKLM filter added later (a Decal plugin installed for all
/// users) from this user's non-elevated clients. Repair Decal removes an existing one.
/// </summary>
public static (bool Machine, bool PerUser) PlanInstall(IDecalCheckHost host)
{
@ -262,7 +262,7 @@ internal static class DecalBridgeCheck
r.NeedsMachineWideRegistration = !where.PerUser;
r.Add(Level.Fail, $"Decal will not load the bridge: {entryProblem} in {whereText}." +
(where.PerUser
? " Repair (or a Decal + RynthCore launch) registers it for your Windows user."
? " Repair (or a Decal + RynthCore launch) adds it there and to the list for all users (Windows may ask for administrator permission once)."
: " That key is shared by all users: Repair adds it there once and Windows asks for administrator permission."));
}
@ -303,7 +303,7 @@ internal static class DecalBridgeCheck
List<string> hidden = HiddenMachineFilters(host, where.Path);
if (hidden.Count > 0)
r.Add(Level.Warn, "Hidden from AC by your per-user filter list (in HKLM, not in the copy): " + string.Join(", ", hidden) +
". If 'World Object Filter' is among them, VTank won't start.");
". If 'World Object Filter' is among them, VTank won't start. Recovery Actions > Repair Decal removes the per-user copy (after a backup).");
}
// 7. Decal's .NET surrogate: Decal must be able to create it, and must not have it disabled.

File diff suppressed because it is too large Load diff

View file

@ -257,6 +257,27 @@ internal sealed class RealRegistryView : IDisposable
return scope;
}
/// <summary>
/// UAC registry virtualization is on for this process right now (outside an
/// <see cref="Enter"/> scope, or when switching it off failed). An HKLM write would then
/// land in the per-user VirtualStore copy, which registration must never create.
/// Fails closed: true when the token can't be read.
/// </summary>
public static bool ProcessVirtualized()
{
try
{
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, out IntPtr token)) return true;
try
{
int on = 0;
return !GetTokenInformation(token, TokenVirtualizationEnabled, ref on, sizeof(int), out _) || on != 0;
}
finally { CloseHandle(token); }
}
catch { return true; }
}
public void Dispose()
{
if (_token == IntPtr.Zero) return;

View file

@ -32,8 +32,10 @@
// (0x0083E03C, CreateUIElementManager 0x0045F900) is not used, to ship no fixed
// address. No manager (tooltip hooks off or not found) = Unknown = fail open.
//
// Not confirmed in game yet: that the element under the mouse over open
// ground is the SmartBox wrapper itself rather than a child. `/rc acmouse`
// In game (2026-10-10 logs) the element under the mouse over open ground is
// NOT the wrapper but gmSmartBoxUI, element 0x1000049A, type 0x10000014
// (gmSmartBoxUI::Register 0x004D71E0; gmGamePlayUI's "<SBOX>"). Both types
// count as the world (AcMouseOverRules.IsWorldType). `/rc acmouse`
// (or `/rc acmouse watch` for 20 s of changes in chat) names what AC has
// under the cursor; Identify is the one place that decides.
//
@ -110,7 +112,7 @@ internal static unsafe class AcMouseOver
}
/// <summary>
/// The one decision: the 3D view is the SmartBox wrapper element (type 0x10000030);
/// The one decision: the 3D view is gmSmartBoxUI (type 0x10000014) or its SmartBox wrapper (0x10000030);
/// any other element AC reports is one of its windows; nothing readable is Unknown.
/// </summary>
private static AcMouseTarget Identify(bool readable, bool outside, IntPtr element, bool typeKnown, int type)

View file

@ -19,7 +19,7 @@ internal enum AcMouseTarget
Unknown,
/// <summary>AC reports nothing under the mouse (cursor outside the client, or no element took it).</summary>
Nothing,
/// <summary>The 3D view: AC's SmartBox wrapper element (UIElement type 0x10000030).</summary>
/// <summary>The 3D view: AC's gmSmartBoxUI panel (type 0x10000014) or its SmartBox wrapper (0x10000030).</summary>
World,
/// <summary>Any other AC element: a window (inventory, chat, radar, vitals, the selected-object bar...).</summary>
AcWindow,
@ -30,6 +30,19 @@ internal static class AcMouseOverRules
/// <summary>UIElement_SmartBoxWrapper::GetUIElementType (0x004E5E80) returns this; it is the 3D view.</summary>
public const int UIElementTypeSmartBoxWrapper = 0x10000030;
/// <summary>
/// gmSmartBoxUI::Register (0x004D71E0) registers this type: the game-play 3D view panel,
/// element 0x1000049A (gmGamePlayUI::SetupChildren 0x004EAB50; SaveScreenLayout 0x004EB9E0
/// writes its rect as "&lt;SBOX&gt;"). In game it is what AC reports under the cursor over open
/// ground (2026-10-10 client logs), not the wrapper: missing it here sent every plate's
/// click to AC.
/// </summary>
public const int UIElementTypeGmSmartBoxUI = 0x10000014;
/// <summary>One of the 3D view's element types.</summary>
public static bool IsWorldType(int elementType) =>
elementType == UIElementTypeSmartBoxWrapper || elementType == UIElementTypeGmSmartBoxUI;
/// <summary>
/// Classifies one read of UIElementManager. <paramref name="stateReadable"/>: the manager
/// was known and its fields readable. <paramref name="mouseOutside"/>: its +0x2D4 flag (the
@ -42,7 +55,7 @@ internal static class AcMouseOverRules
if (!stateReadable) return AcMouseTarget.Unknown;
if (mouseOutside || element == 0) return AcMouseTarget.Nothing;
if (!typeKnown) return AcMouseTarget.Unknown;
return elementType == UIElementTypeSmartBoxWrapper ? AcMouseTarget.World : AcMouseTarget.AcWindow;
return IsWorldType(elementType) ? AcMouseTarget.World : AcMouseTarget.AcWindow;
}
/// <summary>

View file

@ -203,9 +203,11 @@ internal static unsafe class ChatCommandDispatcher
if (StartsWithCmd(trimmed, "/tell "))
return DispatchTell(trimmed.Substring(6));
// /a message (allegiance channel broadcast)
// /a message (allegiance): AC's own chat command, like /f. Event_ChannelBroadcast(1)
// got "You do not have permission to talk in that channel" (2026-10-11): the server
// gives each allegiance its own Turbine chat room, which only AC's /a knows.
if (StartsWithCmd(trimmed, "/a "))
return DispatchChannelBroadcast(1, trimmed.Substring(3));
return DispatchRaw(trimmed);
// /f message (fellowship — no direct Event_*; use the raw chat path)
if (StartsWithCmd(trimmed, "/f "))

View file

@ -0,0 +1,169 @@
// ============================================================================
// RynthCore.Engine - Compatibility/IltDetect.cs
//
// Pure detection for Infinite Leaftide (ILT), the ACECustom server: no AC, no
// engine state, so the offline tests (tools/IltTests) compile this file as is.
// The stateful side (command line, announced world name, engine.json lists,
// the /rc ilt override) is IltInfo.cs.
//
// Signals, either one is enough:
// - the launch command line's -h host: game.infiniteleaftide.online, as the
// public AC server list (acresources/serverslist Servers.xml) gives it, or
// any other host under infiniteleaftide.online;
// - the world name the server announced at login: "InfiniteLeaftide" (the
// name UtilityBelt's Leaftide tools and SilentKelpie's ILT Hub check for),
// or anything with "Leaftide" in it.
// Both lists can be replaced in engine.json ("IltServerNames", "IltHosts").
//
// Unlike Aelrynth detection nothing here unlocks a server-side action that
// could hurt another server: a false positive only shows the ILT bar button,
// and the Bounties window's "/bounty list" gets "Unknown command" (after which
// RynthILT stops reading). So one signal is enough, and a dev copy on
// localhost counts when it announces an ILT world name.
// ============================================================================
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.Compatibility;
/// <summary>One ILT detection result. Immutable.</summary>
internal sealed class IltVerdict
{
public bool IsIlt { get; init; }
/// <summary>Plain-English why, for /rc ilt and the log.</summary>
public string Reason { get; init; } = "";
public static readonly IltVerdict Unknown = new() { Reason = "nothing known yet" };
}
internal static class IltDetect
{
/// <summary>World-name patterns used when engine.json has no "IltServerNames" ('*' = any run of characters, case-insensitive).</summary>
public static readonly string[] DefaultServerNames = { "InfiniteLeaftide", "*Leaftide*" };
/// <summary>Host names used when engine.json has no "IltHosts": the domain and every host under it ('*' allowed too).</summary>
public static readonly string[] DefaultHosts = { "infiniteleaftide.online" };
/// <summary>True when <paramref name="world"/> matches one of <paramref name="patterns"/>.</summary>
public static bool WorldNameMatches(string? world, IEnumerable<string>? patterns, out string matched)
{
matched = "";
if (string.IsNullOrWhiteSpace(world) || patterns == null) return false;
string w = world.Trim();
foreach (string p in patterns)
{
if (string.IsNullOrWhiteSpace(p)) continue;
if (!Matches(w, p.Trim())) continue;
matched = p.Trim();
return true;
}
return false;
}
/// <summary>
/// True when <paramref name="host"/> is one of <paramref name="patterns"/>: the same name, a
/// host under it ("game.infiniteleaftide.online" for "infiniteleaftide.online"), or a '*'
/// pattern match. An IP address matches only itself. Case and a trailing dot are ignored.
/// </summary>
public static bool HostMatches(string? host, IEnumerable<string>? patterns, out string matched)
{
matched = "";
if (string.IsNullOrWhiteSpace(host) || patterns == null) return false;
string h = host.Trim().TrimEnd('.').ToLowerInvariant();
foreach (string raw in patterns)
{
if (string.IsNullOrWhiteSpace(raw)) continue;
string p = raw.Trim().TrimEnd('.').ToLowerInvariant();
bool hit = p.Contains('*')
? Matches(h, p)
: h == p || (!IsIpv4(p) && h.EndsWith("." + p, StringComparison.Ordinal));
if (!hit) continue;
matched = raw.Trim();
return true;
}
return false;
}
/// <summary>
/// Combines the signals: ILT when the launch host or the announced world name matches.
/// Null lists mean the defaults; an empty list turns that signal off.
/// </summary>
public static IltVerdict Decide(string? host, string? announcedWorld,
IReadOnlyList<string>? serverNames, IReadOnlyList<string>? hosts)
{
IReadOnlyList<string> names = serverNames ?? DefaultServerNames;
IReadOnlyList<string> hostList = hosts ?? DefaultHosts;
string where = host is { Length: > 0 } ? host : "no host on the command line";
string world = announcedWorld is { Length: > 0 } ? $"world \"{announcedWorld}\"" : "no world name yet";
bool byHost = HostMatches(host, hostList, out string hostHit);
bool byWorld = WorldNameMatches(announcedWorld, names, out string worldHit);
if (byHost && byWorld)
return new IltVerdict { IsIlt = true, Reason = $"Infinite Leaftide: {where} matches \"{hostHit}\" and {world} matches \"{worldHit}\"" };
if (byHost)
return new IltVerdict { IsIlt = true, Reason = $"Infinite Leaftide: {where} matches \"{hostHit}\" ({world})" };
if (byWorld)
return new IltVerdict { IsIlt = true, Reason = $"Infinite Leaftide: {world} matches \"{worldHit}\" (host {where})" };
return new IltVerdict { Reason = $"not Infinite Leaftide: {where}, {world}" };
}
/// <summary>Case-insensitive match where '*' stands for any run of characters (anywhere in the pattern).</summary>
public static bool Matches(string text, string pattern)
{
if (pattern.Length == 0) return false;
if (!pattern.Contains('*')) return text.Equals(pattern, StringComparison.OrdinalIgnoreCase);
string[] parts = pattern.Split('*');
int pos = 0;
for (int i = 0; i < parts.Length; i++)
{
string part = parts[i];
if (part.Length == 0) continue;
if (i == 0)
{
if (!text.StartsWith(part, StringComparison.OrdinalIgnoreCase)) return false;
pos = part.Length;
continue;
}
if (i == parts.Length - 1)
return text.Length - pos >= part.Length && text.EndsWith(part, StringComparison.OrdinalIgnoreCase);
int at = text.IndexOf(part, pos, StringComparison.OrdinalIgnoreCase);
if (at < 0) return false;
pos = at + part.Length;
}
return true;
}
/// <summary>"InfiniteLeaftide, *Leaftide*" → trimmed, de-duplicated list (case-insensitive). Null for null.</summary>
public static List<string>? ParseList(IEnumerable<string?>? items)
{
if (items == null) return null;
var list = new List<string>();
foreach (string? raw in items)
{
if (string.IsNullOrWhiteSpace(raw)) continue;
foreach (string piece in raw.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries))
{
string p = piece.Trim();
if (p.Length == 0) continue;
bool dup = false;
foreach (string have in list)
if (have.Equals(p, StringComparison.OrdinalIgnoreCase)) { dup = true; break; }
if (!dup) list.Add(p);
}
}
return list;
}
private static bool IsIpv4(string s)
{
int dots = 0;
foreach (char c in s)
{
if (c == '.') dots++;
else if (c < '0' || c > '9') return false;
}
return dots == 3;
}
}

View file

@ -0,0 +1,103 @@
// ============================================================================
// RynthCore.Engine - Compatibility/IltInfo.cs
//
// Is this client on Infinite Leaftide (ILT, the ACECustom server)? IltInfo.IsIlt
// is the one flag the ILT section checks (the bar's ILT button, /rc bounties,
// the Bounties window's reads through the RynthILT plugin).
//
// Signals (combined by IltDetect.Decide, IltDetect.cs):
// - the launch command line's -h host (ServerInfo reads it once);
// - the world name the server announced at login (AccountHooks);
// - the engine.json lists "IltServerNames" / "IltHosts" replace the
// defaults (InfiniteLeaftide / *Leaftide* and infiniteleaftide.online).
// Unknown means not ILT. "/rc ilt on|off|auto" overrides it for this session
// (testing), never saved.
//
// Threads: any. Re-evaluated at most once a second; each read in between is a
// volatile load and a compare. Never touches AC.
// ============================================================================
using System;
using System.Threading;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static class IltInfo
{
public enum Mode { Auto, ForceIlt, ForceOther }
private const int RefreshMs = 1000;
private static volatile IltVerdict _verdict = IltVerdict.Unknown;
private static long _nextRefreshMs;
private static int _mode; // Mode
private static volatile bool _lastIlt;
/// <summary>True when the client is on Infinite Leaftide - or the override says so. Any thread.</summary>
public static bool IsIlt => Current.IsIlt;
public static Mode Override
{
get => (Mode)Volatile.Read(ref _mode);
set
{
Volatile.Write(ref _mode, (int)value);
Volatile.Write(ref _nextRefreshMs, 0);
}
}
/// <summary>The current verdict (re-evaluated at most once a second). Any thread.</summary>
public static IltVerdict Current
{
get
{
long now = Environment.TickCount64;
if (now >= Volatile.Read(ref _nextRefreshMs))
{
Volatile.Write(ref _nextRefreshMs, now + RefreshMs);
Refresh();
}
return _verdict;
}
}
/// <summary>The lists in force, for /rc ilt.</summary>
public static string ListsDescription
{
get
{
var names = EngineSettings.IltServerNames;
var hosts = EngineSettings.IltHosts;
return $"world names {(names == null ? "default " + string.Join(", ", IltDetect.DefaultServerNames) : "engine.json " + Join(names))}; "
+ $"hosts {(hosts == null ? "default " + string.Join(", ", IltDetect.DefaultHosts) : "engine.json " + Join(hosts))}";
}
}
private static string Join(System.Collections.Generic.IReadOnlyList<string> list)
=> list.Count == 0 ? "(none)" : string.Join(", ", list);
private static void Refresh()
{
try
{
IltVerdict v = Override switch
{
Mode.ForceIlt => new IltVerdict { IsIlt = true, Reason = "forced on with /rc ilt on (testing)" },
Mode.ForceOther => new IltVerdict { Reason = "forced off with /rc ilt off (testing)" },
_ => IltDetect.Decide(ServerInfo.LaunchHost, AccountHooks.AnnouncedWorldName,
EngineSettings.IltServerNames, EngineSettings.IltHosts),
};
_verdict = v;
if (v.IsIlt != _lastIlt)
{
_lastIlt = v.IsIlt;
RynthLog.Compat($"IltInfo: {v.Reason}");
}
}
catch (Exception ex)
{
RynthLog.Compat($"IltInfo: refresh failed - {ex.GetType().Name}: {ex.Message}");
}
}
}

View file

@ -0,0 +1,143 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Rewrites acclient's signed "pointer % 4" padding (<see cref="LargeAddressAlignmentScan"/>)
/// to <c>and r, 3</c> in memory, so pack/unpack of buffers above 2 GB pads 0..3 bytes like
/// it does below 2 GB. Without it, a large-address-aware client corrupts dat and network
/// unpacks whenever the heap hands AC a buffer above 0x80000000 (long open-world sessions).
///
/// The patch is never undone: an unloading engine generation leaves it in place and the next
/// generation finds every site already patched. acclient.exe on disk is not touched.
/// </summary>
internal static class LargeAddressAlignmentPatch
{
private const uint PAGE_EXECUTE_READWRITE = 0x40;
private const ushort ImageDosSignature = 0x5A4D;
private const uint ImageNtSignature = 0x00004550;
private const int SectionHeaderSize = 40;
private static string _statusMessage = "Not applied yet.";
public static string StatusMessage => _statusMessage;
/// <summary>Sites rewritten by this engine generation.</summary>
public static int PatchedCount { get; private set; }
/// <summary>Sites a previous engine generation had already rewritten.</summary>
public static int AlreadyPatchedCount { get; private set; }
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FlushInstructionCache(IntPtr hProcess, IntPtr lpBaseAddress, UIntPtr dwSize);
public static void Initialize()
{
if (!Plugins.EngineSettings.EnableLargeAddressAlignmentFix)
{
_statusMessage = "Disabled via engine.json (EnableLargeAddressAlignmentFix=false).";
RynthLog.Info($"Compat: large-address alignment fix - {_statusMessage}");
return;
}
IntPtr moduleBase = GetModuleHandleW("acclient.exe");
if (moduleBase == IntPtr.Zero)
moduleBase = GetModuleHandleW(null);
if (moduleBase == IntPtr.Zero || !TryGetTextSection(moduleBase, out int textRva, out int textSize))
{
_statusMessage = "acclient .text section not found.";
RynthLog.Compat($"Compat: large-address alignment fix skipped - {_statusMessage}");
return;
}
IntPtr textBase = IntPtr.Add(moduleBase, textRva);
byte[] text = new byte[textSize];
Marshal.Copy(textBase, text, 0, textSize);
List<AlignmentSite> sites = LargeAddressAlignmentScan.Find(text, textBase.ToInt32());
int patched = 0, already = 0, failed = 0;
foreach (AlignmentSite site in sites)
{
if (site.AlreadyPatched)
{
already++;
continue;
}
if (TryWriteHighByte(new IntPtr(site.ImmHighByteVa)))
patched++;
else
failed++;
}
if (patched > 0)
FlushInstructionCache(GetCurrentProcess(), textBase, (UIntPtr)(uint)textSize);
PatchedCount = patched;
AlreadyPatchedCount = already;
_statusMessage = $"{patched} site(s) patched, {already} already patched, {failed} failed ({sites.Count} found).";
if (sites.Count == 0 || failed > 0)
RynthLog.Compat($"Compat: large-address alignment fix - {_statusMessage}");
else
RynthLog.Info($"Compat: large-address alignment fix - {_statusMessage}");
}
// One byte, protection restored per site: other hooks may hold different protections on
// neighbouring .text pages, so the whole section is never flipped at once.
private static bool TryWriteHighByte(IntPtr address)
{
if (!VirtualProtect(address, (UIntPtr)1u, PAGE_EXECUTE_READWRITE, out uint oldProtect))
{
RynthLog.Compat($"Compat: large-address alignment fix - VirtualProtect 0x{address.ToInt32():X8} failed (error {Marshal.GetLastWin32Error()}).");
return false;
}
try
{
// Re-check the live byte: the scan worked on a copy.
if (Marshal.ReadByte(address) != LargeAddressAlignmentScan.StockHighByte)
return false;
Marshal.WriteByte(address, LargeAddressAlignmentScan.PatchedHighByte);
return true;
}
finally
{
VirtualProtect(address, (UIntPtr)1u, oldProtect, out _);
}
}
private static bool TryGetTextSection(IntPtr moduleBase, out int rva, out int size)
{
rva = 0;
size = 0;
if ((ushort)Marshal.ReadInt16(moduleBase) != ImageDosSignature)
return false;
int peOffset = Marshal.ReadInt32(moduleBase, 0x3C);
IntPtr nt = IntPtr.Add(moduleBase, peOffset);
if (peOffset <= 0 || (uint)Marshal.ReadInt32(nt) != ImageNtSignature)
return false;
int sectionCount = (ushort)Marshal.ReadInt16(nt, 6);
int optionalHeaderSize = (ushort)Marshal.ReadInt16(nt, 20);
IntPtr section = IntPtr.Add(nt, 24 + optionalHeaderSize);
for (int i = 0; i < sectionCount; i++, section = IntPtr.Add(section, SectionHeaderSize))
{
if (Marshal.PtrToStringAnsi(section, 8).TrimEnd('\0') != ".text")
continue;
size = Marshal.ReadInt32(section, 8);
rva = Marshal.ReadInt32(section, 12);
return size > 0 && rva > 0;
}
return false;
}
}

View file

@ -0,0 +1,107 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.Compatibility;
/// <summary>One signed "pointer % 4" padding site in acclient's code.</summary>
/// <param name="AndVa">VA of the <c>and r32, imm32</c> instruction.</param>
/// <param name="ImmHighByteVa">VA of the immediate's top byte (0x80 stock, 0x00 once patched).</param>
/// <param name="Register">x86 register number (0 = eax ... 7 = edi).</param>
/// <param name="AlreadyPatched">True when the immediate is already 0x00000003.</param>
internal readonly record struct AlignmentSite(int AndVa, int ImmHighByteVa, int Register, bool AlreadyPatched);
/// <summary>
/// Finds AC's 4-byte pack/unpack padding code, which MSVC compiled from a signed
/// <c>(int)ptr % 4</c>:
/// <code>
/// and r, 0x80000003 ; keep the sign bit
/// ... (0-12 bytes, no flag writes)
/// jns +5
/// dec r / or r, -4 / inc r ; negative remainder fix-up
/// [pop r32]
/// je skip ; remainder 0: already aligned
/// ... pad 4 - r bytes
/// </code>
/// With large-address-aware acclient a buffer above 2 GB is a negative int, the remainder
/// comes out -3..-1, and AC pads 4 - r = 5..7 bytes instead of 1..3: the cursor runs 4 bytes
/// past the field, zeroes live data and parses garbage counts (kelpie's motion-table crashes).
/// Clearing the immediate's sign bit (<c>and r, 3</c>) makes the remainder 0..3 at any address.
/// Requiring the trailing <c>je</c> limits the patch to padding code: a signed modulo of a value
/// that can really be negative is left alone.
/// </summary>
internal static class LargeAddressAlignmentScan
{
private const byte StockImmHighByte = 0x80;
private const byte PatchedImmHighByte = 0x00;
// and r32, imm32 to the jns: MSVC interleaves at most a few movs; the largest gap in
// the retail client is 5 bytes.
private const int MaxGapBeforeJns = 12;
/// <summary>Scans <paramref name="text"/> (the bytes of .text, which starts at
/// <paramref name="textVa"/>) for stock and already-patched padding sites.</summary>
public static List<AlignmentSite> Find(ReadOnlySpan<byte> text, int textVa)
{
var sites = new List<AlignmentSite>();
// Leave room for the longest match: 6 (and) + 12 (gap) + 7 (fix-up) + 1 (pop) + 2 (je).
int last = text.Length - 28;
for (int i = 0; i < last; i++)
{
int reg, immOffset;
if (text[i] == 0x25)
{
reg = 0; // and eax, imm32 (short form)
immOffset = 1;
}
else if (text[i] == 0x81 && (text[i + 1] & 0xF8) == 0xE0)
{
reg = text[i + 1] & 0x07; // and r32, imm32 (81 /4, mod=11)
immOffset = 2;
}
else
{
continue;
}
if (text[i + immOffset] != 0x03 || text[i + immOffset + 1] != 0x00 || text[i + immOffset + 2] != 0x00)
continue;
byte high = text[i + immOffset + 3];
if (high != StockImmHighByte && high != PatchedImmHighByte)
continue;
int andEnd = i + immOffset + 4;
if (!HasSignedFixupThenJe(text, andEnd, reg))
continue;
sites.Add(new AlignmentSite(textVa + i, textVa + i + immOffset + 3, reg, high == PatchedImmHighByte));
}
return sites;
}
/// <summary>The immediate's top byte value a site must hold before it is patched.</summary>
public static byte StockHighByte => StockImmHighByte;
/// <summary>The immediate's top byte value after the patch (<c>and r, 3</c>).</summary>
public static byte PatchedHighByte => PatchedImmHighByte;
// jns +5 ; dec r ; or r, 0xFC ; inc r ; [pop r32] ; je rel8|rel32
private static bool HasSignedFixupThenJe(ReadOnlySpan<byte> text, int from, int reg)
{
for (int k = from; k <= from + MaxGapBeforeJns; k++)
{
if (text[k] != 0x79 || text[k + 1] != 0x05 ||
text[k + 2] != 0x48 + reg ||
text[k + 3] != 0x83 || text[k + 4] != 0xC8 + reg || text[k + 5] != 0xFC ||
text[k + 6] != 0x40 + reg)
{
continue;
}
int m = k + 7;
if (text[m] >= 0x58 && text[m] <= 0x5F)
m++;
return text[m] == 0x74 || (text[m] == 0x0F && text[m + 1] == 0x84);
}
return false;
}
}

View file

@ -27,6 +27,9 @@ namespace RynthCore.Engine.Compatibility;
/// <item><c>/rc ui retailvitals [on|off|status]</c> — hide AC's own
/// health/stamina/mana bars (<see cref="RetailVitalsHooks"/>; saved for the
/// PC, also in Settings &gt; UI). Alone it reports the state.</item>
/// <item><c>/rc ui barsize [0-10|+|-|status]</c> - the RynthCore bar's size (its own text
/// size step, <see cref="UI.PanelTextScale"/>; saved for the PC, also in Settings &gt;
/// Display). Alone it reports the size.</item>
/// <item><c>/rc vendor [list|info|status|buy &lt;id|sel&gt; [n]|sell &lt;id|sel&gt; [id ...]]</c>
/// — read / trade with the open vendor through the engine's vendor
/// primitives (<see cref="VendorTrade"/>); a manual test hook for the
@ -34,6 +37,10 @@ namespace RynthCore.Engine.Compatibility;
/// <item><c>/rc chathold [on|off|status]</c> — incoming chat waits for the plugins'
/// verdict before AC prints it, so a line a plugin eats is kept out of AC's chat
/// window too (<see cref="ChatCallbackHooks"/>). On at every start; not saved.</item>
/// <item><c>/rc discord [on|off|status|window|test [route]|resume [route]]</c> — RynthChat's
/// Discord relay (<see cref="UI.Data.Discord.ChatDiscord"/>): switch it on or off for the
/// character you're playing (off for every character by default), list the routes,
/// post a test line, clear a pause; window opens its panel (Chat &gt; gear &gt; Discord).</item>
/// <item><c>/rv plates</c> (aliases <c>/rv nameplates</c>, <c>/rc plates</c>) — the
/// RynthVision nameplates and combat text: monster plates on|off, self, debuffs,
/// numbers, gains [on|off] (with their sub-switches), all on|off, all|engaged,
@ -70,6 +77,9 @@ namespace RynthCore.Engine.Compatibility;
/// the last minutes of client/server messages and engine markers) to
/// Logs\flight-&lt;pid&gt;-&lt;time&gt;.txt; <c>/rc flightdump auto &lt;reason&gt;</c> is the rate-limited
/// automatic form. <c>/rc flight [status|mark &lt;text&gt;|on|off|auto on|off]</c>.</item>
/// <item><c>/rc report [text]</c> - "Report a problem" (<see cref="Report.ProblemReport"/>): alone it
/// opens the panel; with text it sends that report now, with the recent log attached
/// (the panel is where the log can be left out). One report a minute.</item>
/// </list>
/// </summary>
internal static class RynthCoreChatCommands
@ -142,6 +152,14 @@ internal static class RynthCoreChatCommands
return true;
}
// /rc discord [on|off|status|window|test [route]|resume [route]] : RynthChat's Discord relay
if (IsVerb(sub, "discord", out string discordArgs))
{
try { HandleDiscordCommand(discordArgs); }
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc discord failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
// /rc plates [on|off|all|engaged|dist N|max N|scale X|opacity X|lift X|names|hp|level|weak|distance|fade|reset|status]
if (IsVerb(sub, "plates", out string platesArgs) || IsVerb(sub, "nameplates", out platesArgs))
{
@ -158,6 +176,14 @@ internal static class RynthCoreChatCommands
return true;
}
// /rc ilt [auto|on|off] : is this Infinite Leaftide (the ILT section), with a testing override
if (IsVerb(sub, "ilt", out string iltArgs))
{
try { HandleIltCommand(iltArgs); }
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc ilt failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
// /rc mastery : the Aelrynth mastery feed's state, and ask the server again
if (IsVerb(sub, "mastery", out _))
{
@ -228,6 +254,18 @@ internal static class RynthCoreChatCommands
return true;
}
// /rc report [text] : Report a problem - alone it opens the panel; with text it sends now (with the log)
if (IsVerb(sub, "report", out string reportArgs))
{
try
{
foreach (string l in Report.ProblemReport.HandleCommand(reportArgs))
Reply(l);
}
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc report failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
// /rc flight [status|mark <text>|on|off|auto on|off] : the flight recorder
if (IsVerb(sub, "flight", out string flightArgs))
{
@ -299,6 +337,19 @@ internal static class RynthCoreChatCommands
UI.PanelRouter.Toggle(ImGuiBackend.Panels.ItemCountFace.Title);
return true;
case "bounties":
case "bounty":
case "bountys":
// The ImGui Bounties panel (ILT section: ACECustom bounties, the RynthILT plugin's
// tracker), like the ILT bar button. Only on Infinite Leaftide with RynthILT installed.
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.BountiesFace.Title))
Reply("The Bounties panel isn't available (the RynthILT plugin isn't installed, or the ImGui layer is off).");
else if (!IltInfo.IsIlt && !ImGuiBackend.ImGuiPanelHost.IsOpen(ImGuiBackend.Panels.BountiesFace.Title))
Reply("Bounties are an Infinite Leaftide feature, and this isn't Infinite Leaftide (/rc ilt for why).");
else
UI.PanelRouter.Toggle(ImGuiBackend.Panels.BountiesFace.Title);
return true;
case "remote":
case "miniremote":
// The ImGui Mini Remote panel (open/close), like its bar button.
@ -383,6 +434,29 @@ internal static class RynthCoreChatCommands
return;
}
// /rc ui barsize [0-10|+|-|status]: the bar's size. Alone it reports it.
if (parts[0].Equals("barsize", StringComparison.OrdinalIgnoreCase))
{
int cur = UI.PanelTextScale.GetChrome();
if (parts.Length >= 2 && !parts[1].Equals("status", StringComparison.OrdinalIgnoreCase))
{
int next;
// Bare + / -: one step. +n / -n: that many steps. Plain n: that size.
if (parts[1] == "+") next = cur + 1;
else if (parts[1] == "-") next = cur - 1;
else if (!int.TryParse(parts[1], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out next))
{
Reply("Usage: /rc ui barsize [0-10|+|-|status]");
return;
}
else if (parts[1][0] is '+' or '-')
next += cur;
UI.PanelTextScale.SetChrome(next);
}
Reply("Bar size: " + UI.PanelTextScale.Describe(UI.PanelTextScale.GetChrome()) + ".");
return;
}
// /rc ui open|close|popout|redock|snap <Panel>: drive a panel by name (tests,
// dispatch.txt). Names may have spaces ("Monster Detail").
string verb = parts[0].ToLowerInvariant();
@ -415,7 +489,7 @@ internal static class RynthCoreChatCommands
if (parts.Length != 2 || !UI.PanelFaceStore.TryParseFace(parts[1], out UI.PanelFace face))
{
Reply("Usage: /rc ui list | /rc ui <Panel|bar> avalonia|imgui|both | /rc ui open|close|popout|redock|snap <Panel> | /rc ui retailvitals [on|off]");
Reply("Usage: /rc ui list | /rc ui <Panel|bar> avalonia|imgui|both | /rc ui open|close|popout|redock|snap <Panel> | /rc ui retailvitals [on|off] | /rc ui barsize [0-10|+|-|status]");
return;
}
@ -519,6 +593,32 @@ internal static class RynthCoreChatCommands
Reply($"Titles (plugin API v75): {CharacterTitles.Describe()}.");
}
/// <summary>
/// /rc ilt: the Infinite Leaftide verdict, its signals and the lists in force. "on" /
/// "off" force it for this session (testing the ILT section anywhere); "auto" goes back
/// to detecting. Never saved; the lists are engine.json's IltServerNames / IltHosts.
/// </summary>
private static void HandleIltCommand(string args)
{
switch (args.Trim().ToLowerInvariant())
{
case "on": case "ilt": IltInfo.Override = IltInfo.Mode.ForceIlt; break;
case "off": case "other": IltInfo.Override = IltInfo.Mode.ForceOther; break;
case "auto": IltInfo.Override = IltInfo.Mode.Auto; break;
case "": break;
default:
Reply("Usage: /rc ilt [auto|on|off]");
return;
}
IltVerdict v = IltInfo.Current;
Reply($"ILT: {(v.IsIlt ? "Infinite Leaftide" : "not Infinite Leaftide")} - {v.Reason}.");
Reply($"Signals: host {ServerInfo.HostDescription}; world name {AccountHooks.AnnouncedWorldName ?? "(not announced)"}; "
+ $"override {IltInfo.Override}. Lists: {IltInfo.ListsDescription}.");
Reply(ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.BountiesFace.Title)
? "RynthILT: installed (Bounties: the ILT bar button or /rc bounties)."
: "RynthILT: not installed, so there is no ILT section.");
}
private static void HandleMasteryCommand()
{
if (!ServerInfo.IsAelrynth)
@ -737,6 +837,7 @@ internal static class RynthCoreChatCommands
break;
case "players":
S.PlayerNames = Flag(value, S.PlayerNames); break;
case "playerbars": S.PlayerBars = Flag(value, S.PlayerBars); break;
case "names": S.ShowNames = Flag(value, S.ShowNames); break;
case "hp": S.ShowHpNumbers = Flag(value, S.ShowHpNumbers); break;
case "level": S.ShowLevel = Flag(value, S.ShowLevel); break;
@ -805,6 +906,28 @@ internal static class RynthCoreChatCommands
private static bool Flag(string? value, bool current) =>
value?.ToLowerInvariant() switch { "on" or "1" or "true" => true, "off" or "0" or "false" => false, _ => !current };
/// <summary>
/// /rc discord: the relay's switch, status, test and resume (UI.Data.Discord.ChatDiscord);
/// "window" opens its panel, like Chat > gear > Discord settings.
/// </summary>
private static void HandleDiscordCommand(string args)
{
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.ChatDiscordFace.Title))
{
Reply("The Discord relay needs the RynthChat plugin.");
return;
}
string verb = args.Trim();
if (verb.Equals("window", StringComparison.OrdinalIgnoreCase) || verb.Equals("show", StringComparison.OrdinalIgnoreCase)
|| verb.Equals("settings", StringComparison.OrdinalIgnoreCase))
{
UI.PanelRouter.Toggle(ImGuiBackend.Panels.ChatDiscordFace.Title);
return;
}
foreach (string line in UI.Data.Discord.ChatDiscord.HandleCommand(verb))
Reply(line);
}
private static void Reply(string text)
{
RynthLog.Compat($"RynthCoreChatCommands: {text}");

View file

@ -84,6 +84,16 @@ internal static class ServerInfo
}
}
/// <summary>The connect host from the command line, lower case ("" when none). Any thread (IltInfo).</summary>
public static string LaunchHost
{
get
{
ReadHostOnce();
return _host;
}
}
private static void Refresh()
{
try

View file

@ -62,6 +62,10 @@ internal static class EngineLifecycle
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
private static long _lastSignalReloadMs;
/// <summary>Environment.TickCount64 of this engine's last SignalReload (0 = none).</summary>
internal static long LastSignalReloadMs => Interlocked.Read(ref _lastSignalReloadMs);
internal static bool IsShuttingDown => Volatile.Read(ref _shuttingDown) != 0;
internal static bool HasShutDown => Volatile.Read(ref _hasShutDown) != 0;
@ -72,6 +76,9 @@ internal static class EngineLifecycle
/// </summary>
public static bool SignalReload()
{
// Every caller is a player's request (RL, ERl, /rc rl): the reload cap's chat notice
// answers those each time (EntryPoint.ReloadCapped).
Interlocked.Exchange(ref _lastSignalReloadMs, Environment.TickCount64);
IntPtr hEvent = OpenEventW(EVENT_MODIFY_STATE, false, ReloadEventName);
if (hEvent == IntPtr.Zero)
{
@ -174,8 +181,12 @@ internal static class EngineLifecycle
// The chat log is written on the tick pump (UiDataHub), now stopped. Left open,
// it outlived this generation and locked the next one out of the file.
Step("ChatModel.CloseLog", () => UI.Data.ChatModel.CloseLog());
// Discord posts still in flight would finish in this dying generation's code.
Step("ChatDiscord.Shutdown", () => UI.Data.Discord.ChatDiscord.Shutdown());
Step("ServerMessageStream.Shutdown", () => Net.ServerMessageStream.Shutdown());
Step("FlightRecorder.Shutdown", () => Net.FlightRecorder.Shutdown());
// A report still being sent: cancel it and dispose its HttpClient (nothing may outlive this generation).
Step("ProblemReport.Shutdown", () => Report.ProblemReport.Shutdown());
Step("PluginManager.ShutdownAll (defensive)", () => PluginManager.ShutdownAll());

View file

@ -84,6 +84,42 @@ public static class EntryPoint
return 0;
}
/// <summary>
/// The reload cap (ReloadCapNotice): the loader asks this before every hot reload, and
/// refuses the reload once this client has done that many. engine.json MaxHotReloads,
/// default 3; negative = no cap. Loader thread.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthCoreMaxHotReloads")]
public static int MaxHotReloads()
{
try { return EngineSettings.MaxHotReloads; }
catch { return ReloadCapNotice.DefaultMaxHotReloads; }
}
private static readonly ReloadCapNotice s_reloadCapNotice = new();
/// <summary>
/// The loader refused a hot reload because this client has done <paramref name="reloads"/>
/// of them (the cap is <paramref name="cap"/>). The client stays on this engine. Logs it,
/// and says so in chat once, and again when the player asked for the reload by hand.
/// Loader thread.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthCoreReloadCapped")]
public static uint ReloadCapped(int reloads, int cap)
{
try
{
bool byHand = ReloadCapNotice.IsRecentManualSignal(EngineLifecycle.LastSignalReloadMs, Environment.TickCount64);
RynthLog.Warn(ReloadCapNotice.LogText(reloads, cap, byHand));
bool chat;
lock (s_reloadCapNotice) chat = s_reloadCapNotice.ShouldChat(byHand);
if (chat)
Compatibility.AcMainThreadQueue.EnqueueWriteToChat(ReloadCapNotice.ChatText(reloads), 2);
}
catch { }
return 0;
}
[UnmanagedCallersOnly(EntryPoint = "RynthCoreShutdown")]
public static uint Shutdown(IntPtr lpParam)
{
@ -195,6 +231,9 @@ public static class EntryPoint
RynthLog.Info("Early-init: could not resolve engine directory — minhook may not be preloaded before MultiClientHooks.");
RunInitStep("early multi-client hooks", MultiClientHooks.Initialize);
// Before AC's main thread resumes, so no dat or network unpack runs the stock
// signed padding; a hot reload finds every site already patched.
RunInitStep("large-address alignment fix", LargeAddressAlignmentPatch.Initialize);
// DatFileShareHooks force-shares AC's data files at the CreateFile
// layer so we can coexist with Decal-injected clients that other
// launchers (Thwargle etc.) have already opened against the same
@ -941,6 +980,9 @@ public static class EntryPoint
{
UI.Data.ChatModel.EnsureSettingsLoaded();
UI.Data.ChatModel.InstallInput();
// Discord relay settings (file read here, not on AC's thread); a relay left
// on keeps the chat feed running with the Chat panel closed.
UI.Data.Discord.ChatDiscord.EnsureLoaded();
}
// ImGui faces for panels docked in the client (UI.PanelRouter
// picks the face). Registered even while the ImGui layer is off,
@ -951,10 +993,15 @@ public static class EntryPoint
ImGuiBackend.Panels.VisionFace.Register();
if (HasPluginDll("RynthCore.Plugin.RynthNav.dll"))
ImGuiBackend.Panels.RynthNavFace.Register();
// The ILT section (Infinite Leaftide): its faces exist only with RynthILT
// installed, and the bar's ILT button shows them only on ILT (IltInfo).
if (HasPluginDll("RynthCore.Plugin.RynthILT.dll"))
ImGuiBackend.Panels.BountiesFace.Register();
if (HasPluginDll("RynthCore.Plugin.RynthChat.dll"))
{
ImGuiBackend.Panels.ChatFace.Register();
ImGuiBackend.Panels.ChatFiltersFace.Register();
ImGuiBackend.Panels.ChatDiscordFace.Register();
}
ImGuiBackend.Panels.RadarFace.Register();
ImGuiBackend.Panels.SettingsFace.Register();

View file

@ -8,11 +8,17 @@
// an unknown panel shows its first letter), reload (RL) and pop out.
// Dragging the grip moves the bar; the position is the shared bar= row in
// panel_state.txt. Right-click a panel button (or the grip for the bar
// itself) to choose which face shows it docked. Pop out moves the ImGui bar
// itself) to choose which face shows it docked; the grip's menu also has the
// bar's size and "Report a problem". Pop out moves the ImGui bar
// into its own window (ImGuiPopOuts, sized to its content; dock back
// returns it); a bar whose face is Avalonia/Both still pops out as the
// Avalonia bar.
//
// The bar's size is its own text size step (PanelTextScale chrome row): the bar's
// fonts come from that baked set and its metrics scale by the step's factor. Set it
// from the grip's right-click menu, Ctrl+wheel over the bar, Settings > Display or
// /rc ui barsize.
//
// Face key "__bar" in panel_faces.txt; code default Avalonia. While the ImGui
// bar shows, the docked Avalonia bar is hidden and takes no clicks
// (AvaloniaOverlay.DockedBarSuppressed). AC thread except where noted.
@ -23,6 +29,7 @@ using System.Collections.Generic;
using System.Numerics;
using System.Threading;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.ScriptWindows;
@ -48,6 +55,11 @@ internal static class ImGuiBar
private static readonly string[] ImGuiOnlyBarPanels =
{ Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.ItemCountFace.Title, Panels.MiniRemoteFace.Title };
// The ILT section: the RynthILT plugin's ImGui-only panels. They never get buttons of their
// own; one ILT button stands for them, shown only on Infinite Leaftide (IltInfo.IsIlt) and
// only for the ones registered (EntryPoint registers them when RynthILT is installed).
private static readonly string[] IltPanels = { Panels.BountiesFace.Title };
// Known panels' icons (DrakBot's where the same window exists); others show their first letter.
private static readonly Dictionary<string, string> PanelIcons = new(StringComparer.OrdinalIgnoreCase)
{
@ -87,10 +99,26 @@ internal static class ImGuiBar
// Square buttons, logical px (x the DPI scale).
private const float ButtonSize = 20f, ButtonGap = 3f;
/// <summary>
/// The bar's text size step (the nearest one already baked) and its scale factor. The one
/// place either is worked out, so the bar's fonts and its metrics always agree.
/// </summary>
private static int ChromeStep(out float factor)
{
int step = ImGuiFonts.BakedStepNear(PanelTextScale.GetChrome());
factor = PanelTextScale.Factor(step);
return step;
}
private static ButtonInfo[]? _buttons;
private static string _tooltip = "";
private static bool _placed;
private static Vector2 _pos, _persistedPos;
// What may write a new position to the bar= row: the user dragging the grip, or the bar being
// pulled back on screen by a size change (a few frames: the window grows a frame late). A clamp
// from a smaller AC window leaves the saved position alone.
private static bool _userMoved;
private static int _lastStep, _sizeWatch;
private const string PopOutTitle = "__bar";
// Popped out (the ImGui bar in its own window). Read from panel_state once,
@ -173,12 +201,15 @@ internal static class ImGuiBar
private static void DrawPopped(float s, Vector2 display)
{
EnsureButtons();
int step = ChromeStep(out float factor);
s *= factor;
float place = AvaloniaOverlay.InputScale > 0 ? AvaloniaOverlay.InputScale : 1f;
ImGuiNET.ImGui.SetNextWindowPos(ImGuiPopOuts.PanelOrigin, ImGuiCond.Always);
PushBarWindowStyle(s);
ImGuiNET.ImGui.Begin("##rc_bar", BarFlags);
try
{
ImGuiFonts.CurrentStep = step;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
DrawContent(s, place, popped: true);
ImGuiNET.ImGui.PopFont();
@ -189,6 +220,7 @@ internal static class ImGuiBar
}
finally
{
ImGuiFonts.CurrentStep = 0;
ImGuiNET.ImGui.End();
PopBarWindowStyle();
}
@ -218,6 +250,8 @@ internal static class ImGuiBar
public static void Draw(float s)
{
EnsureButtons();
int step = ChromeStep(out float factor);
s *= factor;
float place = AvaloniaOverlay.InputScale > 0 ? AvaloniaOverlay.InputScale : 1f;
bool both = ResolveFace() == PanelFace.Both;
@ -229,18 +263,23 @@ internal static class ImGuiBar
_pos = _persistedPos = logical * place;
ImGuiNET.ImGui.SetNextWindowPos(_pos, ImGuiCond.Always);
_placed = true;
_lastStep = step; // the size the bar loads at is the baseline, not a change
}
if (step != _lastStep) { _lastStep = step; _sizeWatch = 4; }
PushBarWindowStyle(s);
ImGuiNET.ImGui.Begin("##rc_bar", BarFlags);
try
{
ImGuiFonts.CurrentStep = step;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
DrawContent(s, place, popped: false);
ImGuiNET.ImGui.PopFont();
KeepOnScreen();
}
finally
{
ImGuiFonts.CurrentStep = 0;
_pos = ImGuiNET.ImGui.GetWindowPos();
ImGuiNET.ImGui.End();
PopBarWindowStyle();
@ -249,15 +288,35 @@ internal static class ImGuiBar
if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) && _pos != _persistedPos)
{
_persistedPos = _pos;
Vector2 logical = _pos / place - (both ? new Vector2(24, 24) : Vector2.Zero);
double left = logical.X, top = logical.Y;
UiBackgroundWriter.Enqueue("persist bar", () => PanelStateStore.SetBarPosition(left, top));
if (!both) AvaloniaOverlay.SyncDockedBarPosition(left, top);
if (_userMoved || _sizeWatch > 0)
{
Vector2 logical = _pos / place - (both ? new Vector2(24, 24) : Vector2.Zero);
double left = logical.X, top = logical.Y;
UiBackgroundWriter.Enqueue("persist bar", () => PanelStateStore.SetBarPosition(left, top));
if (!both) AvaloniaOverlay.SyncDockedBarPosition(left, top);
}
_userMoved = false;
}
if (_sizeWatch > 0) _sizeWatch--;
}
/// <summary>A bigger size can push the bar's right end off the screen: pull it back (not while it is being dragged).</summary>
private static void KeepOnScreen()
{
Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize;
if (display.X <= 1 || ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) return;
Vector2 pos = ImGuiNET.ImGui.GetWindowPos();
Vector2 next = Vector2.Clamp(pos, Vector2.Zero, Vector2.Max(Vector2.Zero, display - ImGuiNET.ImGui.GetWindowSize()));
if (next != pos) ImGuiNET.ImGui.SetWindowPos(next);
}
private static void DrawContent(float s, float place, bool popped)
{
// Ctrl+wheel over the bar steps its size (the panels' title bars do the same).
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
if (io.KeyCtrl && io.MouseWheel != 0f && ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem))
PanelTextScale.SetChrome(PanelTextScale.GetChrome() + (io.MouseWheel > 0f ? 1 : -1));
var square = new Vector2(ButtonSize, ButtonSize) * s;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Ui14);
@ -280,12 +339,13 @@ internal static class ImGuiBar
if (display.X > 1)
next = Vector2.Clamp(next, Vector2.Zero, Vector2.Max(Vector2.Zero, display - size));
ImGuiNET.ImGui.SetWindowPos(next);
_userMoved = true;
}
ImGuiNET.ImGui.SetItemTooltip(_tooltip);
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
ImGuiNET.ImGui.OpenPopup("##face_bar");
PhosphorIcons.DrawCentered(dl, iconFont, PhosphorIcons.DotsSixVertical, rcPos, new Vector2(square.X * 0.8f, square.Y), RynthTheme.RcLabel);
FacePopup("##face_bar", FaceKey, hasImGuiFace: true);
FacePopup("##face_bar", FaceKey, hasImGuiFace: true, s);
// Collapse: the bar folds to its grip and this caret.
bool collapsed = RynthAiDashboardState.BarCollapsed;
@ -314,6 +374,21 @@ internal static class ImGuiBar
FacePopup(b.PopupId, b.Title, ImGuiPanelHost.HasFace(b.Title));
}
// The ILT section: one button, only on Infinite Leaftide with RynthILT's panels
// registered. With one panel it toggles that panel; with more it opens a menu.
int iltCount = IltPanelCount();
if (iltCount > 0)
{
ImGuiNET.ImGui.SameLine();
string? only = iltCount == 1 ? FirstIltPanel() : null;
if (IconButton("##ilt", iconFont, PhosphorIcons.Leaf, square, RynthTheme.BarText))
{
if (only != null) PanelRouter.Toggle(only);
else ImGuiNET.ImGui.OpenPopup("##ilt_menu");
}
ImGuiNET.ImGui.SetItemTooltip(only != null ? "Infinite Leaftide: " + only : "Infinite Leaftide");
}
// Script windows (decision 2): one button with a menu, only while a ShowInBar
// script window exists. They never get buttons of their own (EnsureButtons
// lists OverlayHost's engine panels only; script windows are dynamic entries).
@ -352,6 +427,44 @@ internal static class ImGuiBar
// Drawn after the bar buttons' style is popped, so the menu has the normal look.
ScriptsMenu(scripts);
IltMenu();
}
/// <summary>The ILT panels the bar offers now: 0 off Infinite Leaftide or without RynthILT. AC thread.</summary>
private static int IltPanelCount()
{
int n = 0;
foreach (string title in IltPanels)
if (ImGuiPanelHost.HasFace(title)) n++;
return n > 0 && IltInfo.IsIlt ? n : 0;
}
private static string? FirstIltPanel()
{
foreach (string title in IltPanels)
if (ImGuiPanelHost.HasFace(title)) return title;
return null;
}
/// <summary>The ILT button's menu (two or more ILT panels): a checkbox item each for open.</summary>
private static void IltMenu()
{
if (!ImGuiNET.ImGui.BeginPopup("##ilt_menu")) return;
try
{
ImGuiNET.ImGui.TextDisabled("Infinite Leaftide");
foreach (string title in IltPanels)
{
if (!ImGuiPanelHost.HasFace(title)) continue;
bool open = ImGuiPanelHost.IsOpen(title);
if (ImGuiNET.ImGui.MenuItem(title, "", open))
PanelRouter.Toggle(title);
}
}
finally
{
ImGuiNET.ImGui.EndPopup();
}
}
/// <summary>
@ -394,7 +507,7 @@ internal static class ImGuiBar
return clicked;
}
private static void FacePopup(string popupId, string title, bool hasImGuiFace)
private static void FacePopup(string popupId, string title, bool hasImGuiFace, float s = 1f)
{
if (!ImGuiNET.ImGui.BeginPopup(popupId)) return;
ImGuiNET.ImGui.TextDisabled(title == FaceKey ? "Bar, docked, shows as" : "Docked, shows as");
@ -407,9 +520,59 @@ internal static class ImGuiBar
}
if (!hasImGuiFace)
ImGuiNET.ImGui.TextDisabled("(no ImGui version yet)");
if (title == FaceKey)
{
BarSizeRows(s);
ReportRow();
}
ImGuiNET.ImGui.EndPopup();
}
/// <summary>The bar's own popup: smaller / bigger, the current size, reset (the panels' text size popup, for the bar).</summary>
private static void BarSizeRows(float s)
{
int step = PanelTextScale.GetChrome();
int max = PanelTextScale.SizeNames.Length - 1;
float btn = ButtonSize * s;
ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Ui14);
uint text = ImGuiNET.ImGui.GetColorU32(ImGuiCol.Text);
ImGuiNET.ImGui.Separator();
ImGuiNET.ImGui.TextUnformatted("Bar size");
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero);
ImGuiNET.ImGui.BeginDisabled(step <= 0);
if (IconButton("##bs_smaller", iconFont, PhosphorIcons.Minus, new Vector2(btn, btn), text))
PanelTextScale.SetChrome(step - 1);
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SetItemTooltip("Smaller");
ImGuiNET.ImGui.SameLine(0, 4 * s);
ImGuiNET.ImGui.BeginDisabled(step >= max);
if (IconButton("##bs_bigger", iconFont, PhosphorIcons.Plus, new Vector2(btn, btn), text))
PanelTextScale.SetChrome(step + 1);
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SetItemTooltip("Bigger");
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.SameLine(0, 8 * s);
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextUnformatted(PanelTextScale.Describe(step));
ImGuiNET.ImGui.BeginDisabled(step == 0);
if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + " Reset"))
PanelTextScale.SetChrome(0);
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SetItemTooltip("Back to normal size");
}
/// <summary>The grip menu's "Report a problem" entry (Report/ProblemReport.cs).</summary>
private static void ReportRow()
{
if (!ImGuiPanelHost.HasFace(Panels.ReportFace.Title)) return;
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.Warning + " Report a problem..."))
Report.ProblemReport.OpenPanel();
ImGuiNET.ImGui.SetItemTooltip("Tell the staff what went wrong (also /rc report).");
}
private static void PushBarButtonStyle(float s)
{
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero);
@ -446,6 +609,6 @@ internal static class ImGuiBar
list.Add(new ButtonInfo(title, "##bar_" + title, "##face_" + title, icon, letter, title, ImGuiOnly: true));
}
_buttons = list.ToArray();
_tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar face.";
_tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar face and size. Ctrl+wheel over the bar: size.";
}
}

View file

@ -0,0 +1,30 @@
// ============================================================================
// RynthCore.Engine - ImGui/MonsterHud/CreatureSizes.cs
// How tall each kind of creature is, for the plates that hang above its head.
//
// The table (CreatureSizes.g.cs) is generated by tools/CreatureSizes from the ACE world database and
// client_portal.dat: weenie class id -> model height x default scale, in centimetres. A creature that is
// not in it (a custom weenie that was not exported, a model with no height) is unknown, and the HUD
// falls back to its estimate by creature type and name. Pure code; tools/CreatureSizesTests compiles it in.
// ============================================================================
using System;
namespace RynthCore.Engine.ImGuiBackend.Hud;
internal static partial class CreatureSizes
{
/// <summary>Creatures in the table.</summary>
public static int Count => Wcids.Length;
/// <summary>Metres from the creature's feet to the top of its model, for a weenie class id; false when the table has none.</summary>
public static bool TryGetTop(uint wcid, out float metres)
{
metres = 0f;
if (wcid > int.MaxValue) return false;
int i = Array.BinarySearch(Wcids, (int)wcid);
if (i < 0) return false;
metres = TopCm[i] / 100f;
return true;
}
}

File diff suppressed because it is too large Load diff

View file

@ -126,6 +126,10 @@ internal static class MonsterHud
/// <summary>RadarKind.Monster: a full monster plate. Npc / Vendor / Player: a name-only label.</summary>
public byte Kind = RadarKind.Monster;
public bool IsLabel => Kind != RadarKind.Monster;
/// <summary>A name label with a thin health bar under it (players, when "Player health bars" is on).</summary>
public bool WithBar;
public bool HpFresh; // the last health observation is recent enough to draw a bar from
public bool HasBar => WithBar && HpKnown && HpFresh;
public int Level; // 0 = unknown
public string LevelText = "";
public float HeadHeight = DefaultHeadHeight;
@ -177,6 +181,10 @@ internal static class MonsterHud
private sealed record WeakTag(string Label, uint Color, string Icon);
private const float DefaultHeadHeight = 2.0f;
// A player's health is only known from what the game happened to tell us; a reading older than this is not drawn.
private const long PlayerBarMemorySec = 90;
// A size from the table is the top of the model: a hand's width above it for the plate, within sane bounds.
private const float HeadMargin = 0.12f, MinKnownHeadHeight = 0.3f, MaxKnownHeadHeight = 120f;
private static readonly Dictionary<uint, Plate> Plates = new(64);
private static readonly List<Plate> DrawOrder = new(64);
private static readonly List<Plate> Placed = new(64);
@ -277,7 +285,7 @@ internal static class MonsterHud
bool monsters = MonsterHudSettings.Enabled;
bool trackMonsters = monsters || MonsterHudSettings.Numbers;
// Name-only labels over NPCs (and, if asked, players): their own switches and cap.
bool track = trackMonsters || MonsterHudSettings.NpcNames || MonsterHudSettings.PlayerNames;
bool track = trackMonsters || MonsterHudSettings.NpcNames || MonsterHudSettings.PlayerNames || MonsterHudSettings.PlayerBars;
if (!track) ClearPlates();
SetDamageSubscription(monsters && MonsterHudSettings.ShowWeakness);
if (monsters && MonsterHudSettings.ShowDebuffs) PortalSpellTable.EnsureLoadQueued();
@ -373,7 +381,8 @@ internal static class MonsterHud
float maxD2 = maxD * maxD;
float targetD2 = MathF.Max(maxD2, 100f * 100f); // the target keeps its plate a bit further out
bool engagedOnly = MonsterHudSettings.Filter == PlateFilter.Engaged && MonsterHudSettings.Enabled;
bool npcNames = MonsterHudSettings.NpcNames, playerNames = MonsterHudSettings.PlayerNames;
bool npcNames = MonsterHudSettings.NpcNames, playerBars = MonsterHudSettings.PlayerBars,
playerNames = MonsterHudSettings.PlayerNames || playerBars; // a bar comes with the name
float npcD = MonsterHudSettings.NpcMaxDistance;
float npcD2 = npcD * npcD;
float npcTargetD2 = MathF.Max(npcD2, 100f * 100f); // a selected NPC keeps its name further out too
@ -491,6 +500,7 @@ internal static class MonsterHud
byte cls = Classes.TryGetValue(id, out ObjClass oc) ? oc.Cls : ClsCreature;
byte kind = cls == ClsPlayer ? RadarKind.Player : cls == ClsVendor ? RadarKind.Vendor : RadarKind.Npc;
Plate plate = GetPlate(id, kind);
plate.WithBar = playerBars && kind == RadarKind.Player;
// Head height once per name; again while selected (selecting appraises: CreatureType may arrive).
if (name != plate.Name || isTarget)
{
@ -586,11 +596,16 @@ internal static class MonsterHud
/// <summary>
/// Metres from the feet to just above the head. The client's own model
/// height isn't read (its CPartArray/CSetup layout isn't mapped here), so
/// this goes by CreatureType from the appraisal cache, then by name, then
/// a humanoid default; "Height lift" in the settings corrects the rest.
/// this goes by the creature's weenie class id against the generated size
/// table (CreatureSizes: model height x scale), then CreatureType from the
/// appraisal cache, then by name, then a humanoid default; "Height lift"
/// in the settings corrects the rest.
/// </summary>
internal static float EstimateHeadHeight(uint id, string name)
{
if (ClientObjectHooks.TryGetObjectWcid(id, out uint wcid) && CreatureSizes.TryGetTop(wcid, out float top))
return Math.Clamp(top, MinKnownHeadHeight, MaxKnownHeadHeight) + HeadMargin;
if (AppraisalHooks.TryGetCachedIntProperty(id, 2, out int ct) && ct > 0 && ct < CreatureTypeHeights.Length &&
CreatureTypeHeights[ct] > 0)
return CreatureTypeHeights[ct];
@ -925,8 +940,8 @@ internal static class MonsterHud
// Appearing: start at the right size; visible: ease (target pop, distance).
p.Scale = wasVisible ? p.Scale + (scaleTarget - p.Scale) * kScale : scaleTarget;
// ── Health (monster plates only) ──
if (!label) UpdateHealth(p, f.Now, kBar, dt);
// ── Health (monster plates, and player labels with a bar) ──
if (!label || p.WithBar) UpdateHealth(p, f.Now, kBar, dt);
if (!show && p.Alpha < 0.01f)
{
@ -979,6 +994,7 @@ internal static class MonsterHud
if (MonsterHudData.TryGetHealth(p.Id, out HealthObservation h))
{
p.HpKnown = true;
p.HpFresh = (now - h.Ticks) < PlayerBarMemorySec * Stopwatch.Frequency;
p.Ratio = h.Ratio;
uint max = h.Max;
if (ObjectQualityCache.TryGetCreatureVitals(p.Id, out CreatureVitals v) && v.MaxHealth > 0)
@ -990,6 +1006,7 @@ internal static class MonsterHud
{
// Never observed: an untouched monster is at full health in practice.
p.HpKnown = false;
p.HpFresh = false;
p.Ratio = 1f;
p.HpMax = ObjectQualityCache.TryGetCreatureVitals(p.Id, out CreatureVitals v) ? v.MaxHealth : 0;
p.HpCur = p.HpMax;
@ -1043,10 +1060,20 @@ internal static class MonsterHud
p.NameFont = ImGuiFonts.Sharp(p.NameSize, bold: true);
p.NameW = TextWidth(p.NameFont, p.NameSize, p.Name);
p.BadgeW = 0f;
p.BarW = p.BarH = 0f;
p.IconSize = 0f;
p.BelowBar = p.IsTarget ? 9f * k : 3f * k; // the target pointer hangs under the name
p.Width = p.NameW + 8f * k;
if (p.HasBar)
{
// A thin bar under the name, at least the name's width.
p.BarW = MathF.Round(MathF.Max(p.NameW, 64f * k));
p.BarH = MathF.Max(3f, MathF.Round(4f * k));
}
else
{
p.BarW = p.BarH = 0f;
}
float barRow = p.BarH > 0f ? p.BarH + MathF.Round(2f * k) : 0f;
p.BelowBar = (p.IsTarget ? 9f * k : 3f * k) + barRow; // the target pointer hangs under the name (and bar)
p.Width = MathF.Max(p.NameW, p.BarW) + 8f * k;
p.Height = p.NameSize + 2f * k + p.BelowBar;
return;
}
@ -1329,6 +1356,16 @@ internal static class MonsterHud
float x = MathF.Round(cx - p.NameW * 0.5f);
float pointerTop = baseY + 2f * k;
if (p.BarH > 0f)
{
// The player's health under the name.
float barTop = MathF.Round(baseY + 2f * k);
float barL = MathF.Round(cx - p.BarW * 0.5f);
PaintBar(dl, new Vector2(barL, barTop), new Vector2(barL + p.BarW, barTop + p.BarH), MathF.Max(1f, 1.5f * k), a,
p.ShownRatio, p.TrailRatio, HealthColor(p.Ratio), ticks: false);
pointerTop = barTop + p.BarH + 2f * k;
}
if (p.Nudge > 10f * uiScale)
dl.AddLine(new Vector2(cx, pointerTop - 1), new Vector2(cx, p.Anchor.Y - 2f * k), Mul(Leader, a), 1f);

View file

@ -56,6 +56,8 @@ internal static class MonsterHudSettings
public static float NpcMaxDistance = 30f; // yards; short so a town isn't a wall of text
public static int MaxNpcLabels = 15;
public static bool PlayerNames = false;
/// <summary>A health bar under other players' names, for those whose health the client has been told (selected, fellowship).</summary>
public static bool PlayerBars = false;
// Debuff icons on the monster plates (PlateDebuffs).
public static bool ShowDebuffs = true;
@ -196,6 +198,7 @@ internal static class MonsterHudSettings
MaxNpcLabels = Math.Clamp(nm, MinNpcLabels, MaxNpcLabelsLimit);
break;
case "playerNames": PlayerNames = val == "1"; break;
case "playerBars": PlayerBars = val == "1"; break;
case "showDebuffs": ShowDebuffs = val == "1"; break;
case "showOthersDebuff": ShowOthersDebuff = val == "1"; break;
case "selfPlate": SelfPlate = val == "1"; break;
@ -277,6 +280,7 @@ internal static class MonsterHudSettings
sw.WriteLine(FormattableString.Invariant($"npcDistance={NpcMaxDistance:0.#}"));
sw.WriteLine(FormattableString.Invariant($"npcMax={MaxNpcLabels}"));
sw.WriteLine($"playerNames={B(PlayerNames)}");
sw.WriteLine($"playerBars={B(PlayerBars)}");
sw.WriteLine($"showDebuffs={B(ShowDebuffs)}");
sw.WriteLine($"showOthersDebuff={B(ShowOthersDebuff)}");
sw.WriteLine($"selfPlate={B(SelfPlate)}");
@ -322,7 +326,7 @@ internal static class MonsterHudSettings
ShowNames = true; ShowHpNumbers = true; ShowDistance = false; ShowLevel = true; ShowWeakness = true;
FadeWithDistance = true; Scale = 1.0f; Opacity = 0.9f; HeightLift = 0f; ClickToSelect = true;
ShowDebuffs = true; ShowOthersDebuff = true;
NpcNames = true; NpcMaxDistance = 30f; MaxNpcLabels = 15; PlayerNames = false;
NpcNames = true; NpcMaxDistance = 30f; MaxNpcLabels = 15; PlayerNames = false; PlayerBars = false;
SelfPlate = true; SelfNumbers = false; SelfName = false; SelfHideFirstPerson = true;
SelfPlacement = SelfPlacement.Fixed; SelfLocked = true; SelfFixedX = DefaultSelfFixedX; SelfFixedY = DefaultSelfFixedY;
Numbers = true; NumDealt = true; NumTaken = true; NumHeals = true; NumKills = true;
@ -359,7 +363,7 @@ internal static class MonsterHudSettings
public static void SetAll(bool on)
{
Enabled = on; ShowDebuffs = on; SelfPlate = on; Numbers = on; Gains = on; NpcNames = on;
if (!on) PlayerNames = false; // "all on" leaves player names as chosen (off by default)
if (!on) { PlayerNames = false; PlayerBars = false; } // "all on" leaves player names and bars as chosen (off by default)
}
/// <summary>One line for chat: the current state.</summary>
@ -368,7 +372,7 @@ internal static class MonsterHudSettings
$"{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)}); " +
$"NPC names {OnOff(NpcNames)} ({NpcMaxDistance:0}yd, max {MaxNpcLabels}), player names {OnOff(PlayerNames)}; " +
$"NPC names {OnOff(NpcNames)} ({NpcMaxDistance:0}yd, max {MaxNpcLabels}), player names {OnOff(PlayerNames)} (bars {OnOff(PlayerBars)}); " +
$"self {OnOff(SelfPlate)} ({(SelfPlacement == SelfPlacement.Fixed ? "fixed on screen, " + (SelfLocked ? "locked" : "unlocked") : "follows you, " + SelfPosition.ToString().ToLowerInvariant())}, " +
$"numbers {OnOff(SelfNumbers)}, name {OnOff(SelfName)}, hide in first person {OnOff(SelfHideFirstPerson)}); " +
$"combat text {OnOff(Numbers)} (dealt {OnOff(NumDealt)}, taken {OnOff(NumTaken)}, heals {OnOff(NumHeals)}, kills {OnOff(NumKills)}); " +

View file

@ -87,6 +87,9 @@ internal static class MonsterHudSettingsUi
"Text size of the names over NPCs and vendors (1.00x = the default). Names have no bar.");
changed |= Toggle("Player names", ref MonsterHudSettings.PlayerNames,
"The name over other players too (blue), within the same distance and count. Chat: /rv plates players.");
changed |= Toggle("Player health bars", ref MonsterHudSettings.PlayerBars,
"A health bar under other players' names (and their name, even with Player names off). The game only tells you a player's health " +
"once you select them or they share it (fellowship), so a bar shows from then on; others keep just the name. Chat: /rv plates playerbars.");
changed |= SizeSlider("Player name size", ref MonsterHudSettings.PlayerTextSize, MonsterHudSettings.MinTextSize, MonsterHudSettings.MaxTextSize, w,
"Text size of the names over other players (1.00x = the default). Names have no bar.");
Note("Names count apart from the monster plates, so they never push one out; the nearest win.", w);

View file

@ -0,0 +1,312 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/BountiesFace.cs
// ACECustom bounties: every active bounty on the server and this character's
// progress on each (kills, cooldown or QB requirement), from the RynthILT
// plugin's tracker (UI/Data/BountiesData.cs). Part of the ILT section: only
// registered when RynthILT is installed, opened from the bar's ILT button or
// "/rc bounties" on Infinite Leaftide only. ImGui-only. Ported from
// SilentKelpie's rynth/RynthCore PR #5.
//
// The plugin reads /bounty list (quietly) only while this face is shown on
// ILT: on open, a moment after each kill, after bounty chat events and every
// few minutes, never more than once per MinRefreshSeconds. Options, Hide
// QB-locked and Closest first live in the plugin (per character); the text
// filter is this face's own.
// ============================================================================
using System;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class BountiesFace : IImGuiPanel
{
public const string Title = "Bounties";
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(560, 420), new Vector2(360, 220), EdgeToEdge: true),
() => new BountiesFace());
private const float RowH = 24, ProgressW = 160, FooterH = 18;
private const int MinRefreshFloor = 5, MinRefreshCeiling = 300, PeriodicCeiling = 60;
private static readonly uint OnBg = RynthTheme.Argb(0xFF104010), OnText = RynthTheme.Argb(0xFF33FF33);
private static readonly uint BarFill = RynthTheme.Argb(0xFF2E8C4A), BarChanged = RynthTheme.Argb(0xFF26C8D9),
BarTrack = RynthTheme.Argb(0xFF0E1A24);
private readonly byte[] _filter = new byte[64];
private bool _showOptions;
public void OnShown()
{
UiSources.Bounties.Subscribe();
UiSources.Bounties.RequestRefresh();
}
public void OnHidden() => UiSources.Bounties.Unsubscribe();
public void Draw()
{
// Off Infinite Leaftide the source stops polling; never show its last list there.
BountiesSnapshot? data = UiSources.Bounties.NotIlt ? null : UiSources.Bounties.Current?.Value;
float w = Begin(out Vector2 origin, out Vector2 size);
DrawToolbar(data, w);
if (data != null)
{
if (_showOptions) DrawOptions(data, w);
DrawFilterRow(data, w);
if (data.LastEvent.Length > 0)
{
Label(data.LastEvent + (data.LastEventAgoSec >= 0 ? " (" + Ago(data.LastEventAgoSec) + " ago)" : ""), Amber);
}
}
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
ImGuiNET.ImGui.BeginChild("##bounties_body", new Vector2(w, Math.Max(60, Remaining(origin, size) - FooterH - GripOverlap())));
float bw = ImGuiNET.ImGui.GetContentRegionAvail().X;
DrawBody(data, bw);
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor();
ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9);
Vector2 fp = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.GetWindowDrawList().AddText(f9, f9.FontSize, fp + new Vector2(2, 3), Mute,
"Kills count in the bounty's own area only (XP/lum mobs you did the most damage to).");
End(origin, size);
}
// ── Header ───────────────────────────────────────────────────────────
private void DrawToolbar(BountiesSnapshot? data, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
bool ready = data != null;
if (Button("##bounty_refresh", PhosphorIcons.ArrowsClockwise + " Refresh", p, new Vector2(90, 22), Teal, BtnFill, ready))
BountiesCommands.Refresh();
string state = !ready
? (UiSources.Bounties.NotIlt ? "not Infinite Leaftide"
: UiSources.Bounties.ExportMissing ? "this RynthILT build has no bounty tracker" : "waiting for RynthILT (log in)")
: data!.Reading ? "reading /bounty list..."
: data.Status.Length > 0 ? data.Status
: data.ListedAgoSec < 0 ? "not read yet"
: "updated " + Ago(data.ListedAgoSec) + " ago";
ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X + 98, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, state);
Vector2 op = new(p.X + w - 26, p.Y);
if (IconButton("##bounty_opts", PhosphorIcons.Gear, op, new Vector2(24, 22), _showOptions ? Teal : Mute, _showOptions ? Selected : BtnFill, ready))
_showOptions = !_showOptions;
ImGuiNET.ImGui.SetItemTooltip("Options");
NextLine(p, 26);
}
private static void DrawOptions(BountiesSnapshot d, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRectFilled(p, p + new Vector2(w, 82), PanelBg, 3);
float ty = (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
float x = p.X + 6, y = p.Y + 4;
dl.AddText(new Vector2(x, y + ty), Text, "Update after my kills");
float bx = x + ImGuiNET.ImGui.CalcTextSize("Update after my kills").X + 8;
if (Button("##bounty_onkills", d.RefreshOnKills ? "ON" : "OFF", new Vector2(bx, y), new Vector2(50, 22),
d.RefreshOnKills ? OnText : Mute, d.RefreshOnKills ? OnBg : BtnFill))
BountiesCommands.Set("refreshonkills", !d.RefreshOnKills);
y += 26;
dl.AddText(new Vector2(x, y + ty), Text, "At most every (sec)");
int min = Spinner("##bounty_min", d.MinRefreshSeconds, MinRefreshFloor, MinRefreshCeiling, 5,
new Vector2(x + 150, y));
if (min != d.MinRefreshSeconds) BountiesCommands.Set("minrefreshseconds", min.ToString(CultureInfo.InvariantCulture));
y += 26;
dl.AddText(new Vector2(x, y + ty), Text, "Re-read every (min, 0 = off)");
int per = Spinner("##bounty_per", d.PeriodicRefreshMinutes, 0, PeriodicCeiling, 1,
new Vector2(x + 190, y));
if (per != d.PeriodicRefreshMinutes) BountiesCommands.Set("periodicminutes", per.ToString(CultureInfo.InvariantCulture));
ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9);
dl.AddText(f9, f9.FontSize, new Vector2(x + 310, p.Y + 8), Mute, "Reads run only while this\nwindow is open; the reply\nis hidden from chat.");
NextLine(p, 86);
}
private void DrawFilterRow(BountiesSnapshot d, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float filterW = Math.Clamp(w - 250, 120, 260);
TextBox("##bounty_filter", _filter, p, filterW, "filter by area or reward", out _);
float x = p.X + filterW + 6;
const string hideLabel = "Hide QB-locked";
float hw = ButtonWidth(hideLabel);
if (Button("##bounty_hideqb", hideLabel, new Vector2(x, p.Y), new Vector2(hw, 22),
d.HideQbLocked ? OnText : Mute, d.HideQbLocked ? OnBg : BtnFill))
BountiesCommands.Set("hideqblocked", !d.HideQbLocked);
if (d.HiddenCount > 0) ImGuiNET.ImGui.SetItemTooltip($"{d.HiddenCount} hidden");
x += hw + 4;
const string sortLabel = "Closest first";
if (Button("##bounty_sort", sortLabel, new Vector2(x, p.Y), new Vector2(ButtonWidth(sortLabel), 22),
d.SortByProgress ? OnText : Mute, d.SortByProgress ? OnBg : BtnFill))
BountiesCommands.Set("sortbyprogress", !d.SortByProgress);
ImGuiNET.ImGui.SetItemTooltip("Nearest to a reward first, then cooldowns, then QB-locked");
NextLine(p, 26);
}
// ── Rows ─────────────────────────────────────────────────────────────
private void DrawBody(BountiesSnapshot? d, float w)
{
if (d == null)
{
Empty(UiSources.Bounties.NotIlt ? "Bounties are an Infinite Leaftide feature (/rc ilt for why)."
: "Log in with RynthILT loaded to track bounties.", w);
return;
}
if (d.Unsupported) { Empty("This server has no /bounty command. Press Refresh to check again.", w); return; }
if (d.Rows.Count == 0)
{
Empty(d.NoneAnywhere ? "No bounties are active anywhere right now."
: d.HiddenCount > 0 ? "Every bounty is QB-locked (Hide QB-locked is on)."
: d.Reading ? "Reading the server's bounties..."
: "No bounties read yet. Press Refresh.", w);
return;
}
float areaW = (w - ProgressW) * 0.42f, rewardW = w - ProgressW - areaW;
TableHeader(areaW, rewardW, w);
string filter = Utf8(_filter).Trim();
int shown = 0;
for (int i = 0; i < d.Rows.Count; i++)
{
BountyRowJson r = d.Rows[i];
if (filter.Length > 0 && !r.Where.Contains(filter, StringComparison.OrdinalIgnoreCase)
&& !r.Item.Contains(filter, StringComparison.OrdinalIgnoreCase)) continue;
ImGuiNET.ImGui.PushID(i);
DrawRow(r, shown++, areaW, rewardW, w);
ImGuiNET.ImGui.PopID();
}
if (shown == 0) Empty("No bounty matches the filter.", w);
}
private static void TableHeader(float areaW, float rewardW, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRectFilled(p, p + new Vector2(w, 22), Selected);
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
float ty = p.Y + (22 - bold.FontSize) * 0.5f;
dl.AddText(bold, bold.FontSize, new Vector2(p.X + 6, ty), Text, "Area");
dl.AddText(bold, bold.FontSize, new Vector2(p.X + areaW + 6, ty), Text, "Reward");
dl.AddText(bold, bold.FontSize, new Vector2(p.X + areaW + rewardW + 6, ty), Text, "Progress");
ImGuiNET.ImGui.Dummy(new Vector2(w, 22));
}
private static void DrawRow(BountyRowJson r, int index, float areaW, float rewardW, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRectFilled(p, p + new Vector2(w, RowH), index % 2 == 0 ? RowAlt : PanelBg);
float ty = p.Y + (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
dl.PushClipRect(p, p + new Vector2(areaW - 4, RowH), true);
dl.AddText(new Vector2(p.X + 6, ty), Text, r.Where);
dl.PopClipRect();
float rx = p.X + areaW;
dl.PushClipRect(new Vector2(rx, p.Y), new Vector2(rx + rewardW - 4, p.Y + RowH), true);
dl.AddText(new Vector2(rx + 6, ty), Text, N0(r.Amount) + " " + r.Item);
dl.PopClipRect();
float px = rx + rewardW;
var status = (BountyRowStatus)r.Status;
switch (status)
{
case BountyRowStatus.Counting:
{
Vector2 b0 = new(px + 4, p.Y + 4), b1 = new(p.X + w - 6, p.Y + RowH - 4);
float frac = r.KillsRequired > 0 ? Math.Clamp(r.Kills / (float)r.KillsRequired, 0f, 1f) : 0f;
dl.AddRectFilled(b0, b1, BarTrack, 3);
if (frac > 0) dl.AddRectFilled(b0, new Vector2(b0.X + (b1.X - b0.X) * frac, b1.Y), r.Changed ? BarChanged : BarFill, 3);
dl.AddRect(b0, b1, BtnBord, 3);
string text = N0(r.Kills) + " / " + N0(r.KillsRequired);
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(text);
dl.AddText(new Vector2((b0.X + b1.X - ts.X) * 0.5f, ty), Text, text);
break;
}
case BountyRowStatus.Cooldown:
dl.AddText(new Vector2(px + 6, ty), Amber, "unlocks in " + Ago(r.UnlockInSec));
break;
default:
dl.AddText(new Vector2(px + 6, ty), Mute, "needs " + Compact(r.QbRequired) + " QB");
break;
}
ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, RowH));
if (ImGuiNET.ImGui.IsItemHovered())
{
string every = $"Every {N0(r.KillsRequired)} kill(s)"
+ (r.CooldownSeconds > 0 ? ", at most every " + Ago(r.CooldownSeconds) : "");
string detail = status switch
{
BountyRowStatus.Cooldown => $"\nKills don't count for {Ago(r.UnlockInSec)}; after that {N0(r.KillsRequired)} kill(s).",
BountyRowStatus.NeedsQb => $"\nNeeds {N0(r.QbRequired)} QB; you have {N0(r.QbHave)}.",
_ => string.Empty,
};
ImGuiNET.ImGui.SetTooltip($"{r.Where}: {N0(r.Amount)} {r.Item}\n{every}{detail}");
}
NextLine(p, RowH);
}
private static void Empty(string message, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.GetWindowDrawList().AddRectFilled(p, p + new Vector2(w, 22), RowAlt);
ImGuiNET.ImGui.GetWindowDrawList().AddText(p + new Vector2(8, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, message);
ImGuiNET.ImGui.Dummy(new Vector2(w, 22));
}
/// <summary>[-] value [+]; returns the new value (same when nothing was clicked).</summary>
private static int Spinner(string id, int value, int min, int max, int step, Vector2 pos)
{
int v = value;
ImGuiNET.ImGui.PushID(id);
if (IconButton("##dec", PhosphorIcons.Minus, pos, new Vector2(22, 22), Teal, BtnFill)) v = Math.Max(min, v - step);
string text = v.ToString(CultureInfo.InvariantCulture);
float tw = ImGuiNET.ImGui.CalcTextSize(text).X;
ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(pos.X + 24 + (40 - tw) * 0.5f, pos.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, text);
if (IconButton("##inc", PhosphorIcons.Plus, new Vector2(pos.X + 66, pos.Y), new Vector2(22, 22), Teal, BtnFill)) v = Math.Min(max, v + step);
ImGuiNET.ImGui.PopID();
return v;
}
// ── Formatting ───────────────────────────────────────────────────────
private static string N0(long v) => v.ToString("N0", CultureInfo.InvariantCulture);
/// <summary>1.2M, 350k, 900.</summary>
private static string Compact(long v) =>
v >= 1_000_000 ? (v / 1_000_000d).ToString("0.#", CultureInfo.InvariantCulture) + "M"
: v >= 10_000 ? (v / 1_000d).ToString("0.#", CultureInfo.InvariantCulture) + "k"
: N0(v);
/// <summary>"45 sec", "2 min 30 sec", "1 hr 5 min", "2 days 3 hr".</summary>
private static string Ago(int seconds)
{
long s = Math.Max(0, seconds);
if (s >= 86400) return $"{s / 86400} day{(s / 86400 == 1 ? "" : "s")}" + (s % 86400 >= 3600 ? $" {s % 86400 / 3600} hr" : "");
if (s >= 3600) return $"{s / 3600} hr" + (s % 3600 >= 60 ? $" {s % 3600 / 60} min" : "");
if (s >= 60) return $"{s / 60} min" + (s % 60 > 0 ? $" {s % 60} sec" : "");
return $"{s} sec";
}
}

View file

@ -0,0 +1,485 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/ChatDiscordFace.cs
// The Discord panel: everything about copying chat to Discord
// (UI/Data/Discord/ChatDiscord.cs). Opened from the Chat panel's gear menu
// (Discord settings...) or /rc discord window.
//
// Routes one tab per destination: webhook URL, or bot token + channel ID;
// which speech channels and which chat tabs it gets, keywords,
// and optionally its own pacing; Send test / Resume
// Settings who relays (the characters it's on for, your own lines, hidden lines),
// the message format, and the default pacing and limits
// Log messages sent, rate limits and errors
//
// Settings fields are edited in place (single-value writes the pump
// tolerates); adding or removing a route replaces the Routes array, and a
// route's tab list is replaced too. Each change saves (ChatDiscord.Save, on
// the background writer). Secrets go to ChatDiscord, which encrypts them off
// this thread; the box is cleared at once and the text is never shown again.
// AC's render thread only.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
using RynthCore.Engine.UI.Data.Discord;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class ChatDiscordFace : IImGuiPanel
{
public const string Title = "Discord";
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(560, 520), new Vector2(420, 300)),
() => new ChatDiscordFace());
private string _secretInput = string.Empty;
private string _secretMessage = string.Empty;
private bool _secretMessageIsError;
private DiscordRoute? _secretFor;
private DiscordRoute? _confirmRemove;
private int _lastLogCount;
public void OnShown()
{
ChatModel.EnsureSettingsLoaded();
ChatDiscord.EnsureLoaded();
ChatDiscord.PanelShown(true);
}
public void OnHidden()
{
_confirmRemove = null;
ChatDiscord.PanelShown(false);
}
public void Draw()
{
var s = ChatDiscord.Settings;
DrawSwitch();
ImGuiNET.ImGui.SameLine();
Label("| " + ChatDiscord.StatusLine(), Mute);
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.BeginTabBar("##dc_tabs"))
{
if (ImGuiNET.ImGui.BeginTabItem("Routes")) { DrawRoutes(s); ImGuiNET.ImGui.EndTabItem(); }
if (ImGuiNET.ImGui.BeginTabItem("Settings")) { DrawSettings(s); ImGuiNET.ImGui.EndTabItem(); }
if (ImGuiNET.ImGui.BeginTabItem("Log")) { DrawLog(); ImGuiNET.ImGui.EndTabItem(); }
ImGuiNET.ImGui.EndTabBar();
}
}
/// <summary>
/// This character's switch (the relay is off for every character until each is switched on).
/// Shared by the Chat panel's gear menu.
/// </summary>
internal static void DrawSwitch()
{
DiscordCharacter? me = ChatDiscord.CurrentCharacter();
bool on = ChatDiscord.IsOn(me);
ImGuiNET.ImGui.BeginDisabled(me == null);
if (ImGuiNET.ImGui.Checkbox("Copy this character's chat to Discord##dc_on", ref on)) ChatDiscord.SetEnabled(on);
ImGuiNET.ImGui.EndDisabled();
if (me == null)
ImGuiNET.ImGui.SetItemTooltip("Log in first: the relay is switched on for one character at a time.");
else
ImGuiNET.ImGui.SetItemTooltip("On for this character only; every other character stays off until it's switched on too.\n" +
"Off: nothing from this character is queued or sent (Send test still works).");
}
// ── Routes ───────────────────────────────────────────────────────────
private void DrawRoutes(ChatDiscordSettings s)
{
if (ImGuiNET.ImGui.SmallButton("Add route"))
{
var r = new DiscordRoute { Name = $"Route {s.Routes.Length + 1}" };
ChatDiscordStore.NormalizeRoute(r);
s.Routes = new List<DiscordRoute>(s.Routes) { r }.ToArray();
ChatDiscord.Save();
}
ImGuiNET.ImGui.SetItemTooltip("A route is one Discord channel and the chat it receives.");
if (s.Routes.Length == 0)
{
ImGuiNET.ImGui.Spacing();
Wrapped("No routes yet. Add one, then paste a webhook URL from Discord: Server Settings > Integrations > "
+ "Webhooks > New Webhook > pick the channel > Copy Webhook URL.", Text);
return;
}
if (!ImGuiNET.ImGui.BeginTabBar("##dc_routes", ImGuiTabBarFlags.FittingPolicyScroll)) return;
DiscordRoute? remove = null;
for (int i = 0; i < s.Routes.Length; i++)
{
DiscordRoute r = s.Routes[i];
string label = (r.Status?.Paused == true ? "! " : r.Enabled ? "" : "(off) ") + r.Name + "###dc_route" + i;
if (!ImGuiNET.ImGui.BeginTabItem(label)) continue;
ImGuiNET.ImGui.PushID(i);
if (DrawRoute(s, r)) remove = r;
ImGuiNET.ImGui.PopID();
ImGuiNET.ImGui.EndTabItem();
}
ImGuiNET.ImGui.EndTabBar();
if (remove != null)
{
var list = new List<DiscordRoute>(s.Routes);
list.Remove(remove);
s.Routes = list.ToArray();
if (ReferenceEquals(_secretFor, remove)) ClearSecretBox(null);
ChatDiscord.Save();
}
}
/// <summary>One route's editor; true when the player asked to remove it.</summary>
private bool DrawRoute(ChatDiscordSettings s, DiscordRoute r)
{
if (!ReferenceEquals(_secretFor, r)) ClearSecretBox(r);
DiscordRouteStatus? st = r.Status;
if (st != null)
{
if (st.Paused) Wrapped("Paused: " + st.LastError, Red);
else if (st.LastError.Length > 0) Wrapped("Last problem: " + st.LastError, Amber);
Label($"{st.MessagesSent} message(s), {st.LinesSent} line(s) sent, {st.Queued} queued, {st.Dropped} dropped"
+ (st.LastSent != default ? $", last {st.LastSent:HH:mm:ss}" : string.Empty), Mute);
}
if (ImGuiNET.ImGui.Checkbox("Enabled##r_on", ref r.Enabled)) ChatDiscord.Save();
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.SetNextItemWidth(200f);
string name = r.Name;
if (Input("Name##r_name", "route name", ref name, 40)) r.Name = name;
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
if (string.IsNullOrWhiteSpace(r.Name)) r.Name = "Discord";
ChatDiscord.Save();
}
// Connection
Heading("Connection");
int mode = Math.Max(0, Array.IndexOf(DiscordRoute.Modes, r.Mode));
ImGuiNET.ImGui.SetNextItemWidth(220f);
if (ImGuiNET.ImGui.Combo("Send with##r_mode", ref mode, DiscordRoute.ModeNames, DiscordRoute.ModeNames.Length))
{
r.Mode = DiscordRoute.Modes[mode];
ClearSecretBox(r);
ChatDiscord.Resume(r);
ChatDiscord.Save();
}
ImGuiNET.ImGui.SetItemTooltip("Webhook: simplest, one URL per channel, posts under any name.\n"
+ "Bot: your own Discord bot posts it (it must be in the server with Send Messages there).");
bool bot = r.Mode == DiscordRoute.ModeBot;
bool saved = bot ? r.BotTokenProtected.Length > 0 : r.WebhookProtected.Length > 0;
ImGuiNET.ImGui.SetNextItemWidth(330f);
Input((bot ? "Bot token" : "Webhook URL") + "##r_secret",
saved ? "saved (paste a new one to replace it)" : bot ? "paste the bot token" : "https://discord.com/api/webhooks/...",
ref _secretInput, 512, ImGuiInputTextFlags.Password);
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.Button("Save##r_secret_save") && _secretInput.Trim().Length > 0)
{
string err = bot ? ChatDiscord.SetBotToken(r, _secretInput) : ChatDiscord.SetWebhook(r, _secretInput);
_secretInput = string.Empty;
_secretMessageIsError = err.Length > 0;
_secretMessage = err.Length > 0 ? err : "Saved, encrypted for this Windows user. Use Send test to check it.";
}
if (saved)
{
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.Button("Clear##r_secret_clear"))
{
if (bot) r.BotTokenProtected = string.Empty; else r.WebhookProtected = string.Empty;
_secretMessage = "Cleared.";
_secretMessageIsError = false;
ChatDiscord.Save();
}
}
if (_secretMessage.Length > 0) Wrapped(_secretMessage, _secretMessageIsError ? Red : Green);
if (bot)
{
ImGuiNET.ImGui.SetNextItemWidth(200f);
string chId = r.ChannelId;
if (Input("Channel ID##r_chid", "e.g. 123456789012345678", ref chId, 24, ImGuiInputTextFlags.CharsDecimal))
{
r.ChannelId = chId.Trim();
ChatDiscord.Resume(r);
}
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Discord: User Settings > Advanced > Developer Mode on, then right-click the channel > Copy Channel ID.");
if (r.ChannelId.Length > 0 && !DiscordFormat.IsSnowflake(r.ChannelId))
Label("A channel ID is 15-22 digits.", Red);
}
else
{
ImGuiNET.ImGui.SetNextItemWidth(200f);
Input("Post as##r_name_as", "character name", ref r.DisplayName, 80);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Name shown on the webhook's messages. Blank uses the character's name.\n"
+ "Discord refuses names containing \"discord\" or \"clyde\"; those fall back to the webhook's own name.");
}
if (ImGuiNET.ImGui.Button("Send test##r_test")) ChatDiscord.SendTest(r);
ImGuiNET.ImGui.SetItemTooltip("Posts one test line to this route now (also clears a pause).");
if (st?.Paused == true)
{
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.Button("Resume##r_resume")) ChatDiscord.Resume(r);
}
DrawSpeech(r);
DrawTabs(r);
Heading("Filter");
ImGuiNET.ImGui.SetNextItemWidth(330f);
Input("Keywords##r_kw", "blank = every line; e.g. rare, Asheron", ref r.Keywords, 300);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Comma-separated. When set, only lines containing one of these words (any case) are relayed.");
Heading("How often");
if (ImGuiNET.ImGui.Checkbox("Own pacing for this route##r_pace", ref r.CustomPace)) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Off: the route uses the pacing on the Settings tab.");
if (r.CustomPace)
DrawPacing(ref r.BatchMs, ref r.MinIntervalMs, "##r");
else
Label($"Using the default: batch {s.BatchMs / 1000.0:0.#} s, at most one message every {s.MinIntervalMs / 1000.0:0.#} s.", Mute);
ImGuiNET.ImGui.Spacing();
ImGuiNET.ImGui.Separator();
bool remove = false;
if (ReferenceEquals(_confirmRemove, r))
{
// The saved webhook URL / bot token goes with the route; there's no undo.
Label("Delete this route and its saved credential?", Amber);
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Delete##r_remove_yes"))
{
remove = true;
_confirmRemove = null;
}
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Cancel##r_remove_no")) _confirmRemove = null;
}
else
{
if (ImGuiNET.ImGui.SmallButton("Remove route##r_remove")) _confirmRemove = r;
ImGuiNET.ImGui.SetItemTooltip("Deletes this route and its saved credential (asks first).");
}
return remove;
}
private static void DrawSpeech(DiscordRoute r)
{
Heading("Speech channels");
if (ImGuiNET.ImGui.SmallButton("All##sp_all")) SetSpeech(r, DiscordRoute.AllSpeechMask());
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("None##sp_none")) SetSpeech(r, 0);
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Defaults##sp_def")) SetSpeech(r, DiscordRoute.DefaultSpeechMask());
ImGuiNET.ImGui.SameLine();
Label("what players say, by channel", Mute);
if (!ImGuiNET.ImGui.BeginTable("##sp_grid", 4, ImGuiTableFlags.SizingStretchSame)) return;
foreach (SpeechChannel ch in ChatSpeech.All)
{
ImGuiNET.ImGui.TableNextColumn();
uint bit = ChatSpeech.Bit(ch);
bool ticked = (r.SpeechMask & bit) != 0;
if (ImGuiNET.ImGui.Checkbox(ChatSpeech.Name(ch) + "##sp" + (int)ch, ref ticked))
SetSpeech(r, ticked ? r.SpeechMask | bit : r.SpeechMask & ~bit);
if (ch == SpeechChannel.Local) ImGuiNET.ImGui.SetItemTooltip("Local speech includes every NPC and player near you; it can be busy.");
}
ImGuiNET.ImGui.EndTable();
}
private static void SetSpeech(DiscordRoute r, uint mask)
{
r.SpeechMask = mask;
ChatDiscord.Save();
}
/// <summary>Chat tabs: every line that shows in a ticked tab goes, whatever it is.</summary>
private static void DrawTabs(DiscordRoute r)
{
Heading("Chat tabs");
Label("every line that shows in the tab (System, Combat, or tabs your chat rules fill)", Mute);
string[] all = ChatModel.AllTabs();
var shown = new List<string>(all);
foreach (string t in r.Tabs)
if (!shown.Exists(x => string.Equals(x, t, StringComparison.OrdinalIgnoreCase))) shown.Add(t);
if (!ImGuiNET.ImGui.BeginTable("##tab_grid", 4, ImGuiTableFlags.SizingStretchSame)) return;
for (int i = 0; i < shown.Count; i++)
{
string tab = shown[i];
ImGuiNET.ImGui.TableNextColumn();
bool ticked = Array.Exists(r.Tabs, t => string.Equals(t, tab, StringComparison.OrdinalIgnoreCase));
bool missing = Array.IndexOf(all, tab) < 0;
if (ImGuiNET.ImGui.Checkbox((missing ? tab + " (gone)" : tab) + "##tab" + i, ref ticked))
{
var list = new List<string>(r.Tabs);
list.RemoveAll(t => string.Equals(t, tab, StringComparison.OrdinalIgnoreCase));
if (ticked) list.Add(tab);
r.Tabs = list.ToArray();
ChatDiscord.Save();
}
if (tab == "All") ImGuiNET.ImGui.SetItemTooltip("Every line in the All tab: very busy. Pair it with keywords.");
else if (missing) ImGuiNET.ImGui.SetItemTooltip("This tab no longer exists; untick it to drop it.");
}
ImGuiNET.ImGui.EndTable();
}
private void ClearSecretBox(DiscordRoute? forRoute)
{
_secretFor = forRoute;
_secretInput = string.Empty;
_secretMessage = string.Empty;
_secretMessageIsError = false;
}
// ── Settings ─────────────────────────────────────────────────────────
private static void DrawSettings(ChatDiscordSettings s)
{
Heading("Who relays");
Label(ChatDiscord.SwitchLine(), Text);
DiscordCharacter[] on = s.Characters;
if (on.Length == 0)
Label("Off for every character.", Mute);
else
{
Label("On for:", Mute);
DiscordCharacter? me = ChatDiscord.CurrentCharacter();
for (int i = 0; i < on.Length; i++)
{
DiscordCharacter c = on[i];
ImGuiNET.ImGui.PushID(i);
if (ImGuiNET.ImGui.SmallButton("Turn off##s_char_off")) ChatDiscord.TurnOffFor(c);
ImGuiNET.ImGui.SameLine();
Label(c.ToString() + (c.Same(me) ? " (this client)" : string.Empty), c.Same(me) ? Green : Text);
ImGuiNET.ImGui.PopID();
}
}
Wrapped("Each character is switched on by itself (the checkbox at the top while you play it, or /rc discord on). "
+ "With several clients in one allegiance or fellowship, switch on just one of them so each line is posted once.", Mute);
if (ImGuiNET.ImGui.Checkbox("Skip lines I type##s_own", ref s.SkipOwn)) ChatDiscord.Save();
if (ImGuiNET.ImGui.Checkbox("Skip lines my chat rules hide##s_hidden", ref s.SkipHidden)) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Lines a Hide rule or standard filter hides in the chat aren't sent either.");
Heading("Message format");
if (ImGuiNET.ImGui.Checkbox("Timestamp (HH:mm:ss)##s_ts", ref s.IncludeTimestamp)) ChatDiscord.Save();
if (ImGuiNET.ImGui.Checkbox("Start lines with [Character]##s_tag", ref s.TagCharacter)) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Useful when several characters post into the same Discord channel.");
Heading("How often (default for every route)");
DrawPacing(ref s.BatchMs, ref s.MinIntervalMs, "##s");
Heading("Limits");
ImGuiNET.ImGui.SetNextItemWidth(200f);
if (ImGuiNET.ImGui.SliderInt("Queue limit (lines)##s_queue", ref s.MaxQueue, ChatDiscordSettings.QueueMin, ChatDiscordSettings.QueueMax))
s.MaxQueue = Math.Clamp(s.MaxQueue, ChatDiscordSettings.QueueMin, ChatDiscordSettings.QueueMax);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Lines waiting per route; past this the oldest are dropped.");
ImGuiNET.ImGui.SetNextItemWidth(200f);
if (ImGuiNET.ImGui.SliderInt("Log size##s_log", ref s.MaxLog, ChatDiscordSettings.LogMin, ChatDiscordSettings.LogMax))
s.MaxLog = Math.Clamp(s.MaxLog, ChatDiscordSettings.LogMin, ChatDiscordSettings.LogMax);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save();
ImGuiNET.ImGui.Spacing();
Wrapped("Routes and settings are shared by every client and character (%AppData%\\RynthCore\\rynthchat_discord.json); "
+ "the on / off switch is per character. Webhook URLs and bot tokens "
+ "are encrypted for this Windows user; on another PC or user they must be pasted again.", Mute);
Wrapped("Relayed text never pings: @everyone, @here and user mentions are sent as plain text, and links don't unfurl.", Mute);
}
/// <summary>Batch window and message spacing sliders (seconds on screen, ms stored).</summary>
private static void DrawPacing(ref int batchMs, ref int intervalMs, string id)
{
float batch = batchMs / 1000f;
ImGuiNET.ImGui.SetNextItemWidth(200f);
if (ImGuiNET.ImGui.SliderFloat("Batch window" + id + "_batch", ref batch, ChatDiscordSettings.BatchMinMs / 1000f,
ChatDiscordSettings.BatchMaxMs / 1000f, "%.1f s", ImGuiSliderFlags.Logarithmic))
batchMs = Math.Clamp((int)MathF.Round(batch * 1000f), ChatDiscordSettings.BatchMinMs, ChatDiscordSettings.BatchMaxMs);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Lines arriving this close together go out as one Discord message.\n"
+ "Longer = fewer, bigger messages (a digest); 0 = each line as soon as allowed.");
float interval = intervalMs / 1000f;
ImGuiNET.ImGui.SetNextItemWidth(200f);
if (ImGuiNET.ImGui.SliderFloat("At most one message every" + id + "_interval", ref interval, ChatDiscordSettings.IntervalMinMs / 1000f,
ChatDiscordSettings.IntervalMaxMs / 1000f, "%.1f s", ImGuiSliderFlags.Logarithmic))
intervalMs = Math.Clamp((int)MathF.Round(interval * 1000f), ChatDiscordSettings.IntervalMinMs, ChatDiscordSettings.IntervalMaxMs);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Spacing between messages to one route. Discord allows about 30 a minute per channel;\n"
+ "2 s stays under it. Lines that arrive meanwhile wait and go in the next message.");
Label($"Up to {60000.0 / Math.Max(1, intervalMs):0.#} messages a minute per route.", Mute);
}
// ── Log ──────────────────────────────────────────────────────────────
private void DrawLog()
{
DiscordLogEntry[] log = ChatDiscord.LogSnapshot();
if (ImGuiNET.ImGui.SmallButton("Clear##log_clear")) ChatDiscord.ClearLog();
ImGuiNET.ImGui.SameLine();
Label($"{log.Length} entries", Mute);
if (!ImGuiNET.ImGui.BeginChild("##dc_log", new Vector2(0, 0), ImGuiChildFlags.Borders)) { ImGuiNET.ImGui.EndChild(); return; }
foreach (DiscordLogEntry e in log)
{
uint col = e.Kind switch { DiscordLogKind.Sent => Green, DiscordLogKind.Error => Red, _ => Amber };
Label(e.Time.ToString("HH:mm:ss"), Mute);
ImGuiNET.ImGui.SameLine();
Label(e.Route, col);
ImGuiNET.ImGui.SameLine();
// Relayed chat and Discord's replies: never a format string (see Wrapped).
WrappedUnformatted(e.Text);
}
// Follow new lines unless the player scrolled up.
if (log.Length != _lastLogCount && ImGuiNET.ImGui.GetScrollY() >= ImGuiNET.ImGui.GetScrollMaxY() - 20f)
ImGuiNET.ImGui.SetScrollHereY(1f);
_lastLogCount = log.Length;
ImGuiNET.ImGui.EndChild();
}
// ── Helpers ──────────────────────────────────────────────────────────
private static void Heading(string text)
{
ImGuiNET.ImGui.Spacing();
Label(text, Teal);
}
/// <summary>
/// Wrapped text in <paramref name="color"/>. ImGui.NET's TextWrapped / Text / TextColored pass
/// their string to ImGui as a printf format, so chat or an error Discord sent back holding
/// "%s" would crash the client. Everything here goes through TextUnformatted.
/// </summary>
private static void Wrapped(string text, uint color)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, color);
WrappedUnformatted(text);
ImGuiNET.ImGui.PopStyleColor();
}
private static void WrappedUnformatted(string text)
{
ImGuiNET.ImGui.PushTextWrapPos(0f);
ImGuiNET.ImGui.TextUnformatted(text);
ImGuiNET.ImGui.PopTextWrapPos();
}
/// <summary>A text box that keeps the keyboard from AC while it's being typed in.</summary>
private static bool Input(string label, string hint, ref string value, uint maxLength,
ImGuiInputTextFlags flags = ImGuiInputTextFlags.None)
{
bool changed = ImGuiNET.ImGui.InputTextWithHint(label, hint, ref value, maxLength, flags);
if (ImGuiNET.ImGui.IsItemActive()) ImGuiTextFocus.NoteActive(label);
return changed;
}
}

View file

@ -900,7 +900,7 @@ internal sealed class ChatFace : IImGuiPanel
ChatModel.LogEnabled = log;
ChatModel.SaveSettings();
}
ImGuiNET.ImGui.SetItemTooltip("%AppData%\\RynthCore\\ChatLogs\\<character>.log");
ImGuiNET.ImGui.SetItemTooltip("%%AppData%%\\RynthCore\\ChatLogs\\<character>.log"); // a format string: %% is a literal %
bool through = ChatModel.CtrlGatedClickThrough;
if (ImGuiNET.ImGui.Checkbox("Click-through (hold Ctrl to interact)", ref through))
ChatModel.SetCtrlGatedClickThrough(through);
@ -934,6 +934,8 @@ internal sealed class ChatFace : IImGuiPanel
ChatModel.SaveSettings();
}
}
// Discord above the colours: the colour grid opens downward, so it stays last.
DrawDiscordSettings();
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.CollapsingHeader("Line colours")) DrawLineColours();
@ -1024,6 +1026,25 @@ internal sealed class ChatFace : IImGuiPanel
ImGuiNET.ImGui.PopID();
}
/// <summary>
/// Settings menu: this character's Discord relay switch, its status and the way into the
/// Discord panel, in two compact rows like the rest of the menu.
/// </summary>
private static void DrawDiscordSettings()
{
ImGuiNET.ImGui.Separator();
ChatDiscordFace.DrawSwitch();
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Discord…##chat_discord"))
{
if (!ImGuiPanelHost.IsOpen(ChatDiscordFace.Title)) PanelRouter.Toggle(ChatDiscordFace.Title);
ImGuiNET.ImGui.CloseCurrentPopup();
}
ImGuiNET.ImGui.SetItemTooltip("Discord panel: connection (webhook or bot), which channels and tabs go where,\n" +
"keywords, how often, and the send log.");
Label(UI.Data.Discord.ChatDiscord.SwitchLine() + " " + UI.Data.Discord.ChatDiscord.StatusLine(), Mute);
}
private void DrawNewTabPopup()
{
if (!ImGuiNET.ImGui.BeginPopup("##chat_newtab"))

View file

@ -269,9 +269,11 @@ internal sealed class LootAddDialog
}
if (ImGuiNET.ImGui.IsItemHovered())
ImGuiNET.ImGui.SetTooltip(
"Also require this item's T11 tier, weapon grade, damage %, every modifier, slot special\n" +
"and Cast on Strike, each at least as good as this one. Works with any match.\n" +
"Not added: Can Wield (depends on your character) and Zone Locked (depends on where it was assessed).");
"Also require this item's T11 tier (the server's stamped tier when it sends one), weapon grade,\n" +
"damage %, gear grade, every modifier, slot special and Cast on Strike, each at least as good\n" +
"as this one. Works with any match.\n" +
"Not added: Can Wield (depends on your character), Zone Locked (depends on where it was assessed),\n" +
"and property slots / Tainted (bag state, not quality).");
if (!d.IsT11)
{
ImGuiNET.ImGui.SameLine();

View file

@ -40,6 +40,9 @@ internal static class P1Faces
// items to use): ImGui only, saved per character in item_huds.txt.
ItemCountFace.Register();
MiniRemoteFace.Register();
// Report a problem (Report/ProblemReport.cs): ImGui only, opened from the bar's grip
// menu, Settings and /rc report (no bar button of its own).
ReportFace.Register();
}
}

View file

@ -0,0 +1,241 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/ReportFace.cs
// The "Report a problem" panel (Report/ProblemReport.cs). ImGui only.
//
// What went wrong? required, 2,500 bytes of UTF-8 at most
// What were you doing? optional, 1,500 bytes
// [x] Attach my recent RynthCore log ticked each time the panel opens
// its size, View (opens exactly what will be sent) and Refresh
// what else is sent, the Send button and the result
//
// Opened from the bar's grip menu, Settings' sidebar and /rc report. Draw reads
// ProblemReport's state and calls Send / RefreshTail / ViewTail, which do their
// work off AC's thread. The log tail is read when the panel opens (and on
// Refresh); Send sends that same tail, so what View showed is what goes.
// ============================================================================
using System;
using System.Globalization;
using System.Numerics;
using System.Text;
using ImGuiNET;
using RynthCore.Engine.Report;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class ReportFace : IImGuiPanel
{
public const string Title = ProblemReport.PanelTitle;
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(390, 490), new Vector2(300, 440), EdgeToEdge: true, GripInBody: true),
() => new ReportFace());
private const string DescId = "##report_desc", DoingId = "##report_doing";
private static readonly byte[] DescLabel = Encoding.UTF8.GetBytes(DescId + "\0");
private static readonly byte[] DoingLabel = Encoding.UTF8.GetBytes(DoingId + "\0");
private readonly byte[] _desc = new byte[ProblemReportCore.MaxDescriptionBytes + 1];
private readonly byte[] _doing = new byte[ProblemReportCore.MaxDoingBytes + 1];
private bool _attachLog = true;
private long _messageSeqAtOpen;
private long _resultSeqAtSend = -1; // >= 0 while a send this panel started is out
private string _localError = "";
private LogTail? _describedTail; // the tail _tailText describes (built when the tail changes, not per frame)
private string _tailText = "";
private static readonly string LogToggleLabel =
$"Attach my recent RynthCore log (last {ProblemReportCore.TailLines:N0} lines)";
public void OnShown()
{
_attachLog = true; // ticked by default, every time
_localError = "";
_messageSeqAtOpen = ProblemReport.MessageSeq;
ProblemReport.RefreshTail();
}
public void Draw()
{
// A send this panel started finished: clear the form when it was taken.
if (_resultSeqAtSend >= 0 && ProblemReport.ResultSeq != _resultSeqAtSend)
{
if (ProblemReport.State == ReportState.Sent)
{
WriteUtf8(_desc, "");
WriteUtf8(_doing, "");
}
_resultSeqAtSend = -1;
}
float w = Begin(out Vector2 origin, out Vector2 size);
Label("What went wrong? (required)", Text);
MultiLine(DescId, DescLabel, _desc, w, 92, "What happened, and what did you expect?");
Label("What were you doing? (optional)", Mute);
MultiLine(DoingId, DoingLabel, _doing, w, 56, "e.g. hunting in a dungeon with the bot on");
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
Separator(w);
LogRow(w);
Separator(w);
Note("Also sent: your character, server, RynthCore / RynthAi / plugin versions, where you are (landblock and cell) " +
"and the client's process id. Reports go to the staff only.", w);
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
SendRow(w);
End(origin, size);
}
// ── The log ─────────────────────────────────────────────────────────
private void LogRow(float w)
{
// Square toggle + label; the whole row toggles (Settings' look).
var dl = ImGuiNET.ImGui.GetWindowDrawList();
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float labelW = ImGuiNET.ImGui.CalcTextSize(LogToggleLabel).X;
if (ImGuiNET.ImGui.InvisibleButton("##report_attach", new Vector2(Math.Min(w, 18 + labelW), 18)))
_attachLog = !_attachLog;
bool hot = ImGuiNET.ImGui.IsItemHovered();
if (hot) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
ImGuiNET.ImGui.SetItemTooltip("Your RynthCore log helps us see what happened. Untick it to send only what you wrote.");
dl.AddRectFilled(p + new Vector2(0, 3), p + new Vector2(12, 15), _attachLog ? Green : C(0xFF334455), 2);
dl.AddText(p + new Vector2(18, (18 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), hot ? Teal : Text, LogToggleLabel);
LogTail? tail = ProblemReport.Tail;
if (!ReferenceEquals(tail, _describedTail))
{
_describedTail = tail;
_tailText = tail != null ? ProblemReportCore.DescribeTail(tail) : "";
}
string info = ProblemReport.TailLoading ? "Reading the log..."
: tail != null ? _tailText
: ProblemReport.TailError.Length > 0 ? ProblemReport.TailError : "Reading the log...";
Wrapped(info, _attachLog ? Mute : Faded(Mute), w);
Vector2 row = ImGuiNET.ImGui.GetCursorScreenPos();
string view = PhosphorIcons.Eye + " View what will be sent";
string refresh = PhosphorIcons.ArrowsClockwise + " Refresh";
float vw = ButtonWidth(view), rw = ButtonWidth(refresh);
bool canView = tail != null && !ProblemReport.TailLoading;
if (Button("##report_view", view, row, new Vector2(vw, 22), Text, BtnFill, enabled: canView))
ProblemReport.ViewTail(tail!);
ImGuiNET.ImGui.SetItemTooltip("Opens the exact log text that will be sent, in your text editor.");
if (Button("##report_refresh", refresh, new Vector2(row.X + vw + 4, row.Y), new Vector2(rw, 22), Text, BtnFill,
enabled: !ProblemReport.TailLoading))
ProblemReport.RefreshTail();
ImGuiNET.ImGui.SetItemTooltip("Take the log again, up to now.");
NextLine(row, 26);
Note("The log has your character names and some chat in it (your account, Windows user and PC names are hidden). View shows exactly what will be sent.", w);
}
// ── Send ────────────────────────────────────────────────────────────
private void SendRow(float w)
{
ReportState state = ProblemReport.State;
long cooldown = ProblemReport.CooldownLeftMs;
bool sending = state == ReportState.Sending;
bool hasText = _desc[0] != 0;
Vector2 row = ImGuiNET.ImGui.GetCursorScreenPos();
string label = sending ? "Sending..." : "Send report";
float bw = Math.Max(110, ButtonWidth(label));
bool enabled = hasText && !sending && cooldown == 0 && !(_attachLog && ProblemReport.TailLoading);
if (Button("##report_send", label, row, new Vector2(bw, 24), Text, StartBg, enabled: enabled))
StartSend();
if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled | ImGuiHoveredFlags.ForTooltip))
ImGuiNET.ImGui.SetTooltip(!hasText ? "Write what went wrong first."
: cooldown > 0 ? "One report a minute: " + CooldownText(cooldown)
: "Send this report to the staff.");
NextLine(row, 28);
// The result (only ones from since the panel opened), then the cooldown.
if (_localError.Length > 0)
Wrapped(_localError, Amber, w);
else if (sending || ProblemReport.MessageSeq != _messageSeqAtOpen)
Wrapped(ProblemReport.Message, state switch
{
ReportState.Sent => Green,
ReportState.Failed => Red,
_ => Mute,
}, w);
if (!sending && cooldown > 0)
Wrapped(CooldownText(cooldown), Faded(Mute), w);
}
// "You can send another report in 42 s.", rebuilt once a second rather than every frame.
private long _cooldownShownS = -1;
private string _cooldownText = "";
private string CooldownText(long ms)
{
long sec = (ms + 999) / 1000;
if (sec != _cooldownShownS)
{
_cooldownShownS = sec;
_cooldownText = $"You can send another report in {ProblemReportCore.FormatWait(ms)}.";
}
return _cooldownText;
}
private void StartSend()
{
string description = Utf8(_desc), doing = Utf8(_doing);
LogTail? tail = _attachLog ? ProblemReport.Tail : null;
long seq = ProblemReport.ResultSeq;
if (ProblemReport.Send(description, doing, tail, readTailIfNull: false, announceInChat: false, out string error))
{
_localError = "";
_resultSeqAtSend = seq;
}
else
{
_localError = error;
}
}
// ── Widgets ─────────────────────────────────────────────────────────
/// <summary>A bordered multi-line text box (FaceKit.TextBox's look) with a grey hint while empty.</summary>
private unsafe void MultiLine(string id, byte[] label, byte[] buffer, float width, float height, string hint)
{
Vector2 pos = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, 3));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 3f);
fixed (byte* l = label)
fixed (byte* b = buffer)
{
if (ImGuiNative.igInputTextMultiline(l, b, (uint)buffer.Length, new Vector2(width, height),
ImGuiInputTextFlags.None, null, null) != 0)
_localError = "";
}
bool active = ImGuiNET.ImGui.IsItemActive();
if (active) ImGuiTextFocus.NoteActive(id); // keys stay out of AC
ImGuiNET.ImGui.PopStyleVar(3);
ImGuiNET.ImGui.PopStyleColor(3);
if (buffer[0] == 0 && !active)
ImGuiNET.ImGui.GetWindowDrawList().AddText(pos + new Vector2(5, 3), Faded(Mute), hint);
}
private static void Wrapped(string text, uint color, float w)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, color);
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w);
ImGuiNET.ImGui.TextUnformatted(text);
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.PopStyleColor();
}
private static void Note(string text, float w) => Wrapped(text, Faded(Mute), w);
private static uint C(uint argb) => RynthTheme.Argb(argb);
}

View file

@ -115,9 +115,30 @@ internal sealed class SettingsFace : IImGuiPanel
float ty = p.Y + (26 - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
dl.AddText(new Vector2(p.X + 8, ty), sel ? Teal : Mute, TabLabel(tabName));
}
ReportButton(w);
ImGuiNET.ImGui.EndChild();
}
// At the sidebar's foot (below the tabs when they fill it): opens Report a problem.
private static void ReportButton(float w)
{
if (!ImGuiPanelHost.HasFace(ReportFace.Title)) return;
const float h = 26;
float bottom = ImGuiNET.ImGui.GetWindowHeight() - ImGuiNET.ImGui.GetStyle().WindowPadding.Y - h;
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
if (ImGuiNET.ImGui.GetCursorPosY() < bottom) ImGuiNET.ImGui.SetCursorPosY(bottom);
var dl = ImGuiNET.ImGui.GetWindowDrawList();
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
if (ImGuiNET.ImGui.InvisibleButton("##report", new Vector2(w, h)))
Report.ProblemReport.OpenPanel();
bool hot = ImGuiNET.ImGui.IsItemHovered();
ImGuiNET.ImGui.SetItemTooltip("Tell the staff what went wrong (also /rc report).");
dl.AddRectFilled(p, p + new Vector2(w, h), hot ? Lighten(BtnFill) : BtnFill);
dl.AddRect(p, p + new Vector2(w, h), BtnBord);
dl.AddText(new Vector2(p.X + 8, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), hot ? Amber : Mute,
PhosphorIcons.Warning + " Report a problem");
}
// ── Content: header + the tab's rows ───────────────────────────────────
private void Content(Vector2 size)

View file

@ -92,6 +92,7 @@ internal static unsafe class PhosphorIcons
public const string Info = "\uE2CE";
public const string Knife = "\uE636";
public const string Lightning = "\uE2DE";
public const string Leaf = "\uE2DA";
public const string ListChecks = "\uEADC";
public const string Lock = "\uE2FA";
public const string LockOpen = "\uE306";
@ -167,7 +168,7 @@ internal static unsafe class PhosphorIcons
+ ArrowCircleUp + Barbell + Brain + GraduationCap + Hourglass + SortDescending + Package
+ Binoculars + Crown + Sun
+ CastleTurret + ClockCounterClockwise + GlobeHemisphereWest + Path + Star + Target + User
+ TextAa;
+ TextAa + Leaf;
/// <summary>
/// Draws <paramref name="glyph"/> (one icon) centred in the box at

View file

@ -21,6 +21,8 @@ internal static class EngineSettings
private static bool _enableImGuiShell = true;
private static bool _enablePlugins = true;
private static bool _enableDatShareHook = true;
// Owned since f81fc8d: Save() writes it only when false (a hand-set false survives saves).
private static bool _enableLargeAddressAlignmentFix = true;
private static bool _enableAvaloniaOverlay = true;
private static bool _enableD3D9Hook = true;
private static bool _enableEngine = true;
@ -36,6 +38,15 @@ internal static class EngineSettings
private static bool _serverMessageStream = true;
private static bool _flightRecorder = true;
private static bool _insertReleasesUi;
// Read-only, like EnableLargeAddressAlignmentFix: only a hand-set value is written back.
private static int _maxHotReloads = ReloadCapNotice.DefaultMaxHotReloads;
// "IltServerNames" / "IltHosts": what counts as Infinite Leaftide (Compatibility/IltInfo.cs).
// null = not in the file: IltDetect's defaults.
private static List<string>? _iltServerNames;
private static List<string>? _iltHosts;
// "ReportEndpoint": where "Report a problem" posts (Report/ProblemReport.cs); null = the built-in URL.
// For testing only (https, or http to this PC); read only, like MaxHotReloads.
private static string? _reportEndpoint;
private static bool _loaded;
public static IReadOnlyList<string> PluginPaths
@ -82,6 +93,19 @@ internal static class EngineSettings
}
}
/// <summary>When false, LargeAddressAlignmentPatch leaves acclient's signed "pointer % 4"
/// padding code alone (stock AC behaviour, which corrupts unpacks of buffers above 2 GB).
/// Default true. Diagnostic kill-switch only: set "EnableLargeAddressAlignmentFix": false
/// in engine.json by hand.</summary>
public static bool EnableLargeAddressAlignmentFix
{
get
{
EnsureLoaded();
return _enableLargeAddressAlignmentFix;
}
}
/// <summary>When false, AvaloniaOverlay.Start() is skipped so the Avalonia STA thread,
/// the offscreen overlay window, and all OverlayHost-registered panels never instantiate.
/// Eliminates the entire Avalonia/Skia surface from the process. Compatibility hooks and
@ -323,6 +347,55 @@ internal static class EngineSettings
}
}
/// <summary>"MaxHotReloads" in engine.json (default 3, 2026-10-11): how many engine hot reloads
/// one client takes; the loader asks before each one (RynthCoreMaxHotReloads) and refuses the
/// rest, so a newer engine then needs a client restart. Clients died with CoreCLR fatal error
/// 0x80131506 after 4+ reloads in one process. Negative = no cap (test clients soaking
/// reloads), 0 = no hot reloads at all. Read at each engine init; edited in the file.</summary>
public static int MaxHotReloads
{
get
{
EnsureLoaded();
return _maxHotReloads;
}
}
/// <summary>"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.</summary>
public static string? ReportEndpoint
{
get
{
EnsureLoaded();
return _reportEndpoint;
}
}
/// <summary>"IltServerNames" in engine.json: world-name patterns ('*' wildcard, case-insensitive)
/// treated as Infinite Leaftide; null when the file has none (IltDetect.DefaultServerNames).
/// An empty array turns the world-name signal off. Read only: edited in the file.</summary>
public static IReadOnlyList<string>? IltServerNames
{
get
{
EnsureLoaded();
return _iltServerNames;
}
}
/// <summary>"IltHosts" in engine.json: launch hosts (a domain covers its subdomains, '*' allowed)
/// treated as Infinite Leaftide; null when the file has none (IltDetect.DefaultHosts).</summary>
public static IReadOnlyList<string>? IltHosts
{
get
{
EnsureLoaded();
return _iltHosts;
}
}
public static void AddPluginPath(string path)
{
EnsureLoaded();
@ -390,6 +463,12 @@ internal static class EngineSettings
_enableDatShareHook = datEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableLargeAddressAlignmentFix", out var laaEl) &&
(laaEl.ValueKind == JsonValueKind.True || laaEl.ValueKind == JsonValueKind.False))
{
_enableLargeAddressAlignmentFix = laaEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableAvaloniaOverlay", out var avEl) &&
(avEl.ValueKind == JsonValueKind.True || avEl.ValueKind == JsonValueKind.False))
{
@ -457,12 +536,30 @@ internal static class EngineSettings
(iruEl.ValueKind == JsonValueKind.True || iruEl.ValueKind == JsonValueKind.False))
_insertReleasesUi = iruEl.GetBoolean();
if (doc.RootElement.TryGetProperty("MaxHotReloads", out var mhrEl) &&
mhrEl.ValueKind == JsonValueKind.Number &&
mhrEl.TryGetInt32(out int mhr))
_maxHotReloads = mhr;
if (doc.RootElement.TryGetProperty("ReportEndpoint", out var repEl) &&
repEl.ValueKind == JsonValueKind.String &&
repEl.GetString() is { Length: > 0 } rep)
_reportEndpoint = rep.Trim();
if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) &&
(pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False))
{
_preventIdleLogoff = pilEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("IltServerNames", out var ilnEl) &&
ilnEl.ValueKind == JsonValueKind.Array)
_iltServerNames = ReadStringList(ilnEl);
if (doc.RootElement.TryGetProperty("IltHosts", out var ilhEl) &&
ilhEl.ValueKind == JsonValueKind.Array)
_iltHosts = ReadStringList(ilhEl);
if (doc.RootElement.TryGetProperty("DisabledUiHooks", out var duhEl) &&
duhEl.ValueKind == JsonValueKind.Array)
{
@ -479,6 +576,20 @@ internal static class EngineSettings
}
}
private static List<string> ReadStringList(JsonElement arr)
{
// Trimmed, blanks dropped, case-insensitive duplicates dropped (the file stays as the player wrote it).
var list = new List<string>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var el in arr.EnumerateArray())
{
if (el.ValueKind != JsonValueKind.String) continue;
string v = (el.GetString() ?? "").Trim();
if (v.Length > 0 && seen.Add(v)) list.Add(v);
}
return list;
}
/// <summary>Every engine.json key EnsureLoaded reads or Save writes. Save rewrites these from
/// memory (one written only when not the default is left out, as before) and keeps every
/// other key as the file had it. A new engine.json setting goes here too
@ -489,7 +600,8 @@ internal static class EngineSettings
"EnableAvaloniaOverlay", "EnableD3D9Hook", "EnableEngine", "EngineHookCount",
"EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge",
"DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream",
"FlightRecorder", "InsertReleasesUi",
"FlightRecorder", "InsertReleasesUi", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix",
"MaxHotReloads", "ReportEndpoint",
};
private static void Save()
@ -534,8 +646,16 @@ internal static class EngineSettings
w.WriteBoolean("ServerMessageStream", false);
if (!_flightRecorder) // default true: leave the file as it was
w.WriteBoolean("FlightRecorder", false);
if (!_enableLargeAddressAlignmentFix) // default true: only a hand-set false is written
w.WriteBoolean("EnableLargeAddressAlignmentFix", false);
if (_insertReleasesUi) // default false: leave the file as it was
w.WriteBoolean("InsertReleasesUi", true);
if (_maxHotReloads != ReloadCapNotice.DefaultMaxHotReloads) // only a hand-set value is written
w.WriteNumber("MaxHotReloads", _maxHotReloads);
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
WriteStringList(w, "IltHosts", _iltHosts);
w.WriteEndObject();
}
@ -554,6 +674,15 @@ internal static class EngineSettings
RynthLog.Plugin($"EngineSettings: Failed to save: {ex.Message}");
}
}
private static void WriteStringList(Utf8JsonWriter w, string name, List<string>? list)
{
if (list == null) return;
w.WriteStartArray(name);
foreach (string v in list)
w.WriteStringValue(v);
w.WriteEndArray();
}
}
/// <summary>engine.json "DecalBridge" (see <see cref="EngineSettings.DecalBridgeMode"/>).</summary>

View file

@ -0,0 +1,49 @@
namespace RynthCore.Engine;
/// <summary>
/// The engine's side of the hot-reload cap (2026-10-11). The native loader (native/Loader/Loader.c,
/// ReloadWatcher) asks the engine for engine.json MaxHotReloads before every hot reload and refuses
/// the reload once this client has done that many; the client keeps running on the current engine
/// and the loader tells the engine (RynthCoreReloadCapped), which logs it and says so in chat: once
/// on its own, and again whenever the player asks for a reload by hand (RL, /rc rl), so a button
/// press never goes unanswered. Clients died with CoreCLR fatal error 0x80131506 after 4+ engine
/// reloads in one process. No engine state here: tools/ReloadCapTests compiles this file in.
/// </summary>
internal sealed class ReloadCapNotice
{
/// <summary>engine.json MaxHotReloads when the file doesn't set it (and the loader's own
/// default for an engine without the export, DEFAULT_MAX_HOT_RELOADS in Loader.c).</summary>
public const int DefaultMaxHotReloads = 3;
/// <summary>How recent the engine's own reload signal must be to count as "asked by hand".</summary>
public const long ManualWindowMs = 10_000;
private bool _told;
/// <summary>The chat line for the player.</summary>
public static string ChatText(int reloads) =>
$"RynthCore: this client has hot reloaded {reloads} {(reloads == 1 ? "time" : "times")}; restart the client to pick up the new engine.";
/// <summary>The engine log line.</summary>
public static string LogText(int reloads, int cap, bool askedByHand) =>
$"Hot reload refused by the loader: this client has hot reloaded {reloads} time(s) and engine.json MaxHotReloads is {cap}" +
(askedByHand ? " (asked for by hand)" : "") + ". Staying on this engine; a client restart picks up the new one.";
/// <summary>True when the refusal should go to chat: the first one, and any the player asked
/// for by hand. Later automatic ones (an engine publish) are logged only.</summary>
public bool ShouldChat(bool askedByHand)
{
if (!_told)
{
_told = true;
return true;
}
return askedByHand;
}
/// <summary>True when a reload signal the engine sent at <paramref name="signaledAtMs"/>
/// (Environment.TickCount64; 0 = never) is recent enough at <paramref name="nowMs"/> to count
/// as the player's.</summary>
public static bool IsRecentManualSignal(long signaledAtMs, long nowMs) =>
signaledAtMs != 0 && nowMs - signaledAtMs >= 0 && nowMs - signaledAtMs < ManualWindowMs;
}

View file

@ -0,0 +1,429 @@
// ============================================================================
// RynthCore.Engine - Report/ProblemReport.cs
// "Report a problem": the player writes what went wrong and it reaches a
// private staff channel on Discord. The engine posts to our server
// (ProblemReportCore.DefaultEndpoint, https://aelrynth.com/rynth/report); the
// server holds the Discord webhook, rate-limits, keeps a copy and posts it
// (C:\Aeshnidae\ops\report-endpoint). The client holds no secret.
//
// Opened from the bar's grip menu, Settings (the sidebar's foot), "/rc report";
// "/rc report <text>" sends at once (with the log, the default).
//
// What is sent: the player's text; character, world, connect host, RynthCore /
// RynthAi / plugin versions, landcell, pid, engine generation; and - ticked by
// default, the player can untick it - the last 2,000 lines of this client's
// RynthCore.<pid>.log (it holds character names and some chat; the account,
// Windows user and PC names are hidden, ProblemReportCore.Redact; View opens
// exactly what will be sent).
//
// Threads:
// Send / RefreshTail / ViewTail / HandleCommand any thread (the panel calls them on AC's).
// The request runs on its own EngineThreads thread with a short-lived HttpClient,
// disposed when it finishes; Shutdown cancels and disposes one still in flight
// (the engine hot-reloads into a collectible context: nothing may outlive it).
// The log tail and the preview file are read / written on UiBackgroundWriter.
// One report per 60 s per client (ProblemReportCore.CooldownMs), kept in a process
// environment variable so an engine reload doesn't reset it.
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using RynthCore.Engine.Compatibility;
namespace RynthCore.Engine.Report;
internal enum ReportState { Idle, Sending, Sent, Failed }
internal static class ProblemReport
{
public const string PanelTitle = "Report a problem";
// Process-wide, so a hot reload (a new engine generation) keeps the cooldown.
private const string NextAllowedEnv = "RYNTHCORE_REPORT_NEXT_MS";
private static readonly object Sync = new();
private static int _state; // ReportState
private static string _message = "";
private static long _resultSeq; // bumps on every finished send (the panel clears its text on success)
private static long _messageSeq; // bumps on every new message (the panel shows only ones newer than its opening)
private static CancellationTokenSource _cts = new();
private static HttpClient? _inFlight;
private static volatile bool _shutdown;
private static volatile LogTail? _tail;
private static volatile string _tailError = "";
private static int _tailLoading;
public static ReportState State => (ReportState)Volatile.Read(ref _state);
public static string Message { get { lock (Sync) return _message; } }
public static long ResultSeq => Interlocked.Read(ref _resultSeq);
public static long MessageSeq => Interlocked.Read(ref _messageSeq);
/// <summary>The log tail the panel shows and sends (null until read, or when there's no log).</summary>
public static LogTail? Tail => _tail;
public static string TailError => _tailError;
public static bool TailLoading => Volatile.Read(ref _tailLoading) != 0;
/// <summary>Milliseconds until another report may be sent (0 = now).</summary>
public static long CooldownLeftMs => ProblemReportCore.CooldownLeft(Environment.TickCount64, NextAllowedMs());
// ── The log tail ─────────────────────────────────────────────────────
/// <summary>Reads this client's log tail again (background). Any thread.</summary>
public static void RefreshTail()
{
if (Interlocked.Exchange(ref _tailLoading, 1) != 0) return;
UI.UiBackgroundWriter.Enqueue("report log tail", static () =>
{
try
{
LogTail? t = ReadTailNow();
_ = t?.Gzip; // compressed here, not on AC's thread when the panel first shows the size
_tail = t;
_tailError = _tail == null ? "There's no RynthCore log for this client yet." : "";
}
catch (Exception ex)
{
_tail = null;
_tailError = "Couldn't read the log: " + ex.Message;
RynthLog.Warn($"ProblemReport: reading the log tail failed - {ex.GetType().Name}: {ex.Message}");
}
finally
{
Volatile.Write(ref _tailLoading, 0);
}
});
}
// The account (login) name, the Windows user name and the PC's name are hidden from the tail
// (ProblemReportCore.Redact), so neither View nor the report shows them.
private static LogTail? ReadTailNow() => ProblemReportCore.ReadTail(LogPaths.LogFilePath, LogPaths.RotatedLogFilePath,
hide: new[]
{
(SessionStateRegistry.LastAccountName ?? "", ProblemReportCore.HiddenAccount),
(SafeEnv(() => Environment.UserName), ProblemReportCore.HiddenUser),
(SafeEnv(() => Environment.MachineName), "<pc>"),
});
private static string SafeEnv(Func<string> read)
{
try { return read() ?? ""; }
catch { return ""; }
}
[DllImport("shell32.dll", CharSet = CharSet.Unicode, EntryPoint = "ShellExecuteW")]
private static extern IntPtr ShellExecuteW(IntPtr hwnd, string lpOperation, string lpFile,
string? lpParameters, string? lpDirectory, int nShowCmd);
/// <summary>
/// Writes <paramref name="tail"/> - exactly the bytes a report would carry - to
/// Logs\report-preview-&lt;pid&gt;.txt and opens it (the default text editor). Any thread.
/// ShellExecute, not Process.Start (the Process API is an AV hazard inside acclient.exe).
/// </summary>
public static void ViewTail(LogTail tail)
{
UI.UiBackgroundWriter.Enqueue("report log preview", () =>
{
try
{
string path = Path.Combine(LogPaths.LogDirectory, $"report-preview-{Environment.ProcessId}.txt");
File.WriteAllBytes(path, tail.Text);
IntPtr r = ShellExecuteW(IntPtr.Zero, "open", path, null, LogPaths.LogDirectory, 1 /* SW_SHOWNORMAL */);
if (r.ToInt64() <= 32)
SetMessage(State, $"Couldn't open the preview (code {r.ToInt64()}); it is at {path}");
}
catch (Exception ex)
{
RynthLog.Warn($"ProblemReport: preview failed - {ex.GetType().Name}: {ex.Message}");
SetMessage(State, "Couldn't write the preview: " + ex.Message);
}
});
}
// ── Sending ──────────────────────────────────────────────────────────
/// <summary>
/// Starts sending a report. <paramref name="tail"/> is the log to attach (null = none;
/// <paramref name="readTailIfNull"/> reads it fresh on the send thread, for /rc report text).
/// False with <paramref name="error"/> when it can't start (no text, cooldown, already
/// sending). <paramref name="announceInChat"/> = also say the result in chat. Any thread.
/// </summary>
public static bool Send(string description, string doing, LogTail? tail, bool readTailIfNull, bool announceInChat, out string error)
{
error = ProblemReportCore.ValidateDescription(description);
if (error.Length > 0) return false;
if (_shutdown) { error = "RynthCore is shutting down."; return false; }
ReportContext ctx;
try { ctx = GatherContext(); }
catch (Exception ex)
{
RynthLog.Warn($"ProblemReport: gathering the client details failed - {ex.GetType().Name}: {ex.Message}");
ctx = new ReportContext { Pid = Environment.ProcessId, RynthCoreVersion = EntryPoint.BuildStamp };
}
CancellationToken token;
lock (Sync)
{
if ((ReportState)_state == ReportState.Sending) { error = "A report is already being sent."; return false; }
long left = CooldownLeftMs;
if (left > 0) { error = $"You can send another report in {ProblemReportCore.FormatWait(left)}."; return false; }
_state = (int)ReportState.Sending;
_message = "Sending...";
Interlocked.Increment(ref _messageSeq);
SetNextAllowed(Environment.TickCount64 + ProblemReportCore.CooldownMs);
token = _cts.Token;
}
string endpoint = ProblemReportCore.ResolveEndpoint(Plugins.EngineSettings.ReportEndpoint, out string? rejected);
if (rejected != null)
RynthLog.Warn($"ProblemReport: engine.json ReportEndpoint '{rejected}' ignored (https only, or http to this PC); using {endpoint}.");
try
{
EngineThreads.Start("ProblemReport send", () => SendWorker(endpoint, description, doing, ctx, tail, readTailIfNull, announceInChat, token));
}
catch (Exception ex)
{
Finish(false, "Couldn't start sending: " + ex.Message, announceInChat, reachedServer: false);
error = "Couldn't start sending: " + ex.Message;
return false;
}
return true;
}
private static void SendWorker(string endpoint, string description, string doing, ReportContext ctx, LogTail? tail,
bool readTailIfNull, bool announceInChat, CancellationToken token)
{
HttpClient? http = null;
try
{
if (tail == null && readTailIfNull)
{
try { tail = ReadTailNow(); }
catch (Exception ex) { RynthLog.Warn($"ProblemReport: reading the log tail failed - {ex.GetType().Name}: {ex.Message}; sending without it."); }
}
if (tail != null && tail.Gzip.Length > ProblemReportCore.MaxGzipBytes)
{
RynthLog.Warn($"ProblemReport: the log is {tail.Gzip.Length} bytes gzipped (limit {ProblemReportCore.MaxGzipBytes}); sending without it.");
tail = null;
}
byte[] body = ProblemReportCore.BuildPayload(description, doing, ctx, tail, DateTime.UtcNow);
var handler = new SocketsHttpHandler
{
AllowAutoRedirect = false,
UseCookies = false,
ConnectTimeout = TimeSpan.FromSeconds(10),
PooledConnectionLifetime = TimeSpan.FromSeconds(30),
};
http = new HttpClient(handler, disposeHandler: true) { Timeout = TimeSpan.FromSeconds(45) };
lock (Sync)
{
if (_shutdown) return;
_inFlight = http;
}
using var req = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = new ByteArrayContent(body) };
req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
req.Headers.UserAgent.ParseAdd("RynthCore-Report/1");
req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using HttpResponseMessage resp = http.Send(req, HttpCompletionOption.ResponseHeadersRead, token);
int status = (int)resp.StatusCode;
string answer = ReadSmall(resp, token);
bool ok = ProblemReportCore.ReadResponse(status, answer, out string message, out string id);
RynthLog.Info($"ProblemReport: HTTP {status} from {endpoint} - {(ok ? "taken" + (id.Length > 0 ? " as " + id : "") : message)} " +
$"(body {body.Length} bytes, log {(tail == null ? "not attached" : $"{tail.Lines} lines")}).");
Finish(ok, message, announceInChat, reachedServer: true);
}
catch (OperationCanceledException) when (_shutdown || token.IsCancellationRequested)
{
Finish(false, "Cancelled (RynthCore was reloading).", announceInChat, reachedServer: false);
}
catch (OperationCanceledException)
{
Finish(false, "The report service didn't answer in time. Please try again in a moment.", announceInChat, reachedServer: false);
}
catch (HttpRequestException ex)
{
RynthLog.Warn($"ProblemReport: network error - {ex.Message}");
Finish(false, "Couldn't reach the report service (" + ex.Message + "). Check your connection and try again.", announceInChat, reachedServer: false);
}
catch (Exception ex)
{
RynthLog.Warn($"ProblemReport: send failed - {ex.GetType().Name}: {ex.Message}");
Finish(false, $"Couldn't send the report ({ex.GetType().Name}).", announceInChat, reachedServer: false);
}
finally
{
lock (Sync)
{
if (ReferenceEquals(_inFlight, http)) _inFlight = null;
}
try { http?.Dispose(); } catch { }
}
}
/// <summary>The answer's first 8 KB as text (the server's answers are tiny).</summary>
private static string ReadSmall(HttpResponseMessage resp, CancellationToken token)
{
try
{
using Stream s = resp.Content.ReadAsStream(token);
var buf = new byte[8192];
int total = 0, n;
while (total < buf.Length && (n = s.Read(buf, total, buf.Length - total)) > 0) total += n;
return Encoding.UTF8.GetString(buf, 0, total);
}
catch
{
return "";
}
}
private static void Finish(bool ok, string message, bool announceInChat, bool reachedServer)
{
lock (Sync)
{
_state = (int)(ok ? ReportState.Sent : ReportState.Failed);
_message = message;
// A send that never reached the server may be retried soon; one that did keeps the full minute.
if (!ok && !reachedServer)
SetNextAllowed(Environment.TickCount64 + ProblemReportCore.RetryAfterFailureMs);
Interlocked.Increment(ref _resultSeq);
Interlocked.Increment(ref _messageSeq);
}
if (announceInChat && !_shutdown)
AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] Report: " + message, 1);
}
private static void SetMessage(ReportState state, string message)
{
lock (Sync)
{
_state = (int)state;
_message = message;
Interlocked.Increment(ref _messageSeq);
}
}
// Read from the process environment once per engine generation; the panel reads the field each frame.
private static long _nextAllowedMs = ReadNextAllowedEnv();
private static long NextAllowedMs() => Interlocked.Read(ref _nextAllowedMs);
private static long ReadNextAllowedEnv()
{
try
{
return long.TryParse(Environment.GetEnvironmentVariable(NextAllowedEnv), out long v) ? v : 0;
}
catch { return 0; }
}
private static void SetNextAllowed(long tickMs)
{
Interlocked.Exchange(ref _nextAllowedMs, tickMs);
try { Environment.SetEnvironmentVariable(NextAllowedEnv, tickMs.ToString(System.Globalization.CultureInfo.InvariantCulture)); }
catch { }
}
// ── What the report says about the client ───────────────────────────
/// <summary>Character, world, versions, landcell, pid. Any thread (cached reads only).</summary>
public static ReportContext GatherContext()
{
var ctx = new ReportContext
{
Pid = Environment.ProcessId,
RynthCoreVersion = EntryPoint.BuildStamp,
ApiVersion = (int)Plugins.PluginContractVersion.Current,
Generation = EntryPoint.InitCount,
};
string character = "";
uint player = ClientHelperHooks.GetPlayerId();
if (player != 0 && ClientObjectHooks.TryGetSnapshotName(player, out string live)) character = live;
if (string.IsNullOrWhiteSpace(character)) character = SessionStateRegistry.LastCharacterName ?? "";
ctx.Character = character;
string world = AccountHooks.AnnouncedWorldName ?? "";
if (string.IsNullOrWhiteSpace(world)) world = SessionStateRegistry.LastServerName ?? "";
ctx.World = world;
string host = ServerInfo.HostDescription;
ctx.Connect = host == "(none)" ? "" : host;
ctx.Aelrynth = ServerInfo.IsAelrynth;
try
{
// A copy (the list changes only on load / unload / RL; a copy taken mid-change just lists less).
Plugins.LoadedPlugin[] plugins = System.Linq.Enumerable.ToArray(Plugins.PluginManager.Plugins);
foreach (Plugins.LoadedPlugin p in plugins)
{
string name = p.DisplayName.Length > 0 ? p.DisplayName : Path.GetFileNameWithoutExtension(p.FileName);
string version = p.VersionString + (p.Failed ? " (failed)" : p.NotStartedReason.Length > 0 ? " (not started)" : "");
ctx.Plugins.Add((name, version));
if (ctx.RynthAiVersion.Length == 0 && !p.Failed
&& (name.Equals("RynthAi", StringComparison.OrdinalIgnoreCase)
|| p.FileName.Equals("RynthCore.Plugin.RynthAi.dll", StringComparison.OrdinalIgnoreCase)))
ctx.RynthAiVersion = p.VersionString.Length > 0 ? p.VersionString : "loaded";
}
}
catch (Exception ex)
{
RynthLog.Verbose($"ProblemReport: plugin list unavailable - {ex.Message}");
}
if (ClientObjectHooks.TryGetPlayerStats(out _, out _, out _, out _, out _, out _, out uint landcell, out _, out _, out _))
ctx.Landcell = landcell;
return ctx;
}
// ── /rc report ───────────────────────────────────────────────────────
/// <summary>"/rc report" opens the panel; "/rc report &lt;text&gt;" sends it now (with the log). Lines for chat.</summary>
public static IEnumerable<string> HandleCommand(string args)
{
if (string.IsNullOrWhiteSpace(args))
{
if (!ImGuiBackend.ImGuiPanelHost.HasFace(PanelTitle))
return new[] { "The Report a problem panel isn't available (the ImGui layer is off?). Use /rc report <what went wrong> to send one from chat." };
OpenPanel();
return Array.Empty<string>();
}
if (!Send(args, "", tail: null, readTailIfNull: true, announceInChat: true, out string error))
return new[] { "Report not sent: " + error };
return new[] { "Sending your report (with your recent RynthCore log; use the panel, /rc report, to leave the log out)..." };
}
/// <summary>Opens the panel (it reads the log tail when it opens). Any thread.</summary>
public static void OpenPanel()
{
if (!ImGuiBackend.ImGuiPanelHost.IsOpen(PanelTitle))
UI.PanelRouter.Toggle(PanelTitle);
}
// ── Shutdown ─────────────────────────────────────────────────────────
/// <summary>Cancels a send in flight and disposes its HttpClient (engine shutdown / hot reload).</summary>
public static void Shutdown()
{
HttpClient? http;
lock (Sync)
{
_shutdown = true;
http = _inFlight;
_inFlight = null;
}
try { _cts.Cancel(); } catch { }
try { http?.Dispose(); } catch { }
_tail = null;
}
}

View file

@ -0,0 +1,462 @@
// ============================================================================
// RynthCore.Engine - Report/ProblemReportCore.cs
// The pure half of "Report a problem" (ProblemReport.cs is the engine half):
// the text limits, the log tail, the request body, the client's cooldown and
// the reading of the server's answer. No engine state, no AC, no network, so
// tools/ProblemReportTests compiles this file and checks it offline.
//
// Wire format (POST https://aelrynth.com/rynth/report, application/json; the
// server side is C:\Aeshnidae\ops\report-endpoint\app.py, which refuses any
// other shape):
// { "schema": 1,
// "description": "...", "doing": "...", the player's text
// "character": "...", "world": "...", "connect": "host:port", "aelrynth": true,
// "rynthcore": "2026.10.9.3 (194ea47)", "api": 81, "generation": 1,
// "rynthai": "2026.10.9.3 (e6fffb0)" | "",
// "plugins": [ { "name": "RynthAi", "version": "..." } ],
// "landcell": "0x12340105" | "",
// "pid": 1234, "clientTime": "2026-10-11T12:00:00Z",
// "log": null | { "name": "RynthCore.1234.log", "lines": 2000, "bytes": 214000,
// "gzip": "<base64 of the gzipped tail>" } }
// The server answers JSON: { "ok": true, "id": "R-..." } or { "error": "..." }.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace RynthCore.Engine.Report;
/// <summary>What the report says about the client, gathered when it is sent.</summary>
internal sealed class ReportContext
{
public string Character = "";
public string World = "";
public string Connect = "";
public bool Aelrynth;
public string RynthCoreVersion = "";
public int ApiVersion;
public int Generation;
public string RynthAiVersion = "";
public List<(string Name, string Version)> Plugins = new();
public uint Landcell;
public int Pid;
}
/// <summary>The end of a log file, exactly as it will be sent (and shown by View).</summary>
internal sealed class LogTail
{
public string FileName = "";
public byte[] Text = Array.Empty<byte>();
public int Lines;
/// <summary>The tail began in the rotated .old file (the current one was shorter than asked).</summary>
public bool IncludesOld;
public DateTime TakenLocal;
private byte[]? _gzip;
/// <summary>The gzipped text (made once).</summary>
public byte[] Gzip => _gzip ??= ProblemReportCore.Gzip(Text);
}
internal static class ProblemReportCore
{
public const string DefaultEndpoint = "https://aelrynth.com/rynth/report";
// Text limits (UTF-8 bytes). The server takes no more (app.py MAX_DESCRIPTION / MAX_DOING).
public const int MaxDescriptionBytes = 2500;
public const int MaxDoingBytes = 1500;
public const int MinDescriptionChars = 3;
// The log: the last 2,000 lines, at most 1.5 MB of them (the end is kept). The server
// takes 2 MB of gzip; 1.5 MB of log text gzips to a few hundred KB.
public const int TailLines = 2000;
public const int MaxTailBytes = 1_500_000;
public const int MaxGzipBytes = 2_000_000;
// Short strings the server checks the same way.
public const int MaxShortField = 64;
public const int MaxConnectField = 100;
public const int MaxPlugins = 32;
/// <summary>One report per minute per client; a send that never reached the server waits only this.</summary>
public const int CooldownMs = 60_000;
public const int RetryAfterFailureMs = 10_000;
// ── Text ─────────────────────────────────────────────────────────────
/// <summary>
/// <paramref name="text"/> trimmed, CR LF made LF, other control characters (except tab)
/// dropped, then cut to <paramref name="maxBytes"/> of UTF-8 at a character boundary.
/// </summary>
public static string CleanText(string? text, int maxBytes)
{
if (string.IsNullOrEmpty(text)) return "";
var sb = new StringBuilder(text.Length);
foreach (char c in text.Replace("\r\n", "\n").Replace('\r', '\n'))
{
if (c == '\n' || c == '\t' || !char.IsControl(c)) sb.Append(c);
}
return TrimUtf8(sb.ToString().Trim(), maxBytes);
}
/// <summary>A one-line field: control characters dropped, trimmed, cut to <paramref name="maxChars"/>.</summary>
public static string CleanShort(string? text, int maxChars)
{
if (string.IsNullOrEmpty(text)) return "";
var sb = new StringBuilder(text.Length);
foreach (char c in text)
if (!char.IsControl(c)) sb.Append(c);
string s = sb.ToString().Trim();
if (s.Length > maxChars)
{
int n = maxChars;
if (char.IsHighSurrogate(s[n - 1])) n--;
s = s.Substring(0, n);
}
return s;
}
/// <summary>Cuts <paramref name="s"/> to at most <paramref name="maxBytes"/> of UTF-8, never inside a character.</summary>
public static string TrimUtf8(string s, int maxBytes)
{
if (Encoding.UTF8.GetByteCount(s) <= maxBytes) return s;
int bytes = 0, i = 0;
while (i < s.Length)
{
int len = char.IsHighSurrogate(s[i]) && i + 1 < s.Length && char.IsLowSurrogate(s[i + 1]) ? 2 : 1;
int cb = Encoding.UTF8.GetByteCount(s.AsSpan(i, len));
if (bytes + cb > maxBytes) break;
bytes += cb;
i += len;
}
return s.Substring(0, i);
}
/// <summary>Why <paramref name="description"/> can't be sent, or "" when it can.</summary>
public static string ValidateDescription(string description)
{
string d = CleanText(description, MaxDescriptionBytes);
if (d.Length == 0) return "Write what went wrong first.";
if (d.Length < MinDescriptionChars) return "Say a little more about what went wrong.";
return "";
}
// ── The log tail ─────────────────────────────────────────────────────
/// <summary>
/// The last <paramref name="maxLines"/> lines of <paramref name="path"/> (at most
/// <paramref name="maxBytes"/>; a cut first line is dropped), read while the engine
/// may be appending to it: the file is opened for shared read/write and read up to the
/// length it had when opened. When it holds fewer lines than asked and
/// <paramref name="olderPath"/> exists (the rotated .old), the rest comes from there.
/// Null when the file doesn't exist. Throws on other I/O errors.
/// </summary>
public static LogTail? ReadTail(string path, string? olderPath, int maxLines = TailLines, int maxBytes = MaxTailBytes,
DateTime? now = null, IReadOnlyList<(string Name, string Replacement)>? hide = null)
{
if (!File.Exists(path)) return null;
byte[] current = TailBytes(path, maxLines, maxBytes, out int lines);
bool includesOld = false;
if (lines < maxLines && current.Length < maxBytes && !string.IsNullOrEmpty(olderPath) && File.Exists(olderPath))
{
byte[] older = TailBytes(olderPath, maxLines - lines, maxBytes - current.Length, out int olderLines);
if (older.Length > 0)
{
// The older file's last line may lack its newline; keep the lines apart.
bool needNewline = older[^1] != (byte)'\n';
var merged = new byte[older.Length + (needNewline ? 1 : 0) + current.Length];
Buffer.BlockCopy(older, 0, merged, 0, older.Length);
if (needNewline) merged[older.Length] = (byte)'\n';
Buffer.BlockCopy(current, 0, merged, merged.Length - current.Length, current.Length);
current = merged;
lines += olderLines;
includesOld = true;
}
}
current = Redact(current, hide);
return new LogTail
{
FileName = Path.GetFileName(path),
Text = current,
Lines = lines,
IncludesOld = includesOld,
TakenLocal = now ?? DateTime.Now,
};
}
/// <summary>The last <paramref name="maxLines"/> whole lines of a file, at most <paramref name="maxBytes"/>.</summary>
internal static byte[] TailBytes(string path, int maxLines, int maxBytes, out int lines)
{
lines = 0;
if (maxLines <= 0 || maxBytes <= 0) return Array.Empty<byte>();
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete,
bufferSize: 1, FileOptions.None);
long length = fs.Length;
if (length == 0) return Array.Empty<byte>();
// Read backwards in chunks until there are enough newlines or the byte cap is reached.
const int Chunk = 64 * 1024;
long start = length;
var chunks = new List<byte[]>();
int newlines = 0;
long have = 0;
// A last line still being written (no newline yet) counts as a line; a trailing newline doesn't start one.
while (start > 0 && have < maxBytes)
{
int size = (int)Math.Min(Chunk, Math.Min(start, maxBytes - have + 1));
start -= size;
var buf = new byte[size];
fs.Position = start;
int read = 0;
while (read < size)
{
int n = fs.Read(buf, read, size - read);
if (n <= 0) break; // the file shrank under us (rotated): use what came
read += n;
}
if (read < size) Array.Resize(ref buf, read);
chunks.Insert(0, buf);
have += buf.Length;
foreach (byte b in buf) if (b == (byte)'\n') newlines++;
if (newlines > maxLines) break;
}
var all = new byte[have];
int at = 0;
foreach (byte[] c in chunks) { Buffer.BlockCopy(c, 0, all, at, c.Length); at += c.Length; }
int end = all.Length;
int scanEnd = end > 0 && all[end - 1] == (byte)'\n' ? end - 1 : end;
// Walk back over maxLines newlines (from the end, not counting the trailing one).
int from = 0;
int seen = 0;
bool cut = false;
for (int i = scanEnd - 1; i >= 0; i--)
{
if (all[i] != (byte)'\n') continue;
seen++;
if (seen == maxLines) { from = i + 1; cut = true; break; }
}
if (!cut && start > 0)
{
// Stopped by the byte cap mid-file: drop the partial first line.
int nl = Array.IndexOf(all, (byte)'\n');
from = nl < 0 ? end : nl + 1;
}
// The byte cap: keep the end, starting at a line.
if (end - from > maxBytes)
{
int nl = Array.IndexOf(all, (byte)'\n', end - maxBytes);
from = nl < 0 ? end : nl + 1;
}
byte[] result = from == 0 ? all : all.AsSpan(from, end - from).ToArray();
lines = CountLines(result);
return result;
}
// SessionStateRegistry logs "account='<login name>'" at login; the login name is half a credential.
private static readonly Regex AccountField = new(@"account='[^'\r\n]*'", RegexOptions.CultureInvariant);
// Paths under the Windows profile (C:\Users\<name>\AppData\...) carry the Windows user name.
private static readonly Regex ProfilePath = new(@"(?i)\b([A-Z]:[\\/]Users[\\/])[^\\/\r\n'""<>|]+", RegexOptions.CultureInvariant);
public const string HiddenAccount = "<account>";
public const string HiddenUser = "<user>";
/// <summary>
/// The log text with private names hidden: every account='...' field and every occurrence (any
/// case) of each name in <paramref name="hide"/> (3 characters or more) become its replacement
/// (&lt;account&gt;, &lt;user&gt;, ...), and the folder after X:\Users\ becomes &lt;user&gt;.
/// Done before the size is shown and before View, so View shows what is sent.
/// </summary>
public static byte[] Redact(byte[] text, IReadOnlyList<(string Name, string Replacement)>? hide)
{
if (text.Length == 0) return text;
string s = Encoding.UTF8.GetString(text);
string r = AccountField.Replace(s, "account='" + HiddenAccount + "'");
r = ProfilePath.Replace(r, "$1" + HiddenUser);
if (hide != null)
{
foreach (var (name, replacement) in hide)
{
string w = (name ?? "").Trim();
if (w.Length < 3) continue;
r = Regex.Replace(r, Regex.Escape(w), replacement.Replace("$", "$$"), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
}
}
return string.Equals(r, s, StringComparison.Ordinal) ? text : Encoding.UTF8.GetBytes(r);
}
/// <summary>Lines in a text: newlines, plus one for a last line without one.</summary>
public static int CountLines(ReadOnlySpan<byte> text)
{
if (text.Length == 0) return 0;
int n = 0;
foreach (byte b in text) if (b == (byte)'\n') n++;
return text[^1] == (byte)'\n' ? n : n + 1;
}
public static byte[] Gzip(byte[] data)
{
using var ms = new MemoryStream(data.Length / 4 + 64);
using (var gz = new GZipStream(ms, CompressionLevel.Optimal, leaveOpen: true))
gz.Write(data, 0, data.Length);
return ms.ToArray();
}
// ── The request body ─────────────────────────────────────────────────
/// <summary>The JSON body (see the file header). <paramref name="log"/> null = not attached.</summary>
public static byte[] BuildPayload(string description, string doing, ReportContext ctx, LogTail? log, DateTime utcNow)
{
using var ms = new MemoryStream(1024 + (log == null ? 0 : log.Gzip.Length * 4 / 3 + 256));
using (var w = new Utf8JsonWriter(ms))
{
w.WriteStartObject();
w.WriteNumber("schema", 1);
w.WriteString("description", CleanText(description, MaxDescriptionBytes));
w.WriteString("doing", CleanText(doing, MaxDoingBytes));
w.WriteString("character", CleanShort(ctx.Character, MaxShortField));
w.WriteString("world", CleanShort(ctx.World, MaxShortField));
w.WriteString("connect", CleanShort(ctx.Connect, MaxConnectField));
w.WriteBoolean("aelrynth", ctx.Aelrynth);
w.WriteString("rynthcore", CleanShort(ctx.RynthCoreVersion, MaxShortField));
w.WriteNumber("api", Math.Clamp(ctx.ApiVersion, 0, 1_000_000));
w.WriteNumber("generation", Math.Clamp(ctx.Generation, 0, 1_000_000));
w.WriteString("rynthai", CleanShort(ctx.RynthAiVersion, MaxShortField));
w.WriteStartArray("plugins");
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var (name, version) in ctx.Plugins)
{
string n = PluginName(name);
if (n.Length == 0 || !seen.Add(n)) continue;
if (seen.Count > MaxPlugins) break;
w.WriteStartObject();
w.WriteString("name", n);
w.WriteString("version", CleanShort(version, MaxShortField));
w.WriteEndObject();
}
w.WriteEndArray();
w.WriteString("landcell", ctx.Landcell != 0 ? "0x" + ctx.Landcell.ToString("X8", CultureInfo.InvariantCulture) : "");
w.WriteNumber("pid", Math.Max(0, ctx.Pid));
w.WriteString("clientTime", utcNow.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture));
if (log == null || log.Text.Length == 0)
{
w.WriteNull("log");
}
else
{
w.WriteStartObject("log");
w.WriteString("name", CleanShort(log.FileName, MaxShortField));
w.WriteNumber("lines", log.Lines);
w.WriteNumber("bytes", log.Text.Length);
w.WriteBase64String("gzip", log.Gzip);
w.WriteEndObject();
}
w.WriteEndObject();
}
return ms.ToArray();
}
/// <summary>A plugin name as the server accepts it: letters, digits, space . _ - (40 at most).</summary>
public static string PluginName(string? name)
{
if (string.IsNullOrEmpty(name)) return "";
var sb = new StringBuilder();
foreach (char c in name)
if (c is (>= 'A' and <= 'Z') or (>= 'a' and <= 'z') or (>= '0' and <= '9') or ' ' or '.' or '_' or '-')
sb.Append(c);
string s = sb.ToString().Trim();
return s.Length > 40 ? s.Substring(0, 40).Trim() : s;
}
// ── The endpoint ─────────────────────────────────────────────────────
/// <summary>
/// The URL reports go to: <paramref name="overrideUrl"/> (engine.json "ReportEndpoint", for
/// testing) when it is https, or http to this PC; otherwise the built-in one.
/// </summary>
public static string ResolveEndpoint(string? overrideUrl, out string? rejected)
{
rejected = null;
if (string.IsNullOrWhiteSpace(overrideUrl)) return DefaultEndpoint;
if (Uri.TryCreate(overrideUrl.Trim(), UriKind.Absolute, out Uri? u) && string.IsNullOrEmpty(u.UserInfo)
&& (u.Scheme == Uri.UriSchemeHttps
|| (u.Scheme == Uri.UriSchemeHttp && (u.IsLoopback || u.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase)))))
return u.AbsoluteUri;
rejected = overrideUrl;
return DefaultEndpoint;
}
// ── The answer ───────────────────────────────────────────────────────
/// <summary>
/// What the player is told about the server's answer. True when the report was taken;
/// <paramref name="id"/> is its id (may be empty). Never throws.
/// </summary>
public static bool ReadResponse(int status, string? body, out string message, out string id)
{
id = "";
string serverError = "";
try
{
if (!string.IsNullOrWhiteSpace(body) && body.TrimStart().StartsWith('{'))
{
using var doc = JsonDocument.Parse(body);
var root = doc.RootElement;
if (root.ValueKind == JsonValueKind.Object)
{
if (root.TryGetProperty("id", out var idEl) && idEl.ValueKind == JsonValueKind.String)
id = CleanShort(idEl.GetString(), 40);
if (root.TryGetProperty("error", out var errEl) && errEl.ValueKind == JsonValueKind.String)
serverError = CleanShort(errEl.GetString(), 200);
}
}
}
catch (JsonException) { }
if (status is >= 200 and < 300)
{
message = id.Length > 0 ? $"Sent. Thank you! (report {id})" : "Sent. Thank you!";
return true;
}
message = status switch
{
429 => serverError.Length > 0 ? serverError : "Too many reports from here right now. Please try again later.",
413 => "The report is too large to send. Untick the log and try again.",
400 or 415 or 422 => serverError.Length > 0 ? "The server refused the report: " + serverError : "The server refused the report.",
404 => "The report service isn't available yet (HTTP 404).",
>= 500 => "The report service has a problem right now (HTTP " + status + "). Please try again later.",
_ => serverError.Length > 0 ? $"HTTP {status}: {serverError}" : $"The report service answered HTTP {status}.",
};
return false;
}
// ── The cooldown ─────────────────────────────────────────────────────
/// <summary>Milliseconds until the next report may be sent (0 = now). <paramref name="nextAllowedMs"/> is a TickCount64 value.</summary>
public static long CooldownLeft(long nowMs, long nextAllowedMs) => Math.Max(0, nextAllowedMs - nowMs);
/// <summary>"42 s" / "1 min 5 s".</summary>
public static string FormatWait(long ms)
{
long s = (ms + 999) / 1000;
return s < 60 ? $"{s} s" : $"{s / 60} min {s % 60} s";
}
/// <summary>"812 bytes" / "214 KB" / "1.4 MB".</summary>
public static string FormatSize(long bytes)
{
if (bytes < 1024) return bytes.ToString(CultureInfo.InvariantCulture) + " bytes";
if (bytes < 1024 * 1024) return ((bytes + 512) / 1024).ToString(CultureInfo.InvariantCulture) + " KB";
return (bytes / (1024.0 * 1024.0)).ToString("0.0", CultureInfo.InvariantCulture) + " MB";
}
/// <summary>The panel's line about the log: "RynthCore.1234.log: 1,987 lines, 214 KB (31 KB compressed), taken 14:02:11".</summary>
public static string DescribeTail(LogTail t) =>
$"{t.FileName}{(t.IncludesOld ? " (+ .old)" : "")}: {t.Lines.ToString("N0", CultureInfo.InvariantCulture)} lines, " +
$"{FormatSize(t.Text.Length)} ({FormatSize(t.Gzip.Length)} compressed), taken {t.TakenLocal:HH:mm:ss}";
}

View file

@ -67,6 +67,8 @@
<PackageReference Include="Avalonia.Skia" Version="11.2.3" />
<PackageReference Include="Avalonia.Themes.Simple" Version="11.2.3" />
<PackageReference Include="Avalonia.AvaloniaEdit" Version="11.2.0" />
<!-- Avalonia pulls Tmds.DBus.Protocol 0.20.0 (GHSA-xrw6-gwf8-vvr9; D-Bus is Linux-only, but pin the fixed version). -->
<PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" />
</ItemGroup>
<ItemGroup>

View file

@ -0,0 +1,103 @@
// ============================================================================
// RynthCore.Engine - UI/Data/BountiesData.cs
// The RynthILT plugin's ACECustom bounty tracker for the Bounties face (the
// ILT section; ported from SilentKelpie's rynth/RynthCore PR #5, where it
// read RynthAi).
//
// RynthILTGetBountiesJson frees its previous buffer on each call, so the hub
// is its only caller (BountiesSource, 1 s). The plugin also reads those polls
// as "the window is open": its quiet /bounty list reads run only while this
// source is subscribed AND polling. The source polls only on Infinite
// Leaftide (IltInfo.IsIlt), so a Bounties window left open anywhere else
// never makes RynthILT send anything. RynthILTBountyCommand runs on the pump
// (it changes state the plugin's tick uses) and refreshes the snapshot.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI.Data;
/// <summary>RynthILTGetBountiesJson while the Bounties face is open on ILT (1 s, and after each command).</summary>
internal sealed unsafe class BountiesSource : UiSource<BountiesSnapshot>
{
/// <summary>The plugin's display name (PluginExportBinder matches on it).</summary>
public const string PluginName = "RynthILT";
private delegate* unmanaged[Cdecl]<IntPtr> _get;
private string? _lastJson;
private volatile bool _exportMissing;
private volatile bool _notIlt;
public BountiesSource() : base("Bounties", periodMs: 1000) { }
/// <summary>True when RynthILT is loaded but has no RynthILTGetBountiesJson (an older or broken build).</summary>
public bool ExportMissing => _exportMissing;
/// <summary>True when the last poll was skipped because this isn't Infinite Leaftide.</summary>
public bool NotIlt => _notIlt;
protected internal override void Poll()
{
// Off ILT nothing is polled, so the plugin never thinks the window is open there.
if (!IltInfo.IsIlt)
{
_notIlt = true;
return;
}
_notIlt = false;
if (_get == null)
_get = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve(PluginName, "RynthILTGetBountiesJson");
_exportMissing = _get == null && PluginExportBinder.Resolve(PluginName, "RynthPluginTick") != IntPtr.Zero;
if (_get == null) return;
IntPtr ptr = _get();
string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(ptr);
if (string.IsNullOrEmpty(json) || json == _lastJson) return;
BountiesSnapshot? parsed;
try { parsed = BountiesSnapshot.Parse(json); }
catch { return; }
if (parsed == null) return;
_lastJson = json;
Publish(parsed);
}
protected internal override void Reset()
{
_get = null;
_lastJson = null;
_exportMissing = false;
ClearSnapshot();
}
}
internal static unsafe class BountiesCommands
{
private static delegate* unmanaged[Cdecl]<IntPtr, void> _command;
static BountiesCommands()
{
PluginManager.PluginsUnloaded += () => _command = null;
}
/// <summary>Re-reads /bounty list (the plugin keeps its own minimum interval).</summary>
public static void Refresh() => Send("refresh");
/// <summary>Sets one tracker option (refreshonkills, minrefreshseconds, periodicminutes, hideqblocked, sortbyprogress).</summary>
public static void Set(string option, string value) => Send($"set {option} {value}");
public static void Set(string option, bool on) => Send($"set {option} {(on ? "1" : "0")}");
private static void Send(string text) => UiDataHub.Post("Bounties " + text, () =>
{
if (!IltInfo.IsIlt) return;
if (_command == null)
_command = (delegate* unmanaged[Cdecl]<IntPtr, void>)PluginExportBinder.Resolve(BountiesSource.PluginName, "RynthILTBountyCommand");
if (_command == null) return;
IntPtr utf8 = Marshal.StringToCoTaskMemUTF8(text);
try { _command(utf8); }
finally { Marshal.FreeCoTaskMem(utf8); }
UiSources.Bounties.RequestRefresh();
});
}

View file

@ -0,0 +1,70 @@
// ============================================================================
// RynthCore.Engine - UI/Data/BountiesSnapshotJson.cs
// The Bounties window's JSON shape, as the RynthILT plugin's
// RynthILTGetBountiesJson writes it (mirrors
// RynthCore.Plugin.RynthILT.Bounty.BountyBridgePayload). Self-contained:
// RynthSuite's Tools/RynthILT.Tests links this file to check the plugin's
// output parses here.
//
// Compatibility: unknown properties are skipped and missing ones keep their
// defaults, so either side can add fields without breaking the other.
// ============================================================================
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace RynthCore.Engine.UI.Data;
/// <summary>Where the player stands on one reward (the plugin's BountyStatus).</summary>
internal enum BountyRowStatus
{
Counting = 0,
Cooldown = 1,
NeedsQb = 2,
}
internal sealed class BountiesSnapshot
{
[JsonPropertyName("unsupported")] public bool Unsupported { get; set; }
[JsonPropertyName("reading")] public bool Reading { get; set; }
[JsonPropertyName("status")] public string Status { get; set; } = string.Empty;
/// <summary>Seconds since the last list read; -1 = never.</summary>
[JsonPropertyName("listedAgoSec")] public int ListedAgoSec { get; set; } = -1;
[JsonPropertyName("noneAnywhere")] public bool NoneAnywhere { get; set; }
[JsonPropertyName("lastEvent")] public string LastEvent { get; set; } = string.Empty;
[JsonPropertyName("lastEventAgoSec")] public int LastEventAgoSec { get; set; } = -1;
[JsonPropertyName("refreshOnKills")] public bool RefreshOnKills { get; set; }
[JsonPropertyName("minRefreshSeconds")] public int MinRefreshSeconds { get; set; }
[JsonPropertyName("periodicRefreshMinutes")] public int PeriodicRefreshMinutes { get; set; }
[JsonPropertyName("hideQbLocked")] public bool HideQbLocked { get; set; }
[JsonPropertyName("sortByProgress")] public bool SortByProgress { get; set; }
/// <summary>Rows the plugin left out because of HideQbLocked.</summary>
[JsonPropertyName("hiddenCount")] public int HiddenCount { get; set; }
[JsonPropertyName("rows")] public List<BountyRowJson> Rows { get; set; } = new();
/// <summary>Parses one RynthILTGetBountiesJson reply; null for "null". Throws on malformed JSON.</summary>
public static BountiesSnapshot? Parse(string json) =>
JsonSerializer.Deserialize(json, BountiesJsonContext.Default.BountiesSnapshot);
}
/// <summary>One reward of one bounty area, with the status as of the plugin's poll.</summary>
internal sealed class BountyRowJson
{
[JsonPropertyName("where")] public string Where { get; set; } = string.Empty;
[JsonPropertyName("amount")] public long Amount { get; set; }
[JsonPropertyName("item")] public string Item { get; set; } = string.Empty;
[JsonPropertyName("killsRequired")] public int KillsRequired { get; set; }
[JsonPropertyName("cooldownSeconds")] public int CooldownSeconds { get; set; }
/// <summary>A <see cref="BountyRowStatus"/> value; an ended cooldown already reads Counting.</summary>
[JsonPropertyName("status")] public int Status { get; set; }
[JsonPropertyName("kills")] public int Kills { get; set; }
[JsonPropertyName("unlockInSec")] public int UnlockInSec { get; set; }
[JsonPropertyName("qbRequired")] public long QbRequired { get; set; }
[JsonPropertyName("qbHave")] public long QbHave { get; set; }
/// <summary>Kills went up (or an award reset them) in the last 15 seconds.</summary>
[JsonPropertyName("changed")] public bool Changed { get; set; }
}
[JsonSerializable(typeof(BountiesSnapshot))]
internal partial class BountiesJsonContext : JsonSerializerContext { }

View file

@ -5,7 +5,9 @@
//
// • ChatSource (hub, 100 ms) pulls new lines from RynthChatGetScrollbackJson
// on the pump thread, keeps the newest 500, routes and colours them with
// the rules, and writes the chat log.
// the rules, and writes the chat log. It also hands each new line to the
// Discord relay and ticks it (UI/Data/Discord/ChatDiscord.cs), which keeps
// this source subscribed while it is on.
// • ChatModel holds the settings (rynthchat_settings.json), the regex
// rules and custom tabs, and the chat input line.
//
@ -82,6 +84,9 @@ internal sealed class ChatLine
/// <summary>Engine-assigned, increasing for the whole session (the plugin's own
/// seq restarts after RL).</summary>
public long Id { get; }
/// <summary>RynthChat's own number for the line (restarts when its plugin reloads); 0 when not
/// from RynthChat. The Discord relay tells news from scrollback by it.</summary>
public ulong Seq { get; init; }
public string Timestamp { get; }
/// <summary>The channel tab it belongs to (ChatClassifier in the plugin).</summary>
public string Channel { get; }
@ -247,7 +252,7 @@ internal sealed class ChatFilterRule
}
}
/// <summary>New RynthChat lines while a chat face is open (100 ms). Publishes the newest 500, routed.</summary>
/// <summary>New RynthChat lines while a chat face or the Discord relay holds it (100 ms). Publishes the newest 500, routed.</summary>
internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
{
private const int MaxLines = 500;
@ -261,6 +266,17 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
public ChatSource() : base("Chat", periodMs: 100) { }
protected internal override void Poll()
{
try { PollLines(); }
finally
{
// Every poll, new lines or not: due Discord posts, results, retries.
try { Discord.ChatDiscord.PumpTick(); }
catch (Exception ex) { RynthLog.UI($"ChatSource: Discord relay tick failed ({ex.GetType().Name}: {ex.Message})."); }
}
}
private void PollLines()
{
if (_get == null)
{
@ -300,12 +316,20 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
IntPtr ptr = _get(_sinceSeq);
if (ptr == IntPtr.Zero) return;
string? json = Marshal.PtrToStringAnsi(ptr);
if (string.IsNullOrEmpty(json) || json == "[]") return;
if (string.IsNullOrEmpty(json) || json == "[]")
{
RelayRead(Array.Empty<ChatLine>());
return;
}
RynthChatLineDto[]? dtos = ParseLines(json, out ulong skippedSeq);
// Lines that couldn't be read still move the mark past them, or they'd come back every poll.
if (skippedSeq > _sinceSeq) _sinceSeq = skippedSeq;
if (dtos == null || dtos.Length == 0) return;
if (dtos == null || dtos.Length == 0)
{
RelayRead(Array.Empty<ChatLine>());
return;
}
var added = new List<ChatLine>(dtos.Length);
foreach (RynthChatLineDto dto in dtos)
@ -314,12 +338,19 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
_sinceSeq = dto.Seq;
string text = StripAcLinks(dto.Text ?? "", out string? linkedName);
var line = new ChatLine(_nextId++, dto.Ts ?? "", dto.Chan ?? "Other", dto.Type,
dto.Sender is { Length: > 0 } s ? StripAcLinks(s, out _) : linkedName, text);
dto.Sender is { Length: > 0 } s ? StripAcLinks(s, out _) : linkedName, text)
{
Seq = dto.Seq,
};
line.Route = router.Evaluate(line, null);
if (line.Route.Mention) ChatModel.PumpMentionSound();
added.Add(line);
}
if (added.Count == 0) return;
if (added.Count == 0)
{
RelayRead(added);
return;
}
ChatLine[] old = Current?.Value ?? Array.Empty<ChatLine>();
int keepOld = Math.Max(0, Math.Min(old.Length, MaxLines - added.Count));
@ -329,6 +360,14 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
added.CopyTo(skipAdded, lines, keepOld, added.Count - skipAdded);
Publish(lines);
ChatModel.PumpLog(added);
RelayRead(added);
}
/// <summary>Every scrollback read goes to the Discord relay, empty or not (its first read is a baseline).</summary>
private static void RelayRead(IReadOnlyList<ChatLine> added)
{
try { Discord.ChatDiscord.PumpRead(added); }
catch (Exception ex) { RynthLog.UI($"ChatSource: Discord relay skipped {added.Count} line(s) ({ex.GetType().Name}: {ex.Message})."); }
}
private int _badLinesLogged;
@ -413,6 +452,7 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
// The lines already shown stay.
_get = null;
_sinceSeq = 0;
Discord.ChatDiscord.PumpSourceReset();
ChatModel.SendLinePtr = IntPtr.Zero;
ChatModel.PluginBound = false;
}

View file

@ -0,0 +1,664 @@
// ============================================================================
// RynthCore.Engine - UI/Data/Discord/ChatDiscord.cs
// RynthChat's Discord relay: copies chosen chat (speech channels, or every
// line that shows in a chat tab) to Discord channels by webhook or bot.
// Configured in the Chat panel's settings (gear > Discord) and its Discord
// panel (ImGui/Panels/ChatDiscordFace.cs); /rc discord for quick control.
//
// Threads
// • ChatSource.Poll (the pump) hands every scrollback read to PumpRead and
// calls PumpTick each poll: routing, batching, at most one HTTP post per
// route in flight, applying results. The relay keeps the chat feed
// subscribed while it is on (or its panel is open), so it runs with the
// Chat panel closed.
// • The panel and /rc discord (AC's thread) edit Settings in place and
// queue Resume / Send test / Clear log; secrets are encrypted and the
// file written on UiBackgroundWriter, never on AC's thread.
// • HTTP posts run on the thread pool and hand results back through a queue.
//
// Per route, lines arriving within the batch window go out as one message
// (<= 2000 characters), spaced by the route's minimum interval or whatever
// Discord's rate limit asks for. Network / 5xx failures retry with backoff;
// 400 / 401 / 403 / 404 pause the route until it's resumed or its
// credential changes. Scrollback read when the relay starts (engine start,
// hot reload, switching it on) is not sent: the first read after it comes
// on is a baseline, judged by RynthChat's line seq (DiscordBacklogGate).
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using RynthCore.Engine.Compatibility;
namespace RynthCore.Engine.UI.Data.Discord;
internal enum DiscordLogKind { Sent, Error, Info }
/// <summary>One line in the Discord panel's log (immutable once added).</summary>
internal sealed record DiscordLogEntry(DateTime Time, DiscordLogKind Kind, string Route, string Text);
internal static class ChatDiscord
{
private static ChatDiscordSettings _settings = new();
private static int _loaded;
private static readonly string FilePath = ChatDiscordStore.DefaultPath;
// Any thread -> pump.
private static readonly ConcurrentQueue<(DiscordRoute Route, DiscordBatch Batch, DiscordSendResult Result)> Done = new();
private static readonly ConcurrentQueue<DiscordRoute> ResumeQueue = new();
private static readonly ConcurrentQueue<DiscordRoute> TestQueue = new();
private static volatile bool _clearLog;
private static volatile bool _shutdown;
private static readonly CancellationTokenSource Cts = new();
private static int _postsRunning;
// Pump only.
private static readonly Dictionary<DiscordRoute, DiscordRouteQueue> States = new(ReferenceEqualityComparer.Instance);
private static readonly List<DiscordLogEntry> Log = new();
// Pump writes, panel reads.
private static DiscordLogEntry[] _logSnapshot = Array.Empty<DiscordLogEntry>();
// The chat feed (UiSources.Chat) is held while some character has the relay on, or its panel is open.
private static int _feedHeld, _panelsOpen;
// Pump only: keeps the scrollback read when the relay comes on out of Discord.
private static readonly DiscordBacklogGate Backlog = new();
// The character playing, as the pump last saw it (the panel can't ask: the lookup may read a file).
private static string _characterName = string.Empty;
// Per-character switch. A switch is applied to the in-memory list at once and queued as an
// op; the next save (background writer) merges the queued ops into the file's list. Until
// that save lands, _pending says what this client's character asked for, so an older
// merge or refresh can't switch it back on (or off) meanwhile.
private sealed record SelfPending(DiscordCharacter Character, bool On);
private static readonly ConcurrentQueue<(DiscordCharacterOp Op, SelfPending? Pending)> CharacterOps = new();
private static SelfPending? _pending;
// Another client may switch characters in the file: the pump looks at its time every few
// seconds and re-reads the list (only the list) when it changed.
private const int FileCheckMs = 3000;
private static long _nextFileCheckMs;
private static long _fileStampTicks;
private static int _refreshQueued;
/// <summary>The live settings. Any thread; fields are edited in place (see ChatDiscordSettings).</summary>
public static ChatDiscordSettings Settings => Volatile.Read(ref _settings);
/// <summary>The character this client relays as ("" before login). Any thread.</summary>
public static string CharacterName => Volatile.Read(ref _characterName);
/// <summary>The character logged in on this client (server + name), or null before login. Any thread.</summary>
public static DiscordCharacter? CurrentCharacter()
=> DiscordCharacter.Of(SessionStateRegistry.LastServerName, SessionStateRegistry.LastCharacterName);
/// <summary>True when the relay is on for <paramref name="character"/>. Any thread.</summary>
public static bool IsOn(DiscordCharacter? character)
{
if (character == null) return false;
SelfPending? p = Volatile.Read(ref _pending);
if (p != null && p.Character.Same(character)) return p.On;
return Settings.IsOnFor(character);
}
/// <summary>True when the relay is on for the character logged in here. Any thread.</summary>
public static bool IsOnHere => IsOn(CurrentCharacter());
// ── Setup (InitWorker / panel) ───────────────────────────────────────
/// <summary>Loads the settings once (file I/O: InitWorker or a background thread) and opens the feed if on.</summary>
public static void EnsureLoaded()
{
if (Interlocked.Exchange(ref _loaded, 1) != 0) return;
ChatDiscordSettings s = ChatDiscordStore.Load(FilePath, out string note);
Volatile.Write(ref _settings, s);
Interlocked.Exchange(ref _fileStampTicks, FileStampTicks());
if (note.Length > 0) RynthLog.UI($"ChatDiscord: {note}.");
// Subscribing touches UiSources; done on the pump, like every other hub change.
UiDataHub.Post("chat discord feed", SyncFeed);
}
/// <summary>
/// Turns the relay on or off for the character logged in here (and saves). False before
/// login: there is no character to switch. Any thread.
/// </summary>
public static bool SetEnabled(bool on)
{
DiscordCharacter? me = CurrentCharacter();
if (me == null) return false;
if (IsOn(me) == on) return true;
var pending = new SelfPending(me, on);
Volatile.Write(ref _pending, pending);
SwitchCharacter(new DiscordCharacterOp(me, on), pending);
return true;
}
/// <summary>Turns the relay off for another character (the panel's list). Any thread.</summary>
public static void TurnOffFor(DiscordCharacter character)
{
DiscordCharacter? me = CurrentCharacter();
if (character.Same(me)) { SetEnabled(false); return; }
SwitchCharacter(new DiscordCharacterOp(character, false), null);
}
private static void SwitchCharacter(DiscordCharacterOp op, SelfPending? pending)
{
var s = Settings;
s.Characters = ChatDiscordStore.ApplyCharacterOps(s.Characters, new[] { op });
CharacterOps.Enqueue((op, pending));
Save();
SyncFeed();
}
/// <summary>The Discord panel opened / closed: it keeps the feed (and so the relay's tick) running. AC thread.</summary>
public static void PanelShown(bool shown)
{
int n = shown ? Interlocked.Increment(ref _panelsOpen) : Interlocked.Decrement(ref _panelsOpen);
if (n < 0) Interlocked.Exchange(ref _panelsOpen, 0);
SyncFeed();
}
/// <summary>
/// Holds the chat feed while any character on this PC has the relay on (the pump then decides
/// for the one logged in, who may only be known after login or a hot reload) or the panel is open.
/// </summary>
private static void SyncFeed()
{
bool want = !_shutdown
&& (Settings.Characters.Length > 0 || Volatile.Read(ref _pending) is { On: true }
|| Volatile.Read(ref _panelsOpen) > 0);
if (want)
{
if (Interlocked.CompareExchange(ref _feedHeld, 1, 0) == 0)
{
UiSources.Chat.Subscribe();
UiSources.Chat.RequestRefresh();
}
}
else if (Interlocked.CompareExchange(ref _feedHeld, 0, 1) == 1)
UiSources.Chat.Unsubscribe();
}
/// <summary>Saves in the background (the JSON is taken now; the character list is merged then). Any thread.</summary>
public static void Save()
{
string json;
try { json = ChatDiscordStore.Serialize(Settings); }
catch (Exception ex)
{
RynthLog.UI($"ChatDiscord: settings not saved ({ex.GetType().Name}: {ex.Message}).");
return;
}
UiBackgroundWriter.Enqueue("persist chat discord", () => WriteMerged(json));
}
/// <summary>
/// Background writer: re-reads the file, applies this client's queued character switches to
/// its list, writes our settings with that list, and takes the list back. Other clients'
/// switches survive; ours win for our own character.
/// </summary>
private static void WriteMerged(string ours)
{
var ops = new List<(DiscordCharacterOp Op, SelfPending? Pending)>();
while (CharacterOps.TryDequeue(out var o)) ops.Add(o);
var plain = new List<DiscordCharacterOp>(ops.Count);
foreach (var o in ops) plain.Add(o.Op);
try
{
string? disk = null;
try { if (File.Exists(FilePath)) disk = File.ReadAllText(FilePath); }
catch (IOException) { }
string json = ChatDiscordStore.MergeForSave(ours, disk, plain, out DiscordCharacter[] merged);
ChatDiscordStore.Write(FilePath, json);
Interlocked.Exchange(ref _fileStampTicks, FileStampTicks());
Settings.Characters = merged;
}
catch
{
// Not written: keep the switches for the next save.
foreach (var o in ops) CharacterOps.Enqueue(o);
throw;
}
// Saved: the file now says what our character asked for (unless it asked again since).
foreach (var o in ops)
if (o.Pending != null) Interlocked.CompareExchange(ref _pending, null, o.Pending);
SyncFeed();
}
/// <summary>Pump: every few seconds, re-reads the character list if another client changed the file.</summary>
private static void CheckFile(long now)
{
if (now < Volatile.Read(ref _nextFileCheckMs)) return;
Volatile.Write(ref _nextFileCheckMs, now + FileCheckMs);
if (FileStampTicks() == Interlocked.Read(ref _fileStampTicks)) return;
if (Interlocked.Exchange(ref _refreshQueued, 1) != 0) return;
// On the writer, so it can't land between a save's read and write.
UiBackgroundWriter.Enqueue("refresh chat discord characters", () =>
{
try
{
long stamp = FileStampTicks();
string? disk = File.Exists(FilePath) ? File.ReadAllText(FilePath) : null;
DiscordCharacter[]? list = ChatDiscordStore.ReadCharacters(disk);
Interlocked.Exchange(ref _fileStampTicks, stamp);
// Switches still queued here go in with the next save; keep them in view.
if (list != null)
{
var queued = new List<DiscordCharacterOp>();
foreach (var o in CharacterOps) queued.Add(o.Op);
Settings.Characters = ChatDiscordStore.ApplyCharacterOps(list, queued);
}
}
finally { Interlocked.Exchange(ref _refreshQueued, 0); }
SyncFeed();
});
}
private static long FileStampTicks()
{
try { return File.Exists(FilePath) ? File.GetLastWriteTimeUtc(FilePath).Ticks : 0; }
catch (Exception) { return 0; }
}
/// <summary>
/// Engine shutdown, after the pump stopped: cancels posts in flight, gives them a moment to
/// unwind (they'd otherwise finish in this dying generation's code), then disposes the HTTP
/// client so nothing of it keeps the generation from unloading.
/// </summary>
public static void Shutdown()
{
_shutdown = true;
try { Cts.Cancel(); } catch { }
var wait = System.Diagnostics.Stopwatch.StartNew();
while (Volatile.Read(ref _postsRunning) > 0 && wait.ElapsedMilliseconds < 1000) Thread.Sleep(10);
int left = Volatile.Read(ref _postsRunning);
if (left > 0) RynthLog.UI($"ChatDiscord: {left} post(s) still running at shutdown; closing the HTTP client under them.");
DiscordClient.Shutdown();
while (Done.TryDequeue(out _)) { }
try { Cts.Dispose(); } catch { }
}
// ── Panel / command requests (any thread) ────────────────────────────
/// <summary>Clears a pause on <paramref name="route"/> (the Resume button, or a credential change).</summary>
public static void Resume(DiscordRoute route) => ResumeQueue.Enqueue(route);
/// <summary>Posts a test line to <paramref name="route"/> (ignoring its filters) and resumes it.</summary>
public static void SendTest(DiscordRoute route)
{
ResumeQueue.Enqueue(route);
TestQueue.Enqueue(route);
}
public static void ClearLog() => _clearLog = true;
public static DiscordLogEntry[] LogSnapshot() => Volatile.Read(ref _logSnapshot);
/// <summary>
/// Stores a pasted webhook URL on <paramref name="route"/>, encrypted on the background writer.
/// Returns an error for the panel, or empty when accepted. The plain text is not kept.
/// </summary>
public static string SetWebhook(DiscordRoute route, string url)
{
if (!DiscordFormat.TryNormalizeWebhookUrl(url, out string normalized))
return "That isn't a Discord webhook URL (https://discord.com/api/webhooks/<id>/<token>).";
UiBackgroundWriter.Enqueue("protect discord webhook", () =>
{
route.WebhookProtected = DiscordSecrets.Protect(normalized);
Save();
Resume(route);
});
return string.Empty;
}
/// <summary>Stores a pasted bot token (encrypted on the background writer). Returns an error, or empty.</summary>
public static string SetBotToken(DiscordRoute route, string token)
{
if (!DiscordFormat.LooksLikeBotToken(token))
return "That doesn't look like a bot token (Developer Portal > Bot > Reset Token).";
string trimmed = token.Trim();
UiBackgroundWriter.Enqueue("protect discord bot token", () =>
{
route.BotTokenProtected = DiscordSecrets.Protect(trimmed);
Save();
Resume(route);
});
return string.Empty;
}
// ── Pump ─────────────────────────────────────────────────────────────
/// <summary>
/// One read of RynthChat's scrollback (the new lines, already routed by the chat rules; empty
/// when nothing was new). ChatSource.Poll, pump thread, after every read, so the first read
/// after the relay comes on can be taken as the baseline (DiscordBacklogGate).
/// </summary>
internal static void PumpRead(IReadOnlyList<ChatLine> added)
{
if (_shutdown) return;
var seqs = new ulong[added.Count];
for (int i = 0; i < seqs.Length; i++) seqs[i] = added[i].Seq;
bool baseline = !Backlog.Live;
bool[] post = Backlog.Admit(RelayOn(), seqs);
if (baseline && Backlog.Live && added.Count > 0)
RynthLog.UI($"ChatDiscord: {added.Count} line(s) of scrollback not relayed (relay started).");
if (Array.IndexOf(post, true) < 0) return;
var s = Settings;
DiscordRoute[] routes = s.Routes;
if (routes.Length == 0) return;
string me = SafeName(ChatModel.PumpCharacterName());
// Lines reach here within a poll (100 ms) of being printed: now is their time.
DateTime time = DateTime.Now;
long nowMs = Environment.TickCount64;
// Keyword lists parsed once per batch of lines (the panel may edit them between polls).
var keywords = new List<string>[routes.Length];
for (int i = 0; i < routes.Length; i++) keywords[i] = DiscordFormat.SplitList(routes[i].Keywords);
for (int n = 0; n < added.Count; n++)
{
if (!post[n]) continue;
ChatLine line = added[n];
ChatRoute chatRoute = line.Route;
if (s.SkipHidden && chatRoute.Hidden) continue;
if (!ChatDiscordLogic.TryClassify(line.Text, line.ChatType, me, out DiscordLineParts parts)) continue;
if (parts.Own && s.SkipOwn) continue;
string channel = line.Channel;
bool ShowsIn(string tab) => chatRoute.ShowsIn(tab, channel);
for (int i = 0; i < routes.Length; i++)
{
DiscordRoute route = routes[i];
if (!route.Enabled || !route.HasSecret) continue;
if (!ChatDiscordLogic.Wants(route, parts.Speech, ShowsIn, out string label)) continue;
if (!DiscordFormat.MatchesKeywords(parts.Haystack, keywords[i])) continue;
DiscordRouteQueue q = State(route);
NoteRetargeted(route, Retarget(q, route));
if (q.Paused) continue;
if (!q.NoteFresh(ChatDiscordLogic.DedupKey(parts, label), nowMs)) continue;
q.Add(ChatDiscordLogic.Format(s, time, parts, label, me), nowMs, s.MaxQueue);
}
}
}
/// <summary>RynthChat's scrollback numbering restarted (ChatSource.Reset, its plugin reloaded). Pump thread.</summary>
internal static void PumpSourceReset() => Backlog.SourceReset();
/// <summary>Applies requests and results, starts due posts, publishes status. ChatSource.Poll, pump thread.</summary>
internal static void PumpTick()
{
if (_shutdown) return;
long now = Environment.TickCount64;
var s = Settings;
DiscordRoute[] routes = s.Routes;
Volatile.Write(ref _characterName, SafeName(ChatModel.PumpCharacterName()));
CheckFile(now);
bool relayOn = RelayOn();
if (!relayOn) Backlog.Off();
PruneStates(routes);
while (ResumeQueue.TryDequeue(out var r))
if (States.TryGetValue(r, out var q)) q.Resume();
while (Done.TryDequeue(out var d)) ApplyResult(d.Route, d.Batch, d.Result, now);
while (TestQueue.TryDequeue(out var t)) QueueTest(t);
if (_clearLog)
{
_clearLog = false;
Log.Clear();
Volatile.Write(ref _logSnapshot, Array.Empty<DiscordLogEntry>());
}
foreach (var route in routes)
{
// Off means off: the relay or the route switched off drops what the route had
// queued, the batch waiting to retry and the post in flight. Only a test goes.
if (!States.TryGetValue(route, out var q)) continue;
if (!(relayOn && route.Enabled)) NoteStopped(route, q.Stop());
// A new webhook / token / channel: what was queued for the old one isn't sent to it.
NoteRetargeted(route, Retarget(q, route));
StartNextPost(s, route, relayOn, now);
}
PublishStatus(routes);
}
/// <summary>Whether this client relays at all right now: the relay is on for the character logged in.</summary>
private static bool RelayOn() => IsOnHere;
private static DiscordRouteQueue State(DiscordRoute route)
{
if (!States.TryGetValue(route, out var q)) States[route] = q = new DiscordRouteQueue();
return q;
}
private static void PruneStates(DiscordRoute[] routes)
{
if (States.Count <= routes.Length) return;
var live = new HashSet<DiscordRoute>(routes, ReferenceEqualityComparer.Instance);
var gone = new List<DiscordRoute>();
foreach (var r in States.Keys) if (!live.Contains(r)) gone.Add(r);
foreach (var r in gone)
{
// A removed route's post in flight (test or not) is cancelled; its result then finds
// no queue and is dropped.
DiscordRouteQueue q = States[r];
q.Stop();
if (q.InFlight is { } flying)
{
try { flying.Cancel?.Cancel(); } catch (ObjectDisposedException) { }
}
States.Remove(r);
}
}
/// <summary>
/// Tells <paramref name="q"/> where <paramref name="route"/> sends now (its mode, channel and
/// saved, encrypted credential); a change drops what was queued for the old destination.
/// </summary>
private static int Retarget(DiscordRouteQueue q, DiscordRoute route)
=> q.Retarget(route.Mode, route.ChannelId,
route.Mode == DiscordRoute.ModeBot ? route.BotTokenProtected : route.WebhookProtected);
private static void NoteRetargeted(DiscordRoute route, int dropped)
{
if (dropped > 0) AddLog(Settings, DiscordLogKind.Info, route.Name, $"Destination changed: {dropped} line(s) queued for the old one dropped.");
}
private static void NoteStopped(DiscordRoute route, int dropped)
{
if (dropped > 0) AddLog(Settings, DiscordLogKind.Info, route.Name, $"Off: {dropped} queued line(s) dropped.");
}
private static void QueueTest(DiscordRoute route)
{
string me = SafeName(ChatModel.PumpCharacterName());
string line = DiscordFormat.FormatLine(DateTime.Now, null, null,
$"RynthChat Discord relay test from {(me.Length > 0 ? me : "RynthCore")} (route \"{route.Name}\").",
Settings.IncludeTimestamp, null);
State(route).QueueTest(line);
}
private static void StartNextPost(ChatDiscordSettings s, DiscordRoute route, bool relayOn, long now)
{
if (!States.TryGetValue(route, out var q)) return;
DiscordBatch? batch = q.Next(now, relayOn && route.Enabled, s.BatchFor(route), s.IntervalFor(route));
if (batch == null) return;
// Decrypt only now, on the way out; the plain text lives in the request task alone.
string mode = route.Mode, channelId = route.ChannelId;
string blob = mode == DiscordRoute.ModeBot ? route.BotTokenProtected : route.WebhookProtected;
if (blob.Length == 0)
{
ApplyResult(route, batch, DiscordSendResult.Fail(
mode == DiscordRoute.ModeBot ? "no bot token saved" : "no webhook URL saved", permanent: true), now);
return;
}
if (!DiscordSecrets.TryUnprotect(blob, out string secret))
{
ApplyResult(route, batch, DiscordSendResult.Fail(
"the saved credential can't be read on this Windows user; paste it again", permanent: true), now);
return;
}
string displayName = route.DisplayName.Length > 0 ? route.DisplayName : SafeName(ChatModel.PumpCharacterName());
// Each post can be cancelled on its own (Stop, a removed route) or with the engine.
CancellationTokenSource cts;
try { cts = CancellationTokenSource.CreateLinkedTokenSource(Cts.Token); }
catch (ObjectDisposedException) { return; } // shutting down
batch.Cancel = cts;
Interlocked.Increment(ref _postsRunning);
_ = Task.Run(async () =>
{
DiscordSendResult r;
try
{
r = mode == DiscordRoute.ModeBot
? await DiscordClient.PostBotAsync(secret, channelId, batch.Content, cts.Token).ConfigureAwait(false)
: await DiscordClient.PostWebhookAsync(secret, batch.Content, displayName, cts.Token).ConfigureAwait(false);
}
catch (Exception ex) { r = DiscordSendResult.Fail(DiscordFormat.Redact(ex.Message, secret)); }
finally
{
batch.Cancel = null;
cts.Dispose();
Interlocked.Decrement(ref _postsRunning);
}
Done.Enqueue((route, batch, r));
});
}
private static void ApplyResult(DiscordRoute route, DiscordBatch batch, DiscordSendResult r, long now)
{
// A route removed meanwhile has no queue: nothing to retry, nothing to report.
if (!States.TryGetValue(route, out var q)) return;
var s = Settings;
switch (q.Apply(batch, r, now, s.IntervalFor(route)))
{
case DiscordOutcome.Sent:
AddLog(s, DiscordLogKind.Sent, route.Name, batch.IsTest ? "Test message sent." : $"{batch.Lines.Count} line(s): {batch.Content}");
break;
case DiscordOutcome.Paused:
AddLog(s, DiscordLogKind.Error, route.Name, $"Paused: {r.Error}");
RynthLog.UI($"ChatDiscord: route '{route.Name}' paused: {r.Error}");
break;
case DiscordOutcome.RateLimited:
AddLog(s, DiscordLogKind.Info, route.Name, r.Error);
break;
case DiscordOutcome.GaveUp:
AddLog(s, DiscordLogKind.Error, route.Name, $"Gave up after {batch.Attempts} tries ({r.Error}); {batch.Lines.Count} line(s) dropped.");
RynthLog.UI($"ChatDiscord: route '{route.Name}' dropped a batch: {r.Error}");
break;
case DiscordOutcome.Retrying:
AddLog(s, DiscordLogKind.Error, route.Name, $"{r.Error}; retrying in {q.BackoffMs / 1000}s.");
break;
case DiscordOutcome.Retargeted:
AddLog(s, DiscordLogKind.Info, route.Name, $"{r.Error}; the destination changed meanwhile, so {batch.Lines.Count} line(s) dropped.");
break;
}
}
private static void PublishStatus(DiscordRoute[] routes)
{
foreach (var route in routes)
{
if (!States.TryGetValue(route, out var q)) continue;
int queued = q.Queued;
DiscordRouteStatus? old = route.Status;
if (old != null && old.Queued == queued && old.MessagesSent == q.MessagesSent && old.Dropped == q.Dropped
&& old.Paused == q.Paused && ReferenceEquals(old.LastError, q.LastError) && old.LastSent == q.LastSent)
continue;
route.Status = new DiscordRouteStatus(queued, q.MessagesSent, q.LinesSent, q.Dropped, q.Paused, q.LastError, q.LastSent);
}
}
private static void AddLog(ChatDiscordSettings s, DiscordLogKind kind, string route, string text)
{
Log.Add(new DiscordLogEntry(DateTime.Now, kind, route, text));
if (Log.Count > s.MaxLog) Log.RemoveRange(0, Log.Count - s.MaxLog);
Volatile.Write(ref _logSnapshot, Log.ToArray());
}
private static string SafeName(string? name) => (name ?? string.Empty).Trim().TrimStart('+');
// ── Status and /rc discord ───────────────────────────────────────────
/// <summary>"2 of 3 route(s) ready." Any thread.</summary>
public static string StatusLine()
{
var s = Settings;
int ready = 0;
foreach (var r in s.Routes) if (r.Enabled && r.HasSecret) ready++;
return $"{ready} of {s.Routes.Length} route(s) ready.";
}
/// <summary>"On for Bob (Aelrynth)." / "Off for Bob (Aelrynth)." / "Log in to switch it on." Any thread.</summary>
public static string SwitchLine()
{
DiscordCharacter? me = CurrentCharacter();
if (me == null) return "Log in to switch it on for a character.";
return $"{(IsOn(me) ? "On" : "Off")} for {me}.";
}
/// <summary>
/// /rc discord [on|off|status|test [route]|resume [route]]. Returns the reply lines ("window"
/// is handled by the caller: it opens the panel). AC's thread.
/// </summary>
public static List<string> HandleCommand(string args)
{
var reply = new List<string>();
var s = Settings;
string[] parts = (args ?? string.Empty).Trim().Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
string verb = parts.Length > 0 ? parts[0].ToLowerInvariant() : "status";
string rest = parts.Length > 1 ? parts[1] : string.Empty;
switch (verb)
{
case "on":
case "off":
if (!SetEnabled(verb == "on"))
{
reply.Add("Log in first: the relay is switched on or off for the character you're playing.");
break;
}
reply.Add($"Discord relay {verb} for {CurrentCharacter()}. {StatusLine()}");
break;
case "test":
case "resume":
// The relay's tick runs while the chat feed is held (a character on, or the panel open).
if (verb == "test" && Volatile.Read(ref _feedHeld) == 0)
{
reply.Add("The relay is off: /rc discord on, or use Send test in the Discord panel (/rc discord window).");
break;
}
int n = 0;
foreach (var r in s.Routes)
{
if (rest.Length > 0 && !r.Name.Equals(rest, StringComparison.OrdinalIgnoreCase)) continue;
if (verb == "test") SendTest(r); else Resume(r);
n++;
}
reply.Add(n == 0
? $"No route{(rest.Length > 0 ? $" named '{rest}'" : "s")}. Add one in Chat > gear > Discord (or /rc discord window)."
: $"{(verb == "test" ? "Test sent to" : "Resumed")} {n} route(s).");
break;
default:
reply.Add($"Discord relay: {SwitchLine()} {StatusLine()}");
if (s.Characters.Length > 0)
reply.Add(" On for: " + string.Join(", ", Array.ConvertAll(s.Characters, c => c.ToString())));
foreach (var r in s.Routes)
{
var st = r.Status;
reply.Add($" {r.Name}: {(r.Enabled ? "on" : "off")}, {(r.HasSecret ? r.Mode : "no destination set")}"
+ (st == null ? string.Empty
: $", {st.MessagesSent} sent, {st.Queued} queued, {st.Dropped} dropped{(st.Paused ? ", PAUSED" : string.Empty)}"
+ (st.LastError.Length > 0 ? $" - {st.LastError}" : string.Empty)));
}
reply.Add("/rc discord on|off (this character) | window | test [route] | resume [route] | status");
break;
}
return reply;
}
}

View file

@ -0,0 +1,134 @@
// ============================================================================
// RynthCore.Engine - UI/Data/Discord/ChatDiscordLogic.cs
// The relay's per-line decisions, kept free of engine state so
// tools/ChatDiscordTests can run them: what a chat line is (speech on a
// channel, or plain text), whether a route wants it and under which label,
// how it is written for Discord, and whether it is scrollback from before
// the relay started (DiscordBacklogGate, by RynthChat's line seq).
// ============================================================================
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.UI.Data.Discord;
/// <summary>A chat line split for the relay. <see cref="Speech"/> null: not player speech.</summary>
internal readonly record struct DiscordLineParts(SpeechChannel? Speech, string Speaker, string Message, bool Own)
{
/// <summary>"Speaker message" (or the message alone): what route keywords are matched against.</summary>
public string Haystack => Speaker.Length > 0 ? Speaker + " " + Message : Message;
}
internal static class ChatDiscordLogic
{
/// <summary>
/// Splits <paramref name="text"/> (AC's name links already stripped). Player speech gets its
/// channel and speaker (yours as <paramref name="me"/> when known); anything else is the text
/// alone. False for blank lines.
/// </summary>
public static bool TryClassify(string? text, int chatType, string me, out DiscordLineParts parts)
{
parts = default;
if (string.IsNullOrWhiteSpace(text)) return false;
if (ChatSpeech.TryParse(text, chatType, out var ch, out string who, out string msg, out bool own))
{
parts = new DiscordLineParts(ch, own && me.Length > 0 ? me : who, msg, own);
return true;
}
string plain = ChatSpeech.Decode(text).Trim();
if (plain.Length == 0) return false;
parts = new DiscordLineParts(null, string.Empty, plain, false);
return true;
}
/// <summary>
/// True when <paramref name="route"/> takes the line: its speech channel is ticked, or the line
/// shows in one of the route's tabs (<paramref name="showsInTab"/>). <paramref name="label"/> is
/// what the Discord line is tagged with: the speech channel, else the tab that matched.
/// </summary>
public static bool Wants(DiscordRoute route, SpeechChannel? speech, Func<string, bool> showsInTab, out string label)
{
label = string.Empty;
if (speech is { } ch && route.RelaysSpeech(ch))
{
label = ChatSpeech.Name(ch);
return true;
}
foreach (string tab in route.Tabs)
{
if (!showsInTab(tab)) continue;
label = speech is { } c ? ChatSpeech.Name(c) : tab;
return true;
}
return false;
}
/// <summary>The Discord text for one relayed line.</summary>
public static string Format(ChatDiscordSettings s, DateTime time, in DiscordLineParts parts, string label, string me)
=> DiscordFormat.FormatLine(time, label.Length > 0 ? label : null,
parts.Speech != null && parts.Speaker.Length > 0 ? parts.Speaker : null,
parts.Message, s.IncludeTimestamp, s.TagCharacter && me.Length > 0 ? me : null);
/// <summary>Key for the per-route repeat filter (the same line twice within a few seconds).</summary>
public static string DedupKey(in DiscordLineParts parts, string label) => $"{label}|{parts.Speaker}|{parts.Message}";
/// <summary>Drops dedup entries older than <paramref name="windowMs"/>.</summary>
public static void PruneRecent(Dictionary<string, long> recent, long now, int windowMs)
{
List<string>? stale = null;
foreach (var kv in recent)
if (now - kv.Value > windowMs) (stale ??= new List<string>()).Add(kv.Key);
if (stale != null) foreach (string k in stale) recent.Remove(k);
}
}
/// <summary>
/// Keeps scrollback out of Discord, by RynthChat's line numbers (seq), not by clock time.
/// ChatSource reads RynthChat's scrollback by seq; the first read after the relay comes on
/// for this character (engine start, hot reload, switching it on, logging in a character that
/// has it on) or after RynthChat's numbering restarts is the baseline: up to 500 lines that were
/// already sent, or are history, so none of it is posted. After that a line is posted only if
/// its seq is newer than any seen. Pump thread only.
/// </summary>
internal sealed class DiscordBacklogGate
{
private bool _live;
private ulong _newestSeq;
/// <summary>True once a baseline read has been taken while on.</summary>
public bool Live => _live;
/// <summary>The relay is off for this character: the next read while on is a baseline again.</summary>
public void Off() => _live = false;
/// <summary>RynthChat's scrollback numbering restarted (its plugin was reloaded): re-baseline.</summary>
public void SourceReset()
{
_live = false;
_newestSeq = 0;
}
/// <summary>
/// One scrollback read (possibly empty) with the seq of each line in it. Returns which lines
/// to post: none while off or for the baseline read, else those newer than any seen.
/// </summary>
public bool[] Admit(bool on, IReadOnlyList<ulong> seqs)
{
var post = new bool[seqs.Count];
if (!on)
{
_live = false;
return post;
}
bool baseline = !_live;
_live = true;
for (int i = 0; i < seqs.Count; i++)
{
ulong seq = seqs[i];
bool newer = seq > _newestSeq;
if (newer) _newestSeq = seq;
post[i] = newer && !baseline;
}
return post;
}
}

View file

@ -0,0 +1,380 @@
// ============================================================================
// RynthCore.Engine - UI/Data/Discord/ChatDiscordSettings.cs
// RynthChat's Discord relay settings, shared by every client and character
// (%AppData%\RynthCore\rynthchat_discord.json, beside rynthchat_settings.json).
// The routes and options are shared; the switch is per character
// (Characters): a character not on the list relays nothing, and the list
// starts empty. Saves merge each client's switch into the file's list.
//
// Threads: the Discord panel (AC's render thread) edits fields in place, each
// a single reference or 32-bit value, so the pump's reads never tear. Arrays
// (Routes, a route's Tabs) are replaced, never changed in place, so the pump
// can walk the one it read without a lock.
//
// Secrets (webhook URL, bot token) are stored only as DPAPI blobs
// (DiscordSecrets); the JSON never holds them in plain text.
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace RynthCore.Engine.UI.Data.Discord;
/// <summary>Route state the panel shows; replaced as a whole by the pump.</summary>
internal sealed record DiscordRouteStatus(int Queued, int MessagesSent, int LinesSent, int Dropped, bool Paused,
string LastError, DateTime LastSent);
/// <summary>One Discord destination and the chat it receives.</summary>
internal sealed class DiscordRoute
{
public const string ModeWebhook = "webhook";
public const string ModeBot = "bot";
public static readonly string[] Modes = { ModeWebhook, ModeBot };
public static readonly string[] ModeNames = { "Webhook URL", "Bot token + channel ID" };
/// <summary>Label shown in the panel, the log and /rc discord.</summary>
public string Name = "Discord";
public bool Enabled = true;
public string Mode = ModeWebhook;
/// <summary>DPAPI blob of the webhook URL (the URL embeds the webhook token).</summary>
public string WebhookProtected = string.Empty;
/// <summary>DPAPI blob of the bot token (bot mode).</summary>
public string BotTokenProtected = string.Empty;
/// <summary>Target channel snowflake (bot mode). Not secret.</summary>
public string ChannelId = string.Empty;
/// <summary>Webhook display name; blank uses the character's name. Ignored in bot mode.</summary>
public string DisplayName = string.Empty;
/// <summary>Speech channels relayed (names, <see cref="ChatSpeech.Name"/>). Saved form of <see cref="SpeechMask"/>.</summary>
public string[]? Speech;
/// <summary>
/// Chat tabs relayed: every line that shows in one of them (channel tabs like System, or
/// tabs the chat rules fill). Replaced, never changed in place.
/// </summary>
public string[] Tabs = Array.Empty<string>();
/// <summary>Comma-separated words; when set, only lines containing one of them are relayed.</summary>
public string Keywords = string.Empty;
/// <summary>Use this route's own pacing instead of the relay's.</summary>
public bool CustomPace;
/// <summary>With <see cref="CustomPace"/>: lines arriving within this window go out in one message.</summary>
public int BatchMs = 1500;
/// <summary>With <see cref="CustomPace"/>: minimum spacing between this route's messages.</summary>
public int MinIntervalMs = 2000;
// ── Runtime only ─────────────────────────────────────────────────────
/// <summary>Bits of <see cref="SpeechChannel"/> (<see cref="ChatSpeech.Bit"/>).</summary>
[JsonIgnore] public uint SpeechMask;
/// <summary>Written by the pump, read by the panel.</summary>
[JsonIgnore] public volatile DiscordRouteStatus? Status;
/// <summary>True when a send secret is stored for the current mode (the plain text is never kept here).</summary>
[JsonIgnore]
public bool HasSecret => Mode == ModeBot
? BotTokenProtected.Length > 0 && ChannelId.Length > 0
: WebhookProtected.Length > 0;
public bool RelaysSpeech(SpeechChannel ch) => (SpeechMask & ChatSpeech.Bit(ch)) != 0;
/// <summary>Tells, fellowship and the allegiance channels: private chat a player usually wants on their phone.</summary>
public static uint DefaultSpeechMask()
{
uint m = 0;
foreach (var ch in new[]
{
SpeechChannel.Tell, SpeechChannel.Fellowship, SpeechChannel.Allegiance,
SpeechChannel.Patron, SpeechChannel.Vassals, SpeechChannel.Covassals, SpeechChannel.Monarch,
})
m |= ChatSpeech.Bit(ch);
return m;
}
public static uint AllSpeechMask()
{
uint m = 0;
foreach (var ch in ChatSpeech.All) m |= ChatSpeech.Bit(ch);
return m;
}
public static string[] NamesFromMask(uint mask)
{
var names = new List<string>();
foreach (var ch in ChatSpeech.All)
if ((mask & ChatSpeech.Bit(ch)) != 0) names.Add(ChatSpeech.Name(ch));
return names.ToArray();
}
/// <summary>The mask for <paramref name="names"/>; <paramref name="fallback"/> when there is no list at all.</summary>
public static uint MaskFromNames(IEnumerable<string>? names, uint fallback)
{
if (names == null) return fallback;
uint m = 0;
foreach (string n in names)
if (ChatSpeech.TryParseName(n, out var ch)) m |= ChatSpeech.Bit(ch);
return m;
}
}
/// <summary>A character the relay is switched on for (server + name, any case).</summary>
internal sealed class DiscordCharacter
{
public string Server = string.Empty;
public string Name = string.Empty;
/// <summary>The character, or null without a name (not logged in yet).</summary>
public static DiscordCharacter? Of(string? server, string? name)
{
string n = (name ?? string.Empty).Trim().TrimStart('+').Trim();
if (n.Length == 0) return null;
return new DiscordCharacter { Server = (server ?? string.Empty).Trim(), Name = n };
}
public bool Same(DiscordCharacter? other)
=> other != null
&& string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(Server, other.Server, StringComparison.OrdinalIgnoreCase);
/// <summary>"Bob (Aelrynth)", or "Bob" when the server isn't known.</summary>
public override string ToString() => Server.Length > 0 ? $"{Name} ({Server})" : Name;
}
/// <summary>Turns the relay on or off for one character; applied to the file's list when saving.</summary>
internal sealed record DiscordCharacterOp(DiscordCharacter Character, bool On);
internal sealed class ChatDiscordSettings
{
/// <summary>2: the relay is switched on per character (<see cref="Characters"/>), not for everyone.</summary>
public const int CurrentVersion = 2;
public int Version = CurrentVersion;
/// <summary>
/// The characters the relay is on for; every other character relays nothing. Each client
/// switches only its own character, and a save merges that change into the file's list
/// (ChatDiscordStore.MergeForSave), so clients don't undo each other. Replaced, never
/// changed in place. Empty (the default): off for everyone.
/// </summary>
public DiscordCharacter[] Characters = Array.Empty<DiscordCharacter>();
/// <summary>Destinations, shared by every character. Replaced (copy-on-write) when one is added or removed.</summary>
public DiscordRoute[] Routes = Array.Empty<DiscordRoute>();
/// <summary>True when the relay is switched on for <paramref name="character"/>.</summary>
public bool IsOnFor(DiscordCharacter? character)
{
if (character == null) return false;
foreach (var c in Characters) if (c.Same(character)) return true;
return false;
}
/// <summary>Leave out lines you typed yourself ("You say", "You tell").</summary>
public bool SkipOwn;
/// <summary>Leave out lines a chat rule hides.</summary>
public bool SkipHidden = true;
/// <summary>Start each relayed line with the game time (HH:mm:ss).</summary>
public bool IncludeTimestamp = true;
/// <summary>Start each relayed line with "[Character]" (useful when several characters share a channel).</summary>
public bool TagCharacter;
/// <summary>Lines arriving within this window go out in one Discord message.</summary>
public int BatchMs = 1500;
/// <summary>Minimum spacing between messages to one route (Discord allows about 30 per minute per channel).</summary>
public int MinIntervalMs = 2000;
/// <summary>Lines waiting per route; the oldest are dropped beyond this.</summary>
public int MaxQueue = 200;
/// <summary>Entries kept in the panel's log.</summary>
public int MaxLog = 200;
// Pacing limits, shared by the panel's sliders and Normalize.
public const int BatchMinMs = 0, BatchMaxMs = 60_000;
public const int IntervalMinMs = 1000, IntervalMaxMs = 600_000;
public const int QueueMin = 20, QueueMax = 2000;
public const int LogMin = 20, LogMax = 2000;
/// <summary>The batch window <paramref name="route"/> uses.</summary>
public int BatchFor(DiscordRoute route) => route.CustomPace ? route.BatchMs : BatchMs;
/// <summary>The message spacing <paramref name="route"/> uses.</summary>
public int IntervalFor(DiscordRoute route) => route.CustomPace ? route.MinIntervalMs : MinIntervalMs;
}
/// <summary>Loads / saves <see cref="ChatDiscordSettings"/>.</summary>
internal static class ChatDiscordStore
{
public static string DefaultPath =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthchat_discord.json");
/// <summary>
/// Reads the settings (or the defaults: off, no routes). <paramref name="note"/> says what
/// happened, for the log. Never throws.
/// </summary>
public static ChatDiscordSettings Load(string path, out string note)
{
note = string.Empty;
ChatDiscordSettings? s = null;
try
{
if (File.Exists(path))
s = JsonSerializer.Deserialize(File.ReadAllText(path), ChatDiscordJsonContext.Default.ChatDiscordSettings);
}
catch (Exception ex)
{
note = $"settings unreadable ({ex.GetType().Name}: {ex.Message}); using defaults";
KeepUnreadable(path);
s = null;
}
s ??= new ChatDiscordSettings();
Normalize(s);
return s;
}
/// <summary>The settings as JSON (speech names refreshed from the masks first). Any thread.</summary>
public static string Serialize(ChatDiscordSettings s)
{
foreach (var r in s.Routes) r.Speech = DiscordRoute.NamesFromMask(r.SpeechMask);
return JsonSerializer.Serialize(s, ChatDiscordJsonContext.Default.ChatDiscordSettings);
}
/// <summary>Writes <paramref name="json"/> beside the file and swaps it in. Background writer thread.</summary>
public static void Write(string path, string json)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = $"{path}.{Environment.ProcessId}.tmp"; // every client shares the file
try
{
File.WriteAllText(tmp, json);
File.Move(tmp, path, overwrite: true);
}
catch
{
try { File.Delete(tmp); } catch { }
throw;
}
}
/// <summary>Repairs missing / out-of-range values and builds the runtime speech masks.</summary>
internal static void Normalize(ChatDiscordSettings s)
{
s.Version = ChatDiscordSettings.CurrentVersion;
s.Routes = (s.Routes ?? Array.Empty<DiscordRoute>()).Where(r => r != null).ToArray();
foreach (var r in s.Routes) NormalizeRoute(r);
s.Characters = NormalizeCharacters(s.Characters);
s.BatchMs = Math.Clamp(s.BatchMs, ChatDiscordSettings.BatchMinMs, ChatDiscordSettings.BatchMaxMs);
s.MinIntervalMs = Math.Clamp(s.MinIntervalMs, ChatDiscordSettings.IntervalMinMs, ChatDiscordSettings.IntervalMaxMs);
s.MaxQueue = Math.Clamp(s.MaxQueue, ChatDiscordSettings.QueueMin, ChatDiscordSettings.QueueMax);
s.MaxLog = Math.Clamp(s.MaxLog, ChatDiscordSettings.LogMin, ChatDiscordSettings.LogMax);
}
internal static void NormalizeRoute(DiscordRoute r)
{
r.Name = string.IsNullOrWhiteSpace(r.Name) ? "Discord" : r.Name.Trim();
if (Array.IndexOf(DiscordRoute.Modes, r.Mode ?? string.Empty) < 0) r.Mode = DiscordRoute.ModeWebhook;
r.WebhookProtected ??= string.Empty;
r.BotTokenProtected ??= string.Empty;
r.ChannelId = (r.ChannelId ?? string.Empty).Trim();
r.DisplayName ??= string.Empty;
r.Keywords ??= string.Empty;
r.SpeechMask = DiscordRoute.MaskFromNames(r.Speech, DiscordRoute.DefaultSpeechMask());
r.Tabs = (r.Tabs ?? Array.Empty<string>())
.Where(t => !string.IsNullOrWhiteSpace(t)).Select(t => t.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
r.BatchMs = Math.Clamp(r.BatchMs, ChatDiscordSettings.BatchMinMs, ChatDiscordSettings.BatchMaxMs);
r.MinIntervalMs = Math.Clamp(r.MinIntervalMs, ChatDiscordSettings.IntervalMinMs, ChatDiscordSettings.IntervalMaxMs);
}
/// <summary>Drops nameless and repeated entries (same server + name, any case).</summary>
internal static DiscordCharacter[] NormalizeCharacters(DiscordCharacter[]? list)
{
var result = new List<DiscordCharacter>();
foreach (var c in list ?? Array.Empty<DiscordCharacter>())
{
DiscordCharacter? n = c == null ? null : DiscordCharacter.Of(c.Server, c.Name);
if (n != null && !result.Exists(x => x.Same(n))) result.Add(n);
}
return result.ToArray();
}
/// <summary><paramref name="list"/> with each switch in <paramref name="ops"/> applied, in order.</summary>
public static DiscordCharacter[] ApplyCharacterOps(DiscordCharacter[]? list, IEnumerable<DiscordCharacterOp> ops)
{
var result = new List<DiscordCharacter>(NormalizeCharacters(list));
foreach (var op in ops)
{
result.RemoveAll(c => c.Same(op.Character));
if (op.On) result.Add(op.Character);
}
return result.ToArray();
}
/// <summary>The character list in a settings file, or null when it can't be read.</summary>
public static DiscordCharacter[]? ReadCharacters(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return null;
try
{
var s = JsonSerializer.Deserialize(json, ChatDiscordJsonContext.Default.ChatDiscordSettings);
return s == null ? null : NormalizeCharacters(s.Characters);
}
catch (Exception) { return null; }
}
/// <summary>
/// What a client writes when it saves: its own settings (<paramref name="ours"/>, from
/// <see cref="Serialize"/>), except the character list, which is the one in the file now
/// (<paramref name="disk"/>, re-read just before) with this client's switches applied. So one
/// client saving can't switch another client's character on or off. When the file is missing
/// or unreadable, our own list is the base. <paramref name="merged"/> is the list written.
/// </summary>
public static string MergeForSave(string ours, string? disk, IReadOnlyList<DiscordCharacterOp> ops, out DiscordCharacter[] merged)
{
var mine = JsonSerializer.Deserialize(ours, ChatDiscordJsonContext.Default.ChatDiscordSettings)
?? throw new InvalidOperationException("settings JSON is empty");
DiscordCharacter[] baseList = ReadCharacters(disk) ?? NormalizeCharacters(mine.Characters);
merged = ApplyCharacterOps(baseList, ops);
mine.Characters = merged;
mine.Version = ChatDiscordSettings.CurrentVersion;
// Not Serialize(): mine has no runtime speech masks; its speech lists are already right.
return JsonSerializer.Serialize(mine, ChatDiscordJsonContext.Default.ChatDiscordSettings);
}
private static void KeepUnreadable(string path)
{
try
{
if (!File.Exists(path)) return;
File.Copy(path, Path.ChangeExtension(path, $".unreadable-{DateTime.Now:yyyyMMdd-HHmmss}.json"), overwrite: false);
}
catch { }
}
}
// JsonSerializerContext must be at namespace scope (not nested) for source generation.
[JsonSerializable(typeof(ChatDiscordSettings))]
[JsonSourceGenerationOptions(
WriteIndented = true,
IncludeFields = true,
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true)]
internal partial class ChatDiscordJsonContext : JsonSerializerContext { }

View file

@ -0,0 +1,213 @@
// ============================================================================
// RynthCore.Engine - UI/Data/Discord/ChatSpeech.cs
// Player speech in a chat line: which channel it was said on (local, tell,
// fellowship, the allegiance channels, the global chat channels), who said
// it and what. The Discord relay uses it to pick lines finer than a chat tab
// ("tells and fellowship only") and to print them as [Channel] Speaker: text.
//
// Ported from RynthAi's translator (ChatTranslator.TryParseInbound) when the
// relay moved into RynthChat (2026-10-11). Pure; covered by
// tools/ChatDiscordTests.
// ============================================================================
using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace RynthCore.Engine.UI.Data.Discord;
/// <summary>Speech channels. Saved by name (<see cref="ChatSpeech.Name"/>), never by number.</summary>
internal enum SpeechChannel
{
Local = 0,
Tell,
Fellowship,
Allegiance,
Patron,
Vassals,
Covassals,
Monarch,
General,
Trade,
Lfg,
Roleplay,
Society,
Olthoi,
}
internal static class ChatSpeech
{
public static readonly SpeechChannel[] All = Enum.GetValues<SpeechChannel>();
/// <summary>AC's ChatMessageType for spell words ("Zojak Bor"): speech-shaped, never relayed as speech.</summary>
public const int ChatTypeSpellcasting = 0x11;
public static uint Bit(SpeechChannel ch) => 1u << (int)ch;
public static string Name(SpeechChannel ch) => ch switch
{
SpeechChannel.Lfg => "LFG",
_ => ch.ToString(),
};
/// <summary>Accepts channel names and the usual short forms (case-insensitive).</summary>
public static bool TryParseName(string? text, out SpeechChannel ch)
{
ch = SpeechChannel.Local;
if (string.IsNullOrWhiteSpace(text)) return false;
switch (text.Trim().ToLowerInvariant())
{
case "local": case "say": case "area": ch = SpeechChannel.Local; return true;
case "tell": case "tells": case "t": ch = SpeechChannel.Tell; return true;
case "fellowship": case "fellow": case "f": ch = SpeechChannel.Fellowship; return true;
case "allegiance": case "alleg": case "a": ch = SpeechChannel.Allegiance; return true;
case "patron": case "p": ch = SpeechChannel.Patron; return true;
case "vassals": case "vassal": case "v": ch = SpeechChannel.Vassals; return true;
case "covassals": case "covassal": case "c": ch = SpeechChannel.Covassals; return true;
case "monarch": case "m": ch = SpeechChannel.Monarch; return true;
case "general": case "cg": case "g": ch = SpeechChannel.General; return true;
case "trade": case "ct": ch = SpeechChannel.Trade; return true;
case "lfg": case "looking for group": case "clfg": ch = SpeechChannel.Lfg; return true;
case "roleplay": case "rp": case "crp": ch = SpeechChannel.Roleplay; return true;
case "society": case "cs": ch = SpeechChannel.Society; return true;
case "olthoi": case "co": ch = SpeechChannel.Olthoi; return true;
default: return false;
}
}
/// <summary>Channel implied by an inbound chat type; null for generic types (Channels / Social).</summary>
public static SpeechChannel? FromChatType(int chatType) => chatType switch
{
0x02 => SpeechChannel.Local,
0x03 => SpeechChannel.Tell,
0x12 => SpeechChannel.Allegiance,
0x13 => SpeechChannel.Fellowship,
0x1B => SpeechChannel.General,
0x1C => SpeechChannel.Trade,
0x1D => SpeechChannel.Lfg,
0x1E => SpeechChannel.Roleplay,
0x20 => SpeechChannel.Olthoi,
0x21 => SpeechChannel.Society,
_ => null,
};
// "[General] " style tab prefix some servers / chat options put in front of channel lines.
private static readonly Regex RxBracket = new(@"^\[(?<b>[A-Za-z ]{1,24})\]\s*", RegexOptions.CultureInvariant,
TimeSpan.FromMilliseconds(20));
// "You say ...", "You tell Bob, ..." - the server echo of your own lines.
private static readonly Regex RxOwn = new(@"^You\s+(?:say|tell)\b(?<mid>[^""]*)""(?<msg>.*)""\s*$",
RegexOptions.Singleline | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(20));
// "Bob says, "..."" / "Bob says on the General channel, "..."" / "Bob tells you, "...""
private static readonly Regex RxSpeech = new(@"^(?<name>.+?)\s+(?<verb>says|tells)\b(?<mid>[^""]*)""(?<msg>.*)""\s*$",
RegexOptions.Singleline | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(20));
private static readonly Regex RxOnChannel = new(@"on the (?<ch>[A-Za-z ]+?) channel",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(20));
private static readonly Regex RxEscape = new(@"<([0-9a-fA-F]{4})>", RegexOptions.CultureInvariant,
TimeSpan.FromMilliseconds(20));
/// <summary>
/// Splits a chat line (AC's name links already stripped) into channel, speaker and message.
/// The channel comes from, in order: a "[Name]" prefix, "on the X channel", "tells you", the
/// chat type, then words like "patron" / "vassal". False for anything that isn't player speech,
/// and for spell words.
/// </summary>
public static bool TryParse(string? text, int chatType, out SpeechChannel channel,
out string speaker, out string message, out bool own)
{
channel = SpeechChannel.Local;
speaker = message = string.Empty;
own = false;
if (chatType == ChatTypeSpellcasting || string.IsNullOrEmpty(text)) return false;
string t = text.Trim();
if (t.Length < 6 || t.IndexOf('"') < 0) return false;
try
{
SpeechChannel? hint = null;
var b = RxBracket.Match(t);
if (b.Success && TryParseName(b.Groups["b"].Value, out var bc))
{
hint = bc;
t = t.Substring(b.Length);
}
string mid;
bool tellsYou;
var mo = RxOwn.Match(t);
if (mo.Success)
{
own = true;
speaker = "You";
mid = mo.Groups["mid"].Value;
message = mo.Groups["msg"].Value;
tellsYou = t.StartsWith("You tell", StringComparison.OrdinalIgnoreCase);
}
else
{
var m = RxSpeech.Match(t);
if (!m.Success) return false;
speaker = m.Groups["name"].Value.Trim().TrimStart('+');
mid = m.Groups["mid"].Value;
message = m.Groups["msg"].Value;
tellsYou = m.Groups["verb"].Value == "tells" && mid.TrimStart().StartsWith("you", StringComparison.OrdinalIgnoreCase);
if (speaker.Length == 0 || speaker.Length > 40) return false;
}
SpeechChannel? ch = hint;
if (ch == null)
{
var oc = RxOnChannel.Match(mid);
if (oc.Success && TryParseName(oc.Groups["ch"].Value, out var named)) ch = named;
}
if (ch == null && tellsYou) ch = SpeechChannel.Tell;
ch ??= FromChatType(chatType);
ch ??= FromWords(mid);
if (ch == null) return false;
channel = ch.Value;
message = Decode(message).Trim();
return message.Length > 0;
}
catch (RegexMatchTimeoutException)
{
return false;
}
}
private static SpeechChannel? FromWords(string mid)
{
string m = mid.ToLowerInvariant();
if (m.Contains("covassal")) return SpeechChannel.Covassals;
if (m.Contains("vassal")) return SpeechChannel.Vassals;
if (m.Contains("patron")) return SpeechChannel.Patron;
if (m.Contains("monarch")) return SpeechChannel.Monarch;
if (m.Contains("fellowship")) return SpeechChannel.Fellowship;
if (m.Contains("allegiance")) return SpeechChannel.Allegiance;
return null;
}
/// <summary>
/// Expands AC's "&lt;c2dc&gt;" escapes (characters above Latin-1 travel as UTF-16 hex in chat)
/// into the characters they stand for.
/// </summary>
public static string Decode(string text)
{
if (string.IsNullOrEmpty(text) || text.IndexOf('<') < 0) return text ?? string.Empty;
try
{
return RxEscape.Replace(text, m =>
{
int cp = int.Parse(m.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
return cp is > 0 and <= 0xFFFF ? ((char)cp).ToString() : m.Value;
});
}
catch (RegexMatchTimeoutException)
{
return text;
}
}
}

View file

@ -0,0 +1,254 @@
// ============================================================================
// RynthCore.Engine - UI/Data/Discord/DiscordClient.cs
// Posts relay messages to Discord. NativeAOT-safe: request JSON is written
// with Utf8JsonWriter and responses are read with JsonDocument (no
// reflection serialization).
//
// webhook POST {webhook url} (no auth header; the URL is the secret)
// bot POST https://discord.com/api/v10/channels/{id}/messages Authorization: Bot {token}
//
// Every message sets allowed_mentions.parse = [] (nobody is pinged) and
// SUPPRESS_EMBEDS (no link previews). 429 returns the wait Discord asks for.
// 400 / 401 / 403 / 404 are permanent: the relay pauses the route so a bad
// credential isn't retried (Discord temporarily bans clients that keep
// sending invalid requests).
// ============================================================================
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.Engine.UI.Data.Discord;
/// <summary>
/// Outcome of one post. <see cref="RetryAfterMs"/> is how long to wait before the next post to
/// this route (rate limit or bucket exhausted); <see cref="Permanent"/> means stop until the
/// settings change.
/// </summary>
internal readonly record struct DiscordSendResult(bool Ok, int Status, int RetryAfterMs, bool Permanent, string Error)
{
public static DiscordSendResult Fail(string error, bool permanent = false, int status = 0, int retryAfterMs = 0)
=> new(false, status, retryAfterMs, permanent, error);
}
internal static class DiscordClient
{
public const string ApiBase = "https://discord.com/api/v10";
/// <summary>MessageFlags.SUPPRESS_EMBEDS: chat links don't unfurl into previews.</summary>
private const int FlagSuppressEmbeds = 1 << 2;
// Built on first post, so an engine that never relays never opens a socket. Disposed by
// Shutdown (engine shutdown / hot reload): the engine loads into a collectible context, and a
// live client (its handler's pool timer, open connections, pending callbacks) must not
// outlive the generation that made it. After Shutdown no new client is built.
private static readonly object HttpLock = new();
private static HttpClient? _http;
private static bool _closed;
private static HttpClient Http()
{
lock (HttpLock)
{
if (_closed) throw new ObjectDisposedException(nameof(DiscordClient), "the relay is shutting down");
return _http ??= CreateHttp();
}
}
/// <summary>Disposes the HTTP client (cancelling anything still using it) and refuses new posts. Engine shutdown.</summary>
public static void Shutdown()
{
HttpClient? http;
lock (HttpLock)
{
_closed = true;
http = _http;
_http = null;
}
try { http?.Dispose(); } catch (Exception) { }
}
private static HttpClient CreateHttp()
{
var handler = new SocketsHttpHandler
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
AllowAutoRedirect = false,
};
var http = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(15) };
// Discord asks bots to send "DiscordBot (url, version)"; webhooks accept it too.
http.DefaultRequestHeaders.UserAgent.ParseAdd("DiscordBot (https://aelrynth.com, 1.0) RynthChat-Relay");
http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return http;
}
/// <summary>
/// Posts <paramref name="content"/> through a webhook. <paramref name="webhookUrl"/> must
/// already be validated by <see cref="DiscordFormat.TryNormalizeWebhookUrl"/>. Never throws.
/// </summary>
public static Task<DiscordSendResult> PostWebhookAsync(string webhookUrl, string content, string displayName, CancellationToken ct)
{
if (!DiscordFormat.TryNormalizeWebhookUrl(webhookUrl, out string url))
return Task.FromResult(DiscordSendResult.Fail("the saved webhook URL is not a Discord webhook URL", permanent: true));
string body = BuildBody(content, DiscordFormat.SafeWebhookName(displayName));
var req = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
return SendAsync(req, url, ct);
}
/// <summary>Posts <paramref name="content"/> as a bot to <paramref name="channelId"/>. Never throws.</summary>
public static Task<DiscordSendResult> PostBotAsync(string botToken, string channelId, string content, CancellationToken ct)
{
if (!DiscordFormat.LooksLikeBotToken(botToken))
return Task.FromResult(DiscordSendResult.Fail("the saved bot token doesn't look like a Discord bot token", permanent: true));
if (!DiscordFormat.IsSnowflake(channelId))
return Task.FromResult(DiscordSendResult.Fail("the channel ID must be the channel's number (Developer Mode > Copy Channel ID)", permanent: true));
string body = BuildBody(content, string.Empty);
var req = new HttpRequestMessage(HttpMethod.Post, $"{ApiBase}/channels/{channelId.Trim()}/messages")
{
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
req.Headers.TryAddWithoutValidation("Authorization", "Bot " + botToken.Trim());
return SendAsync(req, botToken.Trim(), ct);
}
/// <summary>{"content":..., "username":..., "allowed_mentions":{"parse":[]}, "flags":4}</summary>
internal static string BuildBody(string content, string username)
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms))
{
w.WriteStartObject();
w.WriteString("content", content);
if (username.Length > 0) w.WriteString("username", username);
w.WriteStartObject("allowed_mentions");
w.WriteStartArray("parse");
w.WriteEndArray();
w.WriteEndObject();
w.WriteNumber("flags", FlagSuppressEmbeds);
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray());
}
private static async Task<DiscordSendResult> SendAsync(HttpRequestMessage req, string secret, CancellationToken ct)
{
try
{
using (req)
using (var resp = await Http().SendAsync(req, ct).ConfigureAwait(false))
{
int status = (int)resp.StatusCode;
string json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
int bucketWait = BucketWaitMs(resp.Headers);
if (resp.IsSuccessStatusCode) return new DiscordSendResult(true, status, bucketWait, false, string.Empty);
if (status == 429)
{
int wait = ParseRetryAfterMs(json, HeaderValue(resp.Headers, "Retry-After"));
return DiscordSendResult.Fail($"rate limited, waiting {wait / 1000.0:0.0}s", status: status, retryAfterMs: Math.Max(wait, bucketWait));
}
string msg = DiscordFormat.Redact(ErrorText(status, json), secret);
return DiscordSendResult.Fail(msg, permanent: IsPermanent(status), status: status, retryAfterMs: bucketWait);
}
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
return DiscordSendResult.Fail("request timed out");
}
catch (OperationCanceledException)
{
return DiscordSendResult.Fail("cancelled");
}
catch (HttpRequestException ex)
{
return DiscordSendResult.Fail("network error: " + DiscordFormat.Redact(ex.Message, secret));
}
catch (Exception ex)
{
return DiscordSendResult.Fail($"{ex.GetType().Name}: {DiscordFormat.Redact(ex.Message, secret)}");
}
}
/// <summary>
/// 400 (bad body), 401 (bad token), 403 (no permission), 404 (webhook / channel deleted):
/// retrying the same request can't succeed.
/// </summary>
internal static bool IsPermanent(int status) => status is 400 or 401 or 403 or 404;
/// <summary>
/// Wait for a 429, in ms: the JSON "retry_after" (seconds, may be fractional), else the
/// Retry-After header (seconds), else 5 s. Clamped to 0.25 s .. 10 min.
/// </summary>
internal static int ParseRetryAfterMs(string? json, string? header)
{
double seconds = -1;
if (!string.IsNullOrWhiteSpace(json))
{
try
{
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.ValueKind == JsonValueKind.Object
&& doc.RootElement.TryGetProperty("retry_after", out var ra)
&& ra.ValueKind == JsonValueKind.Number)
seconds = ra.GetDouble();
}
catch (JsonException) { }
}
if (seconds < 0 && double.TryParse(header, NumberStyles.Float, CultureInfo.InvariantCulture, out double h)) seconds = h;
if (seconds < 0) seconds = 5;
return (int)Math.Clamp(seconds * 1000.0, 250.0, 600_000.0);
}
/// <summary>When the route's bucket is empty (X-RateLimit-Remaining: 0), ms until it resets.</summary>
private static int BucketWaitMs(HttpResponseHeaders headers)
{
if (HeaderValue(headers, "X-RateLimit-Remaining") != "0") return 0;
return double.TryParse(HeaderValue(headers, "X-RateLimit-Reset-After"), NumberStyles.Float, CultureInfo.InvariantCulture, out double s)
? (int)Math.Clamp(s * 1000.0, 0.0, 600_000.0)
: 0;
}
private static string? HeaderValue(HttpResponseHeaders headers, string name)
{
if (!headers.TryGetValues(name, out var values)) return null;
foreach (string v in values) return v.Trim();
return null;
}
private static string ErrorText(int status, string json)
{
string detail = string.Empty;
try
{
if (!string.IsNullOrWhiteSpace(json))
{
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.ValueKind == JsonValueKind.Object && doc.RootElement.TryGetProperty("message", out var m))
detail = m.GetString() ?? string.Empty;
}
}
catch (JsonException) { }
string hint = status switch
{
401 => " (the token or webhook is invalid)",
403 => " (the bot can't post in that channel; check its permissions)",
404 => " (the webhook or channel no longer exists)",
_ => string.Empty,
};
return $"HTTP {status}{(detail.Length > 0 ? ": " + detail : string.Empty)}{hint}";
}
}

View file

@ -0,0 +1,211 @@
// ============================================================================
// RynthCore.Engine - UI/Data/Discord/DiscordFormat.cs
// Pure helpers for the Discord relay: Markdown escaping, line formatting,
// message packing, credential-shape checks and the keyword filter.
// No I/O; covered by
// tools/ChatDiscordTests.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
namespace RynthCore.Engine.UI.Data.Discord;
internal static class DiscordFormat
{
/// <summary>Discord rejects message content over 2000 characters.</summary>
public const int MaxContent = 2000;
/// <summary>Longest single relayed line; longer chat is cut with an ellipsis.</summary>
public const int MaxLine = 1900;
// discord.com / discordapp.com, optional ptb. / canary., optional /v{n}, then /webhooks/{id}/{token}.
private static readonly Regex RxWebhook = new(
@"^https://(?:(?:ptb|canary)\.)?discord(?:app)?\.com/api/(?:v\d{1,2}/)?webhooks/(?<id>\d{15,22})/(?<token>[A-Za-z0-9_\-]{30,100})/?$",
RegexOptions.CultureInvariant);
private static readonly Regex RxSnowflake = new(@"^\d{15,22}$", RegexOptions.CultureInvariant);
// Bot tokens are three base64url segments separated by dots.
private static readonly Regex RxBotToken = new(@"^[A-Za-z0-9_\-]{20,}\.[A-Za-z0-9_\-]{4,}\.[A-Za-z0-9_\-]{20,}$",
RegexOptions.CultureInvariant);
/// <summary>
/// Checks a pasted webhook URL. Only Discord's own webhook endpoints are accepted, so a typo
/// can't send chat to some other server. Returns the URL without any query string.
/// </summary>
public static bool TryNormalizeWebhookUrl(string? url, out string normalized)
{
normalized = string.Empty;
if (string.IsNullOrWhiteSpace(url)) return false;
string u = url.Trim();
int q = u.IndexOfAny(new[] { '?', '#' });
if (q >= 0) u = u.Substring(0, q);
if (!RxWebhook.IsMatch(u)) return false;
normalized = u.TrimEnd('/');
return true;
}
public static bool IsSnowflake(string? id) => !string.IsNullOrWhiteSpace(id) && RxSnowflake.IsMatch(id.Trim());
public static bool LooksLikeBotToken(string? token) => !string.IsNullOrWhiteSpace(token) && RxBotToken.IsMatch(token.Trim());
/// <summary>
/// Escapes inline Discord Markdown so chat text shows literally: emphasis, code, spoilers,
/// quotes, masked links, and the &lt;@id&gt; / &lt;#id&gt; / &lt;t:..&gt; tags. Newlines become
/// spaces. "@everyone" / "@here" also get a zero-width space; allowed_mentions already blocks
/// the ping, this keeps the text from looking live.
/// </summary>
public static string Escape(string? text)
{
if (string.IsNullOrEmpty(text)) return string.Empty;
var sb = new StringBuilder(text.Length + 8);
foreach (char c in text)
{
switch (c)
{
case '\\': case '*': case '_': case '~': case '`': case '|':
case '>': case '<': case '[': case ']':
sb.Append('\\').Append(c);
break;
case '\r': case '\n':
sb.Append(' ');
break;
default:
sb.Append(c);
break;
}
}
return sb.Replace("@everyone", "@\u200Beveryone").Replace("@here", "@\u200Bhere").ToString();
}
/// <summary>
/// One relayed line: optional `HH:mm:ss`, optional [Character], **[Channel] Speaker:** message.
/// A line with no channel or speaker is relayed as plain text.
/// </summary>
public static string FormatLine(DateTime time, string? channel, string? speaker, string message,
bool timestamp, string? characterTag)
{
var sb = new StringBuilder(message.Length + 48);
if (timestamp) sb.Append('`').Append(time.ToString("HH:mm:ss", CultureInfo.InvariantCulture)).Append("` ");
if (!string.IsNullOrEmpty(characterTag)) sb.Append('\\').Append('[').Append(Escape(characterTag)).Append("\\] ");
bool hasChannel = !string.IsNullOrEmpty(channel);
bool hasSpeaker = !string.IsNullOrEmpty(speaker);
if (hasChannel || hasSpeaker)
{
sb.Append("**");
if (hasChannel) sb.Append("\\[").Append(Escape(channel)).Append("\\]");
if (hasChannel && hasSpeaker) sb.Append(' ');
if (hasSpeaker) sb.Append(Escape(speaker)).Append(':');
sb.Append("** ");
}
string body = Escape(message);
// Headings, lists and subtext only parse at the start of a line.
if (sb.Length == 0) body = EscapeLineStart(body);
sb.Append(body);
return Truncate(sb.ToString(), MaxLine);
}
// "# x", "-# x", "- x", "+ x" and "1. x" are block syntax when they open a line.
private static readonly Regex RxBlockStart = new(@"^(?:#{1,3}\s|-#\s|[-+]\s|\d+\.\s)", RegexOptions.CultureInvariant);
private static string EscapeLineStart(string s) => RxBlockStart.IsMatch(s) ? "\\" + s : s;
/// <summary>Cuts <paramref name="s"/> to <paramref name="max"/> characters, ending with an ellipsis.</summary>
public static string Truncate(string s, int max)
{
if (s.Length <= max) return s;
int cut = max - 1;
// Don't leave a dangling escape backslash or split a surrogate pair at the cut.
if (cut > 0 && char.IsHighSurrogate(s[cut - 1])) cut--;
if (cut > 0 && s[cut - 1] == '\\') cut--;
return s.Substring(0, cut) + "\u2026";
}
/// <summary>
/// Takes lines from the front of <paramref name="lines"/> while they fit one message (newline
/// separated, at most <see cref="MaxContent"/> characters). Always takes at least one line.
/// </summary>
public static string Pack(List<string> lines, out int taken)
{
taken = 0;
if (lines.Count == 0) return string.Empty;
var sb = new StringBuilder();
foreach (string line in lines)
{
string l = Truncate(line, MaxContent);
int add = l.Length + (sb.Length > 0 ? 1 : 0);
if (taken > 0 && sb.Length + add > MaxContent) break;
if (sb.Length > 0) sb.Append('\n');
sb.Append(l);
taken++;
}
return sb.ToString();
}
/// <summary>
/// Webhook display name: Discord refuses names containing "discord" or "clyde" and limits them
/// to 1-80 characters. Returns empty (use the webhook's own name) when the name can't be used.
/// </summary>
public static string SafeWebhookName(string? name)
{
if (string.IsNullOrWhiteSpace(name)) return string.Empty;
string n = name.Trim().TrimStart('+');
if (n.Contains("discord", StringComparison.OrdinalIgnoreCase) || n.Contains("clyde", StringComparison.OrdinalIgnoreCase))
return string.Empty;
if (n.Equals("everyone", StringComparison.OrdinalIgnoreCase) || n.Equals("here", StringComparison.OrdinalIgnoreCase))
return string.Empty;
return n.Length > 80 ? n.Substring(0, 80) : n;
}
/// <summary>Splits a comma-separated list into trimmed, non-empty entries.</summary>
public static List<string> SplitList(string? csv)
{
var list = new List<string>();
if (string.IsNullOrWhiteSpace(csv)) return list;
foreach (string part in csv.Split(','))
{
string p = part.Trim();
if (p.Length > 0) list.Add(p);
}
return list;
}
/// <summary>True when <paramref name="text"/> contains any keyword (case-insensitive), or there are none.</summary>
public static bool MatchesKeywords(string text, List<string> keywords)
{
if (keywords.Count == 0) return true;
foreach (string k in keywords)
if (text.Contains(k, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
// Unanchored: a webhook's token after /webhooks/{id}/, and anything shaped like a bot token.
private static readonly Regex RxWebhookTokenAnywhere = new(
@"(?<=webhooks/\d{15,22}/)[A-Za-z0-9_\-]{30,100}", RegexOptions.CultureInvariant);
private static readonly Regex RxBotTokenAnywhere = new(
@"(?<![A-Za-z0-9_\-])[A-Za-z0-9_\-]{20,}\.[A-Za-z0-9_\-]{4,}\.[A-Za-z0-9_\-]{20,}(?![A-Za-z0-9_\-])", RegexOptions.CultureInvariant);
/// <summary>
/// Removes credentials from an error text before it is shown or logged: <paramref name="secret"/>
/// (the webhook URL or bot token in use) whole, the webhook's bare token on its own, and anything
/// else shaped like a webhook token or a bot token.
/// </summary>
public static string Redact(string text, string? secret)
{
if (string.IsNullOrEmpty(text)) return string.Empty;
string t = text;
if (!string.IsNullOrEmpty(secret))
{
string sec = secret.Trim();
if (sec.Length > 0) t = t.Replace(sec, "***", StringComparison.Ordinal);
Match m = RxWebhook.Match(sec.TrimEnd('/'));
if (m.Success) t = t.Replace(m.Groups["token"].Value, "***", StringComparison.Ordinal);
}
t = RxWebhookTokenAnywhere.Replace(t, "***");
return RxBotTokenAnywhere.Replace(t, "***");
}
}

View file

@ -0,0 +1,282 @@
// ============================================================================
// RynthCore.Engine - UI/Data/Discord/DiscordRouteQueue.cs
// One route's send queue, kept free of engine state so
// tools/ChatDiscordTests can drive it: lines waiting for the batch window,
// the post in flight, a batch waiting to retry, pacing, pause and counters.
// ChatDiscord owns one per route and calls it on the pump thread only; it
// does the decrypting, the HTTP and the log.
//
// Off means off: when the relay is off for this character or the route is
// switched off, Stop drops everything queued for it (pending lines, the
// retry, the post in flight, whose result is then ignored). Only an explicit
// test message gets past the switches.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Threading;
namespace RynthCore.Engine.UI.Data.Discord;
/// <summary>A packed message waiting for, or in, an HTTP post.</summary>
internal sealed class DiscordBatch
{
public required List<string> Lines;
public required string Content;
public bool IsTest;
public int Attempts;
/// <summary>The route's destination when the batch was made (<see cref="DiscordRouteQueue.Credential"/>).</summary>
public string Credential = string.Empty;
/// <summary>Cancels this batch's request (set by ChatDiscord while it's in flight).</summary>
public CancellationTokenSource? Cancel;
}
/// <summary>What <see cref="DiscordRouteQueue.Apply"/> did with a post's result.</summary>
internal enum DiscordOutcome
{
/// <summary>The batch was no longer in flight (stopped, route removed): result dropped.</summary>
Ignored,
Sent,
Paused,
RateLimited,
Retrying,
GaveUp,
/// <summary>The route's destination changed while the post was out: a failure is dropped, not retried or paused.</summary>
Retargeted,
}
internal sealed class DiscordRouteQueue
{
public const int DedupWindowMs = 3000;
public const int MaxTransientRetries = 5;
public const int MaxBackoffMs = 60000;
public readonly List<string> Pending = new();
public long FirstPendingMs;
public long NextAllowedMs;
public DiscordBatch? InFlight;
public DiscordBatch? Retry;
public int BackoffMs;
public bool Paused;
public string LastError = string.Empty;
public int MessagesSent, LinesSent, Dropped;
public DateTime LastSent;
public readonly Dictionary<string, long> Recent = new(StringComparer.Ordinal);
/// <summary>
/// The destination the queued lines are for: the route's mode and its saved (encrypted)
/// webhook or bot token + channel. Set by <see cref="Retarget"/>.
/// </summary>
public string Credential = string.Empty;
/// <summary>Lines waiting, in flight or waiting to retry.</summary>
public int Queued => Pending.Count + (InFlight?.Lines.Count ?? 0) + (Retry?.Lines.Count ?? 0);
/// <summary>
/// Called with the route's current destination before lines are added or a post started.
/// When it changed (a new webhook URL or token pasted, the channel or mode changed), chat
/// queued for the old destination is dropped rather than sent to the new one: the pending
/// lines and a batch waiting to retry. A post already in flight went to the old one; if it
/// fails it isn't retried (<see cref="Apply"/>). A test is kept: it's meant for whatever the
/// route points at now. Returns the number of lines dropped.
/// </summary>
public int Retarget(string credential)
{
_mode = _channel = _blob = null;
return RetargetTo(credential);
}
// The route fields the credential was last built from (compared by reference: the pump
// calls this every tick, and the route's strings are replaced, never edited, on a change).
private string? _mode, _channel, _blob;
/// <summary><see cref="Retarget(string)"/> from a route's mode, channel and saved blob (webhook or bot token).</summary>
public int Retarget(string mode, string channel, string blob)
{
if (ReferenceEquals(mode, _mode) && ReferenceEquals(channel, _channel) && ReferenceEquals(blob, _blob)) return 0;
int dropped = RetargetTo(mode == DiscordRoute.ModeBot ? $"bot|{channel}|{blob}" : $"webhook|{blob}");
(_mode, _channel, _blob) = (mode, channel, blob);
return dropped;
}
private int RetargetTo(string credential)
{
if (string.Equals(credential, Credential, StringComparison.Ordinal)) return 0;
bool first = Credential.Length == 0 && Queued == 0;
Credential = credential;
if (first) return 0;
int dropped = Pending.Count;
Pending.Clear();
if (Retry is { IsTest: false } retry)
{
dropped += retry.Lines.Count;
Retry = null;
}
if (Retry is { } test) test.Credential = credential;
if (dropped > 0)
{
Dropped += dropped;
BackoffMs = 0;
}
return dropped;
}
/// <summary>Adds a relayed line; the oldest are dropped past <paramref name="maxQueue"/>.</summary>
public void Add(string line, long now, int maxQueue)
{
if (Pending.Count == 0) FirstPendingMs = now;
Pending.Add(line);
int over = Pending.Count - maxQueue;
if (over > 0)
{
Pending.RemoveRange(0, over);
Dropped += over;
}
}
/// <summary>
/// True (and remembered) unless the same line went to this route within the dedup window.
/// </summary>
public bool NoteFresh(string key, long now)
{
if (Recent.TryGetValue(key, out long seen) && now - seen < DedupWindowMs) return false;
Recent[key] = now;
if (Recent.Count > 256) ChatDiscordLogic.PruneRecent(Recent, now, DedupWindowMs);
return true;
}
/// <summary>Queues a test line to go next (it replaces a waiting retry: that is dropped).</summary>
public void QueueTest(string line)
{
if (Retry is { IsTest: false } old) Dropped += old.Lines.Count;
Retry = new DiscordBatch { Lines = new List<string> { line }, Content = line, IsTest = true };
NextAllowedMs = 0;
}
/// <summary>Clears a pause (Resume, a credential change, a test).</summary>
public void Resume()
{
Paused = false;
LastError = string.Empty;
BackoffMs = 0;
NextAllowedMs = 0;
}
/// <summary>
/// The relay is off for this character, or the route is: drops the pending lines, the batch
/// waiting to retry and the post in flight (cancelled; its result will be ignored). A test
/// message is kept. Returns the number of lines dropped. Pump thread.
/// </summary>
public int Stop()
{
int dropped = Pending.Count;
Pending.Clear();
if (Retry is { IsTest: false } retry)
{
dropped += retry.Lines.Count;
Retry = null;
}
if (InFlight is { IsTest: false } flying)
{
dropped += flying.Lines.Count;
InFlight = null;
try { flying.Cancel?.Cancel(); } catch (ObjectDisposedException) { }
}
if (dropped > 0)
{
Dropped += dropped;
BackoffMs = 0;
}
return dropped;
}
/// <summary>
/// The next batch to post now, or null. <paramref name="on"/> is the relay's switch for this
/// character and the route's own switch together: off, only a test may go (anything else is
/// dropped, as in <see cref="Stop"/>). The batch becomes <see cref="InFlight"/>.
/// </summary>
public DiscordBatch? Next(long now, bool on, int batchMs, int intervalMs)
{
if (!on) Stop();
if (InFlight != null || Paused || now < NextAllowedMs) return null;
DiscordBatch? batch = Retry;
if (batch == null)
{
if (!on || Pending.Count == 0) return null;
// Wait out the batch window unless the pending text already fills a message.
int chars = 0;
foreach (string l in Pending) chars += l.Length + 1;
if (now - FirstPendingMs < batchMs && chars < DiscordFormat.MaxContent) return null;
string content = DiscordFormat.Pack(Pending, out int taken);
batch = new DiscordBatch { Lines = Pending.GetRange(0, taken), Content = content, Credential = Credential };
Pending.RemoveRange(0, taken);
FirstPendingMs = now;
}
if (batch.IsTest) batch.Credential = Credential;
Retry = null;
InFlight = batch;
NextAllowedMs = now + intervalMs;
return batch;
}
/// <summary>
/// Applies a post's result. A result for a batch that is no longer in flight (stopped, or
/// the route was removed) is ignored: it must not come back as a retry.
/// </summary>
public DiscordOutcome Apply(DiscordBatch batch, DiscordSendResult r, long now, int intervalMs)
{
if (!ReferenceEquals(InFlight, batch)) return DiscordOutcome.Ignored;
InFlight = null;
if (r.Ok)
{
LastError = string.Empty;
BackoffMs = 0;
MessagesSent++;
LinesSent += batch.Lines.Count;
LastSent = DateTime.Now;
NextAllowedMs = Math.Max(NextAllowedMs, now + Math.Max(intervalMs, r.RetryAfterMs));
return DiscordOutcome.Sent;
}
if (!batch.IsTest && !string.Equals(batch.Credential, Credential, StringComparison.Ordinal))
{
// Sent to the old destination; the new one gets neither the retry nor a pause.
Dropped += batch.Lines.Count;
return DiscordOutcome.Retargeted;
}
LastError = r.Error;
if (r.Permanent)
{
Paused = true;
Dropped += batch.Lines.Count + Pending.Count;
Pending.Clear();
return DiscordOutcome.Paused;
}
if (r.Status == 429)
{
// Rate limits don't count as a failed attempt; Discord says exactly when to come back.
Retry = batch;
NextAllowedMs = now + Math.Max(r.RetryAfterMs, intervalMs);
return DiscordOutcome.RateLimited;
}
batch.Attempts++;
if (batch.Attempts >= MaxTransientRetries)
{
Dropped += batch.Lines.Count;
BackoffMs = 0;
return DiscordOutcome.GaveUp;
}
BackoffMs = BackoffMs == 0 ? 2000 : Math.Min(BackoffMs * 2, MaxBackoffMs);
Retry = batch;
NextAllowedMs = now + Math.Max(BackoffMs, r.RetryAfterMs);
return DiscordOutcome.Retrying;
}
}

View file

@ -0,0 +1,115 @@
// ============================================================================
// RynthCore.Engine - UI/Data/Discord/DiscordSecrets.cs
// Windows DPAPI (CurrentUser) protection for the Discord relay's webhook URLs
// and bot tokens.
//
// A webhook URL is itself a credential: anyone holding it can post to the
// channel. Both secrets are kept in rynthchat_discord.json only as base64
// DPAPI blobs, readable by the Windows user who saved them. Decrypt at the
// moment of use; never log, display or echo the plain text.
// ============================================================================
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
namespace RynthCore.Engine.UI.Data.Discord;
internal static class DiscordSecrets
{
// Changing this makes every saved secret unreadable. Change it only with a migration.
private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("RynthCore.RynthChat.DiscordRelay.v1");
private const int CryptProtectUiForbidden = 0x1;
/// <summary>Encrypts <paramref name="plainText"/> for this Windows user. Empty in, empty out.</summary>
public static string Protect(string? plainText)
{
if (string.IsNullOrEmpty(plainText)) return string.Empty;
byte[] plain = Encoding.UTF8.GetBytes(plainText);
try { return Convert.ToBase64String(Transform(plain, protect: true)); }
finally { Array.Clear(plain); }
}
/// <summary>
/// Decrypts a value written by <see cref="Protect"/>. False when it can't be read on this
/// Windows user (copied from another user or PC, damaged base64, wrong entropy).
/// </summary>
public static bool TryUnprotect(string? protectedBase64, out string plainText)
{
plainText = string.Empty;
if (string.IsNullOrEmpty(protectedBase64)) return false;
byte[] blob;
try { blob = Convert.FromBase64String(protectedBase64); }
catch (FormatException) { return false; }
byte[]? plain = null;
try
{
plain = Transform(blob, protect: false);
plainText = Encoding.UTF8.GetString(plain);
return true;
}
catch (Exception ex) when (ex is Win32Exception or PlatformNotSupportedException or EntryPointNotFoundException or DllNotFoundException)
{
return false;
}
finally
{
if (plain != null) Array.Clear(plain);
}
}
private static byte[] Transform(byte[] input, bool protect)
{
GCHandle inputHandle = GCHandle.Alloc(input, GCHandleType.Pinned);
GCHandle entropyHandle = GCHandle.Alloc(Entropy, GCHandleType.Pinned);
var output = new DataBlob();
try
{
var inputBlob = new DataBlob { cbData = input.Length, pbData = inputHandle.AddrOfPinnedObject() };
var entropyBlob = new DataBlob { cbData = Entropy.Length, pbData = entropyHandle.AddrOfPinnedObject() };
bool ok = 0 != (protect
? CryptProtectData(ref inputBlob, IntPtr.Zero, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, ref output)
: CryptUnprotectData(ref inputBlob, IntPtr.Zero, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, ref output));
if (!ok) throw new Win32Exception(Marshal.GetLastWin32Error());
byte[] result = new byte[output.cbData];
if (output.cbData > 0) Marshal.Copy(output.pbData, result, 0, output.cbData);
return result;
}
finally
{
if (output.pbData != IntPtr.Zero)
{
// Wipe the native copy (the plain text, when decrypting) before freeing it.
for (int i = 0; i < output.cbData; i++) Marshal.WriteByte(output.pbData, i, 0);
LocalFree(output.pbData);
}
inputHandle.Free();
entropyHandle.Free();
}
}
[StructLayout(LayoutKind.Sequential)]
private struct DataBlob
{
public int cbData;
public IntPtr pbData;
}
// Win32 BOOL is returned as int so the signatures stay blittable under NativeAOT.
[DllImport("crypt32.dll", SetLastError = true)]
private static extern int CryptProtectData(ref DataBlob pDataIn, IntPtr szDataDescr, ref DataBlob pOptionalEntropy,
IntPtr pvReserved, IntPtr pPromptStruct, int dwFlags, ref DataBlob pDataOut);
[DllImport("crypt32.dll", SetLastError = true)]
private static extern int CryptUnprotectData(ref DataBlob pDataIn, IntPtr ppszDataDescr, ref DataBlob pOptionalEntropy,
IntPtr pvReserved, IntPtr pPromptStruct, int dwFlags, ref DataBlob pDataOut);
[DllImport("kernel32.dll")]
private static extern IntPtr LocalFree(IntPtr hMem);
}

View file

@ -462,6 +462,8 @@ internal static class SettingsSchema
Section("Text Size (in-game panels)"),
Combo("All Panels", PanelTextScale.SizeNames, _ => PanelTextScale.GetAll(), (_, v) => PanelTextScale.SetAll(v),
"Text size for every in-game panel: 0 = normal, each step 10% bigger, yourjokin = 2.5x."),
Combo("Toolbar", PanelTextScale.SizeNames, _ => PanelTextScale.GetChrome(), (_, v) => PanelTextScale.SetChrome(v),
"Size of the RynthCore icon bar (its icons and tooltips), separate from the panels: 0 = normal, each step 10% bigger.\nAlso: right-click the bar's grip, Ctrl+wheel over the bar, or /rc ui barsize."),
Bool("Size Each Panel Separately", _ => PanelTextScale.PerPanel, (_, v) => PanelTextScale.PerPanel = v,
"Off: every panel uses All Panels. On: set each panel's text size below.", gates: true),
TextSize("RynthAi Dashboard", "RynthAi"),

View file

@ -32,9 +32,11 @@ internal static class UiSources
public static readonly MonsterDetailSource MonsterDetail = new();
public static readonly LootEditSource LootEdit = new();
public static readonly SenseSource Sense = new();
public static readonly BountiesSource Bounties = new();
static UiSources()
{
UiDataHub.Register(Bounties);
UiDataHub.Register(Settings);
UiDataHub.Register(Meta);
UiDataHub.Register(LootEdit);

View file

@ -6,7 +6,9 @@
// as "Title=size" lines; set from Settings > Display or from a window's own
// title bar (the text size button, Ctrl+wheel; ImGuiPanelHost). One size
// ("All Panels") applies to every panel unless "Size each panel separately"
// is on.
// is on. The toolbar (the icon bar, ImGuiBar) has its own size, the "chrome"
// row (Settings > Display > Toolbar, the bar's right-click menu, Ctrl+wheel on
// the bar, /rc ui barsize); it is independent of All Panels and per-panel sizes.
// ============================================================================
using System;
@ -27,11 +29,16 @@ internal static class PanelTextScale
private static readonly Dictionary<string, int> Sizes = new(StringComparer.OrdinalIgnoreCase);
private static bool _loaded;
private static string FilePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "panel_text_size.txt");
// RYNTHCORE_PANEL_TEXT_SIZE points a test at its own file instead of the real one.
private static readonly string FilePath =
Environment.GetEnvironmentVariable("RYNTHCORE_PANEL_TEXT_SIZE") is { Length: > 0 } overridePath
? overridePath
: Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "panel_text_size.txt");
private const string AllKey = "__all";
private const string PerPanelKey = "__perPanel";
private const string ChromeKey = "__chrome";
/// <summary>The size (0-10) a panel is drawn at: its own when sizing per panel, else All Panels.</summary>
public static int Get(string title)
@ -59,6 +66,18 @@ internal static class PanelTextScale
public static int GetAll() => GetOwn(AllKey);
public static void SetAll(int size) => Set(AllKey, size);
/// <summary>The toolbar's size (0-10): its own row, 0 unless set; never All Panels.</summary>
public static int GetChrome()
{
lock (Sync)
{
Load();
return Sizes.TryGetValue(ChromeKey, out int c) ? c : 0;
}
}
public static void SetChrome(int size) => Set(ChromeKey, size);
/// <summary>Off: every panel uses All Panels. On: each panel has its own size.</summary>
public static bool PerPanel
{
@ -108,7 +127,7 @@ internal static class PanelTextScale
// effect: start them from what every panel shows now.
var keys = new List<string>(Sizes.Keys);
foreach (string k in keys)
if (k != AllKey && k != PerPanelKey) Sizes[k] = all;
if (k != AllKey && k != PerPanelKey && k != ChromeKey) Sizes[k] = all;
Sizes[PerPanelKey] = 1;
}
Sizes[title] = size;
@ -145,7 +164,7 @@ internal static class PanelTextScale
/// <summary>Font size factor for a size step.</summary>
public static float Factor(int step) => Scales[Math.Clamp(step, 0, Scales.Length - 1)];
/// <summary>The distinct non-zero sizes any panel uses (fonts are baked for these).</summary>
/// <summary>The distinct non-zero sizes any panel or the toolbar uses (fonts are baked for these).</summary>
public static List<int> StepsInUse()
{
lock (Sync)
@ -156,7 +175,7 @@ internal static class PanelTextScale
foreach (var kv in Sizes)
{
if (kv.Key == PerPanelKey) continue;
if (!perPanel && kv.Key != AllKey) continue; // only All Panels is in use
if (!perPanel && kv.Key != AllKey && kv.Key != ChromeKey) continue; // All Panels and the toolbar are in use
if (kv.Value > 0 && !steps.Contains(kv.Value)) steps.Add(kv.Value);
}
return steps;

View file

@ -55,9 +55,8 @@ internal static class Program
/// <summary>
/// --decal-bridge register [--dir &lt;folder&gt;] | check | status | unregister
/// | register-machine [--dir &lt;folder&gt;] | unregister-machine
/// register: where a Decal client started now reads Decal's filter list (per-user copy for
/// a non-elevated client, the machine-wide list otherwise; that needs an elevated prompt),
/// then the check. check: the launcher's "Check Decal bridge", read-only.
/// register: into Decal's machine-wide filter list (needs an administrator prompt; never
/// creates a per-user copy), then the check. check: the launcher's "Check Decal bridge", read-only.
/// The launcher does the same when an account is set to "Decal + RynthCore".
/// See docs/DECAL_BRIDGE_PLAN.md.
/// </summary>

View file

@ -5,6 +5,11 @@ internal static class AgentLog
{
private static string? _logFile;
private static readonly object Gate = new();
// StatusAgent.log never rolled over and reached ~700 MB (2026-10-11, disk at 1.7 GB free).
// Past MaxBytes it becomes StatusAgent.log.old (one old copy) and a fresh file starts.
private const long MaxBytes = 50L * 1024 * 1024;
private const int SizeCheckEvery = 200;
private static int _writesSinceCheck = SizeCheckEvery;
public static bool Verbose;
public static void Init(string logDirectory)
@ -26,6 +31,16 @@ internal static class AgentLog
if (Verbose) Write("DBG", msg);
}
/// <summary>Every SizeCheckEvery writes: past MaxBytes, the log moves to .old and starts again.</summary>
internal static void RollIfBig(string file, long maxBytes = MaxBytes)
{
if (++_writesSinceCheck < SizeCheckEvery) return;
_writesSinceCheck = 0;
var info = new FileInfo(file);
if (!info.Exists || info.Length <= maxBytes) return;
File.Move(file, file + ".old", overwrite: true);
}
private static void Write(string level, string msg)
{
string line = $"[{DateTime.Now:HH:mm:ss.fff}] [{level}] {msg}";
@ -34,6 +49,7 @@ internal static class AgentLog
try { Console.WriteLine(line); } catch { }
if (_logFile != null)
{
try { RollIfBig(_logFile); } catch { }
try { File.AppendAllText(_logFile, line + Environment.NewLine); } catch { }
}
}

View file

@ -3,7 +3,7 @@
<!--
Offline checks for src\RynthCore.Engine\Compatibility\AcMouseOverRules.cs (2026-10-08):
a nameplate drawn under AC's windows may take a click only where AC's own mouse-over is
the 3D world (the SmartBox wrapper, type 0x10000030) - never on one of AC's windows - and
the 3D world (gmSmartBoxUI, type 0x10000014, or the SmartBox wrapper, 0x10000030) - never on one of AC's windows - and
keeps today's behaviour (takes it) whenever AC's UI state can't be read.
The AC-side facts (offsets, the type id) are checked against acclient.exe by
tools\ui_hooks_check.py.

View file

@ -41,12 +41,21 @@ internal static class Program
AcMouseTarget t = AcMouseOverRules.Classify(true, false, SomeElement, true, SmartBox);
Check(t == AcMouseTarget.World, $"SmartBox wrapper under the mouse = World (got {t})");
Check(AcMouseOverRules.UnderUiOverlayMayTakeClick(t), "may take the click");
// 2026-10-10 client logs: over open ground AC reports gmSmartBoxUI (element 0x1000049A,
// type 0x10000014), not the wrapper. Classed as a window, it kept every plate's click from the plate.
Case("cursor on the 3D world as AC reports it in game: gmSmartBoxUI (0x10000014) takes the click");
Check(AcMouseOverRules.UIElementTypeGmSmartBoxUI == 0x10000014, "gmSmartBoxUI::Register registers 0x10000014");
AcMouseTarget g = AcMouseOverRules.Classify(true, false, 0x1000049A, true, AcMouseOverRules.UIElementTypeGmSmartBoxUI);
Check(g == AcMouseTarget.World, $"gmSmartBoxUI under the mouse = World (got {g})");
Check(AcMouseOverRules.UnderUiOverlayMayTakeClick(g), "gmSmartBoxUI: may take the click");
}
private static void AcWindowsKeepTheClick()
{
Case("cursor on one of AC's windows: the click stays with AC");
foreach (int type in new[] { ItemList, 0x10000001, 0x10000032, 0, -1, SmartBox + 1 })
// 0x10000013 / 0x10000015: neighbours of gmSmartBoxUI's type stay windows.
foreach (int type in new[] { ItemList, 0x10000001, 0x10000032, 0, -1, SmartBox + 1, 0x10000013, 0x10000015 })
{
AcMouseTarget t = AcMouseOverRules.Classify(true, false, SomeElement, true, type);
Check(t == AcMouseTarget.AcWindow, $"type 0x{type:X8} = AcWindow (got {t})");

View file

@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for RynthChat's Discord relay (src\RynthCore.Engine\UI\Data\Discord\, the
engine-free parts compiled in): speech parsing, which routes take a line and under which
label, the Discord text, scrollback detection, settings save / load, the request body and
429 handling, a route's send queue, and DPAPI round trips. Nothing is sent.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>ChatDiscordTests</RootNamespace>
<!-- DiscordRoute.Status is written by the engine's pump, which isn't compiled in here. -->
<NoWarn>$(NoWarn);CS0649</NoWarn>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\Discord\ChatSpeech.cs" Link="Engine\ChatSpeech.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\Discord\ChatDiscordLogic.cs" Link="Engine\ChatDiscordLogic.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\Discord\ChatDiscordSettings.cs" Link="Engine\ChatDiscordSettings.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\Discord\DiscordFormat.cs" Link="Engine\DiscordFormat.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\Discord\DiscordClient.cs" Link="Engine\DiscordClient.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\Discord\DiscordSecrets.cs" Link="Engine\DiscordSecrets.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\Discord\DiscordRouteQueue.cs" Link="Engine\DiscordRouteQueue.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,704 @@
using System.Text.Json;
using RynthCore.Engine.UI.Data.Discord;
namespace ChatDiscordTests;
/// <summary>
/// RynthChat's Discord relay, the parts that don't need the engine: what a chat line is, which
/// routes take it, how it reads in Discord, scrollback, settings files, the request body and
/// rate-limit waits, and the DPAPI wrapper. Fake webhook URLs and tokens are built at run time
/// (no credential-shaped literals in the source).
/// </summary>
internal static class Program
{
private static int _checks, _failed;
// A well-formed but fake webhook URL / bot token / channel id.
private static readonly string FakeWebhook =
"https://discord.com/api/webhooks/" + new string('1', 18) + "/" + new string('x', 68);
private static readonly string FakeBotToken =
string.Join(".", new string('A', 24), new string('b', 6), new string('c', 38));
private static readonly string FakeChannel = new string('7', 19);
private static int Main()
{
Speech();
Classify();
Routing();
Formatting();
Backlog();
Packing();
Validation();
RequestBody();
Settings();
Secrets();
Dedup();
Characters();
Queue();
FaceText();
ClientShutdown(); // last: it closes DiscordClient for good
Console.WriteLine(_failed == 0 && _checks > 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks})");
return _failed == 0 && _checks > 0 ? 0 : 1;
}
// ── Speech parsing ───────────────────────────────────────────────────
private static void Speech()
{
Said("Bob tells you, \"hi there\"", 0x03, SpeechChannel.Tell, "Bob", "hi there", own: false);
Said("You tell Bob, \"yo\"", 0x03, SpeechChannel.Tell, "You", "yo", own: true);
Said("Bob says on the General channel, \"wts pyreal\"", 0x1B, SpeechChannel.General, "Bob", "wts pyreal", own: false);
Said("[Trade] Bob says, \"wtb mana stones\"", 0x00, SpeechChannel.Trade, "Bob", "wtb mana stones", own: false);
Said("Bob says, \"hello\"", 0x02, SpeechChannel.Local, "Bob", "hello", own: false);
Said("+Bob says to your fellowship, \"pull\"", 0x00, SpeechChannel.Fellowship, "Bob", "pull", own: false);
Said("Bob says to your covassals, \"gz\"", 0x00, SpeechChannel.Covassals, "Bob", "gz", own: false);
Said("Bob says to your vassals, \"hi\"", 0x00, SpeechChannel.Vassals, "Bob", "hi", own: false);
Said("Bob says, \"caf<00e9> time\"", 0x12, SpeechChannel.Allegiance, "Bob", "caf\u00e9 time", own: false);
Said("Bob says on the LFG channel, \"lf colo\"", 0x00, SpeechChannel.Lfg, "Bob", "lf colo", own: false);
NotSpeech("You say, \"Zojak Bor\"", ChatSpeech.ChatTypeSpellcasting); // spell words
NotSpeech("You have gained 500 experience.", 0x00);
NotSpeech("Bob says, \" \"", 0x02); // nothing said
NotSpeech("", 0x02);
NotSpeech(null, 0x02);
NotSpeech("He says \"hi\"", 0x00); // no channel at all
Check(ChatSpeech.Name(SpeechChannel.Lfg) == "LFG", "LFG is shown upper case");
Check(ChatSpeech.TryParseName("lfg", out var lfg) && lfg == SpeechChannel.Lfg, "LFG parses back");
Check(ChatSpeech.TryParseName(" Fellow ", out var fel) && fel == SpeechChannel.Fellowship, "short names parse");
Check(!ChatSpeech.TryParseName("guild", out _), "unknown names don't parse");
foreach (var ch in ChatSpeech.All)
Check(ChatSpeech.TryParseName(ChatSpeech.Name(ch), out var back) && back == ch, $"{ch} survives a save");
Check(ChatSpeech.Decode("<zzzz> and <0041>") == "<zzzz> and A", "only hex escapes decode");
}
private static void Said(string text, int chatType, SpeechChannel ch, string who, string msg, bool own)
{
bool ok = ChatSpeech.TryParse(text, chatType, out var c, out string s, out string m, out bool o);
Check(ok, $"speech: {text}");
if (!ok) return;
Check(c == ch, $"{text} -> {ch} (got {c})");
Check(s == who, $"{text} speaker {who} (got {s})");
Check(m == msg, $"{text} message \"{msg}\" (got \"{m}\")");
Check(o == own, $"{text} own={own}");
}
private static void NotSpeech(string? text, int chatType)
=> Check(!ChatSpeech.TryParse(text, chatType, out _, out _, out _, out _), $"not speech: {text ?? "(null)"}");
// ── Line classification ──────────────────────────────────────────────
private static void Classify()
{
Check(ChatDiscordLogic.TryClassify("You tell Bob, \"omw\"", 0x03, "Alice", out var mine), "own tell classifies");
Check(mine.Own && mine.Speaker == "Alice" && mine.Speech == SpeechChannel.Tell, "own lines are shown as the character");
Check(ChatDiscordLogic.TryClassify("You tell Bob, \"omw\"", 0x03, "", out var anon) && anon.Speaker == "You",
"own lines before login keep \"You\"");
Check(ChatDiscordLogic.TryClassify("You gain 500 xp.", 0x00, "Alice", out var plain), "plain text classifies");
Check(plain.Speech == null && plain.Speaker.Length == 0 && plain.Message == "You gain 500 xp.", "plain text has no channel");
Check(plain.Haystack == "You gain 500 xp.", "plain haystack is the text");
Check(ChatDiscordLogic.TryClassify("Bob tells you, \"rare drop\"", 0x03, "", out var tell) && tell.Haystack == "Bob rare drop",
"speech haystack is speaker + message");
Check(!ChatDiscordLogic.TryClassify(" ", 0x00, "Alice", out _), "blank lines are skipped");
Check(!ChatDiscordLogic.TryClassify(null, 0x00, "Alice", out _), "null lines are skipped");
}
// ── Which routes take a line ─────────────────────────────────────────
private static void Routing()
{
var route = Route(DiscordRoute.DefaultSpeechMask(), "System");
Check(ChatDiscordLogic.Wants(route, SpeechChannel.Tell, _ => false, out string l1) && l1 == "Tell", "default routes take tells");
Check(ChatDiscordLogic.Wants(route, SpeechChannel.Monarch, _ => false, out _), "default routes take the allegiance channels");
Check(!ChatDiscordLogic.Wants(route, SpeechChannel.Local, _ => false, out _), "default routes skip local");
Check(!ChatDiscordLogic.Wants(route, SpeechChannel.General, _ => false, out _), "default routes skip General");
Check(ChatDiscordLogic.Wants(route, null, t => t == "System", out string l2) && l2 == "System",
"a line in a ticked tab is taken, labelled with the tab");
Check(ChatDiscordLogic.Wants(route, SpeechChannel.Local, t => t == "System", out string l3) && l3 == "Local",
"speech taken through a tab keeps its channel label");
Check(!ChatDiscordLogic.Wants(route, null, t => t == "Combat", out _), "lines only in other tabs are skipped");
var none = Route(0);
Check(!ChatDiscordLogic.Wants(none, SpeechChannel.Tell, _ => true, out _), "a route with nothing ticked takes nothing");
var all = Route(DiscordRoute.AllSpeechMask());
foreach (var ch in ChatSpeech.All)
Check(all.RelaysSpeech(ch), $"all-channels route relays {ch}");
Check(DiscordFormat.MatchesKeywords("Bob rare drop", DiscordFormat.SplitList("loot, RARE ,")), "keywords match case-insensitively");
Check(!DiscordFormat.MatchesKeywords("Bob hi", DiscordFormat.SplitList("loot,rare")), "keywords filter");
Check(DiscordFormat.MatchesKeywords("anything", DiscordFormat.SplitList(" , ")), "no keywords = everything");
var s = new ChatDiscordSettings { BatchMs = 1500, MinIntervalMs = 2000 };
var own = new DiscordRoute { CustomPace = true, BatchMs = 0, MinIntervalMs = 60_000 };
Check(s.BatchFor(route) == 1500 && s.IntervalFor(route) == 2000, "routes use the relay's pacing by default");
Check(s.BatchFor(own) == 0 && s.IntervalFor(own) == 60_000, "own pacing overrides it");
Check(!new DiscordRoute().HasSecret, "a new route has no secret");
Check(new DiscordRoute { WebhookProtected = "blob" }.HasSecret, "webhook routes need the webhook");
Check(!new DiscordRoute { Mode = DiscordRoute.ModeBot, BotTokenProtected = "blob" }.HasSecret, "bot routes need a channel too");
Check(new DiscordRoute { Mode = DiscordRoute.ModeBot, BotTokenProtected = "blob", ChannelId = FakeChannel }.HasSecret, "bot route ready");
}
private static DiscordRoute Route(uint speech, params string[] tabs)
=> new() { SpeechMask = speech, Tabs = tabs };
// ── Discord text ─────────────────────────────────────────────────────
private static void Formatting()
{
var at = new DateTime(2026, 10, 11, 12, 34, 56);
var s = new ChatDiscordSettings { IncludeTimestamp = true, TagCharacter = false };
ChatDiscordLogic.TryClassify("Bob tells you, \"hi *there*\"", 0x03, "Alice", out var tell);
Same(ChatDiscordLogic.Format(s, at, tell, "Tell", "Alice"), "`12:34:56` **\\[Tell\\] Bob:** hi \\*there\\*", "speech line");
s.IncludeTimestamp = false;
s.TagCharacter = true;
Same(ChatDiscordLogic.Format(s, at, tell, "Tell", "Alice"), "\\[Alice\\] **\\[Tell\\] Bob:** hi \\*there\\*", "character tag");
Same(ChatDiscordLogic.Format(s, at, tell, "Tell", ""), "**\\[Tell\\] Bob:** hi \\*there\\*", "no tag before login");
s.TagCharacter = false;
ChatDiscordLogic.TryClassify("# You found a rare!", 0x00, "Alice", out var plain);
Same(ChatDiscordLogic.Format(s, at, plain, "", "Alice"), "\\# You found a rare!", "plain text can't become a heading");
Same(ChatDiscordLogic.Format(s, at, plain, "System", "Alice"), "**\\[System\\]** # You found a rare!", "tab label");
string pinged = DiscordFormat.Escape("@everyone look <@123> [x](y)");
Check(!pinged.Contains("@everyone"), "@everyone is defused");
Check(pinged.Contains("\\<@123\\>") && pinged.Contains("\\[x\\]"), "mentions and links are escaped");
Same(DiscordFormat.Escape("a\r\nb"), "a b", "newlines flatten");
string longLine = DiscordFormat.FormatLine(at, null, null, new string('z', 5000), false, null);
Check(longLine.Length == DiscordFormat.MaxLine && longLine.EndsWith('\u2026'), "long lines are cut");
string cut = DiscordFormat.Truncate(new string('a', 8) + "\\*", 10);
Check(cut.Length <= 10 && !cut.TrimEnd('\u2026').EndsWith('\\'), "cuts don't strand an escape");
Same(DiscordFormat.SafeWebhookName("+Bob"), "Bob", "webhook name drops +");
Same(DiscordFormat.SafeWebhookName("Discord Bob"), "", "Discord refuses names with 'discord'");
Same(DiscordFormat.SafeWebhookName("everyone"), "", "no 'everyone' name");
Check(DiscordFormat.SafeWebhookName(new string('n', 100)).Length == 80, "webhook names cap at 80");
}
// ── Scrollback, by RynthChat's seq ───────────────────────────────────
private static void Backlog()
{
static ulong[] Seqs(ulong from, int count)
{
var a = new ulong[count];
for (int i = 0; i < count; i++) a[i] = from + (ulong)i;
return a;
}
static int Posted(bool[] post) => post.Count(p => p);
// Engine start or hot reload: the first read is RynthChat's whole ring (up to 500 lines).
var g = new DiscordBacklogGate();
Check(Posted(g.Admit(on: true, Seqs(1, 500))) == 0, "the first read after start is a baseline: 500 lines of scrollback, none posted");
Check(g.Live, "after the baseline the relay is live");
Check(Posted(g.Admit(on: true, Seqs(501, 3))) == 3, "lines after the baseline are posted");
Check(Posted(g.Admit(on: true, Seqs(502, 2))) == 0, "a line seen already isn't posted twice");
Check(Posted(g.Admit(on: true, new ulong[] { 503, 504, 505 })) == 2, "only the newer lines of a mixed read");
// An empty first read is still the baseline: the next line is news.
g = new DiscordBacklogGate();
Check(Posted(g.Admit(on: true, Array.Empty<ulong>())) == 0 && g.Live, "an empty first read is the baseline");
Check(Posted(g.Admit(on: true, Seqs(1, 1))) == 1, "the line after an empty baseline is posted");
// Off, then on again: what arrived meanwhile is history.
Check(Posted(g.Admit(on: false, Seqs(2, 10))) == 0 && !g.Live, "nothing is posted while off");
Check(Posted(g.Admit(on: true, Seqs(12, 40))) == 0, "the first read after switching on is a baseline");
Check(Posted(g.Admit(on: true, Seqs(52, 1))) == 1, "then new lines go");
g.Off();
Check(Posted(g.Admit(on: true, Seqs(53, 5))) == 0, "Off (the pump saw it off) re-baselines");
// RynthChat reloaded: its numbers start from 1 again.
g.SourceReset();
Check(Posted(g.Admit(on: true, Seqs(1, 4))) == 0, "after RynthChat restarts its numbering, its first read is a baseline");
Check(Posted(g.Admit(on: true, Seqs(5, 2))) == 2, "and its new lines go, though their numbers are low");
}
// ── Batching ─────────────────────────────────────────────────────────
private static void Packing()
{
var lines = new List<string> { new('a', 900), new('b', 900), new('c', 900) };
string first = DiscordFormat.Pack(lines, out int taken);
Check(taken == 2 && first.Length == 1801, $"two 900-char lines fit one message (took {taken}, {first.Length} chars)");
var huge = new List<string> { new('h', 2500), "next" };
string one = DiscordFormat.Pack(huge, out int t2);
Check(t2 == 1 && one.Length == DiscordFormat.MaxContent, "an oversized line still goes, cut to 2000");
Check(DiscordFormat.Pack(new List<string>(), out int t3) == string.Empty && t3 == 0, "nothing to pack");
}
// ── Pasted values ────────────────────────────────────────────────────
private static void Validation()
{
Check(DiscordFormat.TryNormalizeWebhookUrl(FakeWebhook, out string n1) && n1 == FakeWebhook, "webhook URL accepted");
Check(DiscordFormat.TryNormalizeWebhookUrl(" " + FakeWebhook + "/?wait=true ", out string n2) && n2 == FakeWebhook,
"query and trailing slash are dropped");
Check(DiscordFormat.TryNormalizeWebhookUrl(FakeWebhook.Replace("discord.com", "ptb.discordapp.com").Replace("/api/", "/api/v10/"), out _),
"ptb / discordapp / versioned URLs accepted");
Check(!DiscordFormat.TryNormalizeWebhookUrl(FakeWebhook.Replace("https:", "http:"), out _), "plain http refused");
Check(!DiscordFormat.TryNormalizeWebhookUrl(FakeWebhook.Replace("discord.com", "discord.com.example.net"), out _), "other hosts refused");
Check(!DiscordFormat.TryNormalizeWebhookUrl("", out _), "blank refused");
Check(DiscordFormat.LooksLikeBotToken(FakeBotToken), "bot token shape accepted");
Check(!DiscordFormat.LooksLikeBotToken("Bot " + FakeBotToken), "the 'Bot ' prefix isn't part of the token");
Check(!DiscordFormat.LooksLikeBotToken("short.x.y"), "short tokens refused");
Check(DiscordFormat.IsSnowflake(FakeChannel), "channel id accepted");
Check(!DiscordFormat.IsSnowflake("#general"), "channel names refused");
string secret = new string('s', 40);
Same(DiscordFormat.Redact("error near " + secret, secret), "error near ***", "secrets are redacted");
Same(DiscordFormat.Redact("no secret here", ""), "no secret here", "nothing to redact");
string hookToken = FakeWebhook.Substring(FakeWebhook.LastIndexOf('/') + 1);
Same(DiscordFormat.Redact("Invalid Webhook Token: " + hookToken, FakeWebhook), "Invalid Webhook Token: ***",
"the webhook's bare token is redacted");
string other = "https://discord.com/api/webhooks/" + new string('2', 18) + "/" + new string('y', 68);
Check(!DiscordFormat.Redact("posting to " + other, FakeWebhook).Contains(new string('y', 68)), "any webhook URL's token is redacted");
Same(DiscordFormat.Redact("Authorization: Bot " + FakeBotToken, null), "Authorization: Bot ***", "a bare bot token is redacted without being told");
Same(DiscordFormat.Redact("401 for " + FakeBotToken + ".", FakeBotToken), "401 for ***.", "the bot token in use is redacted");
Same(DiscordFormat.Redact("HTTP 404: Unknown Webhook (v1.2.3)", FakeWebhook), "HTTP 404: Unknown Webhook (v1.2.3)", "ordinary errors are left alone");
}
// ── Request body and status handling ─────────────────────────────────
private static void RequestBody()
{
using (var doc = JsonDocument.Parse(DiscordClient.BuildBody("line \"one\"\nline two", "Alice")))
{
var root = doc.RootElement;
Check(root.GetProperty("content").GetString() == "line \"one\"\nline two", "content round-trips");
Check(root.GetProperty("username").GetString() == "Alice", "username sent");
Check(root.GetProperty("allowed_mentions").GetProperty("parse").GetArrayLength() == 0, "no mentions can ping");
Check(root.GetProperty("flags").GetInt32() == 4, "embeds suppressed");
}
using (var doc = JsonDocument.Parse(DiscordClient.BuildBody("x", "")))
Check(!doc.RootElement.TryGetProperty("username", out _), "no username when blank (bot / webhook default)");
Check(DiscordClient.ParseRetryAfterMs("{\"retry_after\":1.5,\"global\":false}", null) == 1500, "retry_after from JSON");
Check(DiscordClient.ParseRetryAfterMs(null, "3") == 3000, "Retry-After header");
Check(DiscordClient.ParseRetryAfterMs("not json", null) == 5000, "unknown wait is 5 s");
Check(DiscordClient.ParseRetryAfterMs("{\"retry_after\":0.01}", null) == 250, "waits at least 0.25 s");
Check(DiscordClient.ParseRetryAfterMs("{\"retry_after\":99999}", null) == 600_000, "waits at most 10 min");
foreach (int st in new[] { 400, 401, 403, 404 }) Check(DiscordClient.IsPermanent(st), $"HTTP {st} pauses the route");
foreach (int st in new[] { 429, 500, 502, 503 }) Check(!DiscordClient.IsPermanent(st), $"HTTP {st} is retried");
}
// ── Settings file ────────────────────────────────────────────────────
private static void Settings()
{
string dir = TempDir();
try
{
string path = Path.Combine(dir, "rynthchat_discord.json");
var fresh = ChatDiscordStore.Load(path, out string n0);
Check(fresh.Characters.Length == 0 && fresh.Routes.Length == 0 && n0.Length == 0, "no file: defaults, off for everyone");
var s = new ChatDiscordSettings
{
Characters = new[] { DiscordCharacter.Of("Aelrynth", "Alice")! },
SkipOwn = true,
TagCharacter = true,
BatchMs = 999_999, // clamped on load
MinIntervalMs = 5, // clamped on load
Routes = new[]
{
new DiscordRoute
{
Name = "Guild", Mode = DiscordRoute.ModeBot, ChannelId = FakeChannel, BotTokenProtected = "blob",
SpeechMask = ChatSpeech.Bit(SpeechChannel.Tell) | ChatSpeech.Bit(SpeechChannel.Lfg),
Tabs = new[] { "System", "Loot" }, Keywords = "rare", CustomPace = true, BatchMs = 0, MinIntervalMs = 30_000,
},
new DiscordRoute { Name = " ", SpeechMask = 0 },
},
};
string json = ChatDiscordStore.Serialize(s);
Check(json.Contains("\"speech\"") && json.Contains("\"LFG\""), "speech channels are saved by name");
Check(!json.Contains("speechMask", StringComparison.OrdinalIgnoreCase), "the runtime mask isn't saved");
Check(!json.Contains("hasSecret", StringComparison.OrdinalIgnoreCase) && !json.Contains("\"status\""), "runtime state isn't saved");
ChatDiscordStore.Write(path, json);
Check(Directory.GetFiles(dir, "*.tmp").Length == 0, "the temp file is swapped in");
var back = ChatDiscordStore.Load(path, out string n1);
Check(n1.Length == 0, "clean load has no note");
Check(back.SkipOwn && back.TagCharacter && back.Characters.Length == 1 && back.Characters[0].Name == "Alice" && back.Characters[0].Server == "Aelrynth", "switches round-trip");
Check(back.BatchMs == ChatDiscordSettings.BatchMaxMs, "batch window clamped");
Check(back.MinIntervalMs == ChatDiscordSettings.IntervalMinMs, "message spacing clamped");
Check(back.Routes.Length == 2, "routes round-trip");
var g = back.Routes[0];
Check(g.Name == "Guild" && g.Mode == DiscordRoute.ModeBot && g.ChannelId == FakeChannel && g.BotTokenProtected == "blob",
"route connection round-trips");
Check(g.RelaysSpeech(SpeechChannel.Tell) && g.RelaysSpeech(SpeechChannel.Lfg) && !g.RelaysSpeech(SpeechChannel.Fellowship),
"speech channels round-trip");
Check(g.Tabs.SequenceEqual(new[] { "System", "Loot" }) && g.Keywords == "rare", "tabs and keywords round-trip");
Check(g.CustomPace && g.BatchMs == 0 && g.MinIntervalMs == 30_000, "route pacing round-trips");
Check(back.Routes[1].Name == "Discord", "blank route names get a name");
Check(back.Routes[1].SpeechMask == 0, "a route with every channel unticked stays empty");
// Hand-edited file: no speech list means the defaults; bad values repaired.
File.WriteAllText(path, "{ \"enabled\": true, \"routes\": [ { \"name\": \"x\", \"mode\": \"carrier pigeon\", " +
"\"tabs\": [\"System\", \"system\", \" \", null] }, null ], \"maxQueue\": 1 }");
var hand = ChatDiscordStore.Load(path, out _);
Check(hand.Characters.Length == 0, "an old file's global \"enabled\" turns nobody on");
Check(hand.Routes.Length == 1, "null routes dropped");
Check(hand.Routes[0].Mode == DiscordRoute.ModeWebhook, "unknown modes become webhook");
Check(hand.Routes[0].SpeechMask == DiscordRoute.DefaultSpeechMask(), "no speech list = the defaults");
Check(hand.Routes[0].Tabs.Length == 1, $"tabs de-duplicated (got {hand.Routes[0].Tabs.Length})");
Check(hand.MaxQueue == ChatDiscordSettings.QueueMin, "queue size clamped");
// A damaged file: defaults, a note for the log, and a copy kept for the user.
File.WriteAllText(path, "{ not json");
var bad = ChatDiscordStore.Load(path, out string n2);
Check(bad.Characters.Length == 0 && bad.Routes.Length == 0, "damaged file: defaults");
Check(n2.Contains("unreadable"), "damaged file is reported");
Check(Directory.GetFiles(dir, "*.unreadable-*.json").Length == 1, "damaged file is kept aside");
}
finally { TryDelete(dir); }
}
// ── DPAPI ────────────────────────────────────────────────────────────
private static void Secrets()
{
string blob = DiscordSecrets.Protect(FakeWebhook);
Check(blob.Length > 0 && !blob.Contains(FakeWebhook) && !blob.Contains("webhooks"), "protected blobs hide the secret");
Check(DiscordSecrets.TryUnprotect(blob, out string plain) && plain == FakeWebhook, "protect / unprotect round-trip");
Check(DiscordSecrets.Protect(FakeWebhook) != blob, "each protect is salted");
byte[] raw = Convert.FromBase64String(blob);
raw[raw.Length / 2] ^= 0x55;
Check(!DiscordSecrets.TryUnprotect(Convert.ToBase64String(raw), out _), "damaged blobs don't open");
Check(!DiscordSecrets.TryUnprotect("not base64 !!", out _), "garbage doesn't open");
Check(!DiscordSecrets.TryUnprotect("", out _), "empty doesn't open");
Check(DiscordSecrets.Protect("") == string.Empty && DiscordSecrets.Protect(null) == string.Empty, "empty in, empty out");
}
// ── Repeat filter ────────────────────────────────────────────────────
private static void Dedup()
{
ChatDiscordLogic.TryClassify("Bob tells you, \"hi\"", 0x03, "", out var a);
ChatDiscordLogic.TryClassify("Bob tells you, \"hi!\"", 0x03, "", out var b);
Check(ChatDiscordLogic.DedupKey(a, "Tell") != ChatDiscordLogic.DedupKey(b, "Tell"), "different lines, different keys");
Check(ChatDiscordLogic.DedupKey(a, "Tell") != ChatDiscordLogic.DedupKey(a, "General"), "the label is part of the key");
var recent = new Dictionary<string, long> { ["old"] = 1_000, ["new"] = 9_000 };
ChatDiscordLogic.PruneRecent(recent, now: 10_000, windowMs: 5_000);
Check(!recent.ContainsKey("old") && recent.ContainsKey("new"), "old repeat entries are pruned");
}
// ── Per-character switch and merged saves ────────────────────────────
private static void Characters()
{
Check(DiscordCharacter.Of("Aelrynth", " ") == null && DiscordCharacter.Of("Aelrynth", null) == null, "no name, no character");
var alice = DiscordCharacter.Of(" Aelrynth ", "+Alice ")!;
Check(alice.Server == "Aelrynth" && alice.Name == "Alice", "names are trimmed (and lose AC's +)");
Check(alice.Same(DiscordCharacter.Of("aelrynth", "ALICE")), "same character in any case");
Check(!alice.Same(DiscordCharacter.Of("Other", "Alice")), "same name on another server is another character");
Check(!alice.Same(null), "nobody is not Alice");
var bob = DiscordCharacter.Of("Aelrynth", "Bob")!;
var carol = DiscordCharacter.Of("Aelrynth", "Carol")!;
var s = new ChatDiscordSettings();
Check(!s.IsOnFor(alice) && !s.IsOnFor(null), "off for everyone by default");
s.Characters = new[] { alice };
Check(s.IsOnFor(DiscordCharacter.Of("AELRYNTH", "alice")) && !s.IsOnFor(bob), "on only for the characters listed");
var list = ChatDiscordStore.ApplyCharacterOps(new[] { alice, alice, bob }, new[]
{
new DiscordCharacterOp(carol, true), new DiscordCharacterOp(bob, false), new DiscordCharacterOp(carol, true),
});
Check(list.Length == 2 && list[0].Same(alice) && list[1].Same(carol), "switches apply in order, without repeats");
// Two clients start from the same file; each switches its own character.
string dir = TempDir();
try
{
string path = Path.Combine(dir, "rynthchat_discord.json");
var shared = new ChatDiscordSettings
{
Routes = new[] { new DiscordRoute { Name = "Guild", SpeechMask = ChatSpeech.Bit(SpeechChannel.Lfg), WebhookProtected = "blob" } },
};
ChatDiscordStore.Write(path, ChatDiscordStore.Serialize(shared));
var clientA = ChatDiscordStore.Load(path, out _);
var clientB = ChatDiscordStore.Load(path, out _);
string Save(ChatDiscordSettings mine, params DiscordCharacterOp[] ops)
{
string? disk = File.Exists(path) ? File.ReadAllText(path) : null;
string json = ChatDiscordStore.MergeForSave(ChatDiscordStore.Serialize(mine), disk, ops, out var merged);
ChatDiscordStore.Write(path, json);
mine.Characters = merged;
return json;
}
Save(clientA, new DiscordCharacterOp(alice, true));
Save(clientB, new DiscordCharacterOp(bob, true)); // B never saw Alice switched on
var now = ChatDiscordStore.Load(path, out _);
Check(now.IsOnFor(alice) && now.IsOnFor(bob), "B's save keeps A's switch");
Check(clientB.IsOnFor(alice), "a save brings the other clients' switches back");
clientA.SkipOwn = true; // A, still not knowing Bob, saves an option
Save(clientA);
now = ChatDiscordStore.Load(path, out _);
Check(now.IsOnFor(alice) && now.IsOnFor(bob) && now.SkipOwn, "a save with no switch keeps everyone's switch");
Check(now.Routes.Length == 1 && now.Routes[0].RelaysSpeech(SpeechChannel.Lfg) && now.Routes[0].WebhookProtected == "blob",
"routes survive the merge");
Save(clientB, new DiscordCharacterOp(bob, false));
now = ChatDiscordStore.Load(path, out _);
Check(now.IsOnFor(alice) && !now.IsOnFor(bob), "turning one character off leaves the others on");
// A switch another client turned off doesn't come back from a stale list.
clientA.Characters = new[] { alice, bob };
Save(clientA);
Check(!ChatDiscordStore.Load(path, out _).IsOnFor(bob), "a stale in-memory list doesn't switch anyone back on");
File.WriteAllText(path, "{ damaged");
clientA.Characters = new[] { alice, bob };
string fromBad = ChatDiscordStore.MergeForSave(ChatDiscordStore.Serialize(clientA), File.ReadAllText(path),
new[] { new DiscordCharacterOp(carol, true) }, out var m1);
Check(m1.Length == 3 && fromBad.Contains("Carol"), "an unreadable file: our own list is the base");
ChatDiscordStore.MergeForSave(ChatDiscordStore.Serialize(new ChatDiscordSettings()), null,
Array.Empty<DiscordCharacterOp>(), out var m2);
Check(m2.Length == 0, "no file and no switch: off for everyone");
Check(ChatDiscordStore.ReadCharacters("{ \"characters\": [ { \"server\": \"S\", \"name\": \"X\" }, { \"name\": \" \" } ] }") is { Length: 1 },
"the list is read back without blanks");
Check(ChatDiscordStore.ReadCharacters("nope") == null && ChatDiscordStore.ReadCharacters(null) == null, "unreadable lists are null");
}
finally { TryDelete(dir); }
}
// ── A route's queue: off means off ───────────────────────────────────
private static void Queue()
{
const int Batch = 1500, Interval = 2000, Max = 200;
var fail = DiscordSendResult.Fail("HTTP 502");
var ok = new DiscordSendResult(true, 200, 0, false, string.Empty);
// Normal flow: the batch window, then one post.
var q = new DiscordRouteQueue();
q.Add("a", 1000, Max);
q.Add("b", 1200, Max);
Check(q.Next(2000, on: true, Batch, Interval) == null, "lines wait out the batch window");
DiscordBatch? b1 = q.Next(2600, on: true, Batch, Interval);
Check(b1 != null && b1.Content == "a\nb" && ReferenceEquals(q.InFlight, b1) && q.Pending.Count == 0, "the window's lines go as one message");
Check(q.Next(9000, on: true, Batch, Interval) == null, "one post in flight at a time");
Check(q.Apply(b1!, ok, 3000, Interval) == DiscordOutcome.Sent && q.MessagesSent == 1 && q.LinesSent == 2, "a sent batch counts");
// Pending lines, then the relay goes off.
q = new DiscordRouteQueue();
q.Add("x", 0, Max);
q.Add("y", 0, Max);
Check(q.Next(10_000, on: false, Batch, Interval) == null && q.Pending.Count == 0, "off drops pending lines");
Check(q.Dropped == 2, "dropped lines are counted");
q.Add("z", 20_000, Max);
Check(q.Stop() == 1 && q.Queued == 0, "Stop drops pending lines");
// A batch waiting to retry must not go out once the relay or route is off.
q = new DiscordRouteQueue();
q.Add("retry me", 0, Max);
DiscordBatch? b2 = q.Next(5000, on: true, Batch, Interval);
Check(q.Apply(b2!, fail, 5100, Interval) == DiscordOutcome.Retrying && ReferenceEquals(q.Retry, b2), "a network error waits to retry");
Check(q.Next(600_000, on: false, Batch, Interval) == null, "a waiting retry is not sent when off");
Check(q.Retry == null && q.Queued == 0, "off drops the waiting retry");
// Same after a rate limit.
q = new DiscordRouteQueue();
q.Add("limited", 0, Max);
DiscordBatch? b3 = q.Next(5000, on: true, Batch, Interval);
Check(q.Apply(b3!, DiscordSendResult.Fail("rate limited", status: 429, retryAfterMs: 1000), 5100, Interval) == DiscordOutcome.RateLimited,
"429 is a rate limit");
Check(q.Next(600_000, on: false, Batch, Interval) == null && q.Retry == null, "a rate-limited batch is dropped when off");
// The post in flight when it goes off: cancelled, and its result can't come back as a retry.
q = new DiscordRouteQueue();
q.Add("flying", 0, Max);
DiscordBatch? b4 = q.Next(5000, on: true, Batch, Interval);
using (var cts = new CancellationTokenSource())
{
b4!.Cancel = cts;
Check(q.Stop() == 1 && q.InFlight == null, "Stop drops the post in flight");
Check(cts.IsCancellationRequested, "the request in flight is cancelled");
}
Check(q.Apply(b4, fail, 5200, Interval) == DiscordOutcome.Ignored && q.Retry == null, "a stopped post's failure isn't retried");
Check(q.Apply(b4, ok, 5200, Interval) == DiscordOutcome.Ignored && q.MessagesSent == 0, "a stopped post's result is ignored");
Check(q.Next(600_000, on: true, Batch, Interval) == null, "nothing comes back after a stop");
// Only an explicit test gets past the switches.
q = new DiscordRouteQueue();
q.Add("chat", 0, Max);
q.QueueTest("test line");
DiscordBatch? t1 = q.Next(10, on: false, Batch, Interval);
Check(t1 != null && t1.IsTest && t1.Content == "test line", "a test goes while off");
Check(q.Pending.Count == 0, "chat queued with it doesn't");
Check(q.Stop() == 0 && ReferenceEquals(q.InFlight, t1), "Stop keeps a test in flight");
Check(q.Apply(t1!, fail, 20, Interval) == DiscordOutcome.Retrying, "a failed test retries");
Check(q.Next(600_000, on: false, Batch, Interval) is { IsTest: true }, "a test's retry goes while off");
q = new DiscordRouteQueue();
q.Add("old", 0, Max);
DiscordBatch? b5 = q.Next(5000, on: true, Batch, Interval);
q.Apply(b5!, fail, 5100, Interval);
q.QueueTest("test");
Check(q.Retry is { IsTest: true } && q.Dropped == 1, "a test replaces a waiting retry");
// Permanent errors pause; give up after the retries.
q = new DiscordRouteQueue();
q.Add("p", 0, Max);
DiscordBatch? b6 = q.Next(5000, on: true, Batch, Interval);
q.Add("later", 5001, Max);
Check(q.Apply(b6!, DiscordSendResult.Fail("HTTP 401", permanent: true, status: 401), 5100, Interval) == DiscordOutcome.Paused,
"401 pauses");
Check(q.Paused && q.Pending.Count == 0 && q.Next(600_000, on: true, Batch, Interval) == null, "a paused route sends nothing");
q.Resume();
Check(!q.Paused && q.LastError.Length == 0, "Resume clears a pause");
q = new DiscordRouteQueue();
q.Add("doomed", 0, Max);
long now = 5000;
DiscordBatch? b7 = q.Next(now, on: true, Batch, Interval);
DiscordOutcome last = DiscordOutcome.Ignored;
for (int i = 0; i < DiscordRouteQueue.MaxTransientRetries && b7 != null; i++)
{
last = q.Apply(b7, fail, now, Interval);
now += 120_000;
b7 = q.Next(now, on: true, Batch, Interval);
}
Check(last == DiscordOutcome.GaveUp && q.Dropped == 1, "gives up after the retries");
q = new DiscordRouteQueue();
for (int i = 0; i < 25; i++) q.Add("l" + i, 0, maxQueue: 20);
Check(q.Pending.Count == 20 && q.Dropped == 5 && q.Pending[0] == "l5", "the oldest lines go past the queue limit");
Check(q.NoteFresh("k", 1000) && !q.NoteFresh("k", 2000) && q.NoteFresh("k", 1000 + DiscordRouteQueue.DedupWindowMs),
"the repeat filter holds for its window");
// A new credential while a retry waits: the batch was for the old destination.
const string Hook = DiscordRoute.ModeWebhook;
q = new DiscordRouteQueue();
Check(q.Retarget(Hook, "", "blobA") == 0, "the first destination drops nothing");
q.Add("for A", 0, Max);
DiscordBatch? a1 = q.Next(5000, on: true, Batch, Interval);
Check(a1 != null && a1.Credential == q.Credential, "a batch remembers its destination");
q.Apply(a1!, fail, 5100, Interval);
q.Add("also for A", 5200, Max);
Check(q.Retarget(Hook, "", "blobA") == 0 && ReferenceEquals(q.Retry, a1), "the same destination keeps the retry");
Check(q.Retarget(Hook, "", new string("blobA".ToCharArray())) == 0, "an equal credential in a new string is the same destination");
Check(q.Retarget(Hook, "", "blobB") == 2, "a new credential drops the waiting retry and pending lines");
Check(q.Retry == null && q.Pending.Count == 0 && q.Next(600_000, on: true, Batch, Interval) == null,
"nothing queued for A goes to B");
q.Add("for B", 600_000, Max);
Check(q.Next(700_000, on: true, Batch, Interval) is { Content: "for B" }, "new lines go to the new destination");
// A post in flight to the old destination fails after the change: dropped, not retried, no pause.
q = new DiscordRouteQueue();
q.Retarget(DiscordRoute.ModeBot, FakeChannel, "tokA");
q.Add("to channel A", 0, Max);
DiscordBatch? a2 = q.Next(5000, on: true, Batch, Interval);
Check(q.Retarget(DiscordRoute.ModeBot, "8" + FakeChannel.Substring(1), "tokA") == 0, "a new channel with nothing waiting drops nothing");
Check(q.Apply(a2!, fail, 5100, Interval) == DiscordOutcome.Retargeted && q.Retry == null, "a failed post to the old destination isn't retried");
q.Add("x", 5200, Max);
DiscordBatch? a3 = q.Next(600_000, on: true, Batch, Interval);
q.Retarget(DiscordRoute.ModeWebhook, FakeChannel, "hook");
Check(q.Apply(a3!, DiscordSendResult.Fail("HTTP 404", permanent: true, status: 404), 600_100, Interval) == DiscordOutcome.Retargeted
&& !q.Paused, "the old destination's 404 doesn't pause the new one");
// A test follows the route to its new destination.
q = new DiscordRouteQueue();
q.Retarget(Hook, "", "old");
q.QueueTest("t");
q.Retarget(Hook, "", "new");
Check(q.Retry is { IsTest: true } t2 && t2.Credential == q.Credential, "a waiting test goes to the new destination");
}
// ── Engine shutdown closes the HTTP client ───────────────────────────
/// <summary>Last: after Shutdown no client is built again, so a post fails at once, sending nothing.</summary>
private static void ClientShutdown()
{
DiscordClient.Shutdown();
DiscordClient.Shutdown(); // twice is harmless
var r = DiscordClient.PostWebhookAsync(FakeWebhook, "x", "", CancellationToken.None).GetAwaiter().GetResult();
Check(!r.Ok && !r.Permanent && r.Error.Contains("ObjectDisposedException"), $"no posts after shutdown (got \"{r.Error}\")");
Check(!r.Error.Contains(new string('x', 68)), "the refusal doesn't echo the webhook");
}
// ── The panel never formats chat ─────────────────────────────────────
// ImGui.NET passes the string of these to ImGui as a printf format: "%s%s%s" in a relayed
// tell crashed the client while the Discord panel's Log tab was open.
private static readonly System.Text.RegularExpressions.Regex RxFormatCall = new(
@"ImGui\.(?<fn>Text|TextWrapped|TextColored|TextDisabled|BulletText|LabelText|SetTooltip|SetItemTooltip|LogText)\(\s*(?<arg>[^\r\n]*)");
/// <summary>
/// The face can't run here (it needs ImGui), so this reads its source: every call to an ImGui
/// function that formats its text must be given a plain literal with no '%' conversions;
/// anything else (chat, routes, Discord's errors) goes through TextUnformatted.
/// </summary>
private static void FaceText()
{
string face = Path.GetFullPath(Path.Combine(SourceDir(), "..", "..", "src", "RynthCore.Engine", "ImGui", "Panels", "ChatDiscordFace.cs"));
Check(File.Exists(face), $"face source found ({face})");
if (!File.Exists(face)) return;
string src = File.ReadAllText(face);
int calls = 0;
foreach (System.Text.RegularExpressions.Match m in RxFormatCall.Matches(src))
{
calls++;
string arg = m.Groups["arg"].Value;
int line = src.Take(m.Index).Count(c => c == '\n') + 1;
bool literal = arg.StartsWith('"');
Check(literal, $"ChatDiscordFace.cs:{line}: ImGui.{m.Groups["fn"].Value} is given a non-literal (use TextUnformatted)");
if (literal)
Check(!arg.Replace("%%", "").Contains('%'), $"ChatDiscordFace.cs:{line}: '%' in a format string");
}
Check(calls > 0, "the face's tooltips are checked");
Check(!src.Contains("TextWrapped("), "the face has no TextWrapped");
Check(src.Contains("TextUnformatted("), "the face writes text with TextUnformatted");
}
private static string SourceDir([System.Runtime.CompilerServices.CallerFilePath] string path = "")
=> Path.GetDirectoryName(path)!;
// ── Helpers ──────────────────────────────────────────────────────────
private static string TempDir()
{
string dir = Path.Combine(Path.GetTempPath(), "ChatDiscordTests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
return dir;
}
private static void TryDelete(string dir)
{
try { Directory.Delete(dir, recursive: true); } catch { }
}
private static void Same(string got, string want, string what)
=> Check(got == want, $"{what}: want \"{want}\", got \"{got}\"");
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine("FAIL: " + what);
}
}

View file

@ -0,0 +1,28 @@
# Creature sizes
The monster HUD anchors a plate above a creature's head, so it needs the creature's height. The client keeps
that in memory (CPhysicsObj scale, CPartArray, CSetup height and selection sphere), but the engine does not map
those layouts, so the HUD used to guess from the creature type and name. This builds the real numbers from data.
A creature's top = max(model height, selection sphere top) x its default scale. The model (Setup, 0x02xxxxxx)
comes from `client_portal.dat`; the weenie's setup and default scale come from the ACE world database.
Output: `src/RynthCore.Engine/ImGui/MonsterHud/CreatureSizes.g.cs`, used through `CreatureSizes.TryGetTop(wcid)`.
## Regenerate
```powershell
# 1. creature-like weenies with a setup (add the Aelrynth custom weenie .sql exports after the world dump)
python parse_world.py C:\Projects\ACE-World-Database\ACE-World-Database-v0.9.293.sql -o out
# 2. each setup's height / radius / selection sphere / sorting sphere, from a folder holding client_portal.dat
dotnet run --project SetupDims -c Release -- <dat dir> out\setups.json out\setups_dims.json
# 3. the table
python gen_cs.py out\creatures.json out\setups_dims.json ..\..\src\RynthCore.Engine\ImGui\MonsterHud\CreatureSizes.g.cs
```
Pass full Windows paths to step 2 (it is a Windows program). A creature with no row (a custom weenie that was not in
the input, or a model with no height) falls back to the HUD's old estimate by creature type and name.
`tools/CreatureSizesTests` checks the lookup against the generated table.

View file

@ -0,0 +1,27 @@
using System.Globalization;
using System.Text;
using ACE.DatLoader;
using ACE.DatLoader.FileTypes;
// args: <dat dir> <setups.json> <out.json>
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
string datDir = args[0];
string[] ids = System.Text.Json.JsonSerializer.Deserialize<string[]>(
"[" + string.Join(",", System.Text.Json.JsonSerializer.Deserialize<uint[]>(File.ReadAllText(args[1]))!.Select(u => "\"" + u + "\"")) + "]")!;
DatManager.Initialize(datDir, keepOpen: true, loadCell: false);
var sb = new StringBuilder("{");
int ok = 0, bad = 0; bool first = true;
foreach (string s in ids)
{
uint id = uint.Parse(s);
SetupModel m = DatManager.PortalDat.ReadFromDat<SetupModel>(id);
if (m == null) { bad++; continue; }
if (!first) sb.Append(',');
first = false;
string F(float v) => v.ToString("0.####", CultureInfo.InvariantCulture);
sb.Append($"\"{id}\":[{F(m.Height)},{F(m.Radius)},{F(m.SelectionSphere.Origin.Z)},{F(m.SelectionSphere.Radius)},{F(m.SortingSphere.Origin.Z)},{F(m.SortingSphere.Radius)}]");
ok++;
}
sb.Append('}');
File.WriteAllText(args[2], sb.ToString());
Console.WriteLine($"read {ok} setups, {bad} missing");

View file

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Step 2 of the creature size table (see ..\README.md): reads each Setup (model) from client_portal.dat
with ACE's own dat reader. Needs a built ACE server; point AcBin at its bin folder if it is elsewhere. -->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>disable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<PlatformTarget>x64</PlatformTarget>
<AcBin Condition="'$(AcBin)' == ''">C:\Projects\ACE\Source\ACE.Server\bin\x64\Release\net10.0</AcBin>
</PropertyGroup>
<ItemGroup>
<Reference Include="ACE.DatLoader"><HintPath>$(AcBin)\ACE.DatLoader.dll</HintPath></Reference>
<Reference Include="ACE.Common"><HintPath>$(AcBin)\ACE.Common.dll</HintPath></Reference>
<Reference Include="ACE.Entity"><HintPath>$(AcBin)\ACE.Entity.dll</HintPath></Reference>
<Reference Include="log4net"><HintPath>$(AcBin)\log4net.dll</HintPath></Reference>
</ItemGroup>
</Project>

View file

@ -0,0 +1,50 @@
"""Step 3 of the creature size table (see README.md): writes CreatureSizes.g.cs.
usage: python gen_cs.py <creatures.json> <setups_dims.json> <out .cs>
A creature's top is max(model height, selection sphere top) x its default scale, in centimetres.
Entries with no usable height (under 20 cm) are left out, so the HUD falls back to its estimate.
A few creatures are scaled absurdly (a 400x "colossal" that is a trick, not a monster); tops
over 120 m are capped.
"""
import json
import sys
creatures = json.load(open(sys.argv[1]))
dims = json.load(open(sys.argv[2]))
rows = []
for wcid, c in creatures.items():
d = dims.get(str(c["setup"]))
if not d:
continue
height, radius, sel_z, sel_r, sort_z, sort_r = d
top = max(height, sel_z + sel_r) * c["scale"]
if top < 0.2:
continue
rows.append((int(wcid), min(int(round(top * 100)), 12000)))
rows.sort()
lines = [
"// <auto-generated> by tools/CreatureSizes (gen_cs.py); do not edit. </auto-generated>",
"// Weenie class id -> the creature's top in centimetres (model height x default scale).",
"namespace RynthCore.Engine.ImGuiBackend.Hud;",
"",
"internal static partial class CreatureSizes",
"{",
" private static readonly int[] Wcids =",
" {",
]
def chunk(values, per=12):
for i in range(0, len(values), per):
yield ", ".join(str(v) for v in values[i:i + per]) + ","
lines += [" " + l for l in chunk([r[0] for r in rows])]
lines += [" };", "", " private static readonly ushort[] TopCm =", " {"]
lines += [" " + l for l in chunk([r[1] for r in rows], 16)]
lines += [" };", "}", ""]
open(sys.argv[3], "w", encoding="utf-8", newline="\n").write("\n".join(lines))
print(len(rows), "creatures written to", sys.argv[3])

View file

@ -0,0 +1,62 @@
"""Step 1 of the creature size table (see README.md).
Reads the ACE world database dump and writes, to the output folder:
creatures.json {weenie class id: {name, wtype, setup, scale}} for every creature-like weenie
(creature, admin, vendor, cow, AI) that has a Setup (model) property
setups.json the distinct setup ids, for SetupDims
usage: python parse_world.py <ACE-World-Database.sql> [<more weenie .sql files>] -o <out dir>
The extra files are weenie exports in the same INSERT format (the Aelrynth custom weenies).
"""
import argparse
import json
import os
import re
ap = argparse.ArgumentParser()
ap.add_argument("sql", nargs="+")
ap.add_argument("-o", "--out", default=".")
args = ap.parse_args()
# weenie rows: (class_Id,'class_Name',type,'last_Modified')
WEENIE_ROW = re.compile(r"\((\d+),'((?:[^'\\]|\\.|'')*)',(\d+),'[^']*'\)")
PLAIN_ROW = re.compile(r"\(([^()]*)\)")
weenies, setup, scale = {}, {}, {}
for path in args.sql:
text = open(path, encoding="utf-8", errors="replace").read()
def inserts(table):
for m in re.finditer(r"INSERT INTO `%s` VALUES (.*?);\n" % table, text, re.S):
yield m.group(1)
for body in inserts("weenie"):
for r in WEENIE_ROW.finditer(body):
weenies[int(r.group(1))] = {"name": r.group(2), "wtype": int(r.group(3))}
# property rows: (id, object_Id, type, value). Setup = DataId property 1, DefaultScale = float property 39.
for body in inserts("weenie_properties_d_i_d"):
for r in PLAIN_ROW.finditer(body):
p = r.group(1).split(",")
if len(p) == 4 and p[2] == "1":
setup[int(p[1])] = int(p[3])
for body in inserts("weenie_properties_float"):
for r in PLAIN_ROW.finditer(body):
p = r.group(1).split(",")
if len(p) == 4 and p[2] == "39":
scale[int(p[1])] = float(p[3])
out = {}
for w, info in weenies.items():
if info["wtype"] not in (10, 11, 12, 15, 16): # creature, admin, vendor, cow, AI
continue
if w not in setup:
continue
out[w] = {"name": info["name"], "wtype": info["wtype"], "setup": setup[w], "scale": scale.get(w, 1.0)}
os.makedirs(args.out, exist_ok=True)
json.dump(out, open(os.path.join(args.out, "creatures.json"), "w"))
json.dump(sorted(set(v["setup"] for v in out.values())), open(os.path.join(args.out, "setups.json"), "w"))
print(len(weenies), "weenies;", len(out), "creature-like with a setup;",
len(set(v["setup"] for v in out.values())), "distinct setups;",
sum(1 for v in out.values() if v["scale"] != 1.0), "with a default scale")

View file

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\CreatureSizes.cs" Link="Engine\CreatureSizes.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\CreatureSizes.g.cs" Link="Engine\CreatureSizes.g.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,31 @@
// Checks CreatureSizes (the lookup over the generated table) against creatures with known heights.
using RynthCore.Engine.ImGuiBackend.Hud;
int pass = 0, fail = 0;
void Check(string what, bool ok, string detail = "")
{
if (ok) pass++;
else { fail++; Console.WriteLine($"FAIL {what} {detail}"); }
}
void Top(uint wcid, string name, float expected)
{
bool found = CreatureSizes.TryGetTop(wcid, out float m);
Check($"{name} ({wcid}) is in the table", found);
Check($"{name} ({wcid}) top", found && MathF.Abs(m - expected) < 0.006f, $"got {m}, want {expected}");
}
Check("the table is not empty", CreatureSizes.Count > 8000, $"count {CreatureSizes.Count}");
Top(1, "human", 1.84f);
Top(5, "lugianlaigus", 2.08f);
Top(185, "bandit", 1.84f);
Top(1621, "olthoiqueen", 2.59f);
Top(1756, "shadowchild", 0.92f); // a default scale of 0.5 halves its model
// Unknown ids fall through to the HUD's estimate.
Check("wcid 0 is unknown", !CreatureSizes.TryGetTop(0, out _));
Check("a huge id is unknown", !CreatureSizes.TryGetTop(uint.MaxValue, out _));
Console.WriteLine($"{(fail == 0 ? "PASS" : "FAIL")} {pass} checks, {fail} failed");
return fail == 0 ? 0 : 1;

View file

@ -5,7 +5,10 @@
compiled in): which registry view a Decal client reads its filter list from (per-user
VirtualStore copy vs machine-wide HKLM) for non-elevated / elevated / UAC-off /
manifest / run-as-administrator clients, and every check line, against a fake registry.
Never touches the real registry.
Plus DecalBridgeRegistration (register / unregister / Repair Decal, RegistrationTests.cs)
against a scratch registry under HKCU\Software\RynthCoreTests\<run> and a temp folder,
deleted after each scenario. The real Decal keys and VirtualStore copies are only read
(before and after, to prove they did not change).
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>

View file

@ -8,7 +8,7 @@ namespace DecalBridgeCheckTests;
/// (2026-10-03, release 2026.10.3.1) is "elevated client, per-user registration only":
/// Decal reads HKLM, the per-user entry is invisible, the bridge never loads.
/// </summary>
internal static class Program
internal static partial class Program
{
private static int _checks, _failed;
@ -287,6 +287,8 @@ internal static class Program
Check(RealDecalCheckHost.LevelIn("<assembly><description>x</description></assembly>") == null, "no element");
});
RegistrationScenarios();
Console.WriteLine();
Console.WriteLine(_failed == 0 ? $"PASS: {_checks} checks" : $"FAIL: {_failed} of {_checks} checks failed");
return _failed == 0 ? 0 : 1;

View file

@ -0,0 +1,399 @@
using System.Text;
using System.Text.Json;
using Microsoft.Win32;
using RynthCore.App;
namespace DecalBridgeCheckTests;
/// <summary>
/// DecalBridgeRegistration (register / unregister / Repair Decal) against a scratch registry:
/// HKCU\Software\RynthCoreTests\&lt;run&gt;\Machine stands in for HKLM (32-bit view) and
/// ...\User for HKCU (DecalRegistryRoots.ForTests), with a temp folder for %APPDATA%\RynthCore.
/// Every scenario deletes its scratch key and folder. The real Decal keys and the real
/// VirtualStore copies are only read, before and after, to prove nothing changed there.
/// </summary>
internal static partial class Program
{
private static readonly string VsNetworkFilters = DecalBridgeCheck.VirtualStoreDecalPath(true, "NetworkFilters");
private const string VsDecalWow = @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal";
private const string VsDecalPlain = @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\Decal";
private const string MachineFilters = @"SOFTWARE\Decal\NetworkFilters";
private const string ForeignId = "{AAAAAAAA-1111-2222-3333-444444444444}";
private const string LateId = "{BBBBBBBB-1111-2222-3333-444444444444}"; // a filter installed for all users after the copy was made
private static void RegistrationScenarios()
{
string realBefore = RealDecalFingerprint();
RegScenario("ForTests refuses a root outside HKCU\\Software\\RynthCoreTests", _ =>
{
bool threw = false;
try { DecalRegistryRoots.ForTests(@"Software\Classes\VirtualStore\X", Path.GetTempPath(), () => true); }
catch (ArgumentException) { threw = true; }
Check(threw, "ArgumentException");
});
RegScenario("register, HKLM not writable: NeedsAdmin and NO per-user copy", t =>
{
t.MachineWritable = false;
var log = new List<string>();
var o = DecalBridgeRegistration.RegisterCore(t.Roots, t.BridgeDir, log);
Check(o == DecalBridgeRegistration.Outcome.NeedsAdmin, $"NeedsAdmin (got {o}: {string.Join(" ", log)})");
Check(!t.UserExists(VsNetworkFilters), "no per-user NetworkFilters copy created");
Check(!t.UserExists(@"Software\Classes\VirtualStore"), "nothing written under the VirtualStore at all");
Check(!t.MachineExists(MachineFilters + "\\" + Guid), "no machine entry");
Check(t.StateFiles().Length == 0, "no record file written");
});
RegScenario("register, HKLM writable (the elevated step): machine entry only", t =>
{
var log = new List<string>();
var o = DecalBridgeRegistration.RegisterCore(t.Roots, t.BridgeDir, log);
Check(o == DecalBridgeRegistration.Outcome.Registered, $"Registered ({string.Join(" ", log)})");
using (RegistryKey? e = t.OpenMachine(MachineFilters + "\\" + Guid))
{
Check(e?.GetValue("Object") as string == DecalBridgeRegistration.FilterObject, "Object");
Check(e?.GetValue("Path") as string == t.BridgeDir, "Path");
Check(e?.GetValue("Enabled") is int en && en == 1, "Enabled=1");
}
Check(!t.UserExists(VsNetworkFilters), "no per-user copy");
t.MachineWritable = false; // the non-elevated launcher afterwards
log.Clear();
o = DecalBridgeRegistration.RegisterCore(t.Roots, t.BridgeDir, log);
Check(o == DecalBridgeRegistration.Outcome.Registered && log.Any(l => l.Contains("already")), "second call without rights: already registered, no prompt needed");
Check(!t.UserExists(VsNetworkFilters), "still no per-user copy");
});
RegScenario("a per-user copy Decal made itself: our entry goes in, the copy is never deleted", t =>
{
t.SetUser(VsNetworkFilters + "\\" + StockIds[0], new() { [""] = "World Object Filter", ["Enabled"] = 0 }); // Decal toggled it
var log = new List<string>();
var o = DecalBridgeRegistration.RegisterCore(t.Roots, t.BridgeDir, log);
Check(o == DecalBridgeRegistration.Outcome.Registered, $"Registered ({string.Join(" ", log)})");
Check(t.UserExists(VsNetworkFilters + "\\" + Guid), "bridge entry added to the existing copy");
Check(DecalBridgeRegistration.PerUserCleanupNeededCore(t.Roots), "cleanup needed (our entry is there)");
bool ok = DecalBridgeRegistration.UnregisterCore(t.Roots, out string report);
Check(ok, "unregister ok: " + report);
Check(!t.UserExists(VsNetworkFilters + "\\" + Guid), "bridge entry removed");
Check(t.UserExists(VsNetworkFilters + "\\" + StockIds[0]), "Decal's own entry kept");
Check(t.BackupFiles().Length == 0, "no backup needed (only our entry removed)");
Check(!DecalBridgeRegistration.PerUserCleanupNeededCore(t.Roots), "nothing left to clean up");
});
RegScenario("an earlier RynthCore's copy: left alone while HKLM can't be written, migrated once it can", t =>
{
t.MakeOldLauncherCopy();
string before = t.UserFingerprint(VsNetworkFilters);
t.MachineWritable = false;
var log = new List<string>();
var o = DecalBridgeRegistration.RegisterCore(t.Roots, t.BridgeDir, log);
Check(o == DecalBridgeRegistration.Outcome.NeedsAdmin, "NeedsAdmin");
Check(t.UserFingerprint(VsNetworkFilters) == before, "copy untouched until the machine entry exists");
t.MachineWritable = true;
log.Clear();
o = DecalBridgeRegistration.RegisterCore(t.Roots, t.BridgeDir, log);
Check(o == DecalBridgeRegistration.Outcome.Registered, $"Registered ({string.Join(" ", log)})");
Check(t.MachineExists(MachineFilters + "\\" + Guid), "machine entry");
Check(!t.UserExists(VsNetworkFilters), "the old copy is gone (Decal reads HKLM again)");
Check(t.StateFiles().Length == 0, "record file deleted");
string[] backups = t.BackupFiles();
Check(backups.Length == 1 && Path.GetFileName(backups[0]).StartsWith("decal-backup-"), "one decal-backup-<date>.reg");
string text = backups.Length == 1 ? File.ReadAllText(backups[0]) : "";
Check(text.StartsWith("Windows Registry Editor Version 5.00") && text.Contains(Guid) && text.Contains(StockIds[0]), "backup holds the copy (bridge + mirrors)");
Check(log.Any(l => l.Contains("backup:")), "log names the backup");
});
RegScenario("uninstall: an earlier RynthCore's copy goes, whatever is in it now", t =>
{
t.MakeOldLauncherCopy();
// Changed since: Decal disabled a mirrored filter, and wrote a filter installed for
// all users later (in HKLM, not in the record) into the copy.
t.SetMachine(MachineFilters + "\\" + LateId, new() { [""] = "UtilityBelt Service", ["Enabled"] = 1 });
t.SetUser(VsNetworkFilters + "\\" + StockIds[1], new() { [""] = "Echo Filter 2", ["Enabled"] = 0 });
t.SetUser(VsNetworkFilters + "\\" + LateId, new() { [""] = "UtilityBelt Service", ["Enabled"] = 1 });
string machineBefore = t.MachineFingerprint(MachineFilters);
Check(DecalBridgeRegistration.PerUserCleanupNeededCore(t.Roots), "cleanup needed");
bool ok = DecalBridgeRegistration.UnregisterCore(t.Roots, out string report);
Check(ok, "unregister ok: " + report);
Check(!t.UserExists(VsNetworkFilters), "copy removed (bridge, changed and unrecorded mirrors, key)");
Check(t.StateFiles().Length == 0, "record deleted");
Check(t.BackupFiles().Length == 1, "backed up first");
Check(t.MachineFingerprint(MachineFilters) == machineBefore, "HKLM untouched");
Check(!DecalBridgeRegistration.PerUserCleanupNeededCore(t.Roots), "nothing left");
});
RegScenario("uninstall: entries that are neither ours nor in HKLM keep the copy", t =>
{
t.MakeOldLauncherCopy();
t.SetUser(VsNetworkFilters + "\\" + ForeignId, new() { [""] = "Someone's Filter", ["Enabled"] = 1 });
bool ok = DecalBridgeRegistration.UnregisterCore(t.Roots, out string report);
Check(ok, "unregister ok: " + report);
Check(t.UserExists(VsNetworkFilters + "\\" + ForeignId), "foreign entry kept");
Check(!t.UserExists(VsNetworkFilters + "\\" + Guid), "our entry removed");
Check(t.UserExists(VsNetworkFilters + "\\" + StockIds[0]), "mirrors kept with it (a copy of only the foreign entry would hide World Object Filter)");
Check(report.Contains("Someone's Filter") && report.Contains("Repair Decal"), "logged, with the way out");
Check(t.StateFiles().Length == 1, "record kept for a later cleanup");
Check(t.BackupFiles().Length == 0, "no backup (nothing but our entry removed)");
Check(!DecalBridgeRegistration.PerUserCleanupNeededCore(t.Roots), "not 'needed' again at every start");
// Register with such a copy: the bridge must stay visible in it.
var log = new List<string>();
var o = DecalBridgeRegistration.RegisterCore(t.Roots, t.BridgeDir, log);
Check(o == DecalBridgeRegistration.Outcome.Registered && t.UserExists(VsNetworkFilters + "\\" + Guid), "register: copy kept, our entry back in it");
Check(t.UserExists(VsNetworkFilters + "\\" + ForeignId), "foreign entry still kept");
});
RegScenario("no account uses Decal + RynthCore: machine entry removed (only this install's)", t =>
{
var log = new List<string>();
DecalBridgeRegistration.RegisterCore(t.Roots, t.BridgeDir, log);
Check(!DecalBridgeRegistration.PerUserCleanupNeededCore(t.Roots), "nothing per-user to remove (no prompt-free work to do)");
Check(DecalBridgeRegistration.MachineEntryIsOursCore(t.Roots, t.BridgeDir), "entry is this install's");
string other = Path.Combine(t.DataDir, "OtherInstall");
Directory.CreateDirectory(other);
File.WriteAllText(Path.Combine(other, DecalBridgeRegistration.AssemblyFile), "");
Check(!DecalBridgeRegistration.MachineEntryIsOursCore(t.Roots, other), "another install's folder: not ours to remove");
t.MachineWritable = false;
log.Clear();
Check(DecalBridgeRegistration.UnregisterMachineWideCore(t.Roots, t.BridgeDir, log) == DecalBridgeRegistration.Outcome.NeedsAdmin, "needs admin without rights");
Check(t.MachineExists(MachineFilters + "\\" + Guid), "still there");
t.MachineWritable = true;
log.Clear();
Check(DecalBridgeRegistration.UnregisterMachineWideCore(t.Roots, t.BridgeDir, log) == DecalBridgeRegistration.Outcome.Registered, "removed: " + string.Join(" ", log));
Check(!t.MachineExists(MachineFilters + "\\" + Guid), "gone");
Check(t.MachineExists(MachineFilters + "\\" + StockIds[0]), "other filters untouched");
Check(!DecalBridgeRegistration.MachineEntryIsOursCore(t.Roots, t.BridgeDir), "nothing to ask about at the next start");
t.MachineWritable = false;
log.Clear();
Check(DecalBridgeRegistration.UnregisterMachineWideCore(t.Roots, t.BridgeDir, log) == DecalBridgeRegistration.Outcome.Registered, "nothing to remove: no rights needed");
});
RegScenario("dangling machine entry (DLL gone) counts as ours to remove", t =>
{
var gone = BridgeEntryAt(Path.Combine(t.DataDir, "Gone"));
t.SetMachine(MachineFilters + "\\" + Guid, gone);
Check(DecalBridgeRegistration.MachineEntryIsOursCore(t.Roots, t.BridgeDir), "dangling = ours");
});
RegScenario("Repair Decal: backup, then delete both VirtualStore Decal keys; the backup restores", t =>
{
t.MakeOldLauncherCopy();
t.SetUser(VsDecalWow + "\\Plugins\\{CCCCCCCC-1111-2222-3333-444444444444}", new() { [""] = "Some Plugin", ["Enabled"] = 1 });
t.SetUser(VsDecalWow, new() { ["BarAlpha"] = 255, ["BarState"] = "1" });
t.SetUser(VsDecalPlain + "\\Plugins", new() { ["X"] = "y" });
string wowBefore = t.UserFingerprint(VsDecalWow), plainBefore = t.UserFingerprint(VsDecalPlain);
List<string> found = DecalBridgeRegistration.FindVirtualStoreDecalKeysCore(t.Roots);
Check(found.Count == 2, "both spellings found");
var r = DecalBridgeRegistration.RepairDecalCore(t.Roots);
Check(r.Ok, "ok: " + r.Report);
Check(r.Removed.Count == 2 && r.Removed.All(k => k.StartsWith(@"HKCU\Software\Classes\VirtualStore\")), "reports both keys as HKCU paths");
Check(!t.UserExists(VsDecalWow) && !t.UserExists(VsDecalPlain), "both deleted");
Check(r.BackupPath != null && File.Exists(r.BackupPath), "backup file exists");
Check(t.StateFiles().Length == 0, "the earlier RynthCore's record goes with its copy");
string text = r.BackupPath != null ? File.ReadAllText(r.BackupPath) : "";
Check(text.Contains("BarAlpha") && text.Contains("Some Plugin") && text.Contains(Guid), "backup has values, plugins, filters");
int headers = text.Split("Windows Registry Editor Version 5.00").Length - 1;
Check(headers == 1, "one .reg header for both keys");
// Round trip, only into the scratch key: every section in the file must be under it.
string root = @"[HKEY_CURRENT_USER\" + t.Key + @"\User\";
bool allScratch = text.Split('\n').Where(l => l.StartsWith("[")).All(l => l.StartsWith(root, StringComparison.OrdinalIgnoreCase));
Check(allScratch, "every key in the backup is under the scratch root");
if (allScratch && r.BackupPath != null)
{
Check(RegImport(r.BackupPath), "reg import of the backup");
Check(t.UserFingerprint(VsDecalWow) == wowBefore && t.UserFingerprint(VsDecalPlain) == plainBefore, "restored exactly");
}
});
RegScenario("Repair Decal with nothing to repair", t =>
{
var r = DecalBridgeRegistration.RepairDecalCore(t.Roots);
Check(r.Ok && r.Removed.Count == 0 && r.BackupPath == null && t.BackupFiles().Length == 0, "nothing removed, no backup");
});
RegScenario("Repair Decal: a failed backup deletes nothing", t =>
{
t.SetUser(VsDecalWow + "\\Plugins", new() { ["X"] = "y" });
string blocker = Path.Combine(t.DataDir, "not-a-folder");
File.WriteAllText(blocker, "");
var roots = DecalRegistryRoots.ForTests(t.Key, Path.Combine(blocker, "sub"), () => true);
var r = DecalBridgeRegistration.RepairDecalCore(roots);
Check(!r.Ok && r.Removed.Count == 0 && r.Report.Contains("backup failed"), "stopped: " + r.Report);
Check(t.UserExists(VsDecalWow + "\\Plugins"), "key still there");
});
RegScenario("status reads the scratch registry", t =>
{
t.MakeOldLauncherCopy();
t.SetMachine(MachineFilters + "\\" + LateId, new() { [""] = "UtilityBelt Service", ["Enabled"] = 1 });
var s = DecalBridgeRegistration.GetStatusCore(t.Roots);
Check(s.DecalInstalled && s.PerUserKeyExists && s.PerUserKeyCreatedByUs && s.RegisteredPerUser, "copy, ours, bridge in it");
Check(s.HiddenMachineFilters.Contains("UtilityBelt Service"), "the later filter is hidden (the player's bug)");
});
string realAfter = RealDecalFingerprint();
Scenario("the real Decal keys and VirtualStore copies did not change", () =>
Check(realAfter == realBefore, "real HKLM Decal + HKCU VirtualStore Decal fingerprints match"));
Scenario("no scratch keys left", () =>
{
using RegistryKey hkcu = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
using RegistryKey? left = hkcu.OpenSubKey(@"Software\RynthCoreTests");
Check(left == null || left.SubKeyCount == 0, @"HKCU\Software\RynthCoreTests empty or gone");
});
}
private static readonly string[] StockIds = Stock.Select(s => s.Id).ToArray();
private static Dictionary<string, object> BridgeEntryAt(string dir) => new()
{
[""] = DecalBridgeRegistration.FilterName,
["Enabled"] = 1,
["Assembly"] = DecalBridgeRegistration.AssemblyFile,
["Path"] = dir,
["Object"] = DecalBridgeRegistration.FilterObject,
["Surrogate"] = DecalBridgeCheck.SurrogateClsid,
};
private static void RegScenario(string name, Action<RegTestBed> body)
{
Scenario(name, () =>
{
using var t = new RegTestBed();
body(t);
});
}
/// <summary>Read only: the real HKLM Decal tree and the real VirtualStore Decal keys.</summary>
private static string RealDecalFingerprint()
{
var sb = new StringBuilder();
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
using (RegistryKey? d = hklm.OpenSubKey(@"SOFTWARE\Decal"))
sb.Append("HKLM:").Append(d == null ? "<none>" : DecalBridgeRegistration.Fingerprint(d));
using (RegistryKey hkcu = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64))
{
foreach (string k in DecalBridgeRegistration.VirtualStoreDecalKeys)
{
using RegistryKey? v = hkcu.OpenSubKey(k);
sb.Append('|').Append(k).Append(':').Append(v == null ? "<none>" : DecalBridgeRegistration.Fingerprint(v));
}
}
return sb.ToString();
}
private static bool RegImport(string file)
{
var psi = new System.Diagnostics.ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "reg.exe"))
{
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
};
psi.ArgumentList.Add("import");
psi.ArgumentList.Add(file);
psi.ArgumentList.Add("/reg:64");
using var p = System.Diagnostics.Process.Start(psi)!;
p.StandardOutput.ReadToEnd();
string err = p.StandardError.ReadToEnd();
p.WaitForExit(30_000);
if (p.ExitCode != 0) Console.WriteLine(" reg import: " + err.Trim());
return p.ExitCode == 0;
}
}
/// <summary>A scratch registry + folder for one scenario; deleted on Dispose.</summary>
internal sealed class RegTestBed : IDisposable
{
public string Key { get; } = @"Software\RynthCoreTests\DecalBridge-" + Guid.NewGuid().ToString("N");
public string DataDir { get; } = Path.Combine(Path.GetTempPath(), "RynthCoreTests", Guid.NewGuid().ToString("N"));
public string BridgeDir { get; }
public bool MachineWritable { get; set; } = true;
public DecalRegistryRoots Roots { get; }
private static readonly (string Id, string Name)[] Stock =
{
("{53092D1B-F0B0-46FF-BF11-8F031EC9B137}", "World Object Filter"),
("{34239EAD-6317-4c40-A405-193BA5232DD8}", "Echo Filter 2"),
};
public RegTestBed()
{
Roots = DecalRegistryRoots.ForTests(Key, DataDir, () => MachineWritable);
BridgeDir = Path.Combine(DataDir, "DecalBridge");
Directory.CreateDirectory(BridgeDir);
File.WriteAllText(Path.Combine(BridgeDir, DecalBridgeRegistration.AssemblyFile), "");
// A machine with Decal and two stock filters (stands in for HKLM, 32-bit view).
SetMachine(@"SOFTWARE\Decal\Agent", new() { ["AgentPath"] = @"C:\Program Files (x86)\Decal 3.0\" });
SetMachine(@"SOFTWARE\Decal\NetworkFilters", new() { ["Version"] = "2.9.8.3" });
foreach (var f in Stock)
SetMachine(@"SOFTWARE\Decal\NetworkFilters\" + f.Id, new() { [""] = f.Name, ["Enabled"] = 1 });
}
/// <summary>What a launcher before 2026-10-10 left: a full mirror + our entry + its record file.</summary>
public void MakeOldLauncherCopy()
{
string vs = DecalBridgeCheck.VirtualStoreDecalPath(true, "NetworkFilters");
SetUser(vs, new() { ["Version"] = "2.9.8.3" });
foreach (var f in Stock)
SetUser(vs + "\\" + f.Id, new() { [""] = f.Name, ["Enabled"] = 1 });
SetUser(vs + "\\" + DecalBridgeRegistration.FilterGuid, new()
{
[""] = DecalBridgeRegistration.FilterName,
["Enabled"] = 1,
["Assembly"] = DecalBridgeRegistration.AssemblyFile,
["Path"] = BridgeDir,
["Object"] = DecalBridgeRegistration.FilterObject,
["Surrogate"] = DecalBridgeCheck.SurrogateClsid,
});
var state = new
{
CreatedFiltersKey = true,
BridgePath = BridgeDir,
RegisteredUtc = new DateTime(2026, 9, 30, 0, 0, 0, DateTimeKind.Utc),
MirroredKeys = Stock.ToDictionary(f => f.Id, f => "print"),
MirroredValues = new Dictionary<string, string> { ["Version"] = "print" },
};
File.WriteAllText(Path.Combine(DataDir, DecalBridgeRegistration.StateFileName), JsonSerializer.Serialize(state));
}
public void SetMachine(string path, Dictionary<string, object> values) => Set("Machine", path, values);
public void SetUser(string path, Dictionary<string, object> values) => Set("User", path, values);
public bool MachineExists(string path) { using var k = OpenMachine(path); return k != null; }
public bool UserExists(string path) { using var k = Open("User", path); return k != null; }
public RegistryKey? OpenMachine(string path) => Open("Machine", path);
public string MachineFingerprint(string path) { using var k = Open("Machine", path); return k == null ? "<none>" : DecalBridgeRegistration.Fingerprint(k); }
public string UserFingerprint(string path) { using var k = Open("User", path); return k == null ? "<none>" : DecalBridgeRegistration.Fingerprint(k); }
public string[] StateFiles() => Directory.Exists(DataDir) ? Directory.GetFiles(DataDir, DecalBridgeRegistration.StateFileName) : Array.Empty<string>();
public string[] BackupFiles() => Directory.Exists(DataDir) ? Directory.GetFiles(DataDir, "decal-backup-*.reg") : Array.Empty<string>();
private RegistryKey? Open(string part, string path)
{
using RegistryKey hkcu = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
return hkcu.OpenSubKey(Key + "\\" + part + "\\" + path);
}
private void Set(string part, string path, Dictionary<string, object> values)
{
using RegistryKey hkcu = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
using RegistryKey k = hkcu.CreateSubKey(Key + "\\" + part + "\\" + path, writable: true);
foreach (var kv in values)
k.SetValue(kv.Key, kv.Value, kv.Value is int ? RegistryValueKind.DWord : RegistryValueKind.String);
}
public void Dispose()
{
using RegistryKey hkcu = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
try { hkcu.DeleteSubKeyTree(Key, throwOnMissingSubKey: false); } catch (Exception ex) { Console.WriteLine($" (cleanup of HKCU\\{Key} failed: {ex.Message})"); }
try
{
using RegistryKey? parent = hkcu.OpenSubKey(@"Software\RynthCoreTests");
if (parent != null && parent.SubKeyCount == 0 && parent.ValueCount == 0)
hkcu.DeleteSubKey(@"Software\RynthCoreTests", throwOnMissingSubKey: false);
}
catch { }
try { if (Directory.Exists(DataDir)) Directory.Delete(DataDir, recursive: true); } catch { }
}
}

View file

@ -22,6 +22,7 @@
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\Plugins\EngineSettings.cs" Link="Engine\EngineSettings.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\EngineSettingsFile.cs" Link="Engine\EngineSettingsFile.cs" />
<Compile Include="..\..\src\RynthCore.Engine\ReloadCapNotice.cs" Link="Engine\ReloadCapNotice.cs" />
</ItemGroup>
</Project>

View file

@ -49,6 +49,7 @@ namespace EngineSettingsTests
Run(nameof(SaveRoundTripsOwnedKeys), SaveRoundTripsOwnedKeys);
Run(nameof(SaveWithoutFileWritesOwnedKeys), SaveWithoutFileWritesOwnedKeys);
Run(nameof(SaveLeavesMalformedFileAlone), SaveLeavesMalformedFileAlone);
Run(nameof(MaxHotReloadsReadAndKept), MaxHotReloadsReadAndKept);
}
finally
{
@ -85,6 +86,7 @@ namespace EngineSettingsTests
Console.WriteLine("DecalBridge=" + EngineSettings.DecalBridgeMode);
Console.WriteLine("ImGuiBackend=" + EngineSettings.EnableImGuiBackend);
Console.WriteLine("ServerMessageStream=" + EngineSettings.ServerMessageStream);
Console.WriteLine("MaxHotReloads=" + EngineSettings.MaxHotReloads);
break;
default: throw new ArgumentException(args[0]);
}
@ -252,6 +254,52 @@ namespace EngineSettingsTests
Eq(ReadJson(emptyPath).GetProperty("DisabledUiHooks")[0].GetString(), "StartTooltip", "empty: rewritten with the change");
}
// engine.json "MaxHotReloads" (the loader's hot-reload cap): default 3, a hand-set value
// (including -1 = no cap) is read and survives the engine's own saves, the default is
// never written, and a value that isn't a whole number is ignored.
private static void MaxHotReloadsReadAndKept()
{
string dir = NewDir("maxreloads");
string path = Path.Combine(dir, "engine.json");
File.WriteAllText(path, LauncherFile);
var (exit, output) = RunChild(path, "dump");
Eq(exit, 0, "dump (missing)");
Eq(DumpValue(output, "MaxHotReloads"), "3", "missing: the default");
Eq(RunChild(path, "hook-off", "StartTooltip").Exit, 0, "save with the default");
Check(!ReadJson(path).TryGetProperty("MaxHotReloads", out _), "the default isn't written to the file");
foreach ((string json, string expected) in new[] { ("5", "5"), ("-1", "-1"), ("0", "0") })
{
File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"MaxHotReloads\": {json}, \"LoggingLevel\""));
(exit, output) = RunChild(path, "dump");
Eq(exit, 0, $"{json}: dump");
Eq(DumpValue(output, "MaxHotReloads"), expected, $"{json}: read back");
Eq(RunChild(path, "hook-off", "CheckTooltip").Exit, 0, $"{json}: save");
Eq(ReadJson(path).GetProperty("MaxHotReloads").GetRawText(), json, $"{json}: kept by the engine's save");
Eq(DumpValue(RunChild(path, "dump").Out, "MaxHotReloads"), expected, $"{json}: still the same after the save");
}
foreach (string bad in new[] { "\"lots\"", "2.5", "true", "null" })
{
File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"MaxHotReloads\": {bad}, \"LoggingLevel\""));
(exit, output) = RunChild(path, "dump");
Eq(exit, 0, $"{bad}: dump");
Eq(DumpValue(output, "MaxHotReloads"), "3", $"{bad}: ignored, the default");
}
}
/// <summary>The value of a "Name=value" line of the child's dump output ("" if none).</summary>
private static string DumpValue(string output, string name)
{
foreach (string line in output.Split('\n'))
{
string l = line.TrimEnd('\r');
if (l.StartsWith(name + "=", StringComparison.Ordinal)) return l.Substring(name.Length + 1);
}
return "";
}
// ── EngineSettingsFile, direct ──────────────────────────────────────────
private static byte[] Owned(string json) => Encoding.UTF8.GetBytes(json);

View file

@ -11,6 +11,7 @@
<RootNamespace>RynthCore.HookResolver.UI</RootNamespace>
<AssemblyName>RynthCore.HookResolver.UI</AssemblyName>
<LangVersion>latest</LangVersion>
<Version>1.0.1</Version>
</PropertyGroup>
<ItemGroup>
@ -18,6 +19,8 @@
<PackageReference Include="Avalonia.Desktop" Version="11.2.3" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.3" />
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.2.3" />
<!-- Direct reference overrides Avalonia's transitive 0.20.x (NU1903 / GHSA-xrw6-gwf8-vvr9). -->
<PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" />
</ItemGroup>
<ItemGroup>

View file

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the engine's Infinite Leaftide detection
(src\RynthCore.Engine\Compatibility\IltDetect.cs, compiled in, with AelrynthWire.cs for the
launch command line parser it shares): hosts, world names, the engine.json lists and the
combined verdict. Nothing native: no AC, no engine state.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>IltTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\IltDetect.cs" Link="Engine\IltDetect.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AelrynthWire.cs" Link="Engine\AelrynthWire.cs" />
</ItemGroup>
</Project>

140
tools/IltTests/Program.cs Normal file
View file

@ -0,0 +1,140 @@
using RynthCore.Engine.Compatibility;
namespace IltTests;
/// <summary>
/// Infinite Leaftide detection, offline. The host is the public AC server list's
/// (acresources/serverslist Servers.xml: InfiniteLeaftide, game.infiniteleaftide.online:9000);
/// the world name is the one UtilityBelt's Leaftide tools and the ILT Hub check for.
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static string _case = "";
private static int Main()
{
Hosts();
WorldNames();
Decisions();
ConfiguredLists();
FromCommandLines();
Wildcards();
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
if (_checks == 0) { Console.WriteLine("ABORT: no checks ran."); return 1; }
Console.WriteLine(_failed == 0 ? "ALL ILT TESTS PASSED." : $"{_failed} FAILED.");
return _failed == 0 ? 0 : 1;
}
private static void Hosts()
{
Case("hosts");
var d = IltDetect.DefaultHosts;
Check(IltDetect.HostMatches("game.infiniteleaftide.online", d, out string m) && m == "infiniteleaftide.online", "the server list's host");
Check(IltDetect.HostMatches("infiniteleaftide.online", d, out _), "the bare domain");
Check(IltDetect.HostMatches("GAME.InfiniteLeaftide.Online.", d, out _), "case and a trailing dot");
Check(!IltDetect.HostMatches("notinfiniteleaftide.online", d, out _), "a look-alike domain");
Check(!IltDetect.HostMatches("infiniteleaftide.online.evil.net", d, out _), "the domain as a prefix");
Check(!IltDetect.HostMatches("leafdawning.duckdns.org", d, out _), "Leafdawning (another ACE server)");
Check(!IltDetect.HostMatches("aelrynth.com", d, out _), "Aelrynth");
Check(!IltDetect.HostMatches("", d, out _) && !IltDetect.HostMatches(null, d, out _), "no host");
Check(!IltDetect.HostMatches("game.infiniteleaftide.online", null, out _), "no list");
Check(IltDetect.HostMatches("10.0.0.5", new[] { "10.0.0.5" }, out _), "an IP listed matches itself");
Check(!IltDetect.HostMatches("1.10.0.0.5", new[] { "10.0.0.5" }, out _), "an IP never matches as a suffix");
}
private static void WorldNames()
{
Case("world names");
var d = IltDetect.DefaultServerNames;
Check(IltDetect.WorldNameMatches("InfiniteLeaftide", d, out string m) && m == "InfiniteLeaftide", "InfiniteLeaftide");
Check(IltDetect.WorldNameMatches("infiniteleaftide", d, out _), "case-insensitive");
Check(IltDetect.WorldNameMatches(" InfiniteLeaftide ", d, out _), "trimmed");
Check(IltDetect.WorldNameMatches("Leaftide Test", d, out m) && m == "*Leaftide*", "anything with Leaftide in it");
Check(!IltDetect.WorldNameMatches("Leafdawning", d, out _), "Leafdawning");
Check(!IltDetect.WorldNameMatches("Infinite Frosthaven", d, out _), "another Infinite server");
Check(!IltDetect.WorldNameMatches("ACEmulator", d, out _), "ACE's default name");
Check(!IltDetect.WorldNameMatches("Aeshnidae", d, out _), "Aelrynth's world");
Check(!IltDetect.WorldNameMatches("", d, out _) && !IltDetect.WorldNameMatches(null, d, out _), "no name");
}
private static void Decisions()
{
Case("decisions (defaults)");
IltVerdict v = IltDetect.Decide("game.infiniteleaftide.online", null, null, null);
Check(v.IsIlt, "by host before the world name arrives: " + v.Reason);
v = IltDetect.Decide("game.infiniteleaftide.online", "InfiniteLeaftide", null, null);
Check(v.IsIlt && v.Reason.Contains("and"), "both signals: " + v.Reason);
v = IltDetect.Decide("", "InfiniteLeaftide", null, null);
Check(v.IsIlt, "by world name with no host (another launcher): " + v.Reason);
v = IltDetect.Decide("localhost", "InfiniteLeaftide", null, null);
Check(v.IsIlt, "a local ACECustom copy that calls itself InfiniteLeaftide");
v = IltDetect.Decide("play.coldeve.ac", "Coldeve", null, null);
Check(!v.IsIlt && v.Reason.StartsWith("not"), "someone else's server: " + v.Reason);
v = IltDetect.Decide("aelrynth.com", "Aeshnidae", null, null);
Check(!v.IsIlt, "Aelrynth is not ILT");
v = IltDetect.Decide(null, null, null, null);
Check(!v.IsIlt && v.Reason.Length > 0, "nothing known: " + v.Reason);
Check(!IltVerdict.Unknown.IsIlt, "the starting verdict is not ILT");
}
private static void ConfiguredLists()
{
Case("engine.json lists");
IltVerdict v = IltDetect.Decide("ilt.example.net", "MyShard", new[] { "MyShard" }, Array.Empty<string>());
Check(v.IsIlt, "a world name added in engine.json");
v = IltDetect.Decide("game.infiniteleaftide.online", "InfiniteLeaftide", Array.Empty<string>(), Array.Empty<string>());
Check(!v.IsIlt, "empty lists turn both signals off");
v = IltDetect.Decide("ilt.example.net", null, Array.Empty<string>(), new[] { "example.net" });
Check(v.IsIlt, "a host added in engine.json covers its subdomains");
v = IltDetect.Decide("game.infiniteleaftide.online", null, null, new[] { "example.net" });
Check(!v.IsIlt, "an IltHosts list replaces the default host");
var list = IltDetect.ParseList(new[] { " InfiniteLeaftide ", "infiniteleaftide", "*Leaftide*; Other", "", null });
Check(list != null && list.Count == 3 && list[0] == "InfiniteLeaftide" && list[1] == "*Leaftide*" && list[2] == "Other",
"lists are trimmed, split on ; and , and de-duplicated: " + (list == null ? "null" : string.Join("|", list)));
Check(IltDetect.ParseList(null) == null, "no list stays null (the defaults apply)");
}
private static void FromCommandLines()
{
Case("launch command lines");
// The RynthCore launcher's ACE form and the GDLE form, as ServerInfo reads them.
Check(ServerDetect.TryParseLaunchHost("acclient.exe -h game.infiniteleaftide.online:9000 -a tom -v secret", out string h, out int p)
&& IltDetect.Decide(h, null, null, null).IsIlt && p == 9000, "-h host:port");
Check(ServerDetect.TryParseLaunchHost("acclient.exe -h Game.InfiniteLeaftide.Online -p 9000", out h, out _)
&& IltDetect.Decide(h, null, null, null).IsIlt, "-h host -p port, mixed case");
Check(ServerDetect.TryParseLaunchHost("acclient.exe -h aelrynth.com:9020", out h, out _)
&& !IltDetect.Decide(h, null, null, null).IsIlt, "Aelrynth's command line");
}
private static void Wildcards()
{
Case("wildcards");
Check(IltDetect.Matches("InfiniteLeaftide", "Infinite*"), "prefix");
Check(IltDetect.Matches("InfiniteLeaftide", "*Leaftide"), "suffix");
Check(IltDetect.Matches("InfiniteLeaftide", "I*Leaf*e"), "several stars");
Check(!IltDetect.Matches("Leaftide", "Infinite*"), "missing prefix");
Check(!IltDetect.Matches("Leaf", "*Leaftide*"), "too short");
Check(!IltDetect.Matches("anything", ""), "empty pattern never matches");
Check(IltDetect.HostMatches("eu.game.infiniteleaftide.online", new[] { "*.infiniteleaftide.online" }, out _), "host wildcard");
}
// ── harness ─────────────────────────────────────────────────────────────
private static void Case(string name)
{
_case = name;
Console.WriteLine($"-- {name}");
}
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine($" FAIL [{_case}] {what}");
}
}

View file

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the large-address alignment fix
(src\RynthCore.Engine\Compatibility\LargeAddressAlignmentScan.cs, compiled in): the site scan
against the .text of a real acclient.exe read from disk, idempotence once patched, refusal of
near-miss byte patterns, and the padding arithmetic above and below 2 GB. Nothing native: no
AC process, no engine state.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail); after the usual separator, an AC folder or an acclient.exe.
Default: C:\Turbine\Asheron's Call-ryn\acclient.exe.
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>LargeAddressAlignmentTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\LargeAddressAlignmentScan.cs" Link="Engine\LargeAddressAlignmentScan.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,154 @@
using System.Buffers.Binary;
using RynthCore.Engine.Compatibility;
namespace LargeAddressAlignmentTests;
/// <summary>
/// The large-address alignment fix, offline: which acclient code the scan picks, that a patched
/// image rescans as fully patched, that look-alike bytes are refused, and that the patched
/// remainder pads a cursor above 2 GB the same as below it.
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static int Main(string[] args)
{
string exe = FindExe(args.Length > 0 ? args[0] : @"C:\Turbine\Asheron's Call-ryn");
RealClient(exe);
SyntheticPatterns();
PaddingArithmetic();
Console.WriteLine();
Console.WriteLine(_failed == 0 && _checks > 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks} checks failed)");
return _failed == 0 && _checks > 0 ? 0 : 1;
}
private static string FindExe(string arg) =>
File.Exists(arg) ? arg : Path.Combine(arg, "acclient.exe");
private static void RealClient(string path)
{
Section("acclient .text from " + path);
if (!File.Exists(path))
{
Check(false, "acclient.exe exists");
return;
}
byte[] image = File.ReadAllBytes(path);
Check(TryReadText(image, out int textVa, out byte[] text), ".text section read");
if (text.Length == 0) return;
List<AlignmentSite> sites = LargeAddressAlignmentScan.Find(text, textVa);
Console.WriteLine($" {sites.Count} site(s), first 0x{sites.FirstOrDefault().AndVa:X8}, last 0x{sites.LastOrDefault().AndVa:X8}");
Check(sites.Count == 190, "retail client has 190 padding sites");
Check(sites.All(s => !s.AlreadyPatched), "none patched on disk");
// MotionData::UnPack (kelpie's 0x09000009 corruption) and the setup unpack under the
// 0x539153 crashes, plus the one site with a pop before its je.
foreach (int va in new[] { 0x005271A6, 0x00534B48, 0x00534C96, 0x00532E78, 0x004FD1B6, 0x006B394E })
Check(sites.Any(s => s.AndVa == va), $"0x{va:X8} found");
// A 16-bit ring index (movzx, never negative), not cursor padding: no trailing je.
Check(sites.All(s => s.AndVa != 0x00547029), "0x00547029 (ring index) left alone");
foreach (AlignmentSite s in sites)
text[s.ImmHighByteVa - textVa] = LargeAddressAlignmentScan.PatchedHighByte;
List<AlignmentSite> again = LargeAddressAlignmentScan.Find(text, textVa);
Check(again.Count == sites.Count && again.All(s => s.AlreadyPatched), "patched image rescans as all already patched");
Check(again.Select(s => s.AndVa).SequenceEqual(sites.Select(s => s.AndVa)), "same sites after patching");
}
private static void SyntheticPatterns()
{
Section("synthetic byte patterns");
// and eax, 0x80000003 ; jns +5 ; dec eax ; or eax, -4 ; inc eax ; je +0x18
byte[] eax = { 0x25, 0x03, 0x00, 0x00, 0x80, 0x79, 0x05, 0x48, 0x83, 0xC8, 0xFC, 0x40, 0x74, 0x18 };
Check(Scan(eax).Count == 1, "eax short form matches");
Check(Scan(eax)[0].ImmHighByteVa == 0x1000 + 4, "immediate high byte located");
// and ecx, 0x80000003 ; mov [esp+0xC], eax ; jns ; dec ecx ; or ecx, -4 ; inc ecx ; pop ebx ; je
byte[] ecxGap = { 0x81, 0xE1, 0x03, 0x00, 0x00, 0x80, 0x89, 0x44, 0x24, 0x0C, 0x79, 0x05, 0x49, 0x83, 0xC9, 0xFC, 0x41, 0x5B, 0x74, 0x10 };
Check(Scan(ecxGap).Count == 1 && Scan(ecxGap)[0].Register == 1, "ecx long form with gap and pop matches");
byte[] noJe = (byte[])eax.Clone();
noJe[12] = 0x66;
Check(Scan(noJe).Count == 0, "no trailing je: refused");
byte[] wrongReg = (byte[])eax.Clone();
wrongReg[7] = 0x49; // dec ecx after and eax
Check(Scan(wrongReg).Count == 0, "fix-up on another register: refused");
byte[] otherMask = (byte[])eax.Clone();
otherMask[1] = 0x07; // % 8
Check(Scan(otherMask).Count == 0, "and 0x80000007: refused");
byte[] patched = (byte[])eax.Clone();
patched[4] = 0x00;
Check(Scan(patched) is [{ AlreadyPatched: true }], "and eax, 3 reported as already patched");
}
private static void PaddingArithmetic()
{
Section("padding above and below 2 GB");
foreach (uint cursor in new uint[] { 0x2FDC98E1, 0x2FDC98E3, 0x80438035, 0x80438036, 0x8043A4C3, 0xFFFFFFFD })
{
int stock = StockPad(cursor), fixedPad = FixedPad(cursor);
Check((cursor + (uint)fixedPad) % 4 == 0 && fixedPad < 4, $"0x{cursor:X8}: patched pad {fixedPad} aligns");
if (cursor < 0x80000000)
Check(stock == fixedPad, $"0x{cursor:X8}: below 2 GB the patch changes nothing");
else
Check(stock == fixedPad + 4, $"0x{cursor:X8}: stock pad {stock} overshoots by 4");
}
}
// AC's code: r = and(ptr, 0x80000003) with the sign fix-up, pad = r == 0 ? 0 : 4 - r.
private static int StockPad(uint cursor)
{
int r = (int)cursor % 4;
return r == 0 ? 0 : 4 - r;
}
private static int FixedPad(uint cursor)
{
int r = (int)(cursor & 3);
return r == 0 ? 0 : 4 - r;
}
private static List<AlignmentSite> Scan(byte[] code)
{
byte[] padded = new byte[code.Length + 64];
code.CopyTo(padded, 0);
return LargeAddressAlignmentScan.Find(padded, 0x1000);
}
private static bool TryReadText(byte[] image, out int textVa, out byte[] text)
{
textVa = 0;
text = Array.Empty<byte>();
int pe = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(0x3C));
int sections = BinaryPrimitives.ReadUInt16LittleEndian(image.AsSpan(pe + 6));
int optSize = BinaryPrimitives.ReadUInt16LittleEndian(image.AsSpan(pe + 20));
int imageBase = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(pe + 24 + 28));
for (int i = 0; i < sections; i++)
{
int s = pe + 24 + optSize + i * 40;
if (System.Text.Encoding.ASCII.GetString(image, s, 8).TrimEnd('\0') != ".text") continue;
int virtualSize = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(s + 8));
int rva = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(s + 12));
int rawOffset = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(s + 20));
textVa = imageBase + rva;
text = image.AsSpan(rawOffset, virtualSize).ToArray();
return true;
}
return false;
}
private static void Section(string name) => Console.WriteLine($"\n== {name}");
private static void Check(bool ok, string what)
{
_checks++;
if (!ok) _failed++;
Console.WriteLine($" {(ok ? "ok " : "FAIL")} {what}");
}
}

View file

@ -0,0 +1,30 @@
# Builds and runs the offline checks for the loader's reload cap and CoreCLR crash-dump setup
# against the real native/Loader/Loader.c (x86, MSVC): a client that has hot reloaded MaxHotReloads
# times refuses the next reload without shutting down, unloading or staging anything, and tells
# the engine; the dump environment (DOTNET_DbgEnableMiniDump/Type/Name) is set unless already set;
# only the newest 3 clr_*.dmp are kept. Builds and runs in %TEMP%\LoaderReloadCapTests; touches
# nothing under C:\Games.
$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"
$L = (Resolve-Path (Join-Path $PSScriptRoot "..\..\native\Loader")).Path
$out = Join-Path $env:TEMP "LoaderReloadCapTests"
New-Item -ItemType Directory -Force $out | Out-Null
Push-Location $out
try {
foreach ($d in "work", "logs") { if (Test-Path $d) { Remove-Item $d -Recurse -Force } }
# The exe plays the engine: its two fake exports, undecorated, as the engine's are.
& $cl /nologo /O2 /MT /W4 /wd4100 /I $L (Join-Path $PSScriptRoot "test.c") "$L\Hooks.c" "$L\Clr.c" "$L\Services.c" user32.lib /Fe:test.exe `
/link "/EXPORT:RynthCoreMaxHotReloads=_FakeMaxHotReloads@0" "/EXPORT:RynthCoreReloadCapped=_FakeReloadCapped@8"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& .\test.exe @args
exit $LASTEXITCODE
} finally { Pop-Location }

View file

@ -0,0 +1,211 @@
// Offline checks for Loader.c's reload cap and CoreCLR crash-dump setup. Built with the real
// Loader.c included, so these are the shipped functions. Logs go to .\logs (LOG_DIR below),
// never C:\Games. This exe stands in for the engine: it exports RynthCoreMaxHotReloads and
// RynthCoreReloadCapped (Run-Tests.ps1 links them undecorated), and the loader finds them with
// GetProcAddress, the NativeAOT-host path.
#define LOG_DIR "logs"
#include "Loader.c"
static int fails;
#define CHECK(c, ...) do { if (c) printf("ok "); else { printf("FAIL "); fails++; } printf(__VA_ARGS__); printf("\n"); } while (0)
// --- the fake engine ---------------------------------------------------------------
static volatile LONG fakeCap = 3;
static volatile LONG cappedCalls, cappedReloads = -99, cappedCap = -99;
int __stdcall FakeMaxHotReloads(void) { return fakeCap; }
unsigned int __stdcall FakeReloadCapped(int reloads, int cap)
{
cappedReloads = reloads;
cappedCap = cap;
InterlockedIncrement(&cappedCalls);
return 0;
}
// --- helpers -------------------------------------------------------------------------
static void MakeFile(const char* dir, const char* name, int ageMinutes)
{
char p[MAX_PATH];
_snprintf_s(p, sizeof p, _TRUNCATE, "%s\\%s", dir, name);
HANDLE h = CreateFileA(p, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
FILETIME now;
GetSystemTimeAsFileTime(&now);
ULARGE_INTEGER t;
t.LowPart = now.dwLowDateTime;
t.HighPart = now.dwHighDateTime;
t.QuadPart -= (ULONGLONG)ageMinutes * 60 * 10000000ULL;
FILETIME ft = { t.LowPart, t.HighPart };
SetFileTime(h, NULL, NULL, &ft);
CloseHandle(h);
}
static int FileExists(const char* dir, const char* name)
{
char p[MAX_PATH];
_snprintf_s(p, sizeof p, _TRUNCATE, "%s\\%s", dir, name);
return GetFileAttributesA(p) != INVALID_FILE_ATTRIBUTES;
}
static int CountFiles(const char* dir, const char* pattern)
{
char p[MAX_PATH];
_snprintf_s(p, sizeof p, _TRUNCATE, "%s\\%s", dir, pattern);
WIN32_FIND_DATAA fd;
HANDLE f = FindFirstFileA(p, &fd);
if (f == INVALID_HANDLE_VALUE) return 0;
int n = 0;
do { if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) n++; } while (FindNextFileA(f, &fd));
FindClose(f);
return n;
}
static void Env(const char* name, char* out, DWORD cap)
{
out[0] = 0;
if (GetEnvironmentVariableA(name, out, cap) == 0) out[0] = 0;
}
static int WaitForCalls(LONG want)
{
for (int i = 0; i < 200 && cappedCalls < want; i++) Sleep(10);
return cappedCalls >= want;
}
int main(void)
{
InitializeCriticalSection(&g_logLock);
char root[MAX_PATH];
GetFullPathNameA("work", sizeof root, root, NULL);
CreateDirectoryA(root, NULL);
CreateDirectoryA(LOG_DIR, NULL);
DWORD self = GetCurrentProcessId();
// 1. The cap rule.
CHECK(!ReloadCapReached(0, 3) && !ReloadCapReached(2, 3), "under the cap: 0 and 2 reloads of 3 allowed");
CHECK(ReloadCapReached(3, 3) && ReloadCapReached(4, 3), "at/over the cap: the 4th reload (3 done, cap 3) refused");
CHECK(ReloadCapReached(0, 0), "cap 0: no hot reloads at all");
CHECK(!ReloadCapReached(0, -1) && !ReloadCapReached(1000, -1), "negative cap: no cap");
// 2. Where the cap comes from: the engine's export, else the default.
g_engineIsManaged = 0;
g_engineModule = NULL;
CHECK(CurrentReloadCap() == DEFAULT_MAX_HOT_RELOADS && DEFAULT_MAX_HOT_RELOADS == 3,
"no engine export: the default (%d)", CurrentReloadCap());
g_engineModule = GetModuleHandleA(NULL);
CHECK(EngineExport(ENGINE_MAXRELOADS_EXPORT) && EngineExport(ENGINE_CAPPED_EXPORT), "the fake engine's exports resolve");
fakeCap = 7;
CHECK(CurrentReloadCap() == 7, "the engine's MaxHotReloads is used (%d)", CurrentReloadCap());
fakeCap = 3;
// 3. A refused reload, through the real ReloadWatcher: 3 reloads done (gen 4), cap 3.
// Nothing may be shut down, unloaded or staged, and the engine is told each time.
strcpy_s(g_loaderDir, sizeof g_loaderDir, root);
_snprintf_s(g_enginePath, sizeof g_enginePath, _TRUNCATE, "%s\\" ENGINE_DLL_NAME, root);
char staging[MAX_PATH];
_snprintf_s(staging, sizeof staging, _TRUNCATE, "%s\\" STAGING_SUBDIR, root);
CreateDirectoryA(staging, NULL);
char gen4[96], gen5[96], gen3[96];
_snprintf_s(gen3, sizeof gen3, _TRUNCATE, "RynthCore.Engine.p%lu.gen3.dll", self);
_snprintf_s(gen4, sizeof gen4, _TRUNCATE, "RynthCore.Engine.p%lu.gen4.dll", self);
_snprintf_s(gen5, sizeof gen5, _TRUNCATE, "RynthCore.Engine.p%lu.gen5.dll", self);
MakeFile(staging, gen3, 5); // an older generation a real reload would clean up
MakeFile(staging, gen4, 1); // the running generation
g_initCount = 4;
g_reloadEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
HANDLE watcher = CreateThread(NULL, 0, ReloadWatcher, NULL, 0, NULL);
SetEvent(g_reloadEvent);
int told = WaitForCalls(1);
Sleep(50);
CHECK(told && cappedReloads == 3 && cappedCap == 3, "refused: the engine is told (reloads=%ld, cap=%ld)", cappedReloads, cappedCap);
CHECK(g_initCount == 4 && g_reloadInFlight == 0 && g_lastReloadDone == 0, "refused: still gen 4, no reload ran");
CHECK(FileExists(staging, gen4) && FileExists(staging, gen3) && !FileExists(staging, gen5),
"refused: staging untouched (gen 4 and gen 3 kept, no gen 5 staged)");
// A second publish: refused again, told again (the engine decides what goes to chat).
SetEvent(g_reloadEvent);
CHECK(WaitForCalls(2) && g_initCount == 4, "a second signal: refused again, told again (%ld calls)", cappedCalls);
// Cap 0 refuses the first reload too.
g_initCount = 1;
fakeCap = 0;
SetEvent(g_reloadEvent);
CHECK(WaitForCalls(3) && cappedReloads == 0 && cappedCap == 0 && g_initCount == 1, "cap 0: the first reload refused");
fakeCap = 3;
(void)watcher; // runs until the process exits
// 4. Dump type for the free space.
CHECK(CrashDumpType(10ULL << 30) == 2, "10 GB free: dump with heap (type 2)");
CHECK(CrashDumpType((unsigned long long)DUMP_HEAP_MIN_FREE_MB << 20) == 2, "exactly the floor: type 2");
CHECK(CrashDumpType(((unsigned long long)DUMP_HEAP_MIN_FREE_MB << 20) - 1) == 1, "below the floor: normal dump (type 1)");
CHECK(CrashDumpType(0) == 1, "unknown free space (0): type 1");
// 5. Pruning: the newest 3 clr_*.dmp stay; other dumps and folders are left alone.
char dumps[MAX_PATH];
_snprintf_s(dumps, sizeof dumps, _TRUNCATE, "%s\\dumps", root);
CreateDirectoryA(dumps, NULL);
MakeFile(dumps, "clr_100_1.dmp", 50);
MakeFile(dumps, "clr_101_2.dmp", 40);
MakeFile(dumps, "clr_102_3.dmp", 30);
MakeFile(dumps, "clr_103_4.dmp", 20);
MakeFile(dumps, "clr_104_5.dmp", 10);
MakeFile(dumps, "hang_1_old.dmp", 500);
MakeFile(dumps, "clr_notes.txt", 600);
char sub[MAX_PATH];
_snprintf_s(sub, sizeof sub, _TRUNCATE, "%s\\clr_folder.dmp", dumps);
CreateDirectoryA(sub, NULL);
int deleted = PruneCrashDumps(dumps, DUMP_KEEP);
CHECK(deleted == 2 && !FileExists(dumps, "clr_100_1.dmp") && !FileExists(dumps, "clr_101_2.dmp"),
"the 2 oldest clr dumps deleted (%d)", deleted);
CHECK(FileExists(dumps, "clr_102_3.dmp") && FileExists(dumps, "clr_103_4.dmp") && FileExists(dumps, "clr_104_5.dmp"),
"the newest 3 kept");
CHECK(FileExists(dumps, "hang_1_old.dmp") && FileExists(dumps, "clr_notes.txt") &&
GetFileAttributesA(sub) != INVALID_FILE_ATTRIBUTES, "hang dumps, other files and folders untouched");
CHECK(PruneCrashDumps(dumps, DUMP_KEEP) == 0, "a second prune deletes nothing");
char missing[MAX_PATH];
_snprintf_s(missing, sizeof missing, _TRUNCATE, "%s\\nope", root);
CHECK(PruneCrashDumps(missing, DUMP_KEEP) == 0, "a missing folder: nothing to do");
// 6. The environment CoreCLR reads at start.
char v[MAX_PATH], want[MAX_PATH], runtimeDir[MAX_PATH], newDumps[MAX_PATH];
SetEnvironmentVariableA("DOTNET_DbgEnableMiniDump", NULL);
SetEnvironmentVariableA("COMPlus_DbgEnableMiniDump", NULL);
SetEnvironmentVariableA("DOTNET_DbgMiniDumpType", NULL);
SetEnvironmentVariableA("DOTNET_DbgMiniDumpName", NULL);
_snprintf_s(runtimeDir, sizeof runtimeDir, _TRUNCATE, "%s\\dotnet", root); // no createdump.exe: warns
_snprintf_s(newDumps, sizeof newDumps, _TRUNCATE, "%s\\newdumps", root); // created on demand
MakeFile(dumps, "clr_105_6.dmp", 5);
int type = ConfigureCrashDumps(dumps, runtimeDir);
ULARGE_INTEGER freeBytes;
GetDiskFreeSpaceExA(dumps, &freeBytes, NULL, NULL);
CHECK(type == CrashDumpType(freeBytes.QuadPart), "dump type %d for %llu MB free", type, freeBytes.QuadPart >> 20);
Env("DOTNET_DbgEnableMiniDump", v, sizeof v);
CHECK(strcmp(v, "1") == 0, "DOTNET_DbgEnableMiniDump=%s", v);
Env("DOTNET_DbgMiniDumpType", v, sizeof v);
CHECK(atoi(v) == type, "DOTNET_DbgMiniDumpType=%s", v);
Env("DOTNET_DbgMiniDumpName", v, sizeof v);
_snprintf_s(want, sizeof want, _TRUNCATE, "%s\\clr_%lu_%%t.dmp", dumps, self);
CHECK(strcmp(v, want) == 0, "DOTNET_DbgMiniDumpName=%s (pid in the name, createdump's %%t for the time)", v);
CHECK(CountFiles(dumps, "clr_*.dmp") == 3 && !FileExists(dumps, "clr_102_3.dmp"), "pruned at startup to the newest 3");
// Already configured (a test client, or =0 to turn it off): left alone.
SetEnvironmentVariableA("DOTNET_DbgEnableMiniDump", "0");
SetEnvironmentVariableA("DOTNET_DbgMiniDumpName", "C:\\elsewhere\\x.dmp");
CHECK(ConfigureCrashDumps(newDumps, runtimeDir) == 0, "DOTNET_DbgEnableMiniDump=0 already set: returns 0");
Env("DOTNET_DbgEnableMiniDump", v, sizeof v);
CHECK(strcmp(v, "0") == 0, "...and stays 0");
Env("DOTNET_DbgMiniDumpName", v, sizeof v);
CHECK(strcmp(v, "C:\\elsewhere\\x.dmp") == 0, "...name untouched");
SetEnvironmentVariableA("DOTNET_DbgEnableMiniDump", NULL);
SetEnvironmentVariableA("COMPlus_DbgEnableMiniDump", "1");
CHECK(ConfigureCrashDumps(newDumps, runtimeDir) == 0, "the legacy COMPlus_ name counts too");
SetEnvironmentVariableA("COMPlus_DbgEnableMiniDump", NULL);
CHECK(ConfigureCrashDumps(newDumps, runtimeDir) > 0 && GetFileAttributesA(newDumps) != INVALID_FILE_ATTRIBUTES,
"a missing dumps folder is created");
printf(fails ? "\n%d FAILED\n" : "\nALL PASSED\n", fails);
return fails;
}

View file

@ -1,5 +1,6 @@
// Offline checks for Loader.c's staging: CleanStaleStagingFiles rules and CopyGuarded.
// Built with the real Loader.c included, so these are the shipped functions.
#define LOG_DIR "logs" // anything LoaderLog writes goes here, not C:\Games
#include "Loader.c"
static int fails;

View file

@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the toolbar's text size (the "chrome" row of PanelTextScale).
src\RynthCore.Engine\UI\PanelTextScale.cs, compiled in, with a stub ImGuiFonts. The toolbar's
row must survive a window being sized (SetForWindow's reset loop), be baked even when sizing
per panel is off (StepsInUse), be left alone by All Panels changes, stay unbaked at 0, clamp,
and round-trip through the file. PanelTextScale reads its file path once per process, so each
case runs in a child process pointed at a temp file with RYNTHCORE_PANEL_TEXT_SIZE. Never
touches %LOCALAPPDATA%\RynthCore.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>PanelTextScaleTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\UI\PanelTextScale.cs" Link="Engine\PanelTextScale.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,174 @@
using System.Diagnostics;
using RynthCore.Engine.UI;
namespace RynthCore.Engine.ImGuiBackend
{
/// <summary>Stub of the engine's fonts: counts the re-bake requests PanelTextScale makes.</summary>
internal static class ImGuiFonts
{
internal static int Rebuilds;
internal static void RequestRebuild(int delayMs = 0) => Rebuilds++;
}
}
namespace PanelTextScaleTests
{
// Offline tests for the toolbar text size. See the csproj.
internal static class Program
{
private static int _fails, _asserts;
private static void Check(bool cond, string msg)
{
_asserts++;
if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); }
}
private static void Eq<T>(T actual, T expected, string msg) =>
Check(EqualityComparer<T>.Default.Equals(actual, expected), $"{msg}: expected '{expected}', got '{actual}'");
// case name -> the file it starts from (null = no file)
private static readonly (string Name, string? Seed, Action Body)[] Cases =
{
("ChromeSurvivesSetForWindow", "__all=2\n__chrome=3\n", ChromeSurvivesSetForWindow),
("StepsInUseHasChromeWhenPerPanelOff", "__all=0\n__chrome=3\n", StepsInUseHasChromeWhenPerPanelOff),
("UseForAllAndSetAllLeaveChromeAlone", "__chrome=3\n", UseForAllAndSetAllLeaveChromeAlone),
("ChromeZeroIsNotBaked", "__all=0\n__chrome=0\n", ChromeZeroIsNotBaked),
("ChromeDoesNotFallBackToAll", "__all=5\n", ChromeDoesNotFallBackToAll),
("ChromeClamps", null, ChromeClamps),
("RoundTripWrite", null, RoundTripWrite),
("RoundTripRead", null, RoundTripRead),
};
private static int Main(string[] args)
{
if (args.Length > 1 && args[0] == "--child")
{
foreach (var c in Cases)
if (c.Name == args[1]) { c.Body(); return _fails == 0 && _asserts > 0 ? 0 : 1; }
Console.WriteLine(" [FAIL] unknown case " + args[1]);
return 1;
}
string root = Path.Combine(Path.GetTempPath(), "rynth-panel-text-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(root);
int fails = 0;
try
{
foreach (var c in Cases)
{
if (c.Name == "RoundTripRead") continue; // run right after RoundTripWrite, on its file
string file = Path.Combine(root, c.Name + ".txt");
if (c.Seed != null) File.WriteAllText(file, c.Seed);
Console.WriteLine(c.Name);
bool ok = RunChild(c.Name, file);
if (ok && c.Name == "RoundTripWrite")
{
Console.WriteLine("RoundTripRead");
ok = RunChild("RoundTripRead", file);
}
if (!ok) fails++;
}
}
finally
{
try { Directory.Delete(root, true); } catch { }
}
Console.WriteLine();
Console.WriteLine(fails == 0 ? "PASS" : $"FAIL ({fails} case(s) failed)");
return fails == 0 ? 0 : 1;
}
private static bool RunChild(string name, string file)
{
var psi = new ProcessStartInfo(Environment.ProcessPath!)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
psi.ArgumentList.Add("--child");
psi.ArgumentList.Add(name);
psi.Environment["RYNTHCORE_PANEL_TEXT_SIZE"] = file;
using Process p = Process.Start(psi)!;
string output = p.StandardOutput.ReadToEnd() + p.StandardError.ReadToEnd();
p.WaitForExit();
if (output.Length > 0) Console.Write(output);
return p.ExitCode == 0;
}
private static string[] Lines(string? file = null) =>
File.ReadAllLines(file ?? Environment.GetEnvironmentVariable("RYNTHCORE_PANEL_TEXT_SIZE")!);
// Sizing one window with per-panel off rewrites every other row to the All
// Panels size; the toolbar's row is not a panel and must keep its own.
private static void ChromeSurvivesSetForWindow()
{
PanelTextScale.SetForWindow("Radar", 4);
Eq(PanelTextScale.GetChrome(), 3, "chrome after SetForWindow (per-panel off)");
Check(Lines().Contains("__chrome=3"), "chrome row still 3 in the file");
Eq(PanelTextScale.GetOwn("Radar"), 4, "the window itself did change");
Check(PanelTextScale.PerPanel, "SetForWindow switched per-panel on");
Eq(PanelTextScale.Get("Other"), 2, "other panels stay at All Panels");
}
// Per-panel off: StepsInUse used to skip every non-All row, so the toolbar's
// size would never have been baked.
private static void StepsInUseHasChromeWhenPerPanelOff()
{
Check(!PanelTextScale.PerPanel, "per-panel is off");
Eq(PanelTextScale.GetAll(), 0, "All Panels is 0");
var steps = PanelTextScale.StepsInUse();
Check(steps.Contains(3), "StepsInUse contains the chrome step 3 (got [" + string.Join(",", steps) + "])");
Eq(steps.Count, 1, "and nothing else");
}
private static void UseForAllAndSetAllLeaveChromeAlone()
{
PanelTextScale.UseForAll(5);
Eq(PanelTextScale.GetChrome(), 3, "chrome after UseForAll(5)");
PanelTextScale.SetAll(2);
Eq(PanelTextScale.GetChrome(), 3, "chrome after SetAll(2)");
Eq(PanelTextScale.GetAll(), 2, "All Panels did change");
var steps = PanelTextScale.StepsInUse();
Check(steps.Contains(3) && steps.Contains(2), "both steps baked (got [" + string.Join(",", steps) + "])");
}
private static void ChromeZeroIsNotBaked()
{
Eq(PanelTextScale.StepsInUse().Count, 0, "nothing in use with chrome 0 and All 0");
PanelTextScale.SetChrome(3);
Check(PanelTextScale.StepsInUse().Contains(3), "chrome 3 baked");
PanelTextScale.SetChrome(0);
Eq(PanelTextScale.StepsInUse().Count, 0, "back to nothing after SetChrome(0)");
}
private static void ChromeDoesNotFallBackToAll()
{
Eq(PanelTextScale.GetAll(), 5, "All Panels is 5");
Eq(PanelTextScale.GetChrome(), 0, "toolbar without its own row is normal size");
}
private static void ChromeClamps()
{
PanelTextScale.SetChrome(99);
Eq(PanelTextScale.GetChrome(), PanelTextScale.SizeNames.Length - 1, "clamped to the top size");
PanelTextScale.SetChrome(-4);
Eq(PanelTextScale.GetChrome(), 0, "clamped to 0");
}
private static void RoundTripWrite()
{
int before = RynthCore.Engine.ImGuiBackend.ImGuiFonts.Rebuilds;
PanelTextScale.SetChrome(4);
Eq(RynthCore.Engine.ImGuiBackend.ImGuiFonts.Rebuilds, before + 1, "SetChrome requested one re-bake");
Check(Lines().Contains("__chrome=4"), "file has __chrome=4");
PanelTextScale.SetChrome(4);
Eq(RynthCore.Engine.ImGuiBackend.ImGuiFonts.Rebuilds, before + 1, "same size again requests nothing");
}
// A fresh process reads what RoundTripWrite saved.
private static void RoundTripRead()
{
Eq(PanelTextScale.GetChrome(), 4, "chrome read back from the file");
}
}
}

View file

@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline tests for "Report a problem" (src\RynthCore.Engine\Report\ProblemReportCore.cs, compiled
in; pure code, no engine state):
- text cleaning and the UTF-8 byte limits (never cut inside a character);
- the request body: exact keys and types the server's schema expects, limits applied,
plugin names cleaned, the log gzipped + base64 and round-tripping, no log = null;
- the log tail: last N lines, the byte cap (keeps the end, starts at a line), a last line
still being written, CRLF, an empty / missing file, the rotated .old topping up a short
current log, and reading while another thread keeps appending (as the engine does);
- hiding the account (login) name, the Windows user name (profile paths) and the PC name;
- the cooldown arithmetic, the endpoint override rules, and reading the server's answers.
Optional: (double dash) server http://127.0.0.1:18097/report posts real bodies to a local copy
of the endpoint (C:\Aeshnidae\ops\report-endpoint\test_local.py serve) to check both ends agree.
Nothing native: no AC, no engine, no network unless asked.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>ProblemReportTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\Report\ProblemReportCore.cs" Link="Engine\ProblemReportCore.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,473 @@
using System.IO.Compression;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using RynthCore.Engine.Report;
namespace ProblemReportTests;
internal static class Program
{
private static int _checks, _failed;
private static string _case = "";
private static string _tmp = "";
private static int Main(string[] args)
{
_tmp = Path.Combine(Path.GetTempPath(), "ProblemReportTests-" + Environment.ProcessId);
Directory.CreateDirectory(_tmp);
try
{
TextCleaning();
Utf8Limits();
Validation();
PayloadShape();
PayloadLimits();
PayloadNoLog();
TailLastLines();
TailByteCap();
TailPartialLastLine();
TailCrlfAndEdges();
TailTopsUpFromOld();
TailWhileWriting();
AccountHidden();
Cooldown();
Endpoint();
Responses();
Sizes();
int at = Array.IndexOf(args, "server");
if (at >= 0 && at + 1 < args.Length) AgainstServer(args[at + 1]).GetAwaiter().GetResult();
}
finally
{
try { Directory.Delete(_tmp, true); } catch { }
}
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
Console.WriteLine(_failed == 0 ? "ALL PROBLEM REPORT TESTS PASSED." : $"{_failed} FAILED.");
return _failed == 0 ? 0 : 1;
}
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>(T actual, T expected, string what) =>
Check(EqualityComparer<T>.Default.Equals(actual, expected), $"{what}: expected <{expected}>, got <{actual}>");
// ── Text ─────────────────────────────────────────────────────────────
private static void TextCleaning()
{
Case("text cleaning");
Eq(ProblemReportCore.CleanText(" hello\r\nworld\r ", 100), "hello\nworld", "CRLF/CR to LF, trimmed");
Eq(ProblemReportCore.CleanText("a\u0000b\u0007c\td", 100), "abc\td", "control chars dropped, tab kept");
Eq(ProblemReportCore.CleanText(null, 100), "", "null");
Eq(ProblemReportCore.CleanShort(" Tom\nthe\tGreat ", 64), "TomtheGreat", "one-line field drops newline and tab");
Eq(ProblemReportCore.CleanShort(new string('x', 70), 64).Length, 64, "short field cut to 64");
string emoji = new string('a', 63) + "\U0001F600";
Check(!char.IsHighSurrogate(ProblemReportCore.CleanShort(emoji, 64)[^1]), "short field never ends on a lone high surrogate");
Eq(ProblemReportCore.PluginName("Rynth<Ai>!"), "RynthAi", "plugin name cleaned");
Eq(ProblemReportCore.PluginName(new string('p', 50)).Length, 40, "plugin name max 40");
}
private static void Utf8Limits()
{
Case("UTF-8 limits");
Eq(ProblemReportCore.TrimUtf8("abcdef", 4), "abcd", "ascii cut");
Eq(ProblemReportCore.TrimUtf8("aé", 2), "a", "2-byte char not split");
Eq(ProblemReportCore.TrimUtf8("a\U0001F600", 4), "a", "4-byte char not split");
Eq(ProblemReportCore.TrimUtf8("a\U0001F600", 5), "a\U0001F600", "4-byte char fits");
string big = string.Concat(Enumerable.Repeat("ü", 3000)); // 6000 bytes
string cut = ProblemReportCore.CleanText(big, ProblemReportCore.MaxDescriptionBytes);
Check(Encoding.UTF8.GetByteCount(cut) <= ProblemReportCore.MaxDescriptionBytes, "description <= 2500 bytes");
Eq(cut.Length, 1250, "1250 two-byte chars");
}
private static void Validation()
{
Case("validation");
Check(ProblemReportCore.ValidateDescription("").Length > 0, "empty refused");
Check(ProblemReportCore.ValidateDescription(" \r\n ").Length > 0, "blank refused");
Check(ProblemReportCore.ValidateDescription("ab").Length > 0, "too short refused");
Eq(ProblemReportCore.ValidateDescription("bot stuck"), "", "ok accepted");
}
// ── Payload ──────────────────────────────────────────────────────────
private static ReportContext SampleContext() => new()
{
Character = "Drakkon",
World = "Aelrynth",
Connect = "aelrynth.com:9000",
Aelrynth = true,
RynthCoreVersion = "2026.10.9.3 (194ea47)",
ApiVersion = 79,
Generation = 2,
RynthAiVersion = "2026.10.9.3 (e6fffb0)",
Plugins = { ("RynthAi", "2026.10.9.3 (e6fffb0)"), ("RynthNav", "dev (abc1234)"), ("rynthai", "dupe") },
Landcell = 0x12340105,
Pid = 4242,
};
private static readonly string[] TopKeys =
{
"schema", "description", "doing", "character", "world", "connect", "aelrynth", "rynthcore", "api",
"generation", "rynthai", "plugins", "landcell", "pid", "clientTime", "log",
};
private static void PayloadShape()
{
Case("payload shape");
string logText = string.Join("\n", Enumerable.Range(1, 50).Select(i => $"[12:00:{i:00}.000] [pid:4242] [INF] [engine] line {i}")) + "\n";
var tail = new LogTail { FileName = "RynthCore.4242.log", Text = Encoding.UTF8.GetBytes(logText), Lines = 50 };
byte[] body = ProblemReportCore.BuildPayload("Bot <@everyone> stuck **here**", "hunting\r\nwith bot", SampleContext(), tail,
new DateTime(2026, 10, 11, 12, 0, 0, DateTimeKind.Utc));
using var doc = JsonDocument.Parse(body);
JsonElement r = doc.RootElement;
var keys = r.EnumerateObject().Select(p => p.Name).ToArray();
Check(keys.OrderBy(k => k).SequenceEqual(TopKeys.OrderBy(k => k)), "exactly the schema's keys: " + string.Join(",", keys));
Eq(r.GetProperty("schema").GetInt32(), 1, "schema");
Eq(r.GetProperty("description").GetString(), "Bot <@everyone> stuck **here**", "description kept verbatim (the server escapes)");
Eq(r.GetProperty("doing").GetString(), "hunting\nwith bot", "doing CRLF -> LF");
Eq(r.GetProperty("character").GetString(), "Drakkon", "character");
Eq(r.GetProperty("aelrynth").GetBoolean(), true, "aelrynth");
Eq(r.GetProperty("api").GetInt32(), 79, "api");
Eq(r.GetProperty("landcell").GetString(), "0x12340105", "landcell hex");
Eq(r.GetProperty("pid").GetInt32(), 4242, "pid");
Eq(r.GetProperty("clientTime").GetString(), "2026-10-11T12:00:00Z", "clientTime");
Eq(r.GetProperty("plugins").GetArrayLength(), 2, "plugin dupes (any case) dropped");
Eq(r.GetProperty("plugins")[1].GetProperty("name").GetString(), "RynthNav", "second plugin");
JsonElement log = r.GetProperty("log");
Eq(log.GetProperty("name").GetString(), "RynthCore.4242.log", "log name");
Eq(log.GetProperty("lines").GetInt32(), 50, "log lines");
Eq(log.GetProperty("bytes").GetInt32(), tail.Text.Length, "log bytes");
byte[] gz = log.GetProperty("gzip").GetBytesFromBase64();
using var unz = new GZipStream(new MemoryStream(gz), CompressionMode.Decompress);
using var back = new MemoryStream();
unz.CopyTo(back);
Eq(Encoding.UTF8.GetString(back.ToArray()), logText, "log round-trips through gzip + base64");
Check(gz.Length < tail.Text.Length, "gzip is smaller");
}
private static void PayloadLimits()
{
Case("payload limits");
var ctx = SampleContext();
ctx.Character = new string('C', 200);
ctx.Connect = new string('h', 300);
ctx.Landcell = 0;
ctx.Plugins.Clear();
for (int i = 0; i < 50; i++) ctx.Plugins.Add(($"Plugin{i}", "1"));
byte[] body = ProblemReportCore.BuildPayload(new string('d', 5000), new string('w', 5000), ctx, null, DateTime.UtcNow);
using var doc = JsonDocument.Parse(body);
JsonElement r = doc.RootElement;
Eq(r.GetProperty("description").GetString()!.Length, ProblemReportCore.MaxDescriptionBytes, "description capped");
Eq(r.GetProperty("doing").GetString()!.Length, ProblemReportCore.MaxDoingBytes, "doing capped");
Eq(r.GetProperty("character").GetString()!.Length, ProblemReportCore.MaxShortField, "character capped");
Eq(r.GetProperty("connect").GetString()!.Length, ProblemReportCore.MaxConnectField, "connect capped");
Eq(r.GetProperty("plugins").GetArrayLength(), ProblemReportCore.MaxPlugins, "plugins capped at 32");
Eq(r.GetProperty("landcell").GetString(), "", "no landcell = empty");
Check(body.Length < 8192, $"no-log body small ({body.Length} bytes)");
}
private static void PayloadNoLog()
{
Case("payload without log");
byte[] body = ProblemReportCore.BuildPayload("x went wrong", "", SampleContext(), null, DateTime.UtcNow);
using var doc = JsonDocument.Parse(body);
Eq(doc.RootElement.GetProperty("log").ValueKind, JsonValueKind.Null, "log null when unticked");
var empty = new LogTail { FileName = "a.log", Text = Array.Empty<byte>() };
body = ProblemReportCore.BuildPayload("x went wrong", "", SampleContext(), empty, DateTime.UtcNow);
using var doc2 = JsonDocument.Parse(body);
Eq(doc2.RootElement.GetProperty("log").ValueKind, JsonValueKind.Null, "empty log sent as null");
}
// ── Log tail ─────────────────────────────────────────────────────────
private static string WriteLines(string name, int count, string newline = "\n", bool trailing = true, int pad = 0)
{
string path = Path.Combine(_tmp, name);
var sb = new StringBuilder();
for (int i = 1; i <= count; i++)
{
sb.Append("line ").Append(i).Append(new string('.', pad));
if (i < count || trailing) sb.Append(newline);
}
File.WriteAllText(path, sb.ToString());
return path;
}
private static string[] LinesOf(LogTail t) =>
Encoding.UTF8.GetString(t.Text).Split('\n', StringSplitOptions.None).Where(s => s.Length > 0).ToArray();
private static void TailLastLines()
{
Case("tail: last N lines");
string path = WriteLines("a.log", 5000);
LogTail t = ProblemReportCore.ReadTail(path, null, 2000, 10_000_000)!;
string[] lines = LinesOf(t);
Eq(t.Lines, 2000, "2000 lines");
Eq(lines.Length, 2000, "2000 lines in text");
Eq(lines[0], "line 3001", "first kept line");
Eq(lines[^1], "line 5000", "last line");
Check(t.Text[^1] == (byte)'\n', "ends with the newline");
Eq(t.FileName, "a.log", "file name");
LogTail small = ProblemReportCore.ReadTail(WriteLines("b.log", 10), null, 2000, 10_000_000)!;
Eq(small.Lines, 10, "short file: all lines");
Eq(LinesOf(small)[0], "line 1", "short file from the start");
// Exactly the chunk size boundary: 64 KB lines.
string big = WriteLines("c.log", 3000, pad: 60);
LogTail tb = ProblemReportCore.ReadTail(big, null, 2000, 10_000_000)!;
Eq(tb.Lines, 2000, "multi-chunk read: 2000 lines");
Eq(LinesOf(tb)[0], "line 1001" + new string('.', 60), "multi-chunk first line whole");
}
private static void TailByteCap()
{
Case("tail: byte cap keeps the end");
string path = WriteLines("cap.log", 2000, pad: 90); // ~100 bytes a line, ~200 KB
LogTail t = ProblemReportCore.ReadTail(path, null, 2000, 50_000)!;
Check(t.Text.Length <= 50_000, $"<= cap ({t.Text.Length})");
string[] lines = LinesOf(t);
Check(lines[0].StartsWith("line ") && lines[0].EndsWith(new string('.', 90)), "first line whole: " + lines[0][..Math.Min(20, lines[0].Length)]);
Eq(lines[^1], "line 2000" + new string('.', 90), "last line kept");
Eq(t.Lines, lines.Length, "line count matches");
Check(t.Lines < 2000 && t.Lines > 400, $"about 490 lines ({t.Lines})");
}
private static void TailPartialLastLine()
{
Case("tail: last line still being written");
string path = WriteLines("p.log", 3000, trailing: false);
LogTail t = ProblemReportCore.ReadTail(path, null, 2000, 10_000_000)!;
string[] lines = LinesOf(t);
Eq(t.Lines, 2000, "2000 lines incl. the unfinished one");
Eq(lines[^1], "line 3000", "unfinished last line kept");
Eq(lines[0], "line 1001", "first");
}
private static void TailCrlfAndEdges()
{
Case("tail: CRLF, empty, missing");
string path = WriteLines("crlf.log", 2500, newline: "\r\n");
LogTail t = ProblemReportCore.ReadTail(path, null, 2000, 10_000_000)!;
Eq(t.Lines, 2000, "CRLF lines");
Check(Encoding.UTF8.GetString(t.Text).StartsWith("line 501\r\n"), "CRLF first line whole");
File.WriteAllText(Path.Combine(_tmp, "empty.log"), "");
LogTail e = ProblemReportCore.ReadTail(Path.Combine(_tmp, "empty.log"), null)!;
Eq(e.Lines, 0, "empty file: no lines");
Eq(e.Text.Length, 0, "empty file: no bytes");
Check(ProblemReportCore.ReadTail(Path.Combine(_tmp, "nope.log"), null) == null, "missing file: null");
Eq(ProblemReportCore.CountLines("a\nb"u8), 2, "count: unfinished last line");
Eq(ProblemReportCore.CountLines("a\nb\n"u8), 2, "count: trailing newline");
Eq(ProblemReportCore.CountLines(""u8), 0, "count: empty");
}
private static void TailTopsUpFromOld()
{
Case("tail: rotated .old tops up a short log");
string old = WriteLines("r.log.old", 3000, trailing: false); // the old file's last line lacks a newline
File.WriteAllText(Path.Combine(_tmp, "r.log"), "new 1\nnew 2\nnew 3\n");
LogTail t = ProblemReportCore.ReadTail(Path.Combine(_tmp, "r.log"), old, 2000, 10_000_000)!;
string[] lines = LinesOf(t);
Eq(t.Lines, 2000, "2000 lines in all");
Check(t.IncludesOld, "marked as including .old");
Eq(lines[0], "line 1004", "old part starts 1997 lines back");
Eq(lines[1996], "line 3000", "old part's last line");
Eq(lines[1997], "new 1", "then the current log");
Eq(lines[^1], "new 3", "ends with the current log");
LogTail full = ProblemReportCore.ReadTail(WriteLines("f.log", 2500), old, 2000, 10_000_000)!;
Check(!full.IncludesOld, "a full current log doesn't touch .old");
}
private static void TailWhileWriting()
{
Case("tail: file being appended to");
string path = Path.Combine(_tmp, "live.log");
using var stop = new CancellationTokenSource();
long written = 0;
// The engine's writer: open, append one line, close, with FileShare.ReadWrite (EntryPoint.AppendWithRetry).
var writer = new Thread(() =>
{
int i = 0;
while (!stop.IsCancellationRequested)
{
i++;
string line = $"[12:00:00.000] [pid:1] [INF] [engine] hb #{i} up={i}s fps=60 plug=30/s ws=400MB login=1\r\n";
for (int attempt = 0; attempt < 4; attempt++)
{
try
{
using var fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
byte[] b = Encoding.UTF8.GetBytes(line);
// Two writes, so a reader can land between them (a half-written line).
fs.Write(b, 0, b.Length / 2);
fs.Flush();
fs.Write(b, b.Length / 2, b.Length - b.Length / 2);
Interlocked.Increment(ref written);
break;
}
catch (IOException) { Thread.Sleep(1); }
}
}
}) { IsBackground = true };
writer.Start();
while (Interlocked.Read(ref written) < 3000) Thread.Sleep(5);
int reads = 0, bad = 0;
var until = DateTime.UtcNow.AddSeconds(2);
while (DateTime.UtcNow < until)
{
LogTail t = ProblemReportCore.ReadTail(path, null, 2000, 10_000_000)!;
reads++;
string text = Encoding.UTF8.GetString(t.Text);
string[] lines = text.Split("\r\n");
// Whole lines, except possibly the very last one (being written now).
for (int k = 0; k < lines.Length - 1; k++)
if (!lines[k].StartsWith("[12:00:00.000]") || !lines[k].EndsWith("login=1")) { bad++; break; }
if (t.Lines != 2000) bad++;
}
stop.Cancel();
writer.Join();
Check(reads > 5, $"read repeatedly while writing ({reads} reads)");
Eq(bad, 0, "every read: 2000 lines, all whole but the last");
}
private static void AccountHidden()
{
Case("tail: account, Windows user and PC names hidden");
string path = Path.Combine(_tmp, "acct.log");
File.WriteAllText(path,
"[12:00:00.000] [pid:1] [INF] [engine] SessionState: recorded login session for PID 1 account='MyLogin42' character='Drakkon' (IsLoggedIn=true).\n" +
"[12:00:01.000] [pid:1] [INF] [engine] launch context for mylogin42 read\n" +
"[12:00:02.000] [pid:1] [INF] [engine] account='' (empty field)\n" +
"[12:00:03.000] [pid:1] [INF] [engine] watching 'C:\\Users\\Jane Q. Doe\\AppData\\Roaming\\RynthCore\\dispatch.txt'.\n" +
"[12:00:04.000] [pid:1] [INF] [engine] d:/users/jdoe/x.txt on JANES-PC as jdoe; Drakkon says hi\n");
var hide = new[] { ("MyLogin42", ProblemReportCore.HiddenAccount), ("jdoe", ProblemReportCore.HiddenUser), ("JANES-PC", "<pc>") };
LogTail t = ProblemReportCore.ReadTail(path, null, hide: hide)!;
string text = Encoding.UTF8.GetString(t.Text);
Check(!text.Contains("MyLogin42", StringComparison.OrdinalIgnoreCase), "login name gone (any case)");
Check(text.Contains("account='<account>' character='Drakkon'"), "account field hidden, character kept");
Check(text.Contains("launch context for <account> read"), "free-text mention hidden");
Check(text.Contains("account='<account>' (empty field)"), "every account= field hidden");
Check(text.Contains(@"'C:\Users\<user>\AppData\Roaming\RynthCore\dispatch.txt'"), "profile folder hidden (with spaces): " + text.Split('\n')[3]);
Check(text.Contains("d:/users/<user>/x.txt on <pc> as <user>; Drakkon says hi"), "forward-slash path, user and PC names hidden: " + text.Split('\n')[4]);
Check(!text.Contains("Jane") && !text.Contains("jdoe") && !text.Contains("JANES"), "nothing of the names left");
Eq(t.Lines, 5, "line count unchanged");
Check(t.Gzip.Length > 0 && t.Text.Length == Encoding.UTF8.GetByteCount(text), "size and gzip are of the hidden text");
LogTail noHide = ProblemReportCore.ReadTail(path, null, hide: new[] { ("", "<x>"), ("ab", "<x>") })!;
Check(Encoding.UTF8.GetString(noHide.Text).Contains("for mylogin42 read"), "short/empty hide words ignored (only the field and paths are hidden)");
byte[] plain = Encoding.UTF8.GetBytes("nothing to hide\n");
Check(ReferenceEquals(ProblemReportCore.Redact(plain, hide), plain), "unchanged text is the same array");
byte[] dollar = Encoding.UTF8.GetBytes("user bob here\n");
Eq(Encoding.UTF8.GetString(ProblemReportCore.Redact(dollar, new[] { ("bob", "$1<x>") })), "user $1<x> here\n", "replacement text taken literally");
}
// ── Cooldown, endpoint, answers ──────────────────────────────────────
private static void Cooldown()
{
Case("cooldown");
long now = 1_000_000;
long next = now + ProblemReportCore.CooldownMs;
Eq(ProblemReportCore.CooldownLeft(now, 0), 0L, "never sent: now");
Eq(ProblemReportCore.CooldownLeft(now, next), 60_000L, "just sent: 60 s");
Eq(ProblemReportCore.CooldownLeft(now + 59_999, next), 1L, "1 ms left");
Eq(ProblemReportCore.CooldownLeft(now + 60_000, next), 0L, "after 60 s: now");
Eq(ProblemReportCore.CooldownLeft(now + 90_000, next), 0L, "long after: now");
Eq(ProblemReportCore.FormatWait(42_000), "42 s", "42 s");
Eq(ProblemReportCore.FormatWait(41_001), "42 s", "rounds up");
Eq(ProblemReportCore.FormatWait(65_000), "1 min 5 s", "over a minute");
Check(ProblemReportCore.RetryAfterFailureMs < ProblemReportCore.CooldownMs, "a failed send waits less");
}
private static void Endpoint()
{
Case("endpoint override");
Eq(ProblemReportCore.ResolveEndpoint(null, out var r0), ProblemReportCore.DefaultEndpoint, "none: default");
Check(r0 == null, "none: nothing rejected");
Eq(ProblemReportCore.ResolveEndpoint("https://staging.example.org/rynth/report", out _), "https://staging.example.org/rynth/report", "https ok");
Eq(ProblemReportCore.ResolveEndpoint("http://127.0.0.1:18097/report", out _), "http://127.0.0.1:18097/report", "http loopback ok");
Eq(ProblemReportCore.ResolveEndpoint("http://localhost:18097/report", out _), "http://localhost:18097/report", "http localhost ok");
Eq(ProblemReportCore.ResolveEndpoint("http://evil.example.org/report", out var r1), ProblemReportCore.DefaultEndpoint, "plain http elsewhere refused");
Check(r1 != null, "refusal reported");
Eq(ProblemReportCore.ResolveEndpoint("https://user:pw@example.org/", out _), ProblemReportCore.DefaultEndpoint, "credentials in URL refused");
Eq(ProblemReportCore.ResolveEndpoint("file:///c:/x", out _), ProblemReportCore.DefaultEndpoint, "file: refused");
Eq(ProblemReportCore.ResolveEndpoint("not a url", out _), ProblemReportCore.DefaultEndpoint, "garbage refused");
}
private static void Responses()
{
Case("server answers");
Check(ProblemReportCore.ReadResponse(202, "{\"ok\":true,\"id\":\"R-20261011-ab12cd\"}", out string m, out string id), "202 ok");
Eq(id, "R-20261011-ab12cd", "id read");
Check(m.Contains("R-20261011-ab12cd") && m.StartsWith("Sent"), "message names the id: " + m);
Check(ProblemReportCore.ReadResponse(200, "", out m, out id) && id == "", "200 without body ok");
Check(!ProblemReportCore.ReadResponse(429, "{\"error\":\"Too many reports from this address; try again in 40 minutes.\"}", out m, out _), "429 fails");
Check(m.Contains("40 minutes"), "429 shows the server's reason: " + m);
Check(!ProblemReportCore.ReadResponse(429, "<html>nginx</html>", out m, out _) && m.Contains("Too many"), "nginx 429 page: generic text");
Check(!ProblemReportCore.ReadResponse(400, "{\"error\":\"description\"}", out m, out _) && m.Contains("refused") && m.Contains("description"), "400 refusal: " + m);
Check(!ProblemReportCore.ReadResponse(413, "", out m, out _) && m.Contains("Untick"), "413 suggests unticking the log");
Check(!ProblemReportCore.ReadResponse(502, "<html>", out m, out _) && m.Contains("502"), "502 says so");
Check(!ProblemReportCore.ReadResponse(404, "", out m, out _) && m.Contains("404"), "404 says so");
Check(!ProblemReportCore.ReadResponse(400, "{not json", out m, out _), "bad json doesn't throw");
string longErr = "{\"error\":\"" + new string('e', 500) + "\"}";
ProblemReportCore.ReadResponse(400, longErr, out m, out _);
Check(m.Length < 260, "server text capped");
}
private static void Sizes()
{
Case("sizes");
Eq(ProblemReportCore.FormatSize(812), "812 bytes", "bytes");
Eq(ProblemReportCore.FormatSize(214_000), "209 KB", "KB");
Eq(ProblemReportCore.FormatSize(1_468_006), "1.4 MB", "MB");
var t = new LogTail { FileName = "RynthCore.1.log", Text = new byte[2048], Lines = 1987, TakenLocal = new DateTime(2026, 10, 11, 14, 2, 11) };
string d = ProblemReportCore.DescribeTail(t);
Check(d.StartsWith("RynthCore.1.log: 1,987 lines, 2 KB (") && d.EndsWith("compressed), taken 14:02:11"), d);
}
// ── Optional: against a local copy of the server ─────────────────────
private static async Task AgainstServer(string url)
{
Case("against " + url);
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
string logPath = WriteLines("server.log", 2600, pad: 30);
LogTail tail = ProblemReportCore.ReadTail(logPath, null)!;
var ctx = SampleContext();
ctx.Character = "Test Character " + Environment.ProcessId; // its own per-character bucket
async Task<(int, string)> Post(byte[] body)
{
using var content = new ByteArrayContent(body);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
using var resp = await http.PostAsync(url, content);
return ((int)resp.StatusCode, await resp.Content.ReadAsStringAsync());
}
var (s1, b1) = await Post(ProblemReportCore.BuildPayload("Bot stuck at the portal @everyone **bold** `code`", "hunting", ctx, tail, DateTime.UtcNow));
Check(ProblemReportCore.ReadResponse(s1, b1, out string m1, out string id1), $"with log taken: {s1} {b1}");
Check(id1.StartsWith("R-"), "id returned: " + id1);
Console.WriteLine(" " + m1);
var (s2, b2) = await Post(ProblemReportCore.BuildPayload("No log this time", "", ctx, null, DateTime.UtcNow));
Check(ProblemReportCore.ReadResponse(s2, b2, out _, out _), $"without log taken: {s2} {b2}");
// A body the client would never build: refused.
var (s3, _) = await Post(Encoding.UTF8.GetBytes("{\"schema\":1}"));
Eq(s3, 400, "malformed refused");
}
}

View file

@ -0,0 +1,84 @@
using RynthCore.Engine;
namespace ReloadCapTests;
/// <summary>
/// The engine's side of the hot-reload cap (ReloadCapNotice.cs). After 4+ engine hot reloads in
/// one client, clients died with CoreCLR fatal error 0x80131506; the loader now refuses reloads
/// past engine.json MaxHotReloads and the engine tells the player.
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static string _case = "";
private static int Main()
{
ChatTextIsThePlainSentence();
ToldOnceThenOnlyWhenAskedByHand();
AskedByHandFirstStillCountsAsTheOnce();
ManualWindow();
LogLineSaysWhy();
Console.WriteLine($"{_checks} check(s), {_failed} failed.");
return _failed == 0 ? 0 : 1;
}
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine($"[FAIL] {_case}: {what}");
}
private static void ChatTextIsThePlainSentence()
{
_case = "chat text";
Check(ReloadCapNotice.ChatText(3) == "RynthCore: this client has hot reloaded 3 times; restart the client to pick up the new engine.",
$"3: {ReloadCapNotice.ChatText(3)}");
Check(ReloadCapNotice.ChatText(1) == "RynthCore: this client has hot reloaded 1 time; restart the client to pick up the new engine.",
$"1: {ReloadCapNotice.ChatText(1)}");
Check(ReloadCapNotice.ChatText(0).Contains("hot reloaded 0 times"), $"0 (MaxHotReloads 0): {ReloadCapNotice.ChatText(0)}");
Check(ReloadCapNotice.DefaultMaxHotReloads == 3, "the default cap is 3 (Loader.c DEFAULT_MAX_HOT_RELOADS)");
}
private static void ToldOnceThenOnlyWhenAskedByHand()
{
_case = "once";
var n = new ReloadCapNotice();
Check(n.ShouldChat(askedByHand: false), "the first refusal (an engine publish) goes to chat");
Check(!n.ShouldChat(askedByHand: false), "the second automatic one is logged only");
Check(!n.ShouldChat(askedByHand: false), "and the third");
Check(n.ShouldChat(askedByHand: true), "a press of RL is answered");
Check(n.ShouldChat(askedByHand: true), "every time");
Check(!n.ShouldChat(askedByHand: false), "automatic ones stay quiet after that");
}
private static void AskedByHandFirstStillCountsAsTheOnce()
{
_case = "by hand first";
var n = new ReloadCapNotice();
Check(n.ShouldChat(askedByHand: true), "the first refusal, asked by hand, goes to chat");
Check(!n.ShouldChat(askedByHand: false), "the next automatic one doesn't repeat it");
}
private static void ManualWindow()
{
_case = "manual window";
Check(!ReloadCapNotice.IsRecentManualSignal(0, 50_000), "never signalled: not by hand");
Check(ReloadCapNotice.IsRecentManualSignal(100_000, 100_250), "250 ms after RL: by hand");
Check(ReloadCapNotice.IsRecentManualSignal(100_000, 100_000 + ReloadCapNotice.ManualWindowMs - 1), "just inside the window");
Check(!ReloadCapNotice.IsRecentManualSignal(100_000, 100_000 + ReloadCapNotice.ManualWindowMs), "at the window's end: not");
Check(!ReloadCapNotice.IsRecentManualSignal(100_000, 99_000), "a signal 'in the future' (clock oddity): not");
}
private static void LogLineSaysWhy()
{
_case = "log";
string auto = ReloadCapNotice.LogText(3, 3, askedByHand: false);
string hand = ReloadCapNotice.LogText(3, 3, askedByHand: true);
Check(auto.Contains("hot reloaded 3 time(s)") && auto.Contains("MaxHotReloads is 3") && auto.Contains("restart"), auto);
Check(!auto.Contains("by hand") && hand.Contains("(asked for by hand)"), hand);
}
}

View file

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the engine's side of the hot-reload cap (2026-10-11):
src\RynthCore.Engine\ReloadCapNotice.cs, compiled in. When the loader refuses a hot reload
(engine.json MaxHotReloads, default 3), the player hears about it in chat once, and again only
when they asked for the reload by hand (RL, /rc rl) within the last 10 s; the chat line is the
plain sentence agreed for it. The loader's own rule (refuse once reloads >= cap, negative = no
cap; nothing staged on a refusal) is checked in tools\LoaderReloadCapTests (C).
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>ReloadCapTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\ReloadCapNotice.cs" Link="Engine\ReloadCapNotice.cs" />
</ItemGroup>
</Project>

View file

@ -32,6 +32,7 @@ internal static class Program
RaiseCommand();
StatusFileReads();
MoveProtocol();
LogRollover();
if (Arg(args, "--atlas") is { } atlas) RealAtlas(atlas);
if (portal != null) RealSpellTable(portal);
if (cell != null) RealWorldMap(cell, outFile);
@ -41,6 +42,33 @@ internal static class Program
return _failed == 0 ? 0 : 1;
}
// ── log rollover ────────────────────────────────────────────────────────
private static void LogRollover()
{
Section("StatusAgent.log rolls over past its cap");
string dir = Path.Combine(Path.GetTempPath(), "sa-logroll-" + Environment.ProcessId);
Directory.CreateDirectory(dir);
try
{
string f = Path.Combine(dir, "StatusAgent.log");
File.WriteAllText(f, new string('x', 2000));
File.WriteAllText(f + ".old", "older");
AgentLog.RollIfBig(f, maxBytes: 1000);
Check(!File.Exists(f), "the first write checks at once (a big log from before starts over)");
Check(File.Exists(f + ".old") && new FileInfo(f + ".old").Length == 2000, "to .old, replacing the older copy");
File.WriteAllText(f, new string('y', 3000));
for (int i = 0; i < 199; i++) AgentLog.RollIfBig(f, maxBytes: 1000);
Check(File.Exists(f), "then only every 200th write checks the size");
AgentLog.RollIfBig(f, maxBytes: 1000);
Check(!File.Exists(f) && new FileInfo(f + ".old").Length == 3000, "the 200th rolls it over");
File.WriteAllText(f, "small");
for (int i = 0; i < 400; i++) AgentLog.RollIfBig(f, maxBytes: 1000);
Check(File.Exists(f), "under the cap it stays");
}
finally { try { Directory.Delete(dir, true); } catch { } }
}
// ── landblocks ──────────────────────────────────────────────────────────
private static void Landblocks()

View file

@ -173,6 +173,9 @@ def main():
# 8a. the 3D view's element class (Compatibility/AcMouseOver.cs)
smartbox = [t for t in tables if at(u32(t + 0x98), 6) == bytes([0xB8, 0x30, 0x00, 0x00, 0x10, 0xC3])]
check(len(smartbox) == 1, f"UIElement_SmartBoxWrapper: one UIElement vtable whose GetUIElementType returns 0x10000030 ({len(smartbox)})")
# gmSmartBoxUI: what AC actually reports over open ground (element 0x1000049A)
gmsbox = [t for t in tables if at(u32(t + 0x98), 6) == bytes([0xB8, 0x14, 0x00, 0x00, 0x10, 0xC3])]
check(len(gmsbox) == 1, f"gmSmartBoxUI: one UIElement vtable whose GetUIElementType returns 0x10000014 ({len(gmsbox)})")
# 8. AC's mouse-over element (Compatibility/AcMouseOver.cs): UIElementManager +0x244
switch = find([0x53, 0x8B, 0x5C, 0x24, 0x08, 0x56, 0x8B, 0xF1, 0x8B, 0x86, 0x44, 0x02, 0x00, 0x00, 0x57, 0x33, 0xFF,
@ -215,6 +218,9 @@ def main():
check("MgrMouseOver = 0x244" in mo and "MgrMouseOutside = 0x2D4" in mo and "VtGetUIElementType = 0x98" in mo,
"AcMouseOver.cs reads +0x244, +0x2D4 and vtable +0x98")
check("UIElementTypeSmartBoxWrapper = 0x10000030" in rules, "AcMouseOverRules.cs: the 3D view is type 0x10000030")
check("UIElementTypeGmSmartBoxUI = 0x10000014" in rules, "AcMouseOverRules.cs: gmSmartBoxUI (0x10000014) is the 3D view too")
check(len(matches(W, [0x68, 0x14, 0x00, 0x00, 0x10], limit=8)) >= 1,
"push 10000014h present (gmSmartBoxUI::Register registers the type)")
print("=" * 60)
print("PASS - the UI hooks' facts hold on this client." if fails == 0 else f"FAIL - {fails} check(s) failed.")