feat(engine): SK engine and UI work through 2026-10-10 on 2026.10.12.1

See Changelog/2026-10-11-sk-engine-work-through-10-10.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
BlankenshipG 2026-10-12 01:06:53 -04:00
commit c9743a2612
80 changed files with 6312 additions and 366 deletions

View file

@ -0,0 +1,90 @@
# SK engine and UI work through 2026-10-10, rebased on 2026.10.12.1
Replaces the closed per-feature PRs RynthCore #1-#5 and the earlier `sk` commits. This commit
carries everything from those PRs that main doesn't already have, merged onto release 2026.10.12.1
with the conflicts resolved. Work from 2026-10-11 follows in separate commits.
Nothing here changes what 2026.10.12.1 already does unless a setting below says so.
## Merge notes for 2026.10.12.1
- **API v81:** 2026.10.12.1 took v80 for `GetContainerOrder` and `PutItemInContainer`, so
`GetMergeStackResult` moves to v81, after them (engine table, SDK table,
`RynthCoreSdkApiVersion`, `HasGetMergeStackResult`, and the manifest test's slot order).
Plugins built against the earlier SK SDK must be rebuilt.
- **Chat routing:** `ChatRouter` now lives in `UI/Data/ChatRouting.cs`. The standard-filter step
(`RynthChatPresets`) is added there instead of in `ChatData.cs`.
- **Settings:** `LoggingLevel` and `EnablePluginOverlayWindows` sit next to the new
`CloseOnServerDisconnect`; the Items payload keeps both `missingIds` and `autoEquipShield`.
## Launcher and logging
- **Logging level** in the launcher (Error, Warning, Info, Debug, Trace), saved as `LoggingLevel`
in `engine.json`. The engine reads it at start and watches it while running
(`LogSettings`, `LoggingSettingsStore`, `MainWindow.Logging`). Per-category trace switches are
shown with a warning when a category is hidden by the level.
- The heartbeat line is always written, whatever the level, because the launcher uses it to tell
a client is alive (`RynthLog.Heartbeat`).
- `RynthCore.DesktopLog` (new project): rolling launcher log and the .NET desktop x64 prerequisite
check, with host diagnostics in the launcher (`LauncherHostDiagnostics`).
- Install-aware paths: the launcher, injector, loader and status agent find the install folder the
installer recorded (`InstallerHandoff`, `LogPaths`) instead of assuming `C:\Games\RynthCore`.
## Plugin windows and ImGui
- **Plugin overlay windows** while the ImGui shell is off: a plugin that exports
`RynthPluginRenderOverlay` draws its extra ImGui windows over the Avalonia UI.
`engine.json` `"EnablePluginOverlayWindows": false` turns this off. Plugins get the engine's
ImGui context for these windows.
- ImGui draw data is submitted after the Avalonia blit, so ImGui windows stay on top.
- Panel windows are destroyed on the thread that owns them, and a login pop-out waits until the
game window is hooked.
- Docked panels open clear of popped-out windows (`LayeredWindow`).
- `CS0162` (unreachable code) is an error in the engine project: a misplaced statement after a
`return` once left the plugin render snapshot unpublished.
## Items, drag and drop, object data
- **Item drag bridge** (`ItemDragBridge`, `DragDropHooks`): items dragged from the game or from a
popped-out Inventory can be dropped on Mini Remote slots. Game-inventory drags carry the dragged
item, not the previous selection.
- Object name and type are seeded when the object is created, so panels show them before the
first update (`CreateObjectHooks`, `DeleteObjectHooks`).
- Off-thread int property reads are snapshotted from the PWD and kept current with server
updates (`ClientObjectHooks`); IconOverlay and IconUnderlay DIDs are served from the PWD.
- **Merge-stack results** (API v81, `GetMergeStackResult`, after rynth's v80 slots): plugins can see whether a stack merge
went through (`MergeStackResults`). The thunk is cdecl; stdcall corrupted plugin stacks.
## Native crash logging
- `SehTrampoline.c`: the native crash logger records only fatal faults by default, and logs
access violations in the CoreCLR-hosted engine immediately rather than at exit.
## Panels
- **Nav:** route editing in the Nav panel, Breadcrumbs and Route overlay toggles,
and the waypoint list no longer jumps back to the top on every poll.
- **Skills > Progression tab:** XP and augmentation planning laid out like UB's ILT Tools XP and
Augs tabs, an attribute raiser, and per-server augmentation cost settings
(`ProgressionData`). The Char launcher has a menu that opens it.
- **Chat filters:** UB-IT-style standard filters, plain-text custom rule modes, a line tester, and
presets (`RynthChatPresets`).
- **RynthAi dashboard:** Char and Hub launcher buttons, Map and Lua buttons, a Mini Remote drawer,
a Buffs picker in Loaded Files and a Spells window button.
- **Items panel (Avalonia):** Shields section and Add Selected Shield.
- **Inventory:** a menu item that adds an item to RynthAi's item count HUD.
- **Settings:** Charms Tracking tab, an Inventory HUDs button, the Server Features text row, and
one "Describe Items When Selected" toggle (the duplicate "Item Info On Select" row is removed).
- **Loot:** "Include T11 attributes" in the Add to loot profile popup, with a tooltip that covers
the stamped tier and gear grade.
## Build
- `RynthCore.sln` includes `RynthCore.DesktopLog`.
- One `Tmds.DBus.Protocol` 0.21.3 pin in the engine project (GHSA-xrw6-gwf8-vvr9).
## Testing
- Engine (CoreCLR host) and launcher build in Release.
- `tools/PluginManifestTests` pass.
- Each feature was run in game on the SK builds of 2026-10-04 to 2026-10-10.

View file

@ -7,6 +7,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Engine", "src\Ryn
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Injector", "src\RynthCore.Injector\RynthCore.Injector.csproj", "{A1B2C3D4-0002-0002-0002-000000000002}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Injector", "src\RynthCore.Injector\RynthCore.Injector.csproj", "{A1B2C3D4-0002-0002-0002-000000000002}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.DesktopLog", "src\RynthCore.DesktopLog\RynthCore.DesktopLog.csproj", "{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Loader", "src\RynthCore.Loader\RynthCore.Loader.csproj", "{A1B2C3D4-0006-0006-0006-000000000006}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Loader", "src\RynthCore.Loader\RynthCore.Loader.csproj", "{A1B2C3D4-0006-0006-0006-000000000006}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
@ -63,6 +65,18 @@ Global
{A1B2C3D4-0002-0002-0002-000000000002}.Release|Any CPU.Build.0 = Release|Any CPU {A1B2C3D4-0002-0002-0002-000000000002}.Release|Any CPU.Build.0 = Release|Any CPU
{A1B2C3D4-0002-0002-0002-000000000002}.Release|x64.ActiveCfg = Release|Any CPU {A1B2C3D4-0002-0002-0002-000000000002}.Release|x64.ActiveCfg = Release|Any CPU
{A1B2C3D4-0002-0002-0002-000000000002}.Release|x64.Build.0 = Release|Any CPU {A1B2C3D4-0002-0002-0002-000000000002}.Release|x64.Build.0 = Release|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x86.ActiveCfg = Debug|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x86.Build.0 = Debug|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x64.ActiveCfg = Debug|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Debug|x64.Build.0 = Debug|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x86.ActiveCfg = Release|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x86.Build.0 = Release|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|Any CPU.Build.0 = Release|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x64.ActiveCfg = Release|Any CPU
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB}.Release|x64.Build.0 = Release|Any CPU
{A1B2C3D4-0006-0006-0006-000000000006}.Debug|x86.ActiveCfg = Debug|x86 {A1B2C3D4-0006-0006-0006-000000000006}.Debug|x86.ActiveCfg = Debug|x86
{A1B2C3D4-0006-0006-0006-000000000006}.Debug|x86.Build.0 = Debug|x86 {A1B2C3D4-0006-0006-0006-000000000006}.Debug|x86.Build.0 = Debug|x86
{A1B2C3D4-0006-0006-0006-000000000006}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A1B2C3D4-0006-0006-0006-000000000006}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
@ -179,6 +193,7 @@ Global
{2B283E05-12BB-45F9-B8E5-8F53C1FAB737} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {2B283E05-12BB-45F9-B8E5-8F53C1FAB737} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{BB0C5CB5-6C75-4C17-9348-5CA0C481B65C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {BB0C5CB5-6C75-4C17-9348-5CA0C481B65C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{A72E31D3-5D91-4C39-A30C-A96A492BBE82} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {A72E31D3-5D91-4C39-A30C-A96A492BBE82} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{D1E2F3A4-5678-4ABC-8DEF-1234567890AB} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{C1A2B3D4-0007-0007-0007-000000000007} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {C1A2B3D4-0007-0007-0007-000000000007} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{C1A2B3D4-0008-0008-0008-000000000008} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89} {C1A2B3D4-0008-0008-0008-000000000008} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89}
{C1A2B3D4-0009-0009-0009-000000000009} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89} {C1A2B3D4-0009-0009-0009-000000000009} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89}

View file

@ -26,12 +26,36 @@
#define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
#include <windows.h> #include <windows.h>
/* File version of this native module (bump with every behavioural change). */
#define RC_SEH_TRAMPOLINE_VERSION 3 /* v3: CoreCLR-hosted engine AVs logged immediately */
/* Crash-logger state that the SEH_* wrappers and DllMain also touch (defined below). */
static __declspec(thread) int t_sehDepth; /* >0 while inside an SEH_* wrapper call */
static void CrashLoggerFlushOnExit(void);
/* Every SEH_* wrapper brackets its guarded call with these so the crash logger knows an
* access violation on this thread is about to be caught by our own __except. */
#define RC_SEH_ENTER() (++t_sehDepth)
#define RC_SEH_LEAVE() (--t_sehDepth)
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason, LPVOID lpReserved) BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason, LPVOID lpReserved)
{ {
(void)hModule; (void)ul_reason; (void)lpReserved; (void)hModule;
/* lpReserved != NULL on DLL_PROCESS_DETACH means the process is exiting (ExitProcess),
* which is how AC's own crash handling ends the process: write out any recent
* first-chance AVs so a crash AC swallowed still leaves a trace. */
if (ul_reason == DLL_PROCESS_DETACH && lpReserved != NULL) {
CrashLoggerFlushOnExit();
}
return TRUE; return TRUE;
} }
/* Diagnostic: native module version so the engine log can confirm which build is loaded. */
__declspec(dllexport) unsigned int __cdecl RC_SehTrampolineVersion(void)
{
return RC_SEH_TRAMPOLINE_VERSION;
}
/* ── Cdecl helpers ─────────────────────────────────────────────────────── */ /* ── Cdecl helpers ─────────────────────────────────────────────────────── */
/* void* __cdecl fn(unsigned int id) — e.g. GetWeenieObject */ /* void* __cdecl fn(unsigned int id) — e.g. GetWeenieObject */
@ -40,14 +64,17 @@ __declspec(dllexport) int __cdecl
SEH_CdeclPtrUint(Fn_CdeclPtrUint fn, unsigned int arg, void** out_result) SEH_CdeclPtrUint(Fn_CdeclPtrUint fn, unsigned int arg, void** out_result)
{ {
*out_result = NULL; *out_result = NULL;
RC_SEH_ENTER();
__try { __try {
*out_result = fn(arg); *out_result = fn(arg);
} }
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
*out_result = NULL; *out_result = NULL;
return 0; return 0;
} }
RC_SEH_LEAVE();
return 1; return 1;
} }
@ -57,14 +84,17 @@ __declspec(dllexport) int __cdecl
SEH_CdeclPtrVoid(Fn_CdeclPtrVoid fn, void** out_result) SEH_CdeclPtrVoid(Fn_CdeclPtrVoid fn, void** out_result)
{ {
*out_result = NULL; *out_result = NULL;
RC_SEH_ENTER();
__try { __try {
*out_result = fn(); *out_result = fn();
} }
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
*out_result = NULL; *out_result = NULL;
return 0; return 0;
} }
RC_SEH_LEAVE();
return 1; return 1;
} }
@ -73,13 +103,16 @@ typedef void (__cdecl *Fn_CdeclVoidUintByte)(unsigned int, unsigned char);
__declspec(dllexport) int __cdecl __declspec(dllexport) int __cdecl
SEH_CdeclVoidUintByte(Fn_CdeclVoidUintByte fn, unsigned int arg1, unsigned char arg2) SEH_CdeclVoidUintByte(Fn_CdeclVoidUintByte fn, unsigned int arg1, unsigned char arg2)
{ {
RC_SEH_ENTER();
__try { __try {
fn(arg1, arg2); fn(arg1, arg2);
} }
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
return 0; return 0;
} }
RC_SEH_LEAVE();
return 1; return 1;
} }
@ -95,13 +128,16 @@ typedef void (__fastcall *Fn_FreeHandsCast)(void* ecx, void* edx, unsigned int s
__declspec(dllexport) int __cdecl __declspec(dllexport) int __cdecl
SEH_FreeHandsCast(void* fn, void* this_ptr, unsigned int spellId, unsigned int targetId) SEH_FreeHandsCast(void* fn, void* this_ptr, unsigned int spellId, unsigned int targetId)
{ {
RC_SEH_ENTER();
__try { __try {
((Fn_FreeHandsCast)fn)(this_ptr, 0, spellId, targetId); ((Fn_FreeHandsCast)fn)(this_ptr, 0, spellId, targetId);
} }
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
return 0; return 0;
} }
RC_SEH_LEAVE();
return 1; return 1;
} }
@ -152,14 +188,17 @@ SEH_ThiscallByteUint(void* fn, void* this_ptr, unsigned int arg,
unsigned char* out_result) unsigned char* out_result)
{ {
*out_result = 0; *out_result = 0;
RC_SEH_ENTER();
__try { __try {
*out_result = _helper_thiscall_byte_uint(fn, this_ptr, arg); *out_result = _helper_thiscall_byte_uint(fn, this_ptr, arg);
} }
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
*out_result = 0; *out_result = 0;
return 0; return 0;
} }
RC_SEH_LEAVE();
return 1; return 1;
} }
@ -171,14 +210,17 @@ __declspec(dllexport) int __cdecl
SEH_ThiscallUintNoArg(void* fn, void* this_ptr, unsigned int* out_result) SEH_ThiscallUintNoArg(void* fn, void* this_ptr, unsigned int* out_result)
{ {
*out_result = 0; *out_result = 0;
RC_SEH_ENTER();
__try { __try {
*out_result = _helper_thiscall_uint_noarg(fn, this_ptr); *out_result = _helper_thiscall_uint_noarg(fn, this_ptr);
} }
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
*out_result = 0; *out_result = 0;
return 0; return 0;
} }
RC_SEH_LEAVE();
return 1; return 1;
} }
@ -209,179 +251,480 @@ SEH_ThiscallIntUintPtr(void* fn, void* this_ptr, unsigned int arg1, void* arg2,
int* out_result) int* out_result)
{ {
*out_result = 0; *out_result = 0;
RC_SEH_ENTER();
__try { __try {
*out_result = _helper_thiscall_int_uint_ptr(fn, this_ptr, arg1, arg2); *out_result = _helper_thiscall_int_uint_ptr(fn, this_ptr, arg1, arg2);
} }
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
*out_result = 0; *out_result = 0;
return 0; return 0;
} }
RC_SEH_LEAVE();
return 1; return 1;
} }
/* ── Process-wide native crash logger (VEH) ─────────────────────────────── /* ── Process-wide native crash logger (fatal-only, v2) ────────────────────
* Logs the faulting 32-bit context + a module-resolved stack sweep to a * Goal: native-crash.log holds FATAL crashes only. v1 logged every first-chance AV
* dedicated file BEFORE the process dies, for the fatal exceptions that bypass * (including ones AC or our own SEH_* wrappers handle) plus its own stack-sweep faults,
* NativeAOT's managed handlers: 0xC0000005 (AV / corrupted-state) and * so its 24-entry cap filled with noise before a real crash could be recorded.
* 0xC0000602 (STATUS_FAIL_FAST from RaiseFailFastException — e.g. an unhandled
* managed exception or a stack-walk fail-fast in the plugin/engine).
* *
* This is PURE NATIVE: no managed callback / reverse-P/Invoke transition, so * All paths are PURE NATIVE (no managed callback / reverse-P/Invoke — that could itself
* unlike the removed managed CrashLogger VEH it cannot itself re-trigger a * trigger a NativeAOT fail-fast on an AC-owned thread) and observe-only: they always
* NativeAOT fail-fast on an AC-owned thread. It only OBSERVES — returns * return EXCEPTION_CONTINUE_SEARCH or chain, so AC's SEH and the runtime proceed exactly
* EXCEPTION_CONTINUE_SEARCH so AC's own SEH / the runtime still proceed exactly * as before. Only kernel32 APIs + hand-rolled, bounds-checked formatting (no CRT stdio).
* as before. Uses only kernel32 APIs + hand-rolled formatting (no CRT stdio / *
* user32) so the build link line stays unchanged. Hardened: stack sweep in * 1. Unhandled-exception filter (SetUnhandledExceptionFilter, chained to the previous
* __try/__except, capped log count, dedicated file (no contention with the * filter): an exception nobody handled is written immediately as FATAL.
* managed log). x86 (32-bit) context fields only — matches the WOW64 target. * 2. First-chance VEH, immediate: AVs whose faulting address is inside a NativeAOT
* module (engine / plugins). The runtime fail-fasts on those via
* RaiseFailFastException, which bypasses every handler including the filter in (1),
* so first chance is the only chance to record them. 0xC0000602 / 0xC0000409 too.
* 2b. (v3) Same for the CoreCLR-hosted engine (RynthCore.Shim): non-null AVs in JIT'd
* code (private executable memory, no module), coreclr.dll / clrjit.dll, or the
* framework's precompiled System.* / Microsoft.* images. CoreCLR treats a non-null
* AV in managed code as uncatchable and fail-fasts with HandleFatalError (the WER
* signature coreclr.dll+0x2c1c6e c0000005 is that fail-fast site, not the bug), so
* the deferred ring below was never flushed and native-crash.log stayed empty. AVs
* with a data address under 64K are skipped there: CoreCLR turns those into a
* catchable NullReferenceException.
* 3. First-chance VEH, deferred: every other AV (acclient.exe, drivers, DINPUT8, …) is
* formatted into an in-memory ring and written ONLY if the process then dies — via
* the filter in (1), or at ExitProcess (DllMain detach) when it happened within the
* last CL_EXIT_FLUSH_WINDOW_MS (AC's own crash handling ends with ExitProcess).
* AVs that AC handles and survives never reach the file.
*
* Skipped entirely: AVs raised inside our own SEH_* wrappers (t_sehDepth > 0 — our
* __except catches them) and any fault raised while the logger itself is running on
* that thread (t_inLogger — v1 logged its own sweep faults as SehTrampoline.dll+0x13E8).
*
* The stack sweep is bounded to [Esp, NtCurrentTeb()->NtTib.StackBase); v1 read 4096
* slots past ESP unconditionally and ran off the top of the stack.
* x86 (32-bit) context fields only — matches the WOW64 target.
*/ */
#define CL_SLOT_BYTES 8192 /* one formatted record */
#define CL_RING_SLOTS 8 /* deferred first-chance records kept in memory */
#define CL_MAX_IMMEDIATE 16 /* NativeAOT-module / fail-fast records per run */
#define CL_MAX_FATAL 8 /* unhandled-exception records per run */
#define CL_MAX_SWEEP_SLOTS 4096 /* stack slots scanned (also capped by StackBase) */
#define CL_MAX_SWEEP_LINES 96 /* code pointers emitted per record */
#define CL_EXIT_FLUSH_WINDOW_MS 30000 /* deferred AVs this recent are flushed at exit */
#define CL_SLOT_EMPTY 0
#define CL_SLOT_WRITING 1
#define CL_SLOT_PENDING 2 /* deferred first-chance AV, not in the file (yet) */
#define CL_SLOT_DONE 3 /* written to the file, or discarded */
typedef struct {
volatile LONG state;
DWORD tid;
DWORD tick;
unsigned int exAddr;
int len;
char text[CL_SLOT_BYTES];
} CL_SLOT;
static wchar_t g_crashLogPath[MAX_PATH]; static wchar_t g_crashLogPath[MAX_PATH];
static volatile LONG g_crashCount = 0; static PVOID g_vehHandle = NULL;
static PVOID g_vehHandle = NULL; static CL_SLOT g_ring[CL_RING_SLOTS];
static volatile LONG g_ringNext = 0;
static volatile LONG g_immediateCount = 0;
static volatile LONG g_fatalCount = 0;
static LPTOP_LEVEL_EXCEPTION_FILTER g_prevFilter = NULL;
static __declspec(thread) int t_inLogger; /* logger running on this thread */
static __declspec(thread) int t_inUef; /* filter running (guards chain cycles) */
static char* cl_str(char* p, const char* s) { while (*s) { *p++ = *s++; } return p; } /* ── Bounds-checked text writer ── */
typedef struct { char* p; char* end; } CL_W;
static char* cl_hex(char* p, unsigned int v) static void cl_str(CL_W* w, const char* s)
{
while (*s && w->p < w->end) { *w->p++ = *s++; }
}
static void cl_hex(CL_W* w, unsigned int v)
{ {
const char* H = "0123456789ABCDEF"; const char* H = "0123456789ABCDEF";
int i; int i;
*p++ = '0'; *p++ = 'x'; cl_str(w, "0x");
for (i = 28; i >= 0; i -= 4) { *p++ = H[(v >> i) & 0xF]; } for (i = 28; i >= 0 && w->p < w->end; i -= 4) { *w->p++ = H[(v >> i) & 0xF]; }
return p;
} }
static char* cl_u(char* p, unsigned int v) static void cl_u(CL_W* w, unsigned int v)
{ {
char tmp[12]; int n = 0; char tmp[12]; int n = 0;
if (v == 0) { *p++ = '0'; return p; } if (v == 0) { cl_str(w, "0"); return; }
while (v) { tmp[n++] = (char)('0' + (v % 10)); v /= 10; } while (v) { tmp[n++] = (char)('0' + (v % 10)); v /= 10; }
while (n) { *p++ = tmp[--n]; } while (n && w->p < w->end) { *w->p++ = tmp[--n]; }
return p; }
/* Leaf file name of a loaded module, as narrow ASCII (lower-cased when lower != 0). */
static int cl_module_leaf(HMODULE hm, char* out, int cap, int lower)
{
wchar_t wpath[MAX_PATH];
DWORD n = GetModuleFileNameW(hm, wpath, MAX_PATH);
DWORD i, leaf = 0;
int k = 0;
for (i = 0; i < n; i++) { if (wpath[i] == L'\\' || wpath[i] == L'/') { leaf = i + 1; } }
for (i = leaf; i < n && k < cap - 1; i++) {
char ch = (char)wpath[i];
if (lower && ch >= 'A' && ch <= 'Z') { ch = (char)(ch - 'A' + 'a'); }
out[k++] = ch;
}
out[k] = 0;
return k;
} }
/* Append "module.dll+0xRVA", or "0xADDR" if the address is in no module. */ /* Append "module.dll+0xRVA", or "0xADDR" if the address is in no module. */
static char* cl_sym(char* p, unsigned int addr) static void cl_sym(CL_W* w, unsigned int addr)
{ {
HMODULE hm = NULL; HMODULE hm = NULL;
/* GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS(0x4) | UNCHANGED_REFCOUNT(0x2) */ /* GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS(0x4) | UNCHANGED_REFCOUNT(0x2) */
if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) && hm) { if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) && hm) {
wchar_t wpath[MAX_PATH]; char leaf[MAX_PATH];
DWORD n = GetModuleFileNameW(hm, wpath, MAX_PATH); cl_module_leaf(hm, leaf, MAX_PATH, 0);
DWORD i, leaf = 0; cl_str(w, leaf);
for (i = 0; i < n; i++) { if (wpath[i] == L'\\' || wpath[i] == L'/') leaf = i + 1; } cl_str(w, "+");
for (i = leaf; i < n; i++) { *p++ = (char)wpath[i]; } cl_hex(w, addr - (unsigned int)(UINT_PTR)hm);
p = cl_str(p, "+");
p = cl_hex(p, addr - (unsigned int)(UINT_PTR)hm);
} else { } else {
p = cl_hex(p, addr); cl_hex(w, addr);
} }
return p;
} }
static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) static int cl_starts_with(const char* s, const char* prefix)
{ {
while (*prefix) { if (*s++ != *prefix++) { return 0; } }
return 1;
}
/* ── NativeAOT module detection (cached per module base) ── */
#define CL_MOD_CACHE 16
static volatile UINT_PTR g_modBase[CL_MOD_CACHE];
static volatile LONG g_modManaged[CL_MOD_CACHE];
static volatile LONG g_modNext = 0;
/* True when addr lies in a NativeAOT image (engine / plugin). NativeAOT images export
* DotNetRuntimeDebugHeader; RynthCore.* names are a fallback (minus our native DLLs). */
static int cl_is_nativeaot_address(unsigned int addr)
{
HMODULE hm = NULL;
int i, managed;
if (!GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) || !hm) { return 0; }
for (i = 0; i < CL_MOD_CACHE; i++) {
if (g_modBase[i] == (UINT_PTR)hm) { return (int)g_modManaged[i]; }
}
managed = GetProcAddress(hm, "DotNetRuntimeDebugHeader") != NULL;
if (!managed) {
char leaf[MAX_PATH];
cl_module_leaf(hm, leaf, MAX_PATH, 1);
managed = cl_starts_with(leaf, "rynthcore.")
&& !cl_starts_with(leaf, "rynthcore.sehtrampoline")
&& !cl_starts_with(leaf, "rynthcore.cimgui");
}
/* Benign race: base is cleared first and published last, so a concurrent reader
* either misses the entry (and recomputes) or sees a matching flag. */
i = (int)((unsigned int)InterlockedIncrement(&g_modNext) % CL_MOD_CACHE);
g_modBase[i] = 0;
g_modManaged[i] = managed;
g_modBase[i] = (UINT_PTR)hm;
return managed;
}
/* True when addr is code of the CoreCLR-hosted engine: JIT'd code (committed private
* executable memory outside any module), the runtime itself (coreclr.dll, clrjit.dll),
* or a precompiled framework image (System.* / Microsoft.*, e.g. Marshal.ReadIntPtr in
* System.Private.CoreLib.dll). Not cached: the JIT path has no module base to key on,
* and VirtualQuery is cheap next to formatting a record. */
static int cl_is_coreclr_address(unsigned int addr)
{
HMODULE hm = NULL;
if (!GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) || !hm) {
MEMORY_BASIC_INFORMATION mbi;
if (VirtualQuery((LPCVOID)(UINT_PTR)addr, &mbi, sizeof(mbi)) == 0) { return 0; }
return mbi.State == MEM_COMMIT && mbi.Type == MEM_PRIVATE
&& (mbi.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE
| PAGE_EXECUTE_WRITECOPY)) != 0;
}
{
char leaf[MAX_PATH];
cl_module_leaf(hm, leaf, MAX_PATH, 1);
return cl_starts_with(leaf, "coreclr.dll")
|| cl_starts_with(leaf, "clrjit.dll")
|| cl_starts_with(leaf, "system.")
|| cl_starts_with(leaf, "microsoft.");
}
}
/* ── Record formatting ── */
/* Formats one crash record (header, registers, bounded stack sweep) into buf.
* Returns the byte count. Reads of stack memory are guarded by __try. */
static int cl_format(char* buf, int cap, PEXCEPTION_POINTERS ep, const char* banner)
{
CL_W w;
CONTEXT* c = ep->ContextRecord;
DWORD code = ep->ExceptionRecord->ExceptionCode; DWORD code = ep->ExceptionRecord->ExceptionCode;
if (code != 0xC0000005 && code != 0xC0000602 && code != 0xC0000409) { unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress;
return EXCEPTION_CONTINUE_SEARCH;
w.p = buf;
w.end = buf + cap - 64; /* reserve room for the END line */
cl_str(&w, "\r\n==== NATIVE CRASH LOGGER: ");
cl_str(&w, banner);
cl_str(&w, " ====\r\n code=");
cl_hex(&w, code);
cl_str(&w, " exAddr=");
cl_sym(&w, exAddr);
cl_str(&w, " tid=");
cl_u(&w, GetCurrentThreadId());
{
SYSTEMTIME st; GetLocalTime(&st);
cl_str(&w, " time=");
cl_u(&w, st.wHour); cl_str(&w, ":");
if (st.wMinute < 10) { cl_str(&w, "0"); } cl_u(&w, st.wMinute); cl_str(&w, ":");
if (st.wSecond < 10) { cl_str(&w, "0"); } cl_u(&w, st.wSecond);
} }
if (InterlockedIncrement(&g_crashCount) > 24) { if ((code == 0xC0000005 || code == 0xC0000409) && ep->ExceptionRecord->NumberParameters >= 2) {
return EXCEPTION_CONTINUE_SEARCH; unsigned int acc = (unsigned int)ep->ExceptionRecord->ExceptionInformation[0];
unsigned int dataAddr = (unsigned int)ep->ExceptionRecord->ExceptionInformation[1];
cl_str(&w, " access=");
cl_str(&w, acc == 1 ? "WRITE" : (acc == 8 ? "EXEC" : "READ"));
cl_str(&w, " dataAddr=");
cl_hex(&w, dataAddr); /* the [null+X] value, e.g. 0xC for the parser race */
} }
cl_str(&w, "\r\n eip="); cl_sym(&w, c->Eip);
cl_str(&w, " esp="); cl_hex(&w, c->Esp);
cl_str(&w, " ebp="); cl_hex(&w, c->Ebp);
cl_str(&w, "\r\n eax="); cl_hex(&w, c->Eax);
cl_str(&w, " ebx="); cl_hex(&w, c->Ebx);
cl_str(&w, " ecx="); cl_hex(&w, c->Ecx);
cl_str(&w, " edx="); cl_hex(&w, c->Edx);
cl_str(&w, " esi="); cl_hex(&w, c->Esi);
cl_str(&w, " edi="); cl_hex(&w, c->Edi);
cl_str(&w, "\r\n stack code pointers (esp -> StackBase):\r\n");
{ {
HANDLE h = CreateFileW(g_crashLogPath, FILE_APPEND_DATA, /* The handler runs on the faulting thread, so this TEB's stack bounds apply to
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, * the faulting ESP. Never read at or past StackBase (top of the stack). */
FILE_ATTRIBUTE_NORMAL, NULL); NT_TIB* tib = (NT_TIB*)NtCurrentTeb();
if (h == INVALID_HANDLE_VALUE) { return EXCEPTION_CONTINUE_SEARCH; } UINT_PTR base = (UINT_PTR)tib->StackBase;
SetFilePointer(h, 0, NULL, FILE_END); UINT_PTR limit = (UINT_PTR)tib->StackLimit;
UINT_PTR esp = (UINT_PTR)c->Esp;
{
char buf[4096];
char* p = buf;
CONTEXT* c = ep->ContextRecord;
unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress;
DWORD wr;
p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER (SEH VEH) ====\r\n code=");
p = cl_hex(p, code);
p = cl_str(p, " exAddr=");
p = cl_sym(p, exAddr);
p = cl_str(p, " tid=");
p = cl_u(p, GetCurrentThreadId());
{
SYSTEMTIME st; GetLocalTime(&st);
p = cl_str(p, " time=");
p = cl_u(p, st.wHour); p = cl_str(p, ":");
if (st.wMinute < 10) { p = cl_str(p, "0"); } p = cl_u(p, st.wMinute); p = cl_str(p, ":");
if (st.wSecond < 10) { p = cl_str(p, "0"); } p = cl_u(p, st.wSecond);
}
if ((code == 0xC0000005 || code == 0xC0000409) && ep->ExceptionRecord->NumberParameters >= 2) {
unsigned int acc = (unsigned int)ep->ExceptionRecord->ExceptionInformation[0];
unsigned int dataAddr = (unsigned int)ep->ExceptionRecord->ExceptionInformation[1];
p = cl_str(p, " access=");
p = cl_str(p, acc == 1 ? "WRITE" : (acc == 8 ? "EXEC" : "READ"));
p = cl_str(p, " dataAddr=");
p = cl_hex(p, dataAddr); /* the [null+X] value, e.g. 0xC for the parser race */
}
p = cl_str(p, "\r\n eip="); p = cl_sym(p, c->Eip);
p = cl_str(p, " esp="); p = cl_hex(p, c->Esp);
p = cl_str(p, " ebp="); p = cl_hex(p, c->Ebp);
p = cl_str(p, "\r\n eax="); p = cl_hex(p, c->Eax);
p = cl_str(p, " ebx="); p = cl_hex(p, c->Ebx);
p = cl_str(p, " ecx="); p = cl_hex(p, c->Ecx);
p = cl_str(p, " edx="); p = cl_hex(p, c->Edx);
p = cl_str(p, " esi="); p = cl_hex(p, c->Esi);
p = cl_str(p, " edi="); p = cl_hex(p, c->Edi);
p = cl_str(p, "\r\n stack code pointers (esp -> up):\r\n");
WriteFile(h, buf, (DWORD)(p - buf), &wr, NULL);
if (esp < limit || esp >= base) {
cl_str(&w, " <esp outside this thread's stack; sweep skipped>\r\n");
} else {
unsigned int slots = (unsigned int)((base - esp) / sizeof(unsigned int));
if (slots > CL_MAX_SWEEP_SLOTS) { slots = CL_MAX_SWEEP_SLOTS; }
__try { __try {
unsigned int* sp = (unsigned int*)c->Esp; const unsigned int* sp = (const unsigned int*)esp;
int i, emitted = 0; unsigned int i;
for (i = 0; i < 4096 && emitted < 96; i++) { int emitted = 0;
/* 320 bytes of headroom = one full "+0xOFF module+0xRVA" line. */
for (i = 0; i < slots && emitted < CL_MAX_SWEEP_LINES && (w.end - w.p) > 320; i++) {
unsigned int v = sp[i]; unsigned int v = sp[i];
if (v > 0x00401000u && v < 0x7FFF0000u) { if (v > 0x00401000u && v < 0x7FFF0000u) {
HMODULE hm = NULL; HMODULE hm = NULL;
if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)v, &hm) && hm) { if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)v, &hm) && hm) {
char* q = buf; cl_str(&w, " +");
q = cl_str(q, " +"); cl_hex(&w, i * 4u);
q = cl_hex(q, (unsigned int)(i * 4)); cl_str(&w, " ");
q = cl_str(q, " "); cl_sym(&w, v);
q = cl_sym(q, v); cl_str(&w, "\r\n");
q = cl_str(q, "\r\n");
WriteFile(h, buf, (DWORD)(q - buf), &wr, NULL);
emitted++; emitted++;
} }
} }
} }
} }
__except (EXCEPTION_EXECUTE_HANDLER) { __except (EXCEPTION_EXECUTE_HANDLER) {
const char* m = " <stack sweep faulted>\r\n"; cl_str(&w, " <stack sweep faulted>\r\n");
WriteFile(h, m, (DWORD)lstrlenA(m), &wr, NULL);
}
{
const char* e = "==== END NATIVE CRASH ====\r\n";
WriteFile(h, e, (DWORD)lstrlenA(e), &wr, NULL);
} }
} }
CloseHandle(h);
} }
w.end = buf + cap;
cl_str(&w, "==== END NATIVE CRASH ====\r\n");
return (int)(w.p - buf);
}
/* ── Output ── */
static void cl_append_file(const char* data, int len)
{
HANDLE h;
DWORD wr;
if (len <= 0 || g_crashLogPath[0] == 0) { return; }
h = CreateFileW(g_crashLogPath, FILE_APPEND_DATA,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE) { return; }
SetFilePointer(h, 0, NULL, FILE_END);
WriteFile(h, data, (DWORD)len, &wr, NULL);
CloseHandle(h);
}
/* Claims a ring slot for writing. Rotates through the ring, overwriting the oldest
* PENDING/DONE record; never steals a slot another thread is mid-write on. */
static CL_SLOT* cl_claim_slot(void)
{
int tries;
for (tries = 0; tries < CL_RING_SLOTS * 2; tries++) {
CL_SLOT* s = &g_ring[(unsigned int)InterlockedIncrement(&g_ringNext) % CL_RING_SLOTS];
LONG st = s->state;
if (st != CL_SLOT_WRITING &&
InterlockedCompareExchange(&s->state, CL_SLOT_WRITING, st) == st) {
return s;
}
}
return NULL;
}
/* Writes PENDING deferred records to the file. Skips the record matching skipTid/skipAddr
* (the same fault the caller is about to log) and, when maxAgeMs != 0, records older
* than maxAgeMs (handled AVs from long before the exit). */
static void cl_flush_pending(DWORD skipTid, unsigned int skipAddr, DWORD maxAgeMs)
{
DWORD now = GetTickCount();
int i;
for (i = 0; i < CL_RING_SLOTS; i++) {
CL_SLOT* s = &g_ring[i];
if (InterlockedCompareExchange(&s->state, CL_SLOT_WRITING, CL_SLOT_PENDING) != CL_SLOT_PENDING) {
continue;
}
if ((skipTid != 0 && s->tid == skipTid && s->exAddr == skipAddr) ||
(maxAgeMs != 0 && now - s->tick > maxAgeMs)) {
InterlockedExchange(&s->state, CL_SLOT_DONE);
continue;
}
cl_append_file(s->text, s->len);
InterlockedExchange(&s->state, CL_SLOT_DONE);
}
}
/* ── Handlers ── */
static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep)
{
DWORD code = ep->ExceptionRecord->ExceptionCode;
unsigned int exAddr;
int immediate;
int coreclr = 0;
CL_SLOT* s;
if (code != 0xC0000005 && code != 0xC0000602 && code != 0xC0000409) {
return EXCEPTION_CONTINUE_SEARCH;
}
if (t_inLogger) {
return EXCEPTION_CONTINUE_SEARCH; /* our own fault — the logger's __try handles it */
}
if (code == 0xC0000005 && t_sehDepth > 0) {
return EXCEPTION_CONTINUE_SEARCH; /* an SEH_* wrapper's __except will catch it */
}
t_inLogger = 1;
exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress;
immediate = (code != 0xC0000005) || cl_is_nativeaot_address(exAddr);
if (!immediate) {
/* v3: CoreCLR-hosted engine. A data address under 64K is a null-ref that CoreCLR
* hands to managed code as NullReferenceException, so it stays deferred. */
unsigned int dataAddr = ep->ExceptionRecord->NumberParameters >= 2
? (unsigned int)ep->ExceptionRecord->ExceptionInformation[1] : 0;
coreclr = dataAddr >= 0x10000 && cl_is_coreclr_address(exAddr);
immediate = coreclr;
}
if (!immediate || InterlockedIncrement(&g_immediateCount) <= CL_MAX_IMMEDIATE) {
s = cl_claim_slot();
if (s) {
s->tid = GetCurrentThreadId();
s->tick = GetTickCount();
s->exAddr = exAddr;
s->len = cl_format(s->text, CL_SLOT_BYTES, ep,
code != 0xC0000005
? "FAIL-FAST / STACK CHECK (always fatal)"
: (coreclr
? "AV IN CORECLR-HOSTED CODE (JIT / runtime; fail-fast, non-null address)"
: immediate
? "AV IN NATIVEAOT CODE (runtime fail-fasts unless it is a null-ref)"
: "FIRST-CHANCE AV (deferred; written because the process died or exited soon after)"));
if (immediate) {
cl_append_file(s->text, s->len);
InterlockedExchange(&s->state, CL_SLOT_DONE);
} else {
InterlockedExchange(&s->state, CL_SLOT_PENDING);
}
}
}
t_inLogger = 0;
return EXCEPTION_CONTINUE_SEARCH; return EXCEPTION_CONTINUE_SEARCH;
} }
/* Install the VEH once. logPath = wide path to the dedicated crash log. */ /* Unhandled-exception filter: nobody caught this exception, so it is fatal. */
static LONG WINAPI CrashUef(PEXCEPTION_POINTERS ep)
{
LONG verdict = EXCEPTION_CONTINUE_SEARCH;
/* A replaced-then-reasserted filter chain can loop back here; bail out of the cycle. */
if (t_inUef) {
return EXCEPTION_CONTINUE_SEARCH;
}
t_inUef = 1;
if (!t_inLogger && InterlockedIncrement(&g_fatalCount) <= CL_MAX_FATAL) {
unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress;
CL_SLOT* s;
t_inLogger = 1;
/* Earlier first-chance AVs (other threads, earlier faults) are context for this
* crash; the first-chance record of THIS fault is skipped as a duplicate. Flushed
* before claiming a slot so the claim can't overwrite one of them. */
cl_flush_pending(GetCurrentThreadId(), exAddr, 0);
s = cl_claim_slot();
if (s) {
s->len = cl_format(s->text, CL_SLOT_BYTES, ep, "UNHANDLED EXCEPTION (fatal)");
cl_append_file(s->text, s->len);
InterlockedExchange(&s->state, CL_SLOT_DONE);
}
t_inLogger = 0;
}
if (g_prevFilter) {
verdict = g_prevFilter(ep);
}
t_inUef = 0;
return verdict;
}
/* DllMain (process exit): write deferred AVs from the last CL_EXIT_FLUSH_WINDOW_MS. */
static void CrashLoggerFlushOnExit(void)
{
if (g_crashLogPath[0] == 0) { return; }
cl_flush_pending(0, 0, CL_EXIT_FLUSH_WINDOW_MS);
}
/* Installs the VEH once and (re-)asserts the unhandled-exception filter.
* logPath = wide path to the dedicated crash log. Safe to call more than once:
* a later call re-installs the filter if AC or a runtime replaced it. */
__declspec(dllexport) void __cdecl __declspec(dllexport) void __cdecl
RC_InstallCrashLogger(const wchar_t* logPath) RC_InstallCrashLogger(const wchar_t* logPath)
{ {
if (g_vehHandle) { return; } LPTOP_LEVEL_EXCEPTION_FILTER prev;
if (logPath) { if (logPath) {
int i = 0; int i = 0;
for (; logPath[i] && i < MAX_PATH - 1; i++) { g_crashLogPath[i] = logPath[i]; } for (; logPath[i] && i < MAX_PATH - 1; i++) { g_crashLogPath[i] = logPath[i]; }
g_crashLogPath[i] = 0; g_crashLogPath[i] = 0;
} }
g_vehHandle = AddVectoredExceptionHandler(1, CrashVeh); if (!g_vehHandle) {
g_vehHandle = AddVectoredExceptionHandler(1, CrashVeh);
}
prev = SetUnhandledExceptionFilter(CrashUef);
if (prev != CrashUef) {
g_prevFilter = prev;
}
} }
/* ── Tagged-text parser guard (native MinHook detour body) ──────────────── /* ── Tagged-text parser guard (native MinHook detour body) ────────────────

View file

@ -1,6 +1,8 @@
using System;
using Avalonia; using Avalonia;
using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
using RynthCore;
namespace RynthCore.App.Avalonia; namespace RynthCore.App.Avalonia;
@ -13,6 +15,18 @@ public partial class App : Application
public override void OnFrameworkInitializationCompleted() public override void OnFrameworkInitializationCompleted()
{ {
try
{
string t = DateTime.Now.ToString("O");
DesktopRollingLog.AppendLine(DesktopRollingLog.StemLauncher,
$"[{t}] [pid:{Environment.ProcessId}] RynthCore.App.Avalonia started (launcher).");
// Detailed host + sidecar file layout (see LauncherHostDiagnostics) for runtime mis-detection triage.
LauncherHostDiagnostics.AppendDesktopLogBlock(t);
}
catch
{
}
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
desktop.MainWindow = new MainWindow(); desktop.MainWindow = new MainWindow();

View file

@ -120,4 +120,19 @@ internal static class EngineJsonStore
fields[field] = doc.RootElement.Clone(); fields[field] = doc.RootElement.Clone();
Write(fields); Write(fields);
} }
/// <summary>
/// Sets a single string field (e.g. "LoggingLevel"), preserving every other field.
/// </summary>
public static void SetString(string field, string value)
{
Dictionary<string, JsonElement> fields = Read();
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms))
w.WriteStringValue(value);
using var doc = JsonDocument.Parse(ms.ToArray());
fields[field] = doc.RootElement.Clone();
Write(fields);
}
} }

View file

@ -0,0 +1,29 @@
using System;
using System.Runtime.InteropServices;
using RynthCore.Install;
namespace RynthCore.App.Avalonia;
/// <summary>
/// One-shot values the installer leaves under <c>Software\Rynth</c> for the launcher
/// (e.g. <c>PendingPluginRegistration</c>). Kept out of the shared, read-only
/// <see cref="RynthInstallPaths"/>, which must stay byte-identical with RynthSuite's copy.
/// </summary>
internal static class InstallerHandoff
{
/// <summary>A string value from <c>Software\Rynth</c>: HKCU first, then HKLM (32-bit view); null when absent.</summary>
public static string? ReadSetting(string valueName)
=> SystemInstallSettings.Instance.CurrentUser(valueName)
?? SystemInstallSettings.Instance.LocalMachine(valueName);
/// <summary>Deletes a value from HKCU <c>Software\Rynth</c> once it has been acted on. Best effort.</summary>
public static void DeleteUserSetting(string valueName)
{
try { RegDeleteKeyValueW(HKEY_CURRENT_USER, RynthInstallPaths.RegistryKey, valueName); } catch { }
}
private static readonly IntPtr HKEY_CURRENT_USER = new(unchecked((int)0x80000001));
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern int RegDeleteKeyValueW(IntPtr hkey, string lpSubKey, string lpValueName);
}

View file

@ -2,6 +2,7 @@ using System;
using System.IO; using System.IO;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using RynthCore.Install;
namespace RynthCore.App.Avalonia; namespace RynthCore.App.Avalonia;

View file

@ -0,0 +1,110 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using RynthCore;
namespace RynthCore.App.Avalonia;
/// <summary>
/// One-shot host metadata for the Avalonia launcher: helps confirm the renamed apphost
/// (<c>RynthCore.exe</c>) sits next to matching <c>.runtimeconfig.json</c> / <c>.deps.json</c> after installer staging.
/// </summary>
internal static class LauncherHostDiagnostics
{
/// <summary>Single line for the in-window activity feed (short).</summary>
internal static string BuildActivitySummaryLine()
{
string exe = TryGetHostExePath();
string dir = Path.GetDirectoryName(exe) ?? AppContext.BaseDirectory;
HostSidecars side = DescribeSidecars(dir);
// x64 FDD tool prereq: same registry keys as installer/RynthCore.iss (see NetDesktopX64Prerequisite).
string suiteTools = NetDesktopX64Prerequisite.IsSatisfied()
? "x64 suite tools: .NET 10+ OK (registry, same as setup)"
: "x64 suite tools: .NET 10+ not found — install x64 runtime from " + NetDesktopX64Prerequisite.DotNet10RuntimeDownloadUrl;
if (!Environment.Is64BitOperatingSystem)
suiteTools = "x64 suite tools: n/a on 32-bit OS (same as setup)";
return
$"Host: {RuntimeInformation.FrameworkDescription}, arch={RuntimeInformation.ProcessArchitecture}, " +
$"runtimeconfig={(side.RenamedRuntimeConfig ? "RynthCore" : side.LegacyRuntimeConfig ? "App.Avalonia (mismatch?)" : "missing")}, " +
$"deps={(side.RenamedDeps ? "RynthCore" : side.LegacyDeps ? "App.Avalonia (mismatch?)" : "missing")}; {suiteTools}";
}
/// <summary>Writes a detailed block to the desktop rolling launcher log.</summary>
internal static void AppendDesktopLogBlock(string timestampIso)
{
try
{
string exe = TryGetHostExePath();
string dir = Path.GetDirectoryName(exe) ?? AppContext.BaseDirectory;
HostSidecars side = DescribeSidecars(dir);
var sb = new StringBuilder(512);
sb.Append('[').Append(timestampIso).Append("] [pid:").Append(Environment.ProcessId).AppendLine("] Launcher host resolution:");
sb.Append(" ProcessPath: ").AppendLine(exe);
sb.Append(" BaseDirectory: ").AppendLine(AppContext.BaseDirectory);
sb.Append(" Framework: ").AppendLine(RuntimeInformation.FrameworkDescription);
sb.Append(" OSDescription: ").AppendLine(RuntimeInformation.OSDescription);
sb.Append(" ProcessArchitecture: ").AppendLine(RuntimeInformation.ProcessArchitecture.ToString());
sb.Append(" CLR: ").AppendLine(Environment.Version.ToString());
sb.Append(" RynthCore.runtimeconfig.json: ").AppendLine(side.RenamedRuntimeConfig ? "present" : "absent");
sb.Append(" RynthCore.App.Avalonia.runtimeconfig.json: ").AppendLine(side.LegacyRuntimeConfig ? "present (unexpected if exe is RynthCore.exe)" : "absent");
sb.Append(" RynthCore.deps.json: ").AppendLine(side.RenamedDeps ? "present" : "absent");
sb.Append(" RynthCore.App.Avalonia.deps.json: ").AppendLine(side.LegacyDeps ? "present (unexpected if exe is RynthCore.exe)" : "absent");
// Loot/Monster editors are x64 FDD: probe matches RynthCore.iss prerequisite page (64-bit registry view).
sb.Append(" x64 FDD tool runtime (Loot/Monster, same checks as installer): ")
.AppendLine(NetDesktopX64Prerequisite.IsSatisfied() ? "present" : "not detected")
.Append(" .NET 10+ x64 download hub: ")
.AppendLine(NetDesktopX64Prerequisite.DotNet10RuntimeDownloadUrl);
DesktopRollingLog.AppendLine(DesktopRollingLog.StemLauncher, sb.ToString());
}
catch
{
// Logging must never prevent startup.
}
}
private static string TryGetHostExePath()
{
try
{
// Prefer the actual apphost path (works for published rename to RynthCore.exe).
string? p = Environment.ProcessPath;
if (!string.IsNullOrWhiteSpace(p))
return p;
}
catch
{
// ignore
}
try
{
return typeof(App).Assembly.Location;
}
catch
{
return string.Empty;
}
}
private static HostSidecars DescribeSidecars(string directory)
{
if (string.IsNullOrWhiteSpace(directory) || !Directory.Exists(directory))
return new HostSidecars(false, false, false, false);
bool renamedRc = File.Exists(Path.Combine(directory, "RynthCore.runtimeconfig.json"));
bool legacyRc = File.Exists(Path.Combine(directory, "RynthCore.App.Avalonia.runtimeconfig.json"));
bool renamedDeps = File.Exists(Path.Combine(directory, "RynthCore.deps.json"));
bool legacyDeps = File.Exists(Path.Combine(directory, "RynthCore.App.Avalonia.deps.json"));
return new HostSidecars(renamedRc, legacyRc, renamedDeps, legacyDeps);
}
private readonly record struct HostSidecars(
bool RenamedRuntimeConfig,
bool LegacyRuntimeConfig,
bool RenamedDeps,
bool LegacyDeps);
}

View file

@ -0,0 +1,192 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using RynthCore.Install;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Launcher-side access to every live logging switch:
/// <list type="bullet">
/// <item>Engine: engine.json "LoggingLevel" (global threshold) and "LogCategories" (per-category emit
/// level). The engine polls engine.json once a second, so edits apply to running clients.</item>
/// <item>RynthAi: Logs\Diagnostics\diagnostics.json "Categories" and "Events" (Off / Trace / Info).
/// RynthAi polls it every couple of seconds and rewrites it with the full catalog on load.</item>
/// </list>
/// </summary>
internal static class LoggingSettingsStore
{
/// <summary>One engine log category as shown in the launcher.</summary>
internal readonly record struct EngineCategory(string Name, string DefaultLevel, string Description);
/// <summary>One RynthAi category / event row read from diagnostics.json.</summary>
internal sealed record DiagnosticsRow(string Key, string Level, string Description);
/// <summary>Global level choices (engine.json "LoggingLevel"), most to least quiet.</summary>
internal static readonly string[] GlobalLevels = { "Off", "Error", "Warning", "Info", "Debug", "Trace" };
/// <summary>Engine category emit levels. Info = normal log; Debug/Trace show only at that global level.</summary>
internal static readonly string[] EngineCategoryLevels = { "Off", "Trace", "Debug", "Info" };
/// <summary>RynthAi category / event levels: Off, Trace (trace file only), Info (also the normal log).</summary>
internal static readonly string[] RynthAiLevels = { "Off", "Trace", "Info" };
/// <summary>Must match RynthCore.Engine.LogCategory names and LogSettings defaults.</summary>
internal static readonly EngineCategory[] EngineCategories =
{
new("General", "Info", "Uncategorised engine lines."),
new("D3D9", "Info", "D3D9 hook, EndScene, bootstrapper, matrix capture, nav markers."),
new("Compat", "Info", "Client hooks: objects, combat, movement, vitals, chat."),
new("Render", "Off", "ImGui rendering and Win32 input (very chatty)."),
new("Plugin", "Info", "Plugin loader/manager and every plugin host Log line."),
new("UI", "Info", "Avalonia overlay and panels."),
new("Verbose", "Debug", "Detail lines across all subsystems (Info = always in the normal log)."),
};
private const string EngineCategoriesProperty = "LogCategories";
/// <summary>RynthAi's diagnostics.json (created by RynthAi on its first load).</summary>
internal static string DiagnosticsPath =>
Path.Combine(RynthInstallPaths.RynthAiDir, "Logs", "Diagnostics", "diagnostics.json");
// ── Engine ──────────────────────────────────────────────────────────
/// <summary>Current engine category levels; categories missing from engine.json get their defaults.</summary>
internal static Dictionary<string, string> ReadEngineCategoryLevels()
{
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (EngineCategory c in EngineCategories) result[c.Name] = c.DefaultLevel;
Dictionary<string, JsonElement> fields = EngineJsonStore.Read();
if (fields.TryGetValue(EngineCategoriesProperty, out JsonElement cats) && cats.ValueKind == JsonValueKind.Object)
{
foreach (JsonProperty p in cats.EnumerateObject())
{
if (p.Value.ValueKind == JsonValueKind.String && result.ContainsKey(p.Name))
result[p.Name] = p.Value.GetString() ?? result[p.Name];
}
}
return result;
}
/// <summary>Sets one engine category level in engine.json, preserving every other field.</summary>
internal static void SetEngineCategoryLevel(string category, string level)
{
Dictionary<string, string> levels = ReadEngineCategoryLevels();
levels[category] = level;
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms))
{
w.WriteStartObject();
foreach (EngineCategory c in EngineCategories)
w.WriteString(c.Name, levels[c.Name]);
w.WriteEndObject();
}
Dictionary<string, JsonElement> fields = EngineJsonStore.Read();
using var doc = JsonDocument.Parse(ms.ToArray());
fields[EngineCategoriesProperty] = doc.RootElement.Clone();
EngineJsonStore.Write(fields);
}
// ── RynthAi ─────────────────────────────────────────────────────────
/// <summary>
/// Reads RynthAi's category and event rows. Returns false (with empty lists) when diagnostics.json
/// does not exist yet or cannot be parsed (e.g. RynthAi is mid-write; retry later).
/// </summary>
internal static bool TryReadRynthAi(out List<DiagnosticsRow> categories, out List<DiagnosticsRow> events, out string? error)
{
categories = new List<DiagnosticsRow>();
events = new List<DiagnosticsRow>();
error = null;
try
{
if (!File.Exists(DiagnosticsPath))
{
error = "diagnostics.json not found - start RynthAi once to create it.";
return false;
}
if (JsonNode.Parse(File.ReadAllText(DiagnosticsPath)) is not JsonObject root)
{
error = "diagnostics.json is not a JSON object.";
return false;
}
ReadRows(root["Categories"] as JsonArray, "Name", categories);
ReadRows(root["Events"] as JsonArray, "Key", events);
if (categories.Count == 0)
error = "diagnostics.json has no category list - update RynthAi to 0.6.18 or later.";
return true;
}
catch (Exception ex)
{
error = $"diagnostics.json unreadable ({ex.GetType().Name}: {ex.Message}).";
return false;
}
}
/// <summary>Sets a RynthAi category level ("Off", "Trace", "Info") and keeps "Traces" in sync.</summary>
internal static void SetRynthAiCategoryLevel(string category, string level)
=> UpdateDiagnostics("Categories", "Name", category, level);
/// <summary>Sets a RynthAi key-event level ("Off", "Trace", "Info").</summary>
internal static void SetRynthAiEventLevel(string eventKey, string level)
=> UpdateDiagnostics("Events", "Key", eventKey, level);
private static void ReadRows(JsonArray? array, string keyField, List<DiagnosticsRow> into)
{
if (array == null) return;
foreach (JsonNode? node in array)
{
if (node is not JsonObject o) continue;
string key = o[keyField]?.GetValue<string>() ?? string.Empty;
if (key.Length == 0) continue;
into.Add(new DiagnosticsRow(
key,
o["Level"]?.GetValue<string>() ?? "Off",
o["Description"]?.GetValue<string>() ?? string.Empty));
}
}
/// <summary>Read-modify-write of one row's Level; every other field in the file is preserved.</summary>
private static void UpdateDiagnostics(string section, string keyField, string key, string level)
{
string path = DiagnosticsPath;
if (JsonNode.Parse(File.ReadAllText(path)) is not JsonObject root)
throw new InvalidDataException("diagnostics.json is not a JSON object.");
if (root[section] is not JsonArray rows)
throw new InvalidDataException($"diagnostics.json has no \"{section}\" list.");
bool found = false;
foreach (JsonNode? node in rows)
{
if (node is JsonObject o && string.Equals(o[keyField]?.GetValue<string>(), key, StringComparison.OrdinalIgnoreCase))
{
o["Level"] = level;
found = true;
}
}
if (!found)
throw new KeyNotFoundException($"\"{key}\" is not in diagnostics.json {section}.");
// RynthAi reads Categories when present, but older readers (and /ra trace status) use Traces.
if (section == "Categories")
{
var traces = new JsonArray();
foreach (JsonNode? node in rows)
{
if (node is JsonObject o && !string.Equals(o["Level"]?.GetValue<string>(), "Off", StringComparison.OrdinalIgnoreCase))
traces.Add(o["Name"]?.GetValue<string>());
}
root["Traces"] = traces;
}
// Atomic swap so RynthAi's poll never reads a half-written file.
string tmp = path + ".tmp";
File.WriteAllText(tmp, root.ToJsonString(new JsonSerializerOptions { WriteIndented = false }));
File.Move(tmp, path, overwrite: true);
}
}

View file

@ -0,0 +1,153 @@
using System;
using System.Collections.Generic;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Runtime tab → Logging card and the live global Logging level box. Every change is written
/// straight to engine.json / diagnostics.json (see <see cref="LoggingSettingsStore"/>); running
/// clients poll those files, so nothing needs a restart or the Save button.
/// </summary>
internal partial class MainWindow
{
private static readonly IBrush LogNameBrush = new SolidColorBrush(Color.Parse("#EAF0F4"));
private static readonly IBrush LogMutedBrush = new SolidColorBrush(Color.Parse("#9AA8B3"));
// Set while the rows are being (re)built so programmatic selections don't write files.
private bool _suppressLoggingEvents;
/// <summary>Wires the Logging card and the live global level box. Called once after LoadRuntimeControls.</summary>
private void InitLoggingControls()
{
LoggingLevelComboBox.SelectionChanged += (_, _) => OnGlobalLoggingLevelChanged();
ReloadLoggingButton.Click += (_, _) => BuildLoggingRows();
BuildLoggingRows();
}
/// <summary>Global level changed: persist to the launcher settings and push to engine.json now.</summary>
private void OnGlobalLoggingLevelChanged()
{
if (_suppressLoggingEvents) return;
string level = GetSelectedLoggingLevel();
if (string.Equals(level, _settings.LoggingLevel, StringComparison.OrdinalIgnoreCase)) return;
try
{
_settings.LoggingLevel = level;
SaveSettings();
EngineJsonStore.SetString("LoggingLevel", level);
AppendActivity($"Logging level set to {level} (applied live to running clients).");
}
catch (Exception ex)
{
AppendActivity($"Failed to save logging level: {ex.Message}");
}
}
/// <summary>(Re)builds the engine category, RynthAi category and RynthAi event rows from disk.</summary>
private void BuildLoggingRows()
{
_suppressLoggingEvents = true;
try
{
EngineLogCategoriesPanel.Children.Clear();
Dictionary<string, string> engineLevels = LoggingSettingsStore.ReadEngineCategoryLevels();
foreach (LoggingSettingsStore.EngineCategory cat in LoggingSettingsStore.EngineCategories)
{
string name = cat.Name;
EngineLogCategoriesPanel.Children.Add(BuildLoggingRow(
name, cat.Description, LoggingSettingsStore.EngineCategoryLevels, engineLevels[name],
level =>
{
LoggingSettingsStore.SetEngineCategoryLevel(name, level);
AppendActivity($"Engine log category {name} set to {level} (applied live).");
}));
}
RynthAiLogCategoriesPanel.Children.Clear();
RynthAiLogEventsPanel.Children.Clear();
bool ok = LoggingSettingsStore.TryReadRynthAi(
out List<LoggingSettingsStore.DiagnosticsRow> categories,
out List<LoggingSettingsStore.DiagnosticsRow> events,
out string? error);
foreach (LoggingSettingsStore.DiagnosticsRow row in categories)
{
string key = row.Key;
RynthAiLogCategoriesPanel.Children.Add(BuildLoggingRow(
key, row.Description, LoggingSettingsStore.RynthAiLevels, row.Level,
level =>
{
LoggingSettingsStore.SetRynthAiCategoryLevel(key, level);
AppendActivity($"RynthAi log category {key} set to {level} (applied live).");
}));
}
foreach (LoggingSettingsStore.DiagnosticsRow row in events)
{
string key = row.Key;
RynthAiLogEventsPanel.Children.Add(BuildLoggingRow(
key, row.Description, LoggingSettingsStore.RynthAiLevels, row.Level,
level =>
{
LoggingSettingsStore.SetRynthAiEventLevel(key, level);
AppendActivity($"RynthAi log event {key} set to {level} (applied live).");
}));
}
LoggingStatusText.Text = ok && error == null
? $"engine.json: {EngineJsonStore.Path}\ndiagnostics.json: {LoggingSettingsStore.DiagnosticsPath}"
: $"RynthAi: {error}";
}
catch (Exception ex)
{
LoggingStatusText.Text = $"Failed to load logging settings: {ex.Message}";
}
finally
{
_suppressLoggingEvents = false;
}
}
/// <summary>One "Name | level box | description" row. <paramref name="apply"/> runs on user changes only.</summary>
private Control BuildLoggingRow(string name, string description, string[] levels, string current, Action<string> apply)
{
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("170,110,*") };
grid.Children.Add(new TextBlock
{
Text = name,
Foreground = LogNameBrush,
VerticalAlignment = VerticalAlignment.Center,
});
var combo = new ComboBox { ItemsSource = levels, MinWidth = 100, Margin = new global::Avalonia.Thickness(0, 0, 8, 0) };
int index = Array.FindIndex(levels, l => string.Equals(l, current, StringComparison.OrdinalIgnoreCase));
combo.SelectedIndex = index >= 0 ? index : 0;
combo.SelectionChanged += (_, _) =>
{
if (_suppressLoggingEvents || combo.SelectedItem is not string level) return;
try { apply(level); }
catch (Exception ex)
{
AppendActivity($"Failed to set {name} to {level}: {ex.Message}");
// Show what is actually on disk; posted so the combo raising this event isn't torn down mid-handler.
global::Avalonia.Threading.Dispatcher.UIThread.Post(BuildLoggingRows);
}
};
Grid.SetColumn(combo, 1);
grid.Children.Add(combo);
var desc = new TextBlock
{
Text = description,
Foreground = LogMutedBrush,
TextWrapping = TextWrapping.Wrap,
VerticalAlignment = VerticalAlignment.Center,
};
Grid.SetColumn(desc, 2);
grid.Children.Add(desc);
return grid;
}
}

View file

@ -366,7 +366,17 @@
<CheckBox x:Name="OverrideWindowTitleCheckBox" <CheckBox x:Name="OverrideWindowTitleCheckBox"
Content="Rewrite AC window titles per account" Content="Rewrite AC window titles per account"
ToolTip.Tip="Replaces &quot;Asheron's Call&quot; with &quot;Account / Character @ Server&quot; on tracked clients so multi-box taskbars are readable. Untracked external clients are left alone." /> ToolTip.Tip="Replaces &quot;Asheron's Call&quot; with &quot;Account / Character @ Server&quot; on tracked clients so multi-box taskbars are readable. Untracked external clients are left alone." />
<CheckBox x:Name="InjectAllRunningAcCheckBox" Content="Inject all running AC sessions" />
<TextBlock Text="Logging level (applies live)" Foreground="#EAF0F4" Margin="0,4,0,0" />
<ComboBox x:Name="LoggingLevelComboBox" SelectedIndex="3"
ToolTip.Tip="Engine log threshold. Written to engine.json immediately; running clients pick it up within a second. Off = errors only.">
<ComboBoxItem Content="Off" />
<ComboBoxItem Content="Error" />
<ComboBoxItem Content="Warning" />
<ComboBoxItem Content="Info" />
<ComboBoxItem Content="Debug" />
<ComboBoxItem Content="Trace" />
</ComboBox>
<Grid ColumnDefinitions="*,Auto" RowDefinitions="Auto,Auto,Auto" Margin="0,8,0,0"> <Grid ColumnDefinitions="*,Auto" RowDefinitions="Auto,Auto,Auto" Margin="0,8,0,0">
<TextBlock Grid.Row="0" Grid.Column="0" Text="Inter-launch stagger (ms)" Foreground="#EAF0F4" VerticalAlignment="Center" Margin="0,0,8,6" /> <TextBlock Grid.Row="0" Grid.Column="0" Text="Inter-launch stagger (ms)" Foreground="#EAF0F4" VerticalAlignment="Center" Margin="0,0,8,6" />
<NumericUpDown Grid.Row="0" Grid.Column="1" x:Name="LaunchStaggerMsBox" Minimum="0" Maximum="5000" Increment="50" Width="120" Margin="0,0,0,6" /> <NumericUpDown Grid.Row="0" Grid.Column="1" x:Name="LaunchStaggerMsBox" Minimum="0" Maximum="5000" Increment="50" Width="120" Margin="0,0,0,6" />
@ -409,6 +419,42 @@
</StackPanel> </StackPanel>
</Border> </Border>
<!-- Live logging switches: engine categories (engine.json) and RynthAi categories/events
(diagnostics.json). Rows are built in code (MainWindow.Logging.cs). -->
<Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8">
<Grid ColumnDefinitions="*,Auto">
<TextBlock Grid.Column="0" Text="Logging" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" VerticalAlignment="Center" />
<Button Grid.Column="1" x:Name="ReloadLoggingButton" Content="Reload" />
</Grid>
<TextBlock Text="Every change is saved immediately and applies to running clients without a restart (engine within 1 s, RynthAi within 2 s). Set any Trace or Debug item to Info to see it in the normal log; Off silences it."
TextWrapping="Wrap"
Foreground="#9AA8B3" />
<Expander Header="Engine categories" IsExpanded="True" HorizontalAlignment="Stretch">
<StackPanel Spacing="4">
<TextBlock Text="The level each category's lines are written at. A line shows when its level is within the global Logging level above (Info = normal log)."
TextWrapping="Wrap" Foreground="#9AA8B3" />
<StackPanel x:Name="EngineLogCategoriesPanel" Spacing="2" />
</StackPanel>
</Expander>
<Expander Header="RynthAi categories" HorizontalAlignment="Stretch">
<StackPanel Spacing="4">
<TextBlock Text="Where each RynthAi category's trace lines go: Off = dropped, Trace = Logs\Diagnostics\Trace file only, Info = trace file and the normal log."
TextWrapping="Wrap" Foreground="#9AA8B3" />
<StackPanel x:Name="RynthAiLogCategoriesPanel" Spacing="2" />
</StackPanel>
</Expander>
<Expander Header="RynthAi key events" HorizontalAlignment="Stretch">
<StackPanel Spacing="4">
<TextBlock Text="Named milestones (Hub login, options refresh, ...). Off = dropped, Trace = trace file while that category is traced, Info = normal log."
TextWrapping="Wrap" Foreground="#9AA8B3" />
<StackPanel x:Name="RynthAiLogEventsPanel" Spacing="2" />
</StackPanel>
</Expander>
<TextBlock x:Name="LoggingStatusText" TextWrapping="Wrap" Foreground="#9AA8B3" />
</StackPanel>
</Border>
<Border Background="#132028" CornerRadius="16" Padding="18"> <Border Background="#132028" CornerRadius="16" Padding="18">
<StackPanel Spacing="8"> <StackPanel Spacing="8">
<TextBlock Text="Recovery Actions" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" /> <TextBlock Text="Recovery Actions" FontSize="16" FontWeight="SemiBold" Foreground="#26C1A6" />
@ -425,7 +471,7 @@
<Button x:Name="RepairDecalButton" Content="Repair Decal" Margin="0,0,8,8" <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." /> 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> </WrapPanel>
<TextBlock Text="Manual inject targets the first detected acclient.exe session. Reset Overlay Bar signals all running RynthCore clients via the dispatch file." <TextBlock Text="Manual inject target scope follows the 'Inject all running AC sessions' launch behavior toggle. Reset Overlay Bar signals all running RynthCore clients via the dispatch file."
TextWrapping="Wrap" TextWrapping="Wrap"
Foreground="#9AA8B3" /> Foreground="#9AA8B3" />
</StackPanel> </StackPanel>

View file

@ -18,6 +18,7 @@ using Avalonia.Media;
using Avalonia.Platform.Storage; using Avalonia.Platform.Storage;
using Avalonia.Threading; using Avalonia.Threading;
using RynthCore.Injector; using RynthCore.Injector;
using RynthCore.Install;
namespace RynthCore.App.Avalonia; namespace RynthCore.App.Avalonia;
@ -136,6 +137,8 @@ internal partial class MainWindow : Window
SessionList.ItemsSource = _sessionItems; SessionList.ItemsSource = _sessionItems;
LoadSettings(); LoadSettings();
LoadRuntimeControls(); LoadRuntimeControls();
InitLoggingControls();
ApplyInstallerPluginRegistration();
LoadPluginDllPaths(); LoadPluginDllPaths();
BuildPluginLoadout(); BuildPluginLoadout();
WireEvents(); WireEvents();
@ -149,6 +152,8 @@ internal partial class MainWindow : Window
Closing += (_, _) => SaveWindowLayout(); Closing += (_, _) => SaveWindowLayout();
ShowVersion(); ShowVersion();
AppendActivity("Avalonia launcher preview ready."); AppendActivity("Avalonia launcher preview ready.");
// One-line host/runtime sidecar check (full detail in Desktop RynthCore-Launcher.log).
AppendActivity(LauncherHostDiagnostics.BuildActivitySummaryLine());
_ = RefreshServerStatusesAsync(); _ = RefreshServerStatusesAsync();
_updateTimer.Tick += async (_, _) => await CheckForUpdatesAsync(); _updateTimer.Tick += async (_, _) => await CheckForUpdatesAsync();
_updateTimer.Start(); _updateTimer.Start();
@ -312,6 +317,8 @@ internal partial class MainWindow : Window
AutoLaunchHeaderCheckBox.IsChecked = _settings.AutoLaunch; AutoLaunchHeaderCheckBox.IsChecked = _settings.AutoLaunch;
AutoInjectAfterLaunchCheckBox.IsChecked = _settings.AutoInjectAfterLaunch; AutoInjectAfterLaunchCheckBox.IsChecked = _settings.AutoInjectAfterLaunch;
WatchForAcStartCheckBox.IsChecked = _settings.WatchForAcStart; WatchForAcStartCheckBox.IsChecked = _settings.WatchForAcStart;
InjectAllRunningAcCheckBox.IsChecked = _settings.InjectAllRunningClients;
SetLoggingLevelSelection(_settings.LoggingLevel);
OverrideWindowTitleCheckBox.IsChecked = _settings.OverrideWindowTitle; OverrideWindowTitleCheckBox.IsChecked = _settings.OverrideWindowTitle;
LaunchStaggerMsBox.Value = _settings.LaunchStaggerMs; LaunchStaggerMsBox.Value = _settings.LaunchStaggerMs;
CrashRelaunchLimitBox.Value = _settings.CrashRelaunchLimitInWindow; CrashRelaunchLimitBox.Value = _settings.CrashRelaunchLimitInWindow;
@ -1485,6 +1492,8 @@ internal partial class MainWindow : Window
_settings.AutoLaunch = AutoLaunchHeaderCheckBox.IsChecked == true; _settings.AutoLaunch = AutoLaunchHeaderCheckBox.IsChecked == true;
_settings.AutoInjectAfterLaunch = AutoInjectAfterLaunchCheckBox.IsChecked == true; _settings.AutoInjectAfterLaunch = AutoInjectAfterLaunchCheckBox.IsChecked == true;
_settings.WatchForAcStart = WatchForAcStartCheckBox.IsChecked == true; _settings.WatchForAcStart = WatchForAcStartCheckBox.IsChecked == true;
_settings.InjectAllRunningClients = InjectAllRunningAcCheckBox.IsChecked == true;
_settings.LoggingLevel = GetSelectedLoggingLevel();
_settings.OverrideWindowTitle = OverrideWindowTitleCheckBox.IsChecked == true; _settings.OverrideWindowTitle = OverrideWindowTitleCheckBox.IsChecked == true;
if (LaunchStaggerMsBox.Value is decimal staggerMs) if (LaunchStaggerMsBox.Value is decimal staggerMs)
_settings.LaunchStaggerMs = (int)staggerMs; _settings.LaunchStaggerMs = (int)staggerMs;
@ -1499,8 +1508,12 @@ internal partial class MainWindow : Window
if (_settings.EnabledPluginIds.Count == 0) if (_settings.EnabledPluginIds.Count == 0)
_settings.EnabledPluginIds.Add("rynthcore-engine"); _settings.EnabledPluginIds.Add("rynthcore-engine");
SaveSettings(); SaveSettings();
SyncPluginPathsToEngineSettings();
if (appendActivity) if (appendActivity)
{
AppendActivity($"Logging level saved: {_settings.LoggingLevel}.");
AppendActivity("Launch behavior saved."); AppendActivity("Launch behavior saved.");
}
} }
private void SaveAutoLaunchPreference() private void SaveAutoLaunchPreference()
@ -2157,6 +2170,78 @@ internal partial class MainWindow : Window
AppendActivity($"Runtime loadout updated: {Path.GetFileName(dllPath)} {(enabled ? "enabled" : "disabled")} (engine.json synced)."); AppendActivity($"Runtime loadout updated: {Path.GetFileName(dllPath)} {(enabled ? "enabled" : "disabled")} (engine.json synced).");
} }
/// <summary>
/// Applies the installer's one-shot plugin hand-off: the full installer writes the plugin
/// DLL paths it placed in the user-chosen RynthSuite folder to
/// <c>Software\Rynth\PendingPluginRegistration</c> (';'-separated). Each existing DLL is added
/// to the Plugins list, and any entry with the same file name that no longer exists (e.g. the
/// old <c>C:\Games\RynthSuite\...</c> path after moving the Suite folder) is replaced.
/// Rows pointing inside the RynthCore folder whose file the installer removed are dropped too.
/// The value is consumed once (deleted from HKCU; remembered in settings for HKLM).
/// </summary>
private void ApplyInstallerPluginRegistration()
{
try
{
string? pending = InstallerHandoff.ReadSetting("PendingPluginRegistration");
if (string.IsNullOrWhiteSpace(pending)
|| string.Equals(pending, _settings.AppliedInstallerPluginRegistration, StringComparison.OrdinalIgnoreCase))
return;
_settings.PluginDllPaths ??= [];
var added = new List<string>();
// The installer clears loose DLLs out of the RynthCore folder (old 0.4.x layouts kept plugins
// and SDK DLLs there), so drop rows that pointed inside it and are now gone. Rows elsewhere are
// left alone, since a missing file there may just be on a drive that isn't mounted.
string coreRoot = Path.TrimEndingDirectorySeparator(RynthInstallPaths.CoreDir) + Path.DirectorySeparatorChar;
bool IsRemovedCoreFile(string p) =>
p.StartsWith(coreRoot, StringComparison.OrdinalIgnoreCase) && !File.Exists(p);
int pruned = _settings.PluginDllPaths.RemoveAll(IsRemovedCoreFile);
_settings.DisabledPluginDllPaths.RemoveAll(IsRemovedCoreFile);
foreach (string raw in pending.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
string path;
try { path = Path.GetFullPath(raw); } catch { continue; }
if (!File.Exists(path)) continue;
string fileName = Path.GetFileName(path);
// Drop stale rows for the same plugin that point at a file which is gone.
_settings.PluginDllPaths.RemoveAll(p =>
string.Equals(Path.GetFileName(p), fileName, StringComparison.OrdinalIgnoreCase)
&& !string.Equals(p, path, StringComparison.OrdinalIgnoreCase)
&& !File.Exists(p));
if (!_settings.PluginDllPaths.Any(p => string.Equals(p, path, StringComparison.OrdinalIgnoreCase)))
{
_settings.PluginDllPaths.Add(path);
added.Add(fileName);
}
}
_settings.AppliedInstallerPluginRegistration = pending;
SaveSettings();
InstallerHandoff.DeleteUserSetting("PendingPluginRegistration");
_pluginDllPaths.Clear();
foreach (string p in _settings.PluginDllPaths) _pluginDllPaths.Add(p);
SyncPluginPathsToEngineSettings();
string msg = added.Count > 0
? $"Installer registered plugin(s): {string.Join(", ", added)} (engine.json synced)."
: "Installer plugin registration already up to date.";
if (pruned > 0)
msg += $" Removed {pruned} plugin path(s) for files the installer cleared from {RynthInstallPaths.CoreDir}.";
LauncherDiag.Info("PLUGINS: " + msg);
try { AppendActivity(msg); } catch { }
}
catch (Exception ex)
{
LauncherDiag.Info("PLUGINS: installer registration failed: " + ex.Message);
}
}
private void LoadPluginDllPaths() private void LoadPluginDllPaths()
{ {
_pluginDllPaths.Clear(); _pluginDllPaths.Clear();
@ -2245,6 +2330,8 @@ internal partial class MainWindow : Window
.Where(p => !disabled.Contains(p)) .Where(p => !disabled.Contains(p))
.ToList(); .ToList();
EngineJsonStore.SetStringArray("PluginPaths", enabledPaths); EngineJsonStore.SetStringArray("PluginPaths", enabledPaths);
// The engine reads its log verbosity from engine.json on init (EngineSettings.LoggingLevel).
EngineJsonStore.SetString("LoggingLevel", GetSelectedLoggingLevel());
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -2740,18 +2827,28 @@ internal partial class MainWindow : Window
try try
{ {
SetOperationState(true); SetOperationState(true);
Process target = targets.OrderBy(process => process.Id).First(); IReadOnlyList<Process> orderedTargets = targets.OrderBy(process => process.Id).ToList();
AppendActivity($"Applying selected loadout to running AC (PID {target.Id})."); bool injectAllSessions = InjectAllRunningAcCheckBox.IsChecked == true;
IReadOnlyList<Process> targetsToInject = injectAllSessions
? orderedTargets
: [orderedTargets[0]];
AppendActivity(injectAllSessions
? $"Applying selected loadout to {targetsToInject.Count} running AC session(s)."
: $"Applying selected loadout to first running AC session (PID {targetsToInject[0].Id}).");
InjectionResult result = await Task.Run(() => _injector.InjectIntoProcess(target, enginePath, AppendActivity)); foreach (Process target in targetsToInject)
if (result.Success)
{ {
_launchedSessionPids.Add(target.Id); AppendActivity($"Injecting running AC (PID {target.Id}).");
AppendActivity($"Injection complete for PID {target.Id}."); InjectionResult result = await Task.Run(() => _injector.InjectIntoProcess(target, enginePath, AppendActivity));
} if (result.Success)
else {
{ _launchedSessionPids.Add(target.Id);
AppendActivity($"Injection failed: {result.Summary}"); AppendActivity($"Injection complete for PID {target.Id}.");
}
else
{
AppendActivity($"Injection failed for PID {target.Id}: {result.Summary}");
}
} }
} }
catch (Exception ex) catch (Exception ex)
@ -2765,6 +2862,39 @@ internal partial class MainWindow : Window
} }
} }
private string GetSelectedLoggingLevel()
{
return LoggingLevelComboBox.SelectedItem is ComboBoxItem item
? item.Content?.ToString() ?? "Info"
: "Info";
}
private void SetLoggingLevelSelection(string? loggingLevel)
{
string desiredLevel = string.IsNullOrWhiteSpace(loggingLevel) ? "Info" : loggingLevel.Trim();
if (LoggingLevelComboBox.Items == null)
{
LoggingLevelComboBox.SelectedIndex = 0;
return;
}
foreach (object? item in LoggingLevelComboBox.Items)
{
if (item is not ComboBoxItem comboItem)
continue;
string candidate = comboItem.Content?.ToString() ?? string.Empty;
if (!string.Equals(candidate, desiredLevel, StringComparison.OrdinalIgnoreCase))
continue;
LoggingLevelComboBox.SelectedItem = comboItem;
return;
}
// Unknown saved value: fall back to Info (index 3 after Off, Error, Warning), not the quietest level.
LoggingLevelComboBox.SelectedIndex = 3;
}
private void OnPrimarySelectionChanged() private void OnPrimarySelectionChanged()
{ {
if (_suppressPrimarySelectionChanged) if (_suppressPrimarySelectionChanged)

View file

@ -1,6 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<!-- Launcher assembly version (bump when changing launcher-only behavior). Previous: 0.1.4.
No hard-coded InformationalVersion: release builds pass -p:Version=yyyy.m.d.n, and the
product version derived from it is what the launcher/About show (BuildVersion.Format). -->
<Version>0.1.5</Version>
<AssemblyVersion>0.1.5.0</AssemblyVersion>
<FileVersion>0.1.5.0</FileVersion>
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
<TargetFramework>net10.0-windows7.0</TargetFramework> <TargetFramework>net10.0-windows7.0</TargetFramework>
<PlatformTarget>x86</PlatformTarget> <PlatformTarget>x86</PlatformTarget>
@ -11,6 +17,8 @@
<RootNamespace>RynthCore.App.Avalonia</RootNamespace> <RootNamespace>RynthCore.App.Avalonia</RootNamespace>
<AssemblyName>RynthCore.App.Avalonia</AssemblyName> <AssemblyName>RynthCore.App.Avalonia</AssemblyName>
<RuntimeIdentifiers>win-x86</RuntimeIdentifiers> <RuntimeIdentifiers>win-x86</RuntimeIdentifiers>
<!-- Build-Installer.ps1 publishes self-contained so RynthCore.exe does not require a machine-wide
.NET 10 Desktop Runtime. Local dotnet build or dotnet run still use the SDK. -->
<ApplicationIcon>LogoCore.ico</ApplicationIcon> <ApplicationIcon>LogoCore.ico</ApplicationIcon>
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract> <IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
</PropertyGroup> </PropertyGroup>
@ -25,10 +33,14 @@
<PackageReference Include="Avalonia.Desktop" Version="11.2.3" /> <PackageReference Include="Avalonia.Desktop" Version="11.2.3" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.3" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.3" />
<PackageReference Include="Avalonia.Fonts.Inter" 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). --> <!-- Direct reference overrides Avalonia's transitive 0.20.x (NU1903 / GHSA-xrw6-gwf8-vvr9). -->
<PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" /> <PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\RynthCore.DesktopLog\RynthCore.DesktopLog.csproj" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="..\RynthCore.App\LaunchServerProfile.cs" Link="Shared\LaunchServerProfile.cs" /> <Compile Include="..\RynthCore.App\LaunchServerProfile.cs" Link="Shared\LaunchServerProfile.cs" />
<Compile Include="..\RynthCore.App\LaunchAccountProfile.cs" Link="Shared\LaunchAccountProfile.cs" /> <Compile Include="..\RynthCore.App\LaunchAccountProfile.cs" Link="Shared\LaunchAccountProfile.cs" />

View file

@ -17,6 +17,8 @@ internal sealed class AppSettings
public bool AutoLaunch { get; set; } public bool AutoLaunch { get; set; }
public bool AutoInjectAfterLaunch { get; set; } = true; public bool AutoInjectAfterLaunch { get; set; } = true;
public bool WatchForAcStart { get; set; } = true; public bool WatchForAcStart { get; set; } = true;
public bool InjectAllRunningClients { get; set; } = true;
public string LoggingLevel { get; set; } = "Info";
public int LaunchStaggerMs { get; set; } = 250; public int LaunchStaggerMs { get; set; } = 250;
public int CrashRelaunchLimitInWindow { get; set; } = 3; public int CrashRelaunchLimitInWindow { get; set; } = 3;
public int CrashRelaunchWindowMinutes { get; set; } = 5; public int CrashRelaunchWindowMinutes { get; set; } = 5;
@ -68,6 +70,14 @@ internal sealed class AppSettings
/// the UI), but is filtered out when syncing PluginPaths into engine.json. /// the UI), but is filtered out when syncing PluginPaths into engine.json.
/// Case-insensitive set semantics; comparisons must use OrdinalIgnoreCase. /// Case-insensitive set semantics; comparisons must use OrdinalIgnoreCase.
public List<string> DisabledPluginDllPaths { get; set; } = []; public List<string> DisabledPluginDllPaths { get; set; } = [];
/// <summary>
/// Last installer plugin hand-off (registry <c>Software\Rynth\PendingPluginRegistration</c>)
/// the launcher applied. Lets an all-users install, whose HKLM value the launcher cannot
/// delete, register its plugins once without re-adding a plugin the user later removed.
/// </summary>
public string? AppliedInstallerPluginRegistration { get; set; }
public List<LaunchServerProfile> ServerProfiles { get; set; } = []; public List<LaunchServerProfile> ServerProfiles { get; set; } = [];
public List<LaunchAccountProfile> AccountProfiles { get; set; } = []; public List<LaunchAccountProfile> AccountProfiles { get; set; } = [];

View file

@ -0,0 +1,130 @@
using System.Globalization;
using System.Text;
namespace RynthCore;
/// <summary>
/// Desktop text logs with a fixed size cap and per-day roll retention. Active file lives on the user
/// desktop as <c>{fileStem}.log</c>. When the active file reaches <see cref="MaxActiveFileBytes"/>,
/// it is moved into <c>Desktop\RynthLogs\</c> with a time-stamped name, then a new active file is
/// created. For each <paramref name="fileStem"/> and each calendar day, at most
/// <see cref="MaxRolledFilesPerLocalDay"/> archived files are kept (oldest for that day deleted first).
/// </summary>
public static class DesktopRollingLog
{
// 10 MB active segment, up to 10 rolled segments per local calendar day.
public const long MaxActiveFileBytes = 10L * 1024 * 1024;
public const int MaxRolledFilesPerLocalDay = 10;
private static readonly string DesktopDir =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
private static readonly string ArchiveDir = Path.Combine(DesktopDir, "RynthLogs");
/// <summary>Pre-defined stems for the three Rynth products (one file each on the desktop).</summary>
public const string StemEngine = "RynthCore";
public const string StemLauncher = "RynthCore-Launcher";
public const string StemInjector = "RynthCore-Injector";
private static readonly object Gate = new();
/// <param name="fileStem">File name without extension, e.g. <see cref="StemEngine"/>.</param>
public static void AppendLine(string fileStem, string line)
{
string stem = SanitizeStem(fileStem);
string text = line ?? string.Empty;
if (text.Length > 0 && text[^1] is not '\n' and not '\r')
text += Environment.NewLine;
lock (Gate)
{
try
{
string active = Path.Combine(DesktopDir, stem + ".log");
Directory.CreateDirectory(ArchiveDir);
if (File.Exists(active) && new FileInfo(active).Length + Encoding.UTF8.GetByteCount(text) > MaxActiveFileBytes)
RotateToArchive(stem, active);
using var stream = new FileStream(active, FileMode.Append, FileAccess.Write, FileShare.Read);
var bytes = Encoding.UTF8.GetBytes(text);
stream.Write(bytes, 0, bytes.Length);
}
catch
{
// Intentionally silent: logging must not crash host.
}
}
}
// Moves current active file to RynthLogs; trims same-day archives for this stem, then the move.
private static void RotateToArchive(string stem, string activePath)
{
string ymd = DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
string prefix = stem + "-roll-" + ymd + "-";
PruneOldestRolledForPrefix(prefix);
string destName = prefix + DateTime.Now.ToString("HHmmssfff", CultureInfo.InvariantCulture) + ".log";
string destPath = Path.Combine(ArchiveDir, destName);
if (File.Exists(destPath)) File.Delete(destPath);
try
{
File.Move(activePath, destPath, overwrite: false);
}
catch
{
try
{
if (File.Exists(destPath)) File.Delete(destPath);
}
catch
{
// ignore
}
if (File.Exists(activePath)) File.Delete(activePath);
}
}
// Ensures that after a new file with this prefix is created, at most MaxRolledFilesPerLocalDay rolled files for this prefix+day exist.
private static void PruneOldestRolledForPrefix(string prefix)
{
if (!Directory.Exists(ArchiveDir)) return;
var todaysRolled = new DirectoryInfo(ArchiveDir)
.GetFiles(prefix + "*.log", SearchOption.TopDirectoryOnly)
.OrderBy(f => f.CreationTimeUtc)
.ThenBy(f => f.Name, StringComparer.OrdinalIgnoreCase)
.ToList();
// Delete oldest rolled segments until a new one would not exceed the daily cap.
while (todaysRolled.Count >= MaxRolledFilesPerLocalDay)
{
try
{
todaysRolled[0].Delete();
todaysRolled.RemoveAt(0);
}
catch
{
break;
}
}
}
private static string SanitizeStem(string? stem)
{
if (string.IsNullOrWhiteSpace(stem)) return "RynthLog";
var invalid = Path.GetInvalidFileNameChars();
var b = new StringBuilder(stem.Length);
foreach (var ch in stem.Trim())
{
if (!invalid.Contains(ch) && ch != Path.DirectorySeparatorChar && ch != Path.AltDirectorySeparatorChar)
b.Append(ch);
}
string t = b.ToString();
return t.Length == 0 ? "RynthLog" : t;
}
}

View file

@ -0,0 +1,105 @@
// Detects the same "Suite tools" .NET 10+ x64 prerequisite as the Inno installer
// (installer\RynthCore.iss, IsNetDesktop* helpers). If you change registry checks here,
// update RynthCore.iss in lockstep and vice versa.
using System;
using System.Globalization;
using System.Linq;
using System.Runtime.Versioning;
using Microsoft.Win32;
namespace RynthCore;
/// <summary>
/// Registry probe for the optional x64 framework-dependent tools (Loot Editor, Monster Editor).
/// Must match <c>IsNetDesktop10PlusX64Present</c> and its helpers in <c>installer/RynthCore.iss</c>
/// (Path A: <c>Microsoft.WindowsDesktop.App</c> shared folders; Path B: <c>sharedhost</c> Version;
/// Path C: <c>InstalledManifests\x64</c> manifest-10. bands). Uses 64-bit registry view from an x86 process.
/// </summary>
[SupportedOSPlatform("windows")]
public static class NetDesktopX64Prerequisite
{
// Same string as RynthCore.iss DotNet10DesktopDownloadUrl (x64 runtime hub; user picks Desktop / ASP.NET as needed).
public const string DotNet10RuntimeDownloadUrl = "https://dotnet.microsoft.com/en-us/download/dotnet/10.0/runtime";
/// <summary>True if the x64 FDD tool prerequisite is met, or the OS is 32-bit (N/A, same as Inno skip).</summary>
public static bool IsSatisfied()
{
if (!Environment.Is64BitOperatingSystem)
return true;
return
IsWindowsDesktopSharedFramework10Plus()
|| IsDotNet10BandInInstalledManifestsX64()
|| IsSharedHostVersion10PlusX64();
}
// Path A: HKLM\SOFTWARE\dotnet\shared\Microsoft.WindowsDesktop.App\10.x.y
private static bool IsWindowsDesktopSharedFramework10Plus()
{
using RegistryKey? base64 = OpenLocalMachine64();
using RegistryKey? key = base64?.OpenSubKey(@"SOFTWARE\dotnet\shared\Microsoft.WindowsDesktop.App");
if (key is null)
return false;
foreach (string name in key.GetSubKeyNames())
{
if (ParseMajorFromVersionFolder(name) >= 10)
return true;
}
return false;
}
// Path B: sharedhost Version 10+ under Setup\InstalledVersions\x64\sharedhost
private static bool IsSharedHostVersion10PlusX64()
{
if (ReadSharedHostMajor(@"SOFTWARE\dotnet\Setup\InstalledVersions\x64\sharedhost") >= 10)
return true;
if (ReadSharedHostMajor(@"SOFTWARE\Microsoft\dotnet\Setup\InstalledVersions\x64\sharedhost") >= 10)
return true;
return false;
}
private static int ReadSharedHostMajor(string subKeyPath)
{
using RegistryKey? base64 = OpenLocalMachine64();
using RegistryKey? key = base64?.OpenSubKey(subKeyPath);
if (key is null)
return 0;
string? v = key.GetValue("Version") as string;
if (string.IsNullOrWhiteSpace(v))
return 0;
return ParseMajorFromVersionFolder(v.Trim());
}
// Path C: InstalledManifests x64, subkeys like ...Manifest-10.0.100
private static bool IsDotNet10BandInInstalledManifestsX64()
{
using RegistryKey? base64 = OpenLocalMachine64();
using RegistryKey? key = base64?.OpenSubKey(@"SOFTWARE\Microsoft\dotnet\InstalledManifests\x64");
if (key is null)
return false;
return key.GetSubKeyNames().Any(s => s != null
&& s.IndexOf("Manifest-10.", StringComparison.OrdinalIgnoreCase) >= 0);
}
private static RegistryKey? OpenLocalMachine64() =>
RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
/// <summary>First numeric segment of a "10.0.5" style folder or version string (Pascal: Copy before first '.').</summary>
private static int ParseMajorFromVersionFolder(string name)
{
int dot = name.IndexOf('.');
if (dot <= 0)
return 0;
return int.TryParse(
name.AsSpan(0, dot),
NumberStyles.Integer,
CultureInfo.InvariantCulture,
out int m)
? m
: 0;
}
}

View file

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>RynthCore</RootNamespace>
<AssemblyName>RynthCore.DesktopLog</AssemblyName>
<Version>1.0.1</Version>
</PropertyGroup>
</Project>

View file

@ -656,12 +656,21 @@ internal static class ClientHelperHooks
/// </summary> /// </summary>
public static bool MergeStackInternal(uint sourceObjectId, uint targetObjectId) public static bool MergeStackInternal(uint sourceObjectId, uint targetObjectId)
{ {
// Every exit records its outcome in MergeStackResults so the plugin can poll
// GetMergeStackResult instead of guessing from a later inventory snapshot.
if (!MainThreadGuard.IsOnMainThread()) if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId); {
bool queued = AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId);
MergeStackResults.Record(sourceObjectId, targetObjectId,
queued ? MergeStackResults.Queued : MergeStackResults.QueueFull);
return queued;
}
if (_eventStackableMerge == null) return false; if (_eventStackableMerge == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId))
if (!IsValidObjectId(sourceObjectId)) return false; {
if (!IsValidObjectId(targetObjectId)) return false; MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed);
return false;
}
// Read counts via the PWD fast path (stypes 11/12 are served from // Read counts via the PWD fast path (stypes 11/12 are served from
// PublicWeenieDesc directly — no broken InqInt for inventory items). // PublicWeenieDesc directly — no broken InqInt for inventory items).
@ -680,6 +689,7 @@ internal static class ClientHelperHooks
if (room <= 0) if (room <= 0)
{ {
RynthLog.Verbose($"Compat: Event_StackableMerge skipped - target 0x{targetObjectId:X8}({targetCount}) is full (max={maxStack})"); RynthLog.Verbose($"Compat: Event_StackableMerge skipped - target 0x{targetObjectId:X8}({targetCount}) is full (max={maxStack})");
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.TargetFull);
return false; return false;
} }
amount = Math.Min(sourceCount, room); amount = Math.Min(sourceCount, room);
@ -690,17 +700,24 @@ internal static class ClientHelperHooks
amount = sourceCount; amount = sourceCount;
} }
if (amount <= 0) return false; if (amount <= 0)
{
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed);
return false;
}
try try
{ {
byte rv = _eventStackableMerge(sourceObjectId, targetObjectId, amount); byte rv = _eventStackableMerge(sourceObjectId, targetObjectId, amount);
RynthLog.Verbose($"Compat: Event_StackableMerge from=0x{sourceObjectId:X8}({sourceCount}) to=0x{targetObjectId:X8}({targetCount}) amount={amount}/{maxStack} rv={rv}"); RynthLog.Verbose($"Compat: Event_StackableMerge from=0x{sourceObjectId:X8}({sourceCount}) to=0x{targetObjectId:X8}({targetCount}) amount={amount}/{maxStack} rv={rv}");
MergeStackResults.Record(sourceObjectId, targetObjectId,
rv != 0 ? MergeStackResults.Sent : MergeStackResults.Failed, rv != 0 ? amount : 0);
return rv != 0; return rv != 0;
} }
catch (Exception ex) catch (Exception ex)
{ {
RynthLog.Compat($"Compat: Event_StackableMerge threw - {ex.Message}"); RynthLog.Compat($"Compat: Event_StackableMerge threw - {ex.Message}");
MergeStackResults.Record(sourceObjectId, targetObjectId, MergeStackResults.Failed);
return false; return false;
} }
} }

View file

@ -241,6 +241,24 @@ internal static class ClientObjectHooks
private static DateTime _lastObjectIdentityPrefetchUtc = DateTime.MinValue; private static DateTime _lastObjectIdentityPrefetchUtc = DateTime.MinValue;
private static bool _loggedObjectIdentityServe; private static bool _loggedObjectIdentityServe;
private const int ObjectIdentityPrefetchThrottleMs = 500; private const int ObjectIdentityPrefetchThrottleMs = 500;
// Create-time identity seeds. ACCObjectMaint::CreateObject receives the server's
// PublicWeenieDesc, which already carries the object's name and ITEM_TYPE before
// qualities/appraisal exist. The main-thread snapshot above can't resolve names for
// ~10 s after login (qualities not populated yet), so off-thread readers fall back to
// these seeds when the snapshot has no entry (or reports type 0). Entries live from
// create until delete; the cap only guards against a missed delete hook.
private static readonly object _createSeedLock = new();
private static readonly Dictionary<uint, string> _createSeedNames = new(1024);
private static readonly Dictionary<uint, uint> _createSeedTypes = new(1024);
private const int CreateSeedCap = 16384;
// PublicWeenieDesc field offsets (Chorizite Weenie.cs; same layout the PWD-direct
// fallbacks in TryGetObjectName / TryGetItemType read from the embedded copy).
// PwdTypeOffset is declared with the other PublicWeenieDesc offsets further down.
private const int PwdNameOffset = 4;
private static int _createSeedCount;
private static bool _loggedCreateSeedServe;
// Every id the same walk visited, swapped whole (readers never see a half-built array). // Every id the same walk visited, swapped whole (readers never see a half-built array).
private static volatile uint[] _liveObjectIds = Array.Empty<uint>(); private static volatile uint[] _liveObjectIds = Array.Empty<uint>();
@ -393,6 +411,7 @@ internal static class ClientObjectHooks
private static readonly object _weeniePtrSwapLock = new(); private static readonly object _weeniePtrSwapLock = new();
private static Dictionary<uint, IntPtr> _weeniePtrFront = new(512); private static Dictionary<uint, IntPtr> _weeniePtrFront = new(512);
private static Dictionary<uint, IntPtr> _weeniePtrBack = new(512); private static Dictionary<uint, IntPtr> _weeniePtrBack = new(512);
// Diagnostic (temporary): periodic snapshot-size log + live-read probe of // Diagnostic (temporary): periodic snapshot-size log + live-read probe of
// objects with a position but no cached name. Remove once the missing- // objects with a position but no cached name. Remove once the missing-
// monsters cause is pinned. _diagSampleBuf preallocated to stay low-alloc. // monsters cause is pinned. _diagSampleBuf preallocated to stay low-alloc.
@ -2019,8 +2038,9 @@ internal static class ClientObjectHooks
value = 0; value = 0;
if (pwdFieldOffset < 0 || pwdFieldOffset > 172 || (pwdFieldOffset & 3) != 0) if (pwdFieldOffset < 0 || pwdFieldOffset > 172 || (pwdFieldOffset & 3) != 0)
return false; return false;
// Off-thread: served from the main-thread PWD byte snapshot, never from AC memory.
if (!MainThreadGuard.IsOnMainThread()) if (!MainThreadGuard.IsOnMainThread())
return false; return TryGetPwdSnapshotRawInt32(objectId, pwdFieldOffset, out value);
if (_getWeenieObject == null) if (_getWeenieObject == null)
{ {
if (!Probe() || _getWeenieObject == null) if (!Probe() || _getWeenieObject == null)
@ -2393,6 +2413,19 @@ internal static class ClientObjectHooks
// Off-thread: serve from the main-thread snapshot populated by PrefetchObjectIdentity(). // Off-thread: serve from the main-thread snapshot populated by PrefetchObjectIdentity().
if (!MainThreadGuard.IsOnMainThread()) if (!MainThreadGuard.IsOnMainThread())
{ {
lock (_objectIdentityCacheLock)
{
// A zero snapshot value means qualities weren't populated when the walk
// ran; prefer the create-time descriptor type in that case.
if (_objectTypeCache.TryGetValue(objectId, out typeFlags) && typeFlags != 0)
return true;
}
if (TryGetCreateSeedType(objectId, out uint seeded))
{
typeFlags = seeded;
return true;
}
// Snapshot hit with flags=0 is still an answer (static scenery often has no type).
lock (_objectIdentityCacheLock) lock (_objectIdentityCacheLock)
{ {
if (_objectTypeCache.TryGetValue(objectId, out typeFlags)) if (_objectTypeCache.TryGetValue(objectId, out typeFlags))
@ -2592,36 +2625,7 @@ internal static class ClientObjectHooks
return TryGetPwdSnapshotInt(objectId, stype, out value); return TryGetPwdSnapshotInt(objectId, stype, out value);
} }
if (pwdFieldOffset >= 0 && _weeniePhysicsObjOffset >= 0) // CBaseQualities::InqInt for stypes not in PWD.
{
try
{
IntPtr weeniePtr = _getWeenieObject(objectId);
if (weeniePtr == IntPtr.Zero)
return false;
int pwdBase = _weeniePhysicsObjOffset + 4;
IntPtr fieldAddr = weeniePtr + pwdBase + pwdFieldOffset;
// Page-probe BOTH ends of the 4-byte read span (mirrors
// TryGetObjectOwnershipInfo's dual-end probe): a freed-but-decommitted
// weenie whose field straddles a committed/decommitted page boundary is
// an uncatchable AV under NativeAOT; the catch below only covers
// null-page faults. All stypes served here are Marshal.ReadInt32
// (4 bytes), so the span is [fieldAddr, fieldAddr+3].
if (!IsReadablePointer(fieldAddr) || !IsReadablePointer(fieldAddr + 3))
return false;
value = Marshal.ReadInt32(fieldAddr);
return true;
}
catch
{
return false;
}
}
// Fall through to CBaseQualities::InqInt for stypes not in PWD.
// (IsOnMainThread already checked above, before the PWD fast path.)
if (_inqInt == null) if (_inqInt == null)
{ {
if (!Probe() || _inqInt == null) if (!Probe() || _inqInt == null)
@ -3341,6 +3345,101 @@ internal static class ClientObjectHooks
} }
} }
/// <summary>
/// Records an object's name and ITEM_TYPE straight from the PublicWeenieDesc passed
/// to ACCObjectMaint::CreateObject. Called from the create hook on AC's main thread,
/// after the original returns. The descriptor is server data that exists before the
/// object's qualities do, so this makes names/types readable off-thread immediately
/// instead of after the first successful identity snapshot (~10 s at login).
/// Every read is pointer-validated; a bad descriptor simply records nothing.
/// </summary>
internal static void SeedIdentityFromCreate(uint objectId, IntPtr weenieDesc)
{
if (objectId == 0 || weenieDesc == IntPtr.Zero)
return;
try
{
// PublicWeenieDesc derives from PackObj, so a real descriptor starts with an
// acclient.exe vtable; reject anything else before reading fields.
if (!LooksLikeAcHeapObject(weenieDesc))
return;
bool gotName = TryReadPwdString(weenieDesc, PwdNameOffset, out string name);
uint typeFlags = 0;
IntPtr typeAddr = weenieDesc + PwdTypeOffset;
bool gotType = IsReadablePointer(typeAddr);
if (gotType)
typeFlags = unchecked((uint)Marshal.ReadInt32(typeAddr));
if (!gotName && (!gotType || typeFlags == 0))
return;
lock (_createSeedLock)
{
// Safety valve for a missed delete: drop everything rather than grow forever.
// The live snapshot covers anything still in the world.
if (_createSeedNames.Count >= CreateSeedCap || _createSeedTypes.Count >= CreateSeedCap)
{
_createSeedNames.Clear();
_createSeedTypes.Clear();
}
if (gotName)
_createSeedNames[objectId] = name;
if (gotType && typeFlags != 0)
_createSeedTypes[objectId] = typeFlags;
}
int seedNo = System.Threading.Interlocked.Increment(ref _createSeedCount);
// First few samples let a log reader confirm the descriptor offsets resolve
// to sensible names/types on this client build.
if (seedNo <= 5)
RynthLog.Compat($"[CreateSeed] #{seedNo} 0x{objectId:X8} name='{(gotName ? name : "")}' type=0x{typeFlags:X8}");
if (!_loggedCreateSeedServe && seedNo >= 50)
{
_loggedCreateSeedServe = true;
int names, types;
lock (_createSeedLock) { names = _createSeedNames.Count; types = _createSeedTypes.Count; }
RynthLog.Compat($"ClientObjectHooks: create-descriptor identity seeds active — {names} names, {types} types captured at CreateObject.");
}
}
catch
{
// Descriptor read failures are non-fatal; the periodic snapshot still runs.
}
}
/// <summary>Drops create-time seeds for a deleted object (called from the delete hook).</summary>
internal static void ForgetCreateSeed(uint objectId)
{
lock (_createSeedLock)
{
_createSeedNames.Remove(objectId);
_createSeedTypes.Remove(objectId);
}
}
private static bool TryGetCreateSeedName(uint objectId, out string name)
{
lock (_createSeedLock)
{
if (_createSeedNames.TryGetValue(objectId, out string? seeded) && seeded.Length > 0)
{
name = seeded;
return true;
}
}
name = string.Empty;
return false;
}
private static bool TryGetCreateSeedType(uint objectId, out uint typeFlags)
{
lock (_createSeedLock)
return _createSeedTypes.TryGetValue(objectId, out typeFlags);
}
public static bool TryGetObjectName(uint objectId, out string name) public static bool TryGetObjectName(uint objectId, out string name)
{ {
name = string.Empty; name = string.Empty;
@ -3356,6 +3455,10 @@ internal static class ClientObjectHooks
return true; return true;
} }
} }
// Snapshot miss (login burst / object newer than the last walk): serve the
// name captured from the create descriptor.
if (TryGetCreateSeedName(objectId, out name))
return true;
name = string.Empty; name = string.Empty;
return false; return false;
} }
@ -3809,6 +3912,21 @@ internal static class ClientObjectHooks
&& PwdLayout.TryGetInt(e.Bytes, stype, out value); && PwdLayout.TryGetInt(e.Bytes, stype, out value);
} }
/// <summary>
/// Off-thread read of one 4-byte PWD field by raw offset (the <see cref="TryReadPwdInt32"/>
/// contract) from the main-thread snapshot. False for objects the last walk didn't see.
/// </summary>
private static bool TryGetPwdSnapshotRawInt32(uint objectId, int pwdFieldOffset, out int value)
{
value = 0;
if (pwdFieldOffset < 0 || pwdFieldOffset + 4 > PwdLayout.Size)
return false;
if (!TryGetPwdSnapshot(objectId, out PwdEntry e))
return false;
value = System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian(((ReadOnlySpan<byte>)e.Bytes).Slice(pwdFieldOffset));
return true;
}
private static bool TryGetPwdSnapshotFloat(uint objectId, uint stype, out double value) private static bool TryGetPwdSnapshotFloat(uint objectId, uint stype, out double value)
{ {
value = 0; value = 0;

View file

@ -81,6 +81,9 @@ internal static class CreateObjectHooks
if (count <= 0) if (count <= 0)
RynthLog.Verbose($"Compat: create object #{count} id=0x{objectId:X8} ptr=0x{result.ToInt32():X8}"); RynthLog.Verbose($"Compat: create object #{count} id=0x{objectId:X8} ptr=0x{result.ToInt32():X8}");
// Capture name/type from the create descriptor BEFORE the plugin is told about the
// object, so its off-thread classifier can read them on the very first attempt.
ClientObjectHooks.SeedIdentityFromCreate(objectId, weenieDesc);
PluginManager.QueueCreateObject(objectId); PluginManager.QueueCreateObject(objectId);
AutoIdService.Enqueue(objectId); AutoIdService.Enqueue(objectId);
return result; return result;

View file

@ -71,6 +71,7 @@ internal static class DeleteObjectHooks
if (objectId != 0) if (objectId != 0)
{ {
PaletteCache.Remove(objectId); PaletteCache.Remove(objectId);
ClientObjectHooks.ForgetCreateSeed(objectId);
PluginManager.QueueDeleteObject(objectId); PluginManager.QueueDeleteObject(objectId);
AutoIdService.Evict(objectId); AutoIdService.Evict(objectId);
} }

View file

@ -0,0 +1,110 @@
// ============================================================================
// RynthCore.Engine - Compatibility/DragDropHooks.cs
// Hooks UIElementManager::StartDragandDrop so the engine knows which item AC
// is actually dragging. AC does not change the selected object when a drag
// starts, so the selection is the previously clicked item, not the dragged one.
//
// The dragged UI element is resolved to an object id with AC's own
// UIElement_ItemList::InqDropIconInfo (the same call AC makes when the drop
// lands), then handed to ItemDragBridge, which republishes it to ImGui.
//
// Threads: AC's main thread (AC's input / UI processing).
// ============================================================================
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.ImGuiBackend;
namespace RynthCore.Engine.Compatibility;
internal static unsafe class DragDropHooks
{
// bool __thiscall UIElementManager::StartDragandDrop(UIElementManager*, UIElement* elem, int clickX, int clickY)
private const int StartDragandDropVa = 0x0045E120;
// void __cdecl UIElement_ItemList::InqDropIconInfo(const UIElement* icon, uint& itemId, uint& spellId, DropItemFlags& flags)
private const int InqDropIconInfoVa = 0x004E3380;
// Both verified unique in the shipped client (sub esp,34h / mov edi,[esp+48h] / mov esi,ecx prologue;
// InqDropIconInfo zeroes its out-params up front).
private static readonly byte?[] StartDragandDropPattern =
[
0x83, 0xEC, 0x34, 0x53, 0x55, 0x56, 0x57, 0x8B, 0x7C, 0x24, 0x48, 0x85, 0xFF, 0x8B, 0xF1, 0x0F, 0x84,
null, null, null, null, 0xA1, null, null, null, null, 0x85, 0xC0
];
private static readonly byte?[] InqDropIconInfoPattern =
[
0x8B, 0x44, 0x24, 0x10, 0x83, 0xEC, 0x3C, 0x53, 0x55, 0x8B, 0x6C, 0x24, 0x50, 0x56, 0x8B, 0x74, 0x24, 0x4C,
0x33, 0xDB, 0x3B, 0xF3, 0x57, 0x8B, 0x7C, 0x24, 0x54, 0x89, 0x1F
];
private static IntPtr _originalStartDrag;
private static delegate* unmanaged[Cdecl]<IntPtr, uint*, uint*, uint*, void> _inqDropIconInfo;
private static int _logCount;
/// <summary>The drag-start hook is live, so ItemDragBridge gets the real dragged item.</summary>
public static bool IsInstalled { get; private set; }
public static string StatusMessage { get; private set; } = "Not probed yet.";
public static void Initialize()
{
if (IsInstalled) return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
StatusMessage = "acclient.exe not available.";
return;
}
var inq = HookResolver.Resolve(text, "DragDrop.InqDropIconInfo", InqDropIconInfoPattern, InqDropIconInfoVa);
var start = HookResolver.Resolve(text, "DragDrop.StartDragandDrop", StartDragandDropPattern, StartDragandDropVa);
// A guessed address for either would mean calling or patching the wrong code: pattern hits only.
if (inq.Source != HookResolver.ResolveSource.PatternScan || start.Source != HookResolver.ResolveSource.PatternScan)
{
StatusMessage = $"drag-start hook skipped (InqDropIconInfo {inq.Detail}, StartDragandDrop {start.Detail}).";
RynthLog.Compat($"Compat: {StatusMessage}");
return;
}
try
{
_inqDropIconInfo = (delegate* unmanaged[Cdecl]<IntPtr, uint*, uint*, uint*, void>)inq.Address;
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, int, byte> detour = &StartDragandDropDetour;
MinHook.Hook(start.Address, (IntPtr)detour, out _originalStartDrag);
IsInstalled = true;
StatusMessage = $"Hooked UIElementManager::StartDragandDrop @ 0x{start.Address.ToInt32():X8}.";
RynthLog.Info($"Compat: drag-start hook ready - StartDragandDrop=0x{start.Address.ToInt32():X8}, InqDropIconInfo=0x{inq.Address.ToInt32():X8}");
}
catch (Exception ex)
{
StatusMessage = ex.Message;
RynthLog.Compat($"Compat: drag-start hook failed - {ex.Message}");
}
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
private static byte StartDragandDropDetour(IntPtr manager, IntPtr element, int clickX, int clickY)
{
try
{
if (element != IntPtr.Zero && _inqDropIconInfo != null)
{
uint itemId = 0, spellId = 0, flags = 0;
_inqDropIconInfo(element, &itemId, &spellId, &flags);
// Spell-bar drags carry a spell id and no item.
if (itemId != 0)
{
if (_logCount < 20) { _logCount++; RynthLog.UI($"DragDropHooks: AC drag start item=0x{itemId:X8} flags=0x{flags:X}"); }
ItemDragBridge.OnNativeDragStart(itemId);
}
}
}
catch (Exception ex)
{
try { RynthLog.Compat($"Compat: drag-start detour error - {ex.GetType().Name}: {ex.Message}"); } catch { }
}
var original = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, int, byte>)_originalStartDrag;
return original(manager, element, clickX, clickY);
}
}

View file

@ -168,7 +168,8 @@ internal static class HeartbeatLogger
string vpField = ""; string vpField = "";
try { vpField = D3D9.VideoPatch.OnHeartbeat(draw); } try { vpField = D3D9.VideoPatch.OnHeartbeat(draw); }
catch { } catch { }
RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}{vpField}"); // Unfiltered on purpose: it is the launcher's liveness signal (see RynthLog.Heartbeat).
RynthLog.Heartbeat($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}{vpField}");
// Every 60 s: garbage collections and the time they paused the process. // Every 60 s: garbage collections and the time they paused the process.
// Under the CoreCLR host the engine and managed plugins share one GC, so a // Under the CoreCLR host the engine and managed plugins share one GC, so a

View file

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Outcome of the most recent <see cref="ClientHelperHooks.MergeStackInternal"/> request per
/// (source, target) pair, so a plugin can learn what happened on AC's main thread instead of
/// only "queued". Before this, a merge the engine skipped (target already full) or that AC
/// rejected looked identical to one in flight, and RynthAi's AutoStack waited 10 s per pair
/// and logged a "confirmed failure". Thread-safe; bounded.
/// </summary>
internal static class MergeStackResults
{
// ABI status codes (GetMergeStackResult return value). Never renumber.
public const int None = 0; // no request recorded for this pair (or it aged out)
public const int Queued = 1; // accepted onto the main-thread queue, not executed yet
public const int Sent = 2; // Event_StackableMerge sent for 'amount' units
public const int TargetFull = 3; // skipped: target stack already at max stack size
public const int Failed = 4; // invalid ids, merge API unavailable, AC returned 0, or threw
public const int QueueFull = 5; // main-thread queue full; request dropped before execution
private struct Entry { public int Status; public int Amount; public long TickMs; }
private const int MaxEntries = 512; // prune threshold
private const long PruneAgeMs = 120_000; // results older than this are dropped on prune
private static readonly object _lock = new();
private static readonly Dictionary<ulong, Entry> _results = new();
private static ulong Key(uint source, uint target) => ((ulong)source << 32) | target;
/// <summary>Records the latest outcome for a pair (replaces any earlier one).</summary>
public static void Record(uint source, uint target, int status, int amount = 0)
{
long now = Environment.TickCount64;
lock (_lock)
{
if (_results.Count >= MaxEntries)
Prune(now);
_results[Key(source, target)] = new Entry { Status = status, Amount = amount, TickMs = now };
}
}
/// <summary>Latest outcome for the pair, or <see cref="None"/>. <paramref name="amount"/>
/// is the unit count sent (Sent only) and <paramref name="ageMs"/> how long ago it was recorded.</summary>
public static int Get(uint source, uint target, out int amount, out int ageMs)
{
amount = 0;
ageMs = 0;
lock (_lock)
{
if (!_results.TryGetValue(Key(source, target), out Entry e))
return None;
amount = e.Amount;
long age = Environment.TickCount64 - e.TickMs;
ageMs = age > int.MaxValue ? int.MaxValue : (int)age;
return e.Status;
}
}
// Drops aged results; if everything is recent, clears the map (callers re-request anyway).
private static void Prune(long now)
{
List<ulong>? old = null;
foreach (var kv in _results)
if (now - kv.Value.TickMs > PruneAgeMs)
(old ??= new List<ulong>()).Add(kv.Key);
if (old == null)
{
_results.Clear();
return;
}
foreach (ulong k in old)
_results.Remove(k);
}
}

View file

@ -43,12 +43,24 @@ internal static class SehTrampoline
/// no managed callback / reverse-P/Invoke transition — so unlike the removed /// no managed callback / reverse-P/Invoke transition — so unlike the removed
/// managed CrashLogger VEH it cannot itself re-trigger a NativeAOT fail-fast on an /// managed CrashLogger VEH it cannot itself re-trigger a NativeAOT fail-fast on an
/// AC-owned thread. Writes the faulting 32-bit context + a module-resolved stack /// AC-owned thread. Writes the faulting 32-bit context + a module-resolved stack
/// sweep to <paramref name="logPath"/> for the 0xC0000005 (AV/CSE) and 0xC0000602 /// sweep (bounded by the thread's StackBase) to <paramref name="logPath"/> for FATAL
/// (RaiseFailFast) classes that bypass managed handlers. Observes only. /// crashes only: unhandled exceptions (chained unhandled-exception filter), AVs in
/// NativeAOT code (which the runtime fail-fasts past every filter), and other
/// first-chance AVs only if the process dies shortly after. AVs caught by the SEH_*
/// wrappers and the logger's own faults are never written. Observes only.
/// </summary> /// </summary>
public static void InstallCrashLogger(string logPath) public static void InstallCrashLogger(string logPath)
{ {
try { _InstallCrashLogger(logPath); } try
{
_InstallCrashLogger(logPath);
// v2+ logs fatal crashes only (unhandled-exception filter + NativeAOT-module AVs);
// v1 (no version export) logged every first-chance AV.
uint version = 1;
try { version = _SehTrampolineVersion(); }
catch (EntryPointNotFoundException) { }
RynthLog.Compat($"SehTrampoline: native crash logger installed (v{version}{(version >= 2 ? ", fatal-only" : ", logs every first-chance AV")}) -> {logPath}");
}
catch (Exception ex) { RynthLog.Compat($"SehTrampoline: InstallCrashLogger failed - {ex.GetType().Name}: {ex.Message}"); } catch (Exception ex) { RynthLog.Compat($"SehTrampoline: InstallCrashLogger failed - {ex.GetType().Name}: {ex.Message}"); }
} }
@ -104,6 +116,10 @@ internal static class SehTrampoline
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)] CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern void _InstallCrashLogger([MarshalAs(UnmanagedType.LPWStr)] string logPath); private static extern void _InstallCrashLogger([MarshalAs(UnmanagedType.LPWStr)] string logPath);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_SehTrampolineVersion",
CallingConvention = CallingConvention.Cdecl)]
private static extern uint _SehTrampolineVersion();
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_GetTagParserGuardAddress", [DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_GetTagParserGuardAddress",
CallingConvention = CallingConvention.Cdecl)] CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr _GetTagParserGuardAddress(); private static extern IntPtr _GetTagParserGuardAddress();

View file

@ -458,6 +458,11 @@ internal static class EndSceneHook
if (_uiFrameCount < 30) if (_uiFrameCount < 30)
RynthLog.D3D9($"EndSceneHook: OverlayTextureRenderer.Render error: {ovEx.GetType().Name}: {ovEx.Message}"); RynthLog.D3D9($"EndSceneHook: OverlayTextureRenderer.Render error: {ovEx.GetType().Name}: {ovEx.Message}");
} }
// ImGui draw data (in-client panels, plugin overlay windows such as the ILT Hub)
// is submitted LAST so it sits on top of the Avalonia layer. Built in OnEndScene;
// guarded internally, so an ImGui draw failure can't skip the original EndScene.
EngineFrameController.RenderDeferredImGui();
} }
catch (Exception ex) catch (Exception ex)
{ {

View file

@ -169,6 +169,7 @@ internal static class EngineLifecycle
// tick pump and plugins go away — both otherwise keep firing in the old // tick pump and plugins go away — both otherwise keep firing in the old
// generation's (intentionally still-mapped) module across hot-reloads. // generation's (intentionally still-mapped) module across hot-reloads.
Step("ChatFileDispatcher.Stop", () => Compatibility.ChatFileDispatcher.Stop()); Step("ChatFileDispatcher.Stop", () => Compatibility.ChatFileDispatcher.Stop());
Step("LogSettings.StopWatcher", () => LogSettings.StopWatcher());
Step("AutoIdService.Stop", () => Compatibility.AutoIdService.Stop()); Step("AutoIdService.Stop", () => Compatibility.AutoIdService.Stop());
// Stop the headless tick pump BEFORE plugin shutdown / FreeLibrary. // Stop the headless tick pump BEFORE plugin shutdown / FreeLibrary.

View file

@ -12,6 +12,7 @@ using System.Runtime.InteropServices;
using System.Threading; using System.Threading;
using System.Collections.Generic; using System.Collections.Generic;
using ImGuiNET; using ImGuiNET;
using RynthCore;
using RynthCore.Engine.Compatibility; using RynthCore.Engine.Compatibility;
using RynthCore.Engine.D3D9; using RynthCore.Engine.D3D9;
using RynthCore.Engine.Plugins; using RynthCore.Engine.Plugins;
@ -45,7 +46,21 @@ public static class EntryPoint
private static readonly Queue<string> RecentLogLines = new(); private static readonly Queue<string> RecentLogLines = new();
private static long _recentLogSeq; private static long _recentLogSeq;
/// <summary>Set true to enable verbose startup logging (hook ready messages, plugin lifecycle, etc.).</summary> internal enum EngineLogLevel
{
/// <summary>As a global threshold: nothing but errors. As a category level: never written.</summary>
Off = -1,
Error = 0,
Warning = 1,
Info = 2,
Debug = 3,
Trace = 4
}
/// <summary>Active engine logging threshold loaded from engine settings.</summary>
internal static EngineLogLevel LoggingLevel = EngineLogLevel.Info;
/// <summary>Legacy convenience flag used by existing verbose call sites.</summary>
internal static bool VerboseLogging = false; internal static bool VerboseLogging = false;
/// <summary>Set by EngineFrameController once the game window is confirmed. Read by AvaloniaOverlay.</summary> /// <summary>Set by EngineFrameController once the game window is confirmed. Read by AvaloniaOverlay.</summary>
@ -190,8 +205,14 @@ public static class EntryPoint
} }
catch { } catch { }
// engine.json "LoggingLevel" + "LogCategories" (launcher Logging card) set the threshold
// and per-category levels first so every line written below honours them. The watcher
// started later re-reads them whenever the launcher edits the file.
string logSummary = LogSettings.Reload();
// Set up the unified log sink BEFORE anything else so all // Set up the unified log sink BEFORE anything else so all
// subsequent failures are captured in C:\Games\RynthCore\Logs. // subsequent failures are captured in <CoreDir>\Logs (installer-chosen;
// resolved here on the init worker, never under the loader lock).
LogPaths.EnsureLogDirectory(); LogPaths.EnsureLogDirectory();
if (_initCount <= 1) if (_initCount <= 1)
{ {
@ -206,10 +227,18 @@ public static class EntryPoint
InstallManagedExceptionHandlers(); InstallManagedExceptionHandlers();
RynthLog.Info("================================================================"); // The banner bypasses the category levels: it must be in every log, whatever engine.json says.
RynthLog.Info($"RynthCore.Engine init build={BuildStamp} initCount={_initCount} pid={Environment.ProcessId}"); LogTagged("engine", "================================================================", "INF");
RynthLog.Info($" os={Environment.OSVersion} clr={Environment.Version} cwd={Environment.CurrentDirectory}"); LogTagged("engine", $"RynthCore.Engine init build={BuildStamp} initCount={_initCount} pid={Environment.ProcessId}", "INF");
RynthLog.Info("================================================================"); LogTagged("engine", $" os={Environment.OSVersion} clr={Environment.Version} cwd={Environment.CurrentDirectory}", "INF");
LogTagged("engine", $" logging {logSummary}", "INF");
LogTagged("engine", "================================================================", "INF");
string hiddenCategories = LogSettings.HiddenCategoriesWarning();
if (hiddenCategories.Length > 0) RynthLog.Warn(hiddenCategories);
// Live logging config: launcher edits to engine.json apply without a client restart.
// Stopped in EngineLifecycle.Shutdown before the module can be unloaded.
LogSettings.StartWatcher();
CrashLogger.Install(); CrashLogger.Install();
@ -217,18 +246,10 @@ public static class EntryPoint
// logging AC's main-thread native stack when its EndScene beat stalls. // logging AC's main-thread native stack when its EndScene beat stalls.
MainThreadHangWatchdog.Start(); MainThreadHangWatchdog.Start();
// MultiClientHooks.Initialize installs MinHook detours synchronously // MultiClientHooks installs MinHook-based detours immediately. P/Invoke resolves
// here, BEFORE InitWorker spawns and runs the main PreloadNativeDll // minhook.x86.dll before InitWorker runs, so preload it from the engine directory;
// pass. If we don't preload minhook.x86.dll first, the P/Invoke // otherwise Client::IsAlreadyRunning fires unpatched on second-and-later clients.
// into minhook fails with DllNotFoundException and the multi- TryPreloadMinHookForEarlyInit();
// client hook silently skips — which means AC's
// Client::IsAlreadyRunning check fires unpatched on the second-
// and-later concurrent acclient.exe processes.
string? earlyEngineDir = GetEngineDirectory();
if (!string.IsNullOrEmpty(earlyEngineDir))
PreloadNativeDll(earlyEngineDir, "minhook.x86.dll");
else
RynthLog.Info("Early-init: could not resolve engine directory — minhook may not be preloaded before MultiClientHooks.");
RunInitStep("early multi-client hooks", MultiClientHooks.Initialize); RunInitStep("early multi-client hooks", MultiClientHooks.Initialize);
// Before AC's main thread resumes, so no dat or network unpack runs the stock // Before AC's main thread resumes, so no dat or network unpack runs the stock
@ -339,6 +360,33 @@ public static class EntryPoint
return new string(buffer, 0, (int)length); return new string(buffer, 0, (int)length);
} }
/// <summary>
/// Loads MinHook on the RynthCoreInit thread so <see cref="MultiClientHooks.Initialize"/> can
/// call <see cref="Hooking.MinHook"/> P/Invokes without relying on the default DLL search path
/// (which often resolves against the AC client directory, not <c>Runtime\</c>).
/// </summary>
private static void TryPreloadMinHookForEarlyInit()
{
try
{
string? engineDir = GetEngineDirectory();
if (string.IsNullOrEmpty(engineDir))
{
RynthLog.Info("Early MinHook preload skipped: could not resolve engine directory.");
return;
}
if (PreloadNativeDll(engineDir, "minhook.x86.dll"))
RynthLog.Verbose($"Early MinHook preload OK (engine dir: {engineDir})");
else
RynthLog.Info($"Early MinHook preload failed: minhook.x86.dll not found beside engine ({engineDir}).");
}
catch (Exception ex)
{
RynthLog.Info($"Early MinHook preload exception: {ex.Message}");
}
}
/// <summary> /// <summary>
/// No-op anchor whose address is taken via `&EngineDirAnchor` to give us a /// No-op anchor whose address is taken via `&EngineDirAnchor` to give us a
/// stable pointer inside the engine's own module image — used by /// stable pointer inside the engine's own module image — used by
@ -695,6 +743,8 @@ public static class EntryPoint
Step("account hooks", AccountHooks.Initialize); Step("account hooks", AccountHooks.Initialize);
Step("client combat hooks", () => ClientCombatHooks.Probe()); Step("client combat hooks", () => ClientCombatHooks.Probe());
Step("selected-target hooks", SelectedTargetHooks.Initialize); Step("selected-target hooks", SelectedTargetHooks.Initialize);
// Which item AC is dragging (AC keeps the old selection during a drag).
Step("drag-start hook", DragDropHooks.Initialize);
Step("smartbox hooks", SmartBoxHooks.Initialize); Step("smartbox hooks", SmartBoxHooks.Initialize);
Step("player vitals hooks", PlayerVitalsHooks.Initialize); Step("player vitals hooks", PlayerVitalsHooks.Initialize);
Step("enchantment hooks", () => EnchantmentHooks.Initialize()); Step("enchantment hooks", () => EnchantmentHooks.Initialize());
@ -1686,10 +1736,34 @@ public static class EntryPoint
internal static void LogVerbose(string message) internal static void LogVerbose(string message)
{ {
if (VerboseLogging) if (ShouldLog(EngineLogLevel.Debug))
Log(message); Log(message);
} }
/// <summary>
/// True when a line at <paramref name="level"/> passes the global threshold. Off-level lines
/// never pass; an Off threshold blocks everything (errors bypass this gate).
/// </summary>
internal static bool ShouldLog(EngineLogLevel level)
=> level != EngineLogLevel.Off && level <= LoggingLevel;
/// <summary>Parses the global level: Off, Error, Warning/Warn, Info, Debug/Verbose, Trace. Unknown → Info.</summary>
internal static EngineLogLevel ParseLoggingLevel(string? configuredLevel)
{
if (string.IsNullOrWhiteSpace(configuredLevel))
return EngineLogLevel.Info;
string normalized = configuredLevel.Trim();
if (string.Equals(normalized, "Verbose", StringComparison.OrdinalIgnoreCase))
return EngineLogLevel.Debug;
if (string.Equals(normalized, "Warn", StringComparison.OrdinalIgnoreCase))
return EngineLogLevel.Warning;
return Enum.TryParse(normalized, ignoreCase: true, out EngineLogLevel parsed) && Enum.IsDefined(parsed)
? parsed
: EngineLogLevel.Info;
}
internal static string[] GetRecentLogLines() internal static string[] GetRecentLogLines()
{ {
lock (LogLock) lock (LogLock)

View file

@ -23,6 +23,7 @@ using System.Runtime.InteropServices;
using ImGuiNET; using ImGuiNET;
using RynthCore.Engine.D3D9; using RynthCore.Engine.D3D9;
using RynthCore.Engine.Plugins; using RynthCore.Engine.Plugins;
using RynthCore.Install;
namespace RynthCore.Engine.ImGuiBackend; namespace RynthCore.Engine.ImGuiBackend;
@ -48,6 +49,9 @@ internal static class EngineFrameController
private static bool _imguiInitFailed; private static bool _imguiInitFailed;
private static bool _coreResolved; private static bool _coreResolved;
private static bool _pluginsInitialized; private static bool _pluginsInitialized;
// Pump frames plugin init has waited for the ImGui context (PumpPluginFrame; ~16 ms each).
private static int _pluginInitContextWaits;
private const int PluginInitContextMaxWaits = 300;
private static IntPtr _context; private static IntPtr _context;
private static IntPtr _gameHwnd; private static IntPtr _gameHwnd;
@ -61,6 +65,25 @@ internal static class EngineFrameController
/// </summary> /// </summary>
internal static volatile IntPtr CachedDevice; internal static volatile IntPtr CachedDevice;
private static int _pluginPumpInFrame; // re-entrancy guard for the pump private static int _pluginPumpInFrame; // re-entrancy guard for the pump
// ImGui pipeline diagnostics (render thread only): one-time lines plus a 30 s heartbeat so a
// log shows whether frames start, which branch runs and whether draw data is submitted.
private const long HeartbeatIntervalMs = 30_000;
private static long _engineErrorCount;
private static long _nextEngineErrorLogAt;
private static bool _loggedFirstSubmit;
private static int _loggedBranch = -1;
private static string _initFailStep = "unknown";
private static long _drawSubmits;
private static long _nextHeartbeatAt;
// Device for this frame's built ImGui draw data, submitted by RenderDeferredImGui after the
// Avalonia blit. Render thread only; Zero = nothing pending. The draw data stays valid until
// the next NewFrame on the main context.
private static IntPtr _deferredSubmitDevice;
// Build + pop-out time of the frame waiting in _deferredSubmitDevice (UiFrameStats adds the submit).
private static long _deferredUiTicks;
private static long _lastFrameTicks; private static long _lastFrameTicks;
private static int _frameCount; private static int _frameCount;
@ -103,7 +126,10 @@ internal static class EngineFrameController
return true; return true;
if (!EnsureCore(pDevice)) if (!EnsureCore(pDevice))
{
_initFailStep = "EnsureCore (game window not found)";
return false; return false;
}
// Before any context exists: the loaded cimgui.dll must be the exact // Before any context exists: the loaded cimgui.dll must be the exact
// build ImGui.NET wraps, or every struct read below is at wrong offsets. // build ImGui.NET wraps, or every struct read below is at wrong offsets.
@ -131,7 +157,7 @@ internal static class EngineFrameController
System.IO.Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir); System.IO.Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir);
IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath); IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath);
unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; } unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; }
RynthLog.Render($"EngineFrameController: imgui.ini pinned to {iniPath}"); RynthLog.Info($"EngineFrameController: imgui.ini pinned to {iniPath}");
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -155,10 +181,16 @@ internal static class EngineFrameController
ImGuiFonts.Build(io, _uiScale); ImGuiFonts.Build(io, _uiScale);
if (!Win32Backend.Init(_gameHwnd)) if (!Win32Backend.Init(_gameHwnd))
{
_initFailStep = "Win32Backend.Init";
return false; return false;
}
if (!DX9Backend.InitImGui(pDevice)) if (!DX9Backend.InitImGui(pDevice))
{
_initFailStep = "DX9Backend.InitImGui";
return false; return false;
}
_lastFrameTicks = Stopwatch.GetTimestamp(); _lastFrameTicks = Stopwatch.GetTimestamp();
_imguiInitialized = true; _imguiInitialized = true;
@ -229,6 +261,8 @@ internal static class EngineFrameController
// EngineSettings.EnableImGuiBackend, so world→screen capture, nav- // EngineSettings.EnableImGuiBackend, so world→screen capture, nav-
// marker rendering, and plugin lifecycle stay alive when the ImGui // marker rendering, and plugin lifecycle stay alive when the ImGui
// surface is disabled. // surface is disabled.
// A frame that throws before its build must not resubmit last frame's draw data.
_deferredSubmitDevice = IntPtr.Zero;
try try
{ {
// Resolve game HWND and seed EntryPoint.GameHwnd. Required even // Resolve game HWND and seed EntryPoint.GameHwnd. Required even
@ -344,10 +378,10 @@ internal static class EngineFrameController
// calls it at all. // calls it at all.
// ── ImGui-gated work ───────────────────────────────────────── // ── ImGui-gated work ─────────────────────────────────────────
// The frame is BUILT here and SUBMITTED after the Nav3D fallback and // The frame is BUILT here and SUBMITTED by RenderDeferredImGui, which
// the vital HUD, so ImGui windows sit above both. The Avalonia quad // EndSceneHook calls after the Avalonia quad, so ImGui windows sit above
// (EndSceneHook, after this returns) stays topmost while both stacks // the Nav3D fallback, the vital HUD and the Avalonia panels. Input order
// run, matching input order: Avalonia gets the first hit test. // matches: Win32Backend gives ImGui the mouse while it wants it.
bool imguiEnabled = Plugins.EngineSettings.EnableImGuiBackend; bool imguiEnabled = Plugins.EngineSettings.EnableImGuiBackend;
bool imguiBuilt = false; bool imguiBuilt = false;
long uiTicks = 0; long uiTicks = 0;
@ -370,17 +404,33 @@ internal static class EngineFrameController
if (imguiEnabled) if (imguiEnabled)
{ {
long t0 = Stopwatch.GetTimestamp(); long t0 = Stopwatch.GetTimestamp();
if (imguiBuilt)
SubmitImGuiFrame(pDevice);
// Popped-out panels: their own contexts, windows and render targets. // Popped-out panels: their own contexts, windows and render targets.
if (_imguiInitialized) if (_imguiInitialized)
ImGuiPopOuts.RenderAll(pDevice, _uiScale, PanelsLive); ImGuiPopOuts.RenderAll(pDevice, _uiScale, PanelsLive);
UiFrameStats.Record(uiTicks + (Stopwatch.GetTimestamp() - t0)); long ticks = uiTicks + (Stopwatch.GetTimestamp() - t0);
if (imguiBuilt)
{
_deferredUiTicks = ticks;
_deferredSubmitDevice = pDevice;
}
else
{
UiFrameStats.Record(ticks);
}
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
RynthLog.Info($"EngineFrameController: frame {_frameCount} engine error: {ex.GetType().Name}: {ex.Message}"); // An exception here skips everything after it this frame (including RunImGuiFrame), so
// the first one gets a stack trace; repeats are summarised every 30 s instead of per frame.
_engineErrorCount++;
long errNow = Environment.TickCount64;
if (_engineErrorCount == 1)
RynthLog.Error($"EngineFrameController: engine frame error (rest of this frame skipped): {ex}");
else if (errNow >= _nextEngineErrorLogAt)
RynthLog.Error($"EngineFrameController: engine frame errors so far={_engineErrorCount}, latest {ex.GetType().Name}: {ex.Message}");
if (errNow >= _nextEngineErrorLogAt)
_nextEngineErrorLogAt = errNow + HeartbeatIntervalMs;
} }
finally finally
{ {
@ -442,14 +492,26 @@ internal static class EngineFrameController
return; // never re-enter PluginManager from two stacks return; // never re-enter PluginManager from two stacks
try try
{ {
// Plugins only get the ImGui context when they may draw with it // Plugins only get the ImGui context when they may draw with it: the
// (EnableImGuiShell, FORCE-gated). The engine's own ImGui panels // ImGui shell (EnableImGuiShell, FORCE-gated) or their own overlay
// don't need plugins to see it, and handing it over switched // windows (EnablePluginOverlayWindows: RynthAi's ILT Hub, HUDs, Item
// RynthAi into its legacy-ImGui setup (first ImGui-on test, // Info; RynthPluginRenderOverlay). RynthAi only reads the context for
// 2026-09-28) - plugins must behave exactly as in Avalonia-only mode. // those windows, so this does not switch it into a legacy-ImGui setup.
IntPtr pluginContext = Plugins.EngineSettings.EnableImGuiShell ? _context : IntPtr.Zero; bool pluginsDraw = Plugins.EngineSettings.EnableImGuiShell
|| (Plugins.EngineSettings.EnablePluginOverlayWindows && Plugins.EngineSettings.EnableImGuiBackend);
// _context is written by the render thread (Init); this is the pump thread.
IntPtr pluginContext = pluginsDraw ? System.Threading.Volatile.Read(ref _context) : IntPtr.Zero;
if (!_pluginsInitialized) if (!_pluginsInitialized)
{ {
// The plugin host copies the context once at init, so wait for the
// render path's ImGui init (first ImGui frame) rather than hand over
// zero for the whole session. Bounded: a failed or stalled ImGui init
// must not hold plugins (and the bot) back.
if (pluginsDraw && pluginContext == IntPtr.Zero && !_imguiInitFailed
&& ++_pluginInitContextWaits <= PluginInitContextMaxWaits)
return;
if (pluginsDraw && pluginContext == IntPtr.Zero)
RynthLog.Warn($"EngineFrameController: plugins initialised without an ImGui context (imguiInitFailed={_imguiInitFailed}, waits={_pluginInitContextWaits}) - plugin overlay windows will not draw this session.");
_pluginsInitialized = true; _pluginsInitialized = true;
PluginManager.InitPlugins(pluginContext, device, _gameHwnd); PluginManager.InitPlugins(pluginContext, device, _gameHwnd);
} }
@ -501,9 +563,16 @@ internal static class EngineFrameController
if (!PanelsLive) return false; if (!PanelsLive) return false;
ImGuiPanelHost.RestoreOnce(); ImGuiPanelHost.RestoreOnce();
return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame return ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame
|| D3D9.VideoPatch.WantsBanner; || D3D9.VideoPatch.WantsBanner || PluginOverlayWindowsLive;
} }
/// <summary>
/// In the world, with the shell off, and some loaded plugin exports
/// RynthPluginRenderOverlay: its windows need a frame every frame.
/// </summary>
private static bool PluginOverlayWindowsLive =>
PanelsLive && Plugins.EngineSettings.EnablePluginOverlayWindows && PluginManager.HasOverlayPlugins;
/// <summary> /// <summary>
/// Panel faces show only in the world, like the Avalonia overlay (hidden /// Panel faces show only in the world, like the Avalonia overlay (hidden
/// between characters, not closed). Also off as soon as AC leaves the world screen /// between characters, not closed). Also off as soon as AC leaves the world screen
@ -544,7 +613,8 @@ internal static class EngineFrameController
} }
private static bool HasImGuiContentNoRestore() => private static bool HasImGuiContentNoRestore() =>
Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame || D3D9.VideoPatch.WantsBanner)); Plugins.EngineSettings.EnableImGuiShell || ImGuiFontTest.Enabled || (PanelsLive && (ImGuiPanelHost.NeedsFrame || ImGuiBar.Visible || ImGuiBar.PoppedOut || Hud.MonsterHud.WantsFrame || D3D9.VideoPatch.WantsBanner))
|| PluginOverlayWindowsLive;
// Keyboard owner between the stacks (plan §3.2 d): whichever side started // Keyboard owner between the stacks (plan §3.2 d): whichever side started
// text entry most recently keeps the keyboard. // text entry most recently keeps the keyboard.
@ -573,6 +643,7 @@ internal static class EngineFrameController
if (!Init(pDevice)) if (!Init(pDevice))
{ {
_imguiInitFailed = true; _imguiInitFailed = true;
RynthLog.Error($"EngineFrameController: ImGui init FAILED at step '{_initFailStep}' - ImGui frames disabled for this session.");
return false; return false;
} }
} }
@ -596,7 +667,6 @@ internal static class EngineFrameController
ImGuiNET.ImGui.SetCurrentContext(_context); ImGuiNET.ImGui.SetCurrentContext(_context);
bool frameStarted = false; bool frameStarted = false;
bool frameEnded = false; bool frameEnded = false;
try try
{ {
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
@ -644,6 +714,9 @@ internal static class EngineFrameController
ImGuiNET.ImGui.NewFrame(); ImGuiNET.ImGui.NewFrame();
frameStarted = true; frameStarted = true;
// Before any window: a drag from a popped-out Inventory or AC's inventory becomes
// a payload the client's drop targets (Mini Remote slots) see this frame.
ItemDragBridge.SubmitMainFrame(io);
ImGuiTextFocus.BeginFrame(); ImGuiTextFocus.BeginFrame();
if (_dropImGuiTextFocus) if (_dropImGuiTextFocus)
{ {
@ -653,11 +726,29 @@ internal static class EngineFrameController
} }
// EnableImGuiShell gates the old diagnostic shell and plugin-drawn // EnableImGuiShell gates the old diagnostic shell and plugin-drawn
// ImGui windows (plugin code on AC's thread: FORCE-gated, stays off). // ImGui windows (plugin code on AC's thread: FORCE-gated, stays off).
int branch;
if (Plugins.EngineSettings.EnableImGuiShell) if (Plugins.EngineSettings.EnableImGuiShell)
{ {
branch = 1;
RynthCoreShell.Render(_frameCount); RynthCoreShell.Render(_frameCount);
PluginManager.RenderAll(); PluginManager.RenderAll();
} }
else if (PluginOverlayWindowsLive)
{
branch = 2;
// Only the opt-in extra windows (RynthPluginRenderOverlay), never the
// plugins' full ImGui UIs.
PluginManager.RenderOverlayAll();
}
else
{
branch = 0;
}
if (branch != _loggedBranch)
{
_loggedBranch = branch;
RynthLog.Info($"EngineFrameController: ImGui plugin branch = {(branch == 1 ? "shell (RenderAll)" : branch == 2 ? "overlay windows (RenderOverlayAll)" : "none")}.");
}
if (PanelsLive) if (PanelsLive)
{ {
// World overlays: built into UnderUiLayer's list, drawn next frame at // World overlays: built into UnderUiLayer's list, drawn next frame at
@ -744,6 +835,24 @@ internal static class EngineFrameController
_prevAvaloniaText = avaloniaText; _prevAvaloniaText = avaloniaText;
} }
/// <summary>
/// Submits this frame's ImGui draw data. EndSceneHook calls it after
/// OverlayTextureRenderer.Render so ImGui windows draw on top of the Avalonia layer.
/// Runs whether or not the Avalonia blit ran (character select, Avalonia off), and is
/// a no-op when <see cref="OnEndScene"/> built nothing this frame. Never throws.
/// </summary>
public static void RenderDeferredImGui()
{
IntPtr device = _deferredSubmitDevice;
if (device == IntPtr.Zero)
return;
_deferredSubmitDevice = IntPtr.Zero; // one submission per frame, even if it throws
long t0 = Stopwatch.GetTimestamp();
SubmitImGuiFrame(device);
UiFrameStats.Record(_deferredUiTicks + (Stopwatch.GetTimestamp() - t0));
}
/// <summary>Draws the frame <see cref="BuildImGuiFrame"/> produced.</summary> /// <summary>Draws the frame <see cref="BuildImGuiFrame"/> produced.</summary>
private static void SubmitImGuiFrame(IntPtr pDevice) private static void SubmitImGuiFrame(IntPtr pDevice)
{ {
@ -751,7 +860,15 @@ internal static class EngineFrameController
ImGuiNET.ImGui.SetCurrentContext(_context); ImGuiNET.ImGui.SetCurrentContext(_context);
try try
{ {
DX9Backend.RenderDrawData(ImGuiNET.ImGui.GetDrawData(), pDevice); ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
DX9Backend.RenderDrawData(drawData, pDevice);
_drawSubmits++;
if (!_loggedFirstSubmit)
{
_loggedFirstSubmit = true;
RynthLog.Info("EngineFrameController: first ImGui draw submitted.");
}
LogHeartbeatIfDue(drawData);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -763,6 +880,29 @@ internal static class EngineFrameController
} }
} }
/// <summary>
/// Every 30 s: built ImGui frames, submits, draw list / vertex counts of the
/// latest frame and the overlay-window stats from PluginManager. Zero draw lists means no
/// ImGui window was drawn that frame. One string per interval; no per-frame allocation.
/// </summary>
private static void LogHeartbeatIfDue(ImDrawDataPtr drawData)
{
long now = Environment.TickCount64;
if (now < _nextHeartbeatAt) return;
bool first = _nextHeartbeatAt == 0;
_nextHeartbeatAt = now + HeartbeatIntervalMs;
if (first) return; // first interval starts now; the first-frame line already covers t=0
int lists = 0, vertices = 0;
unsafe
{
// ImDrawData: +4 CmdListsCount, +8 TotalIdxCount, +12 TotalVtxCount (see CLAUDE.md offsets).
byte* p = (byte*)drawData.NativePtr;
if (p != null) { lists = *(int*)(p + 4); vertices = *(int*)(p + 12); }
}
RynthLog.Info($"EngineFrameController: ImGui heartbeat frames={_framesBuilt} submits={_drawSubmits} lastFrame drawLists={lists} vertices={vertices} {PluginManager.DescribeOverlayState()}.");
}
internal static IntPtr FindGameWindow() internal static IntPtr FindGameWindow()
{ {
uint pid = GetCurrentProcessId(); uint pid = GetCurrentProcessId();

View file

@ -67,6 +67,10 @@ internal sealed record PanelSpec(
// Where the panel first opens (logical units) when nothing is saved for its // Where the panel first opens (logical units) when nothing is saved for its
// key; null = the cascade. (Script windows: a FirstUseEver position.) // key; null = the cascade. (Script windows: a FirstUseEver position.)
Vector2? DefaultPos = null, Vector2? DefaultPos = null,
// With nothing saved and no DefaultPos: open centred in the game view rather
// than in the top-left cascade, where popped-out panels (separate windows
// above the game frame) usually sit and would hide it.
bool OpenCentered = false,
// No resize grip, docked or popped out: the face sizes itself (the RynthNav arrow // No resize grip, docked or popped out: the face sizes itself (the RynthNav arrow
// fits its height to what it shows). Chromeless and GripInBody panels only. // fits its height to what it shows). Chromeless and GripInBody panels only.
bool NoResize = false); bool NoResize = false);
@ -651,6 +655,10 @@ internal static class ImGuiPanelHost
{ {
pos = defaultPos; // the face's own first spot (a script window's FirstUseEver position) pos = defaultPos; // the face's own first spot (a script window's FirstUseEver position)
} }
else if (entry.Spec.OpenCentered && CenteredLogicalPos(size, placeScale) is Vector2 centered)
{
pos = centered;
}
else else
{ {
int shown = 0; int shown = 0;
@ -670,6 +678,104 @@ internal static class ImGuiPanelHost
entry.NeedsPlacement = true; entry.NeedsPlacement = true;
entry.DesiredPos = entry.Pos != pos * placeScale ? pos * placeScale : null; entry.DesiredPos = entry.Pos != pos * placeScale ? pos * placeScale : null;
entry.DesiredForDisplay = ImGuiNET.ImGui.GetIO().DisplaySize; entry.DesiredForDisplay = ImGuiNET.ImGui.GetIO().DisplaySize;
// Popped-out windows sit above the game frame, so a docked panel opening under
// one would be invisible. The new spot is saved by the open's Persist, so the
// panel comes back where it could be seen.
if (ClearOfPopOuts(entry.Pos, entry.Size) is Vector2 clear)
{
RynthLog.UI($"ImGuiPanelHost: {entry.Title} would open under a popped-out window; " +
$"moved from ({entry.Pos.X:0},{entry.Pos.Y:0}) to ({clear.X:0},{clear.Y:0}).");
entry.Pos = clear;
entry.PersistedPos = clear;
entry.DesiredPos = null; // don't pull it back under the pop-out as the display grows
}
}
/// <summary>Above this share of a docked panel hidden by popped-out windows, it opens elsewhere.</summary>
private const float MaxCoveredFraction = 0.5f;
/// <summary>Candidate spots per axis when looking for a clear place (a grid over the game view).</summary>
private const int ClearSpotSteps = 8;
/// <summary>
/// A spot (client px) for a docked window of <paramref name="size"/> at <paramref name="pos"/>
/// that popped-out windows hide less, nearest the original among the least-covered; null when
/// at most half of it is covered or no spot is better.
/// </summary>
private static Vector2? ClearOfPopOuts(Vector2 pos, Vector2 size)
{
float area = size.X * size.Y;
if (area <= 0) return null;
List<(Vector2 Min, Vector2 Max)> covers = PopOutRectsInClient();
if (covers.Count == 0) return null;
float covered = CoveredArea(pos, size, covers);
if (covered <= area * MaxCoveredFraction) return null;
Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize;
if (display.X <= 1 || display.Y <= 1) return null;
Vector2 room = Vector2.Max(Vector2.Zero, display - size);
// Pass 1: the least coverage any grid spot reaches. Pass 2: the nearest spot within
// 2% of the panel's area of that, so a nearly-as-clear nearby spot beats a far one.
float least = float.MaxValue;
for (int i = 0; i <= ClearSpotSteps; i++)
for (int j = 0; j <= ClearSpotSteps; j++)
least = Math.Min(least, CoveredArea(GridSpot(room, i, j), size, covers));
if (least >= covered) return null;
float tolerance = least + area * 0.02f;
Vector2? best = null;
float bestDist = float.MaxValue;
for (int i = 0; i <= ClearSpotSteps; i++)
for (int j = 0; j <= ClearSpotSteps; j++)
{
Vector2 spot = GridSpot(room, i, j);
if (CoveredArea(spot, size, covers) > tolerance) continue;
float dist = Vector2.DistanceSquared(spot, pos);
if (dist < bestDist) { bestDist = dist; best = spot; }
}
return best;
}
private static Vector2 GridSpot(Vector2 room, int i, int j) =>
new(MathF.Round(room.X * i / ClearSpotSteps), MathF.Round(room.Y * j / ClearSpotSteps));
/// <summary>Visible popped-out windows' rects in the game window's client px (ImGui coordinates).</summary>
private static List<(Vector2 Min, Vector2 Max)> PopOutRectsInClient()
{
Vector2 origin = ImGuiPopOuts.ClientOriginOnScreen();
var rects = new List<(Vector2, Vector2)>();
foreach (var (left, top, width, height) in UI.LayeredWindow.VisibleContentRects())
{
var min = new Vector2(left, top) - origin;
rects.Add((min, min + new Vector2(width, height)));
}
return rects;
}
/// <summary>Area of the window hidden by <paramref name="covers"/> (overlaps between covers count twice).</summary>
private static float CoveredArea(Vector2 pos, Vector2 size, List<(Vector2 Min, Vector2 Max)> covers)
{
Vector2 max = pos + size;
float total = 0;
foreach (var (cMin, cMax) in covers)
{
float w = MathF.Min(max.X, cMax.X) - MathF.Max(pos.X, cMin.X);
float h = MathF.Min(max.Y, cMax.Y) - MathF.Max(pos.Y, cMin.Y);
if (w > 0 && h > 0) total += w * h;
}
return total;
}
/// <summary>
/// Top-left (logical units) that centres a window of logical <paramref name="size"/> in the
/// game view; null while the display size isn't known yet.
/// </summary>
private static Vector2? CenteredLogicalPos(Vector2 size, float placeScale)
{
Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize;
if (display.X <= 1 || display.Y <= 1 || placeScale <= 0) return null;
return Vector2.Max(Vector2.Zero, (display / placeScale - size) * 0.5f);
} }
private static Vector2 ClampToDisplay(Vector2 pos, Vector2 size) private static Vector2 ClampToDisplay(Vector2 pos, Vector2 size)

View file

@ -0,0 +1,251 @@
// ============================================================================
// RynthCore.Engine - ImGui/ItemDragBridge.cs
// Carries an item drag into the MAIN ImGui context when it didn't start there,
// so drop targets in the client (RynthAi's Mini Remote slots) can take it:
//
// • A popped-out Inventory: the pop-out has its own ImGui context and holds
// mouse capture for the whole drag, so the main context never sees it.
// The pop-out face reports the dragged item (NotePopOutDrag); the main
// frame republishes it as an extern payload. The main context sees no
// button press, so the payload uses PayloadAutoExpire: it is delivered to
// the hovered target on the first frame it is no longer submitted.
// • AC's own inventory: a press that began on the game belongs to the game,
// and ImGui ignores hovering for it. DragDropHooks reports the item AC
// starts dragging (OnNativeDragStart); a carried one is republished the
// same way, under PayloadType, and delivered when ImGui sees the button go
// up. AC does not select the dragged item, so without that hook the bridge
// can only guess from the selection: the guess goes out under
// NativePayloadType, which targets treat as unreliable.
//
// A native drag released over an ImGui window would otherwise complete in AC
// as a drop on the 3D view (the item lands on the ground). TryRedirectNativeDrop
// moves that button-up back to where the drag began, which AC treats as
// putting the item back.
//
// Threads: AC's main thread only (game WndProc, EndScene, pop-out frames).
// ============================================================================
using System;
using System.Diagnostics;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class ItemDragBridge
{
/// <summary>Payload type for one item (uint object id). Must match RynthAi's MiniRemoteHud.ItemPayloadType.</summary>
public const string PayloadType = "RYNTH_INV_ITEM";
/// <summary>
/// Payload type for a game drag whose item was guessed from the selection (DragDropHooks not
/// installed). Any game left-drag with a carried item selected looks like this (moving an AC
/// panel too), so targets should take it only where a wrong item does no harm (RynthAi: empty
/// slots). Must match MiniRemoteHud.GameItemPayloadType.
/// </summary>
public const string NativePayloadType = "RYNTH_GAME_ITEM";
private const uint WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202;
private const int MK_LBUTTON = 0x0001, MK_OTHER = 0x0002 | 0x0010 | 0x0020 | 0x0040;
/// <summary>Movement (px, squared) before a game press counts as a drag.</summary>
private const int DragThresholdSq = 5 * 5;
/// <summary>AC may select the pressed item a few messages after the press: keep re-reading it this long.</summary>
private static readonly long SelectionSettleTicks = Stopwatch.Frequency / 2;
/// <summary>A pop-out drag with no report for this long is over (the pop-out closed mid-drag).</summary>
private static readonly long PopOutStaleTicks = Stopwatch.Frequency;
// Popped-out Inventory drag.
private static uint _popOutItem;
private static long _popOutSeenAt;
// Native (AC inventory) drag.
private static bool _pressPending;
private static IntPtr _pressLParam;
private static int _pressX, _pressY;
private static long _pressAt;
private static uint _nativeItem;
/// <summary>_nativeItem came from AC's drag start (DragDropHooks), not from the selection.</summary>
private static bool _nativeFromHook;
/// <summary>The left button is down on a press that belongs to the game.</summary>
private static bool _gamePressHeld;
private static bool _nativeReleased;
/// <summary>The cursor was over an ImGui window in the last main frame (only tracked during a native drag).</summary>
private static bool _overImGui;
// ── Popped-out Inventory ────────────────────────────────────────────────
/// <summary>A popped-out Inventory is dragging <paramref name="itemId"/> (call every pop-out frame of the drag).</summary>
public static void NotePopOutDrag(uint itemId)
{
if (itemId == 0) return;
if (_popOutItem != itemId)
RynthLog.UI($"ItemDragBridge: pop-out drag 0x{itemId:X8} published to the client.");
_popOutItem = itemId;
_popOutSeenAt = Stopwatch.GetTimestamp();
}
/// <summary>The popped-out Inventory's drag ended (dropped or cancelled).</summary>
public static void EndPopOutDrag() => _popOutItem = 0;
// ── Native drag (game WndProc) ──────────────────────────────────────────
/// <summary>
/// Every game-window mouse message, after the backend decided who owns the held buttons.
/// <paramref name="gameOwned"/>: the current press began on the game, not on ImGui.
/// </summary>
public static void OnGameMouse(uint msg, IntPtr wParam, IntPtr lParam, bool gameOwned)
{
int keys = (int)((long)wParam & 0xFFFF);
switch (msg)
{
case WM_LBUTTONDOWN:
// Only a plain left press that belongs to the game can be an inventory drag.
_pressPending = gameOwned && (keys & MK_OTHER) == 0;
_pressLParam = lParam;
_pressX = LoWord(lParam);
_pressY = HiWord(lParam);
_pressAt = Stopwatch.GetTimestamp();
_gamePressHeld = _pressPending;
if (_pressPending) { _nativeItem = 0; _nativeFromHook = false; _nativeReleased = false; }
break;
case WM_MOUSEMOVE:
if ((keys & MK_LBUTTON) == 0)
{
// A release we never saw (outside the window): finish the drag.
_pressPending = false;
_gamePressHeld = false;
if (_nativeItem != 0) _nativeReleased = true;
break;
}
if (_pressPending)
{
int dx = LoWord(lParam) - _pressX, dy = HiWord(lParam) - _pressY;
if (dx * dx + dy * dy >= DragThresholdSq)
{
_pressPending = false;
// With the drag-start hook the real item arrives through OnNativeDragStart.
if (_nativeItem == 0 && !DragDropHooks.IsInstalled)
{
_nativeItem = CarriedSelection();
if (_nativeItem != 0)
RynthLog.UI($"ItemDragBridge: native inventory drag 0x{_nativeItem:X8} (from the selection) published to ImGui.");
}
}
}
else if (_nativeItem != 0 && !_nativeFromHook && !_nativeReleased && Stopwatch.GetTimestamp() - _pressAt < SelectionSettleTicks)
{
// The selection can trail the press by a few messages: follow it while it settles.
uint sel = CarriedSelection();
if (sel != 0) _nativeItem = sel;
}
break;
case WM_LBUTTONUP:
_pressPending = false;
_gamePressHeld = false;
if (_nativeItem != 0) _nativeReleased = true;
break;
}
}
/// <summary>
/// AC started dragging <paramref name="itemId"/> (DragDropHooks, AC's main thread). Taken while
/// a game-owned left press is held and only for items the player carries.
/// </summary>
public static void OnNativeDragStart(uint itemId)
{
if (!_gamePressHeld || itemId == 0 || !IsCarried(itemId)) return;
_pressPending = false;
_nativeItem = itemId;
_nativeFromHook = true;
_nativeReleased = false;
RynthLog.UI($"ItemDragBridge: native inventory drag 0x{itemId:X8} published to ImGui.");
}
/// <summary>
/// A native item drag is being released over an ImGui window: returns the press position
/// to send AC instead, so AC puts the item back rather than dropping it on the ground.
/// </summary>
public static bool TryRedirectNativeDrop(uint msg, out IntPtr pressLParam)
{
pressLParam = _pressLParam;
if (msg != WM_LBUTTONUP || _nativeItem == 0 || !_overImGui) return false;
RynthLog.UI($"ItemDragBridge: native drag 0x{_nativeItem:X8} released over an ImGui window; AC gets the drop back at its start ({_pressX},{_pressY}).");
return true;
}
// ── Main frame (after ImGui.NewFrame, before any window) ────────────────
/// <summary>Republishes a pop-out or native drag in the main context for this frame.</summary>
public static void SubmitMainFrame(ImGuiIOPtr io)
{
uint id = 0;
string type = PayloadType;
if (_popOutItem != 0)
{
if (Stopwatch.GetTimestamp() - _popOutSeenAt > PopOutStaleTicks) _popOutItem = 0;
else id = _popOutItem;
}
if (id == 0 && _nativeItem != 0)
{
type = _nativeFromHook ? PayloadType : NativePayloadType;
// After the button-up, stop once ImGui itself sees the button up: that frame
// delivers the drop (the payload outlives its last submission by one frame).
if (_nativeReleased && !io.MouseDown[0])
{
_nativeItem = 0;
_nativeFromHook = false;
_nativeReleased = false;
_overImGui = false;
return;
}
id = _nativeItem;
_overImGui = ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow | ImGuiHoveredFlags.AllowWhenBlockedByActiveItem);
}
if (id == 0) return;
const ImGuiDragDropFlags flags = ImGuiDragDropFlags.SourceExtern | ImGuiDragDropFlags.SourceNoPreviewTooltip
| ImGuiDragDropFlags.PayloadAutoExpire;
if (ImGuiNET.ImGui.BeginDragDropSource(flags))
{
ImGuiNET.ImGui.SetDragDropPayload(type, (IntPtr)(&id), sizeof(uint));
ImGuiNET.ImGui.EndDragDropSource();
}
}
/// <summary>Forget every drag (focus lost, logout, engine shutdown).</summary>
public static void Reset()
{
_popOutItem = 0;
_pressPending = false;
_gamePressHeld = false;
_nativeItem = 0;
_nativeFromHook = false;
_nativeReleased = false;
_overImGui = false;
}
/// <summary>The game's selected object when the player carries it, else 0.</summary>
private static uint CarriedSelection()
{
uint id = ClientHelperHooks.GetSelectedItemId();
return IsCarried(id) ? id : 0;
}
/// <summary><paramref name="id"/> is in the player's pack, a side pack, or worn.</summary>
private static bool IsCarried(uint id)
{
if (id == 0 || !ClientHelperHooks.HasGetPlayerId) return false;
uint player = ClientHelperHooks.GetPlayerId();
if (player == 0 || id == player) return false;
if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _)) return false;
if (wielder == player || container == player) return true;
// Side pack in the main pack.
return container != 0 && ClientObjectHooks.TryGetObjectOwnershipInfo(container, out uint outer, out _, out _) && outer == player;
}
private static int LoWord(IntPtr l) => unchecked((short)((long)l & 0xFFFF));
private static int HiWord(IntPtr l) => unchecked((short)(((long)l >> 16) & 0xFFFF));
}

View file

@ -138,6 +138,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel
Label("No rules yet. Click \"Add rule\", or right-click a line in the chat", Mute); Label("No rules yet. Click \"Add rule\", or right-click a line in the chat", Mute);
Label("and pick \"Move them to\", \"Hide them\" or \"Colour them\".", Mute); Label("and pick \"Move them to\", \"Hide them\" or \"Colour them\".", Mute);
} }
DrawStandardFilters(rowW);
ImGuiNET.ImGui.PopStyleColor(2); ImGuiNET.ImGui.PopStyleColor(2);
ImGuiNET.ImGui.EndChild(); ImGuiNET.ImGui.EndChild();
@ -181,6 +182,58 @@ internal sealed class ChatFiltersFace : IImGuiPanel
edit?.Invoke(); // after drawing: the rows above drew from the old list edit?.Invoke(); // after drawing: the rows above drew from the old list
} }
// ── Standard filters (RynthChatPresets) ──────────────────────────────
/// <summary>
/// The canned filters, by group: tick to hide, or pick a tab to move the lines there.
/// The router checks them after the rules, for lines no rule moved or hid.
/// </summary>
private void DrawStandardFilters(float rowW)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
if (!ImGuiNET.ImGui.CollapsingHeader("Standard filters##std")) return;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9));
Label("Checked after the rules above, only for lines no rule moved or hid.", Mute);
Label("Tick to hide the lines; pick a tab to move them there instead.", Mute);
ImGuiNET.ImGui.PopFont();
foreach (string group in UI.Panels.RynthChatPresets.Groups)
{
int on = 0, total = 0;
foreach (var p in UI.Panels.RynthChatPresets.All)
if (p.Group == group) { total++; if (p.Enabled) on++; }
if (!ImGuiNET.ImGui.TreeNode($"{group} ({on}/{total})###grp_{group}")) continue;
foreach (var p in UI.Panels.RynthChatPresets.All)
{
if (p.Group != group) continue;
ImGuiNET.ImGui.PushID(p.Id);
bool enabled = p.Enabled;
if (ImGuiNET.ImGui.Checkbox(p.Label, ref enabled)) { p.Enabled = enabled; ChatModel.FiltersChanged(); }
ImGuiNET.ImGui.SetItemTooltip(p.Description + "\nExample: " + p.Example);
ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, rowW * 0.6f));
string tabText = (p.Tab.Length == 0 ? "hide" : "to " + p.Tab) + Caret;
if (ImGuiNET.ImGui.SmallButton(tabText))
OpenPresetTabPicker(p, new Vector2(ImGuiNET.ImGui.GetItemRectMin().X, ImGuiNET.ImGui.GetItemRectMax().Y + 2));
ImGuiNET.ImGui.SetItemTooltip("Where its lines go: hidden, or moved to a tab");
ImGuiNET.ImGui.PopID();
}
ImGuiNET.ImGui.TreePop();
}
}
private void OpenPresetTabPicker(UI.Panels.RynthChatPresets.Preset preset, Vector2 below)
{
string[] tabs = ChatModel.TargetTabs();
var items = new string[tabs.Length + 1];
items[0] = "Hide";
Array.Copy(tabs, 0, items, 1, tabs.Length);
int selected = preset.Tab.Length == 0 ? 0 : Math.Max(0, Array.FindIndex(tabs, t => string.Equals(t, preset.Tab, StringComparison.OrdinalIgnoreCase)) + 1);
_picker.Open(below, items, selected, k =>
{
preset.Tab = k <= 0 ? "" : items[k];
ChatModel.FiltersChanged();
}, 160);
}
private void Flash(string message) private void Flash(string message)
{ {
_flash = message; _flash = message;
@ -548,7 +601,12 @@ internal sealed class ChatFiltersFace : IImGuiPanel
var trace = new List<ChatRouter.Step>(); var trace = new List<ChatRouter.Step>();
ChatRoute route = ChatModel.TestRouter().Evaluate(text, channel, type, trace); ChatRoute route = ChatModel.TestRouter().Evaluate(text, channel, type, trace);
foreach (ChatRouter.Step step in trace) foreach (ChatRouter.Step step in trace)
_testResult.Add(((step.Rule < 0 ? "Your name" : $"Rule {step.Rule + 1}") + ": " + step.What, Text)); _testResult.Add((step.Rule switch
{
ChatRouter.StandardFilterStep => "Standard",
< 0 => "Your name",
_ => $"Rule {step.Rule + 1}",
} + ": " + step.What, Text));
if (trace.Count == 0) _testResult.Add(("No rule matches.", Faded(Mute))); if (trace.Count == 0) _testResult.Add(("No rule matches.", Faded(Mute)));
string where; string where;

View file

@ -10,8 +10,8 @@
// //
// The mechanics live here (tabs, slide, side, placement, the one window); // The mechanics live here (tabs, slide, side, placement, the one window);
// each drawer only draws its panel (DashboardDrawer.DrawPanel) and says how // each drawer only draws its panel (DashboardDrawer.DrawPanel) and says how
// big it is. Drawers today: Ranges (RangesSlideOut.cs), Loaded files and // big it is. Drawers today: Ranges (RangesSlideOut.cs), Loaded files,
// Patrol (RynthAiFace.Drawers.cs). // Patrol and Mini Remote (RynthAiFace.Drawers.cs).
// //
// A top-level ImGui window of its own, begun from inside the dashboard's Draw // A top-level ImGui window of its own, begun from inside the dashboard's Draw
// and placed against the dashboard's window every frame, so it follows the // and placed against the dashboard's window every frame, so it follows the

View file

@ -44,7 +44,7 @@ internal sealed class DungeonMapFace : IImGuiPanel
{ {
DungeonMapSettingsStore.Load(); // engine init thread: the file read stays off AC's thread DungeonMapSettingsStore.Load(); // engine init thread: the file read stays off AC's thread
ImGuiPanelHost.Register(Title, ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(480, 520), new Vector2(240, 200), Background: 0, EdgeToEdge: true), new PanelSpec(new Vector2(480, 520), new Vector2(240, 200), Background: 0, EdgeToEdge: true, OpenCentered: true),
() => new DungeonMapFace()); () => new DungeonMapFace());
} }

View file

@ -813,7 +813,7 @@ internal sealed partial class InventoryFace
_hover = it; _hover = it;
if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left))
{ {
_selected = it.Id; SelectItem(it);
_pressItem = it; _pressItem = it;
_pressAt = ImGuiNET.ImGui.GetMousePos(); _pressAt = ImGuiNET.ImGui.GetMousePos();
} }

View file

@ -130,6 +130,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
InventoryModel.Hover(0); InventoryModel.Hover(0);
InventoryModel.Unsubscribe(); InventoryModel.Unsubscribe();
_dragItem = _pressItem = null; _dragItem = _pressItem = null;
ItemDragBridge.EndPopOutDrag();
UiDropTargets.EngineDragObject = 0; UiDropTargets.EngineDragObject = 0;
_lootAdd.Cancel(); _lootAdd.Cancel();
} }
@ -538,7 +539,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left)) if (hot != null && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Left))
{ {
_selected = hot.Id; SelectItem(hot);
_pressItem = hot; _pressItem = hot;
_pressAt = mouse; _pressAt = mouse;
} }
@ -838,6 +839,7 @@ internal sealed partial class InventoryFace : IImGuiPanel
_dragItem = null; _dragItem = null;
_pressItem = null; _pressItem = null;
if (item == null) return; if (item == null) return;
ItemDragBridge.EndPopOutDrag();
Vector2 m = ImGuiNET.ImGui.GetMousePos(); Vector2 m = ImGuiNET.ImGui.GetMousePos();
foreach (Target t in _targets) foreach (Target t in _targets)
{ {
@ -852,13 +854,50 @@ internal sealed partial class InventoryFace : IImGuiPanel
} }
} }
private void DrawDragGhost() /// <summary>
/// ImGui drag-and-drop payload type for one item (uint object id), published while an item is
/// dragged so other ImGui windows (RynthAi's Mini Remote slots) can accept the drop. Must
/// match MiniRemoteHud.ItemPayloadType in RynthAi.
/// </summary>
public const string ItemPayloadType = "RYNTH_INV_ITEM";
/// <summary>
/// Selects <paramref name="it"/> here and in the game, like a click in the retail inventory, so
/// "selected item" features (Mini Remote slots, item info, loot rules) see it too.
/// </summary>
private void SelectItem(InventoryItem it)
{
_selected = it.Id;
// Queued, not called inline: Draw runs inside EndScene, and AC's SetSelectedObject rebuilds
// UI elements, so it runs at the main-thread queue's drain point instead.
if (ClientHelperHooks.GetSelectedItemId() != it.Id)
AcMainThreadQueue.EnqueueSetSelectedObject(it.Id);
}
private unsafe void DrawDragGhost()
{ {
if (_dragItem == null) return; if (_dragItem == null) return;
var fg = ImGuiNET.ImGui.GetForegroundDrawList(); var fg = ImGuiNET.ImGui.GetForegroundDrawList();
Vector2 m = ImGuiNET.ImGui.GetMousePos() - new Vector2(Icon * 0.5f, Icon * 0.5f); Vector2 m = ImGuiNET.ImGui.GetMousePos() - new Vector2(Icon * 0.5f, Icon * 0.5f);
DrawItemIcon(fg, _dragItem.Id, m, Icon, 0xD0FFFFFF); DrawItemIcon(fg, _dragItem.Id, m, Icon, 0xD0FFFFFF);
ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
// A popped-out Inventory draws in its own ImGui context: the client's drop targets
// only see the drag through the bridge, which republishes it in the main context.
if (ImGuiPopOuts.InPopOutFrame)
{
ItemDragBridge.NotePopOutDrag(_dragItem.Id);
return;
}
// Re-submitted every frame of the drag (an extern source expires when it isn't); the
// ghost above is the preview, so no ImGui tooltip.
if (ImGuiNET.ImGui.BeginDragDropSource(ImGuiDragDropFlags.SourceExtern | ImGuiDragDropFlags.SourceNoPreviewTooltip))
{
uint id = _dragItem.Id;
ImGuiNET.ImGui.SetDragDropPayload(ItemPayloadType, (IntPtr)(&id), sizeof(uint));
ImGuiNET.ImGui.EndDragDropSource();
}
} }
// ── Tooltip ───────────────────────────────────────────────────────── // ── Tooltip ─────────────────────────────────────────────────────────
@ -985,6 +1024,11 @@ internal sealed partial class InventoryFace : IImGuiPanel
_lootAdd.Open(it.Id, it.Name, toOpenProfile: false); _lootAdd.Open(it.Id, it.Name, toOpenProfile: false);
if (ImGuiNET.ImGui.IsItemHovered()) if (ImGuiNET.ImGui.IsItemHovered())
ImGuiNET.ImGui.SetTooltip("Make a RynthAi loot rule for this item (preview first)"); ImGuiNET.ImGui.SetTooltip("Make a RynthAi loot rule for this item (preview first)");
if (!it.IsPack && ImGuiNET.ImGui.MenuItem("Add to item count HUD"))
UI.Data.RynthAiCommands.ApplyRemoteCommand("itemhudadd", it.Name);
if (ImGuiNET.ImGui.IsItemHovered())
ImGuiNET.ImGui.SetTooltip("Track how many of these you carry on RynthAi's floating item count HUD (/ra itemhud add)");
if (!it.IsPack) MiniRemoteMenu(it);
if (!idle) if (!idle)
ImGuiNET.ImGui.TextDisabled("(an item action is waiting)"); ImGuiNET.ImGui.TextDisabled("(an item action is waiting)");
} }
@ -995,6 +1039,36 @@ internal sealed partial class InventoryFace : IImGuiPanel
} }
} }
/// <summary>RynthAi Mini Remote quick-use grid size (HudState.MiniRemoteSlotCount, 6 rows of 5).</summary>
private const int MiniRemoteSlots = 30, MiniRemoteColumns = 5;
/// <summary>
/// "Add to Mini Remote" submenu: first empty slot, or a numbered grid laid out like the
/// remote's own slots. RynthAi validates the item and reports the result in chat.
/// </summary>
private static void MiniRemoteMenu(InventoryItem it)
{
if (!ImGuiNET.ImGui.BeginMenu("Add to Mini Remote")) return;
if (ImGuiNET.ImGui.MenuItem("First empty slot"))
UI.Data.RynthAiCommands.ApplyRemoteCommand("remoteslot", "first " + it.Id.ToString(CultureInfo.InvariantCulture));
ImGuiNET.ImGui.Separator();
ImGuiNET.ImGui.TextDisabled("Or pick a slot (replaces what's there):");
for (int i = 0; i < MiniRemoteSlots; i++)
{
if (i % MiniRemoteColumns != 0) ImGuiNET.ImGui.SameLine();
string label = (i + 1).ToString("00", CultureInfo.InvariantCulture);
if (ImGuiNET.ImGui.Button(label, new Vector2(28, 0)))
{
UI.Data.RynthAiCommands.ApplyRemoteCommand("remoteslot",
(i + 1).ToString(CultureInfo.InvariantCulture) + " " + it.Id.ToString(CultureInfo.InvariantCulture));
ImGuiNET.ImGui.CloseCurrentPopup();
}
}
ImGuiNET.ImGui.Separator();
ImGuiNET.ImGui.TextDisabled("Tip: you can also drag the item onto a slot.");
ImGuiNET.ImGui.EndMenu();
}
// ── Split dialog ──────────────────────────────────────────────────── // ── Split dialog ────────────────────────────────────────────────────
private void SplitDialog(InventoryView view) private void SplitDialog(InventoryView view)

View file

@ -1,21 +1,28 @@
// ============================================================================ // ============================================================================
// RynthCore.Engine - ImGui/Panels/NavFace.cs // RynthCore.Engine - ImGui/Panels/NavFace.cs
// ImGui face of the Nav panel (UI/Panels/NavPanel.cs): active nav + status, // ImGui face of the Nav panel (UI/Panels/NavPanel.cs): active nav + status,
// Start/Stop, route type and insert mode, Add Waypoint / Portal (not yet) / // Start/Stop, route type and insert mode, the Breadcrumbs and Route overlay
// Recall / Clear / Save / Dungeon Patrol, a chat waypoint, Save As, the nav // toggles, Add Waypoint / Portal (selected object) /
// file picker, the nav point reach (RynthAi's FollowNavMin, the same row as // Recall / Clear / Save / Dungeon Patrol, the route editor (move / duplicate /
// Settings > Navigation), and the waypoint list (click selects the insert // delete / set active / move here on the selection; nearest, reverse, snap to
// point, X deletes, => marks the active one). // path, point at selection, pause, simplify; recording and trail -> route),
// a chat waypoint, Save As, the nav file picker, the nav point reach
// (RynthAi's FollowNavMin, the same row as Settings > Navigation), and the
// waypoint list (click selects, Ctrl/Shift-click multi-selects, double-click
// sets active, right-click edits, X or Delete deletes, => marks the active one).
// //
// Data: UiSources.Nav (hub) and NavCommands. Button actions change a private // Data: UiSources.Nav (hub) and NavCommands. Button actions change a private
// copy at once; the plugin applies commands immediately, so the next // copy at once; the plugin applies commands immediately, so the next
// snapshot (requested right after) replaces the copy. The reach row reads // snapshot (requested right after) replaces the copy. Edits send indices into
// UiSources.Settings and saves through SettingsCommands, like the Settings face. // the route this face shows, so the selection is remapped locally as the copy
// changes. The reach row reads UiSources.Settings and saves through
// SettingsCommands, like the Settings face.
// ============================================================================ // ============================================================================
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Linq;
using System.Numerics; using System.Numerics;
using ImGuiNET; using ImGuiNET;
using RynthCore.Engine.UI.Data; using RynthCore.Engine.UI.Data;
@ -28,7 +35,7 @@ internal sealed class NavFace : IImGuiPanel
public const string Title = "Nav"; public const string Title = "Nav";
public static void Register() => ImGuiPanelHost.Register(Title, public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(400, 560), new Vector2(360, 380), EdgeToEdge: true), new PanelSpec(new Vector2(400, 680), new Vector2(360, 440), EdgeToEdge: true),
() => new NavFace()); () => new NavFace());
private static readonly string[] Actions = private static readonly string[] Actions =
@ -38,12 +45,30 @@ internal sealed class NavFace : IImGuiPanel
}; };
private const string StartNav = PhosphorIcons.Play + " Start Navigation", StopNav = PhosphorIcons.Stop + " Stop Navigation"; private const string StartNav = PhosphorIcons.Play + " Start Navigation", StopNav = PhosphorIcons.Stop + " Stop Navigation";
private const string AddChat = PhosphorIcons.Plus + " Add Chat", SaveAs = PhosphorIcons.FloppyDisk + " Save As"; private const string AddChat = PhosphorIcons.Plus + " Add Chat", SaveAs = PhosphorIcons.FloppyDisk + " Save As";
private static readonly bool[] ActionsEnabled = { true, false, true, true, true, true };
// Route editor rows. Edit acts on the selected waypoints; Tools on the route.
private static readonly string[] EditActions =
{
PhosphorIcons.ArrowUp + " Up", PhosphorIcons.ArrowDown + " Down", PhosphorIcons.Copy + " Duplicate",
PhosphorIcons.Trash + " Delete", PhosphorIcons.Target + " Set Active", PhosphorIcons.Crosshair + " Move Here",
};
private static readonly string[] ToolActions =
{
PhosphorIcons.NavigationArrow + " Nearest", PhosphorIcons.ArrowsClockwise + " Reverse", PhosphorIcons.Path + " Snap to Path",
PhosphorIcons.MapPin + " Point at Selected", PhosphorIcons.Hourglass + " Add Pause", PhosphorIcons.Scissors + " Simplify",
};
private static readonly string[] RowMenu =
{ "Set Active", "Move Here", "Move Up", "Move Down", "Duplicate", "Delete" };
private const string FromTrail = PhosphorIcons.Footprints + " Route from Trail...";
private readonly bool[] _editEnabled = new bool[6];
private NavPayload _data = new(); private NavPayload _data = new();
private long _seenVersion = -1; private long _seenVersion = -1;
private readonly List<string> _pointText = new(); private readonly List<string> _pointText = new();
private int _selected = -1, _addMode; // _selected is the focus row (insert point, chat editing); _multi is every selected row,
// always containing _selected when it is set. _anchor starts Shift-click ranges.
private int _selected = -1, _anchor = -1, _addMode;
private readonly HashSet<int> _multi = new();
private bool _typing; private bool _typing;
private string _routeLabel = "Route: Once", _insertLabel = "Insert: End", _activeLabel = "Active Nav: None (Unsaved)"; private string _routeLabel = "Route: Once", _insertLabel = "Insert: End", _activeLabel = "Active Nav: None (Unsaved)";
private string _fileLabel = "Select nav file..."; private string _fileLabel = "Select nav file...";
@ -130,13 +155,32 @@ internal sealed class NavFace : IImGuiPanel
}); });
NextLine(p, 26); NextLine(p, 26);
// Breadcrumbs | Route overlay (RynthAi's NavOverlaySettings; saved per character)
p = ImGuiNET.ImGui.GetCursorScreenPos();
if (OverlayToggle("##crumbs", "Breadcrumbs", _data.TrackBreadcrumbs, p, half,
"Record the trail you walk and draw it on the ground (/ra navtrail on|off).\nTurning it off hides the trail; /ra navtrail clear wipes it."))
{
bool on = !_data.TrackBreadcrumbs;
NavCommands.Send(new NavCmd { Cmd = "setBreadcrumbs", On = on });
_data.TrackBreadcrumbs = on;
}
if (OverlayToggle("##routeovl", "Route overlay", _data.ShowRouteOverlay, new Vector2(p.X + half + 4, p.Y), half,
"Draw the route in the world: waypoint rings and lines, waypoint labels and the guide line\nto the active waypoint (/ra navoverlay on|off). The waypoint HUD window is separate."))
{
bool on = !_data.ShowRouteOverlay;
NavCommands.Send(new NavCmd { Cmd = "setRouteOverlay", On = on });
_data.ShowRouteOverlay = on;
}
NextLine(p, 26);
typing |= ReachRow(w); typing |= ReachRow(w);
// Actions // Actions
int action = WrapButtons("nav_act", Actions, w, 24, ActionsEnabled); int action = WrapButtons("nav_act", Actions, w, 24);
switch (action) switch (action)
{ {
case 0: NavCommands.Send(new NavCmd { Cmd = "addWaypoint", AddMode = _addMode, InsertAt = _selected }); break; case 0: NavCommands.Send(new NavCmd { Cmd = "addWaypoint", AddMode = _addMode, InsertAt = _selected }); break;
case 1: NavCommands.Send(new NavCmd { Cmd = "addPortal", AddMode = _addMode, InsertAt = _selected }); break;
case 2: case 2:
_picker.Open(ImGuiNET.ImGui.GetIO().MousePos, NavCommands.RecallLabels, -1, i => _picker.Open(ImGuiNET.ImGui.GetIO().MousePos, NavCommands.RecallLabels, -1, i =>
NavCommands.Send(new NavCmd { Cmd = "addRecall", SpellId = NavCommands.RecallIds[i], AddMode = _addMode, InsertAt = _selected })); NavCommands.Send(new NavCmd { Cmd = "addRecall", SpellId = NavCommands.RecallIds[i], AddMode = _addMode, InsertAt = _selected }));
@ -144,13 +188,15 @@ internal sealed class NavFace : IImGuiPanel
case 3: case 3:
NavCommands.Send(new NavCmd { Cmd = "clearRoute" }); NavCommands.Send(new NavCmd { Cmd = "clearRoute" });
_data.Points.Clear(); _data.Points.Clear();
_selected = -1; ClearSelection();
RebuildPointText(); RebuildPointText();
break; break;
case 4: NavCommands.Send(new NavCmd { Cmd = "saveRoute" }); break; case 4: NavCommands.Send(new NavCmd { Cmd = "saveRoute" }); break;
case 5: NavCommands.Send(new NavCmd { Cmd = "dunPatrol" }); break; case 5: NavCommands.Send(new NavCmd { Cmd = "dunPatrol" }); break;
} }
RouteEditor(w);
// Chat waypoint: sent as if typed when the route reaches it. Selecting an // Chat waypoint: sent as if typed when the route reaches it. Selecting an
// existing chat waypoint loads its command here; Update saves the edit. // existing chat waypoint loads its command here; Update saves the edit.
bool chatSelected = _selected >= 0 && _selected < _data.Points.Count bool chatSelected = _selected >= 0 && _selected < _data.Points.Count
@ -230,6 +276,9 @@ internal sealed class NavFace : IImGuiPanel
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1)); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1));
ImGuiNET.ImGui.BeginChild("##nav_points", new Vector2(w, listH)); ImGuiNET.ImGui.BeginChild("##nav_points", new Vector2(w, listH));
Waypoints(ImGuiNET.ImGui.GetContentRegionAvail().X); Waypoints(ImGuiNET.ImGui.GetContentRegionAvail().X);
if (!typing && _multi.Count > 0 && ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Delete, false)
&& (ImGuiNET.ImGui.IsWindowHovered() || ImGuiNET.ImGui.IsWindowFocused()))
DeleteSelected();
ImGuiNET.ImGui.EndChild(); ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleVar(); ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(); ImGuiNET.ImGui.PopStyleColor();
@ -239,6 +288,18 @@ internal sealed class NavFace : IImGuiPanel
_picker.Draw(); _picker.Draw();
} }
/// <summary>
/// A checkbox-style toggle button: ticked box and teal text when on, empty box and muted
/// text when off. Returns true when clicked (the caller flips the value).
/// </summary>
private static bool OverlayToggle(string id, string label, bool on, Vector2 pos, float width, string tooltip)
{
string text = (on ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " " + label;
bool clicked = Button(id, text, pos, new Vector2(width, 22), on ? Teal : Mute, BtnFill, leftAlign: true);
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(tooltip);
return clicked;
}
/// <summary> /// <summary>
/// Nav point reach (yd): how close nav gets to each nav point before moving on. Label, /// Nav point reach (yd): how close nav gets to each nav point before moving on. Label,
/// [-] value [+]; the typed value commits on Enter or when the box loses focus. Saves the /// [-] value [+]; the typed value commits on Enter or when the box loses focus. Saves the
@ -303,20 +364,24 @@ internal sealed class NavFace : IImGuiPanel
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
const float h = 22; const float h = 22;
if (p.Y + h < clipMin.Y || p.Y > clipMax.Y) { ImGuiNET.ImGui.Dummy(new Vector2(w, h)); continue; } if (p.Y + h < clipMin.Y || p.Y > clipMax.Y) { ImGuiNET.ImGui.Dummy(new Vector2(w, h)); continue; }
bool active = i == _data.ActiveNavIndex, selected = i == _selected; bool active = i == _data.ActiveNavIndex, selected = _multi.Contains(i);
ImGuiNET.ImGui.PushID(i); ImGuiNET.ImGui.PushID(i);
// Row click selects (drawn first so the X button on top wins). // Row click selects (drawn first so the X button on top wins).
ImGuiNET.ImGui.SetCursorScreenPos(p); ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.SetNextItemAllowOverlap(); // the X button on top gets its clicks ImGuiNET.ImGui.SetNextItemAllowOverlap(); // the X button on top gets its clicks
if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h))) _selected = i; if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h))) ClickRow(i);
if (ImGuiNET.ImGui.IsItemHovered() && ImGuiNET.ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left))
SetActive(i);
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
{
if (!selected) SelectOnly(i);
_picker.Open(ImGuiNET.ImGui.GetIO().MousePos, RowMenu, -1, RowMenuPick, width: 140);
}
dl.AddRectFilled(p, p + new Vector2(w, h), selected ? Selected : i % 2 == 0 ? PanelBg : RowAlt); dl.AddRectFilled(p, p + new Vector2(w, h), selected ? Selected : i % 2 == 0 ? PanelBg : RowAlt);
if (IconButton("##del", PhosphorIcons.X, new Vector2(p.X + 2, p.Y + 2), new Vector2(18, 18), Text, DeleteBg, font: UiFont.Ui11)) if (IconButton("##del", PhosphorIcons.X, new Vector2(p.X + 2, p.Y + 2), new Vector2(18, 18), Text, DeleteBg, font: UiFont.Ui11))
{ {
NavCommands.Send(new NavCmd { Cmd = "deletePoint", Index = i }); NavCommands.Send(new NavCmd { Cmd = "deletePoint", Index = i });
if (_selected == i) _selected = -1; RemoveLocal(new HashSet<int> { i });
else if (_selected > i) _selected--;
_data.Points.RemoveAt(i);
RebuildPointText();
ImGuiNET.ImGui.PopID(); ImGuiNET.ImGui.PopID();
return; return;
} }
@ -331,6 +396,216 @@ internal sealed class NavFace : IImGuiPanel
} }
} }
/// <summary>
/// Route editor: Edit row (on the selection), Tools row (on the route), the Record toggle
/// with "Route from Trail...", and the last edit's result. Picker-backed buttons (pause,
/// simplify, trail) double as the confirmation for edits that can't be undone.
/// </summary>
private void RouteEditor(float w)
{
int n = _multi.Count, count = _data.Points.Count;
bool one = n == 1 && _selected >= 0;
_editEnabled[0] = n > 0 && _multi.Min() > 0;
_editEnabled[1] = n > 0 && _multi.Max() < count - 1;
_editEnabled[2] = _editEnabled[3] = n > 0;
_editEnabled[4] = _editEnabled[5] = one;
Label(n > 1 ? $"Edit ({n} selected)" : "Edit", Mute);
switch (WrapButtons("nav_edit", EditActions, w, 22, _editEnabled))
{
case 0: MoveSelected(-1); break;
case 1: MoveSelected(+1); break;
case 2: DuplicateSelected(); break;
case 3: DeleteSelected(); break;
case 4: SetActive(_selected); break;
case 5: NavCommands.Send(new NavCmd { Cmd = "movePointHere", Index = _selected }); break;
}
Vector2 at = ImGuiNET.ImGui.GetIO().MousePos;
switch (WrapButtons("nav_tools", ToolActions, w, 22))
{
case 0: NavCommands.Send(new NavCmd { Cmd = "nearestActive" }); break;
case 1:
if (count < 2) break;
NavCommands.Send(new NavCmd { Cmd = "reverseRoute" });
ReverseLocal();
break;
case 2: NavCommands.Send(new NavCmd { Cmd = "snapToPath" }); break;
case 3: NavCommands.Send(new NavCmd { Cmd = "addPointAtSelected", AddMode = _addMode, InsertAt = _selected }); break;
case 4:
_picker.Open(at, NavCommands.PauseLabels, -1, i => NavCommands.Send(new NavCmd
{ Cmd = "addPause", Seconds = NavCommands.PauseSeconds[i], AddMode = _addMode, InsertAt = _selected }), width: 140);
break;
case 5:
_picker.Open(at, NavCommands.SimplifyLabels, -1, i =>
NavCommands.Send(new NavCmd { Cmd = "simplifyRoute", Yards = NavCommands.SimplifyYards[i] }), width: 300);
break;
}
// Record | Route from Trail...
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float half = (w - 4) / 2;
if (OverlayToggle("##record", "Record route", _data.IsRecording, p, half,
"Add a point every few yards as you walk, and portal steps as you use portals\n(/ra navrec on|off). Points go into the current route."))
{
bool on = !_data.IsRecording;
NavCommands.Send(new NavCmd { Cmd = "setRecording", On = on });
_data.IsRecording = on;
}
Vector2 tp = new(p.X + half + 4, p.Y);
if (Button("##fromtrail", FromTrail, tp, new Vector2(half, 22), Text, BtnFill, enabled: _data.TrailPoints >= 2))
_picker.Open(new Vector2(tp.X, tp.Y + 22), NavCommands.TrailChoices, -1, i =>
NavCommands.Send(new NavCmd { Cmd = "trailToRoute", Reverse = i == 1 }), width: 300);
if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
ImGuiNET.ImGui.SetTooltip(_data.TrailPoints >= 2
? $"Breadcrumb trail: {_data.TrailPoints} crumbs, {_data.TrailYards:0} yd.\nThe new route is unsaved; the loaded nav file is not changed."
: "Turn on Breadcrumbs and walk a while to build a trail.");
NextLine(p, 26);
if (_data.EditStatus.Length > 0) Label(_data.EditStatus, Amber);
}
/// <summary>Plain click selects one row, Ctrl toggles a row, Shift selects from the anchor.</summary>
private void ClickRow(int i)
{
var io = ImGuiNET.ImGui.GetIO();
if (io.KeyShift && _anchor >= 0)
{
if (!io.KeyCtrl) _multi.Clear();
for (int k = Math.Min(_anchor, i); k <= Math.Max(_anchor, i); k++) _multi.Add(k);
_selected = i;
}
else if (io.KeyCtrl)
{
if (!_multi.Remove(i)) { _multi.Add(i); _selected = i; }
else if (_selected == i) _selected = _multi.Count > 0 ? _multi.Min() : -1;
_anchor = i;
}
else SelectOnly(i);
}
private void SelectOnly(int i)
{
_multi.Clear();
_multi.Add(i);
_selected = _anchor = i;
}
private void ClearSelection()
{
_multi.Clear();
_selected = _anchor = -1;
}
private List<int> SelectedIndices()
{
var list = new List<int>(_multi);
list.Sort();
return list;
}
private void RowMenuPick(int item)
{
switch (item)
{
case 0: if (_selected >= 0) SetActive(_selected); break;
case 1: if (_selected >= 0) NavCommands.Send(new NavCmd { Cmd = "movePointHere", Index = _selected }); break;
case 2: MoveSelected(-1); break;
case 3: MoveSelected(+1); break;
case 4: DuplicateSelected(); break;
case 5: DeleteSelected(); break;
}
}
private void SetActive(int i)
{
if (i < 0 || i >= _data.Points.Count) return;
NavCommands.Send(new NavCmd { Cmd = "setActive", Index = i });
_data.ActiveNavIndex = i;
}
/// <summary>Moves the selected rows one slot, the way the plugin does (NavRouteEditing.Move).</summary>
private void MoveSelected(int delta)
{
if (_multi.Count == 0) return;
NavCommands.Send(new NavCmd { Cmd = "movePoints", Indices = SelectedIndices(), Delta = delta });
var pts = _data.Points;
var sel = new HashSet<NavPoint>();
foreach (int i in _multi) sel.Add(pts[i]);
NavPoint? focus = _selected >= 0 ? pts[_selected] : null, anchor = _anchor >= 0 && _anchor < pts.Count ? pts[_anchor] : null;
if (delta < 0)
{
for (int i = 1; i < pts.Count; i++)
if (sel.Contains(pts[i]) && !sel.Contains(pts[i - 1])) (pts[i - 1], pts[i]) = (pts[i], pts[i - 1]);
}
else
{
for (int i = pts.Count - 2; i >= 0; i--)
if (sel.Contains(pts[i]) && !sel.Contains(pts[i + 1])) (pts[i + 1], pts[i]) = (pts[i], pts[i + 1]);
}
_multi.Clear();
for (int i = 0; i < pts.Count; i++) if (sel.Contains(pts[i])) _multi.Add(i);
_selected = focus != null ? pts.IndexOf(focus) : -1;
_anchor = anchor != null ? pts.IndexOf(anchor) : _selected;
RebuildPointText();
}
/// <summary>Each selected row gets a copy right after it (as the plugin does); the copies end up selected.</summary>
private void DuplicateSelected()
{
if (_multi.Count == 0) return;
NavCommands.Send(new NavCmd { Cmd = "duplicatePoints", Indices = SelectedIndices() });
var result = new List<NavPoint>(_data.Points.Count + _multi.Count);
var copies = new HashSet<int>();
for (int i = 0; i < _data.Points.Count; i++)
{
NavPoint pt = _data.Points[i];
result.Add(pt);
if (!_multi.Contains(i)) continue;
copies.Add(result.Count);
result.Add(new NavPoint { Type = pt.Type, Desc = pt.Desc, Text = pt.Text, NS = pt.NS, EW = pt.EW, Z = pt.Z });
}
_data.Points = result;
_multi.Clear();
_multi.UnionWith(copies);
_selected = _anchor = _multi.Count > 0 ? _multi.Min() : -1;
RebuildPointText();
}
private void DeleteSelected()
{
if (_multi.Count == 0) return;
NavCommands.Send(new NavCmd { Cmd = "deletePoints", Indices = SelectedIndices() });
RemoveLocal(new HashSet<int>(_multi));
}
/// <summary>Drops rows from the local copy and shifts the selection past them.</summary>
private void RemoveLocal(HashSet<int> removed)
{
int Shift(int i) { int s = 0; foreach (int r in removed) if (r < i) s++; return i - s; }
var keep = new List<int>();
foreach (int i in _multi) if (!removed.Contains(i)) keep.Add(Shift(i));
_selected = _selected >= 0 && !removed.Contains(_selected) ? Shift(_selected) : -1;
_anchor = _anchor >= 0 && !removed.Contains(_anchor) ? Shift(_anchor) : _selected;
_multi.Clear();
_multi.UnionWith(keep);
if (_selected < 0 && _multi.Count > 0) _selected = _multi.Min();
for (int i = _data.Points.Count - 1; i >= 0; i--) if (removed.Contains(i)) _data.Points.RemoveAt(i);
RebuildPointText();
}
private void ReverseLocal()
{
int last = _data.Points.Count - 1;
_data.Points.Reverse();
var flipped = new List<int>();
foreach (int i in _multi) flipped.Add(last - i);
_multi.Clear();
_multi.UnionWith(flipped);
if (_selected >= 0) _selected = last - _selected;
if (_anchor >= 0) _anchor = last - _anchor;
RebuildPointText();
}
private void TakeSnapshot() private void TakeSnapshot()
{ {
var snap = UiSources.Nav.Current; var snap = UiSources.Nav.Current;
@ -338,7 +613,11 @@ internal sealed class NavFace : IImGuiPanel
_seenVersion = snap.Version; _seenVersion = snap.Version;
_data = snap.Value.Clone(); _data = snap.Value.Clone();
_navFiles = _data.NavFiles.ToArray(); _navFiles = _data.NavFiles.ToArray();
if (_selected >= _data.Points.Count) _selected = -1; int count = _data.Points.Count;
_multi.RemoveWhere(i => i >= count);
if (_selected >= count) _selected = -1;
if (_selected < 0 && _multi.Count > 0) _selected = _multi.Min();
if (_anchor >= count) _anchor = _selected;
RebuildPointText(); RebuildPointText();
UpdateLabels(); UpdateLabels();
} }

View file

@ -12,12 +12,19 @@
// recorded hazards and the saved routes. Was the Patrol // recorded hazards and the saved routes. Was the Patrol
// launcher's right-click popup; right-click now opens this // launcher's right-click popup; right-click now opens this
// drawer (popped out: still the popup). // drawer (popped out: still the popup).
// Mini Remote RynthAi's Mini Remote (session rates, target, summon,
// item slots, toggles, bank, rebuff, Translate, Guardian)
// with its Options menu. The plugin draws it here through
// RynthPluginRenderEmbed("miniremote") and says how big it
// wants the panel; the Hub launcher's right-click opens it
// (popped out: the floating Mini Remote instead).
// AC thread only (inside the dashboard's Draw). // AC thread only (inside the dashboard's Draw).
// ============================================================================ // ============================================================================
using System; using System;
using System.Numerics; using System.Numerics;
using ImGuiNET; using ImGuiNET;
using RynthCore.Engine.Plugins;
using RynthCore.Engine.UI; using RynthCore.Engine.UI;
using RynthCore.Engine.UI.Data; using RynthCore.Engine.UI.Data;
@ -25,7 +32,7 @@ namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed partial class RynthAiFace internal sealed partial class RynthAiFace
{ {
/// <summary>Meta state, bot activity and the four file pickers.</summary> /// <summary>Meta state, bot activity and the five file pickers.</summary>
private sealed class FilesDrawer : DashboardDrawer private sealed class FilesDrawer : DashboardDrawer
{ {
private readonly RynthAiFace _face; private readonly RynthAiFace _face;
@ -40,9 +47,10 @@ internal sealed partial class RynthAiFace
public override string TabTooltip(bool right) public override string TabTooltip(bool right)
{ {
RynthAiView? v = _face._view; RynthAiView? v = _face._view;
return "Loaded files: the Profile, Nav, Loot and Meta pickers, meta state and bot activity.\n" + return "Loaded files: the Profile, Nav, Loot, Meta and Buffs pickers, meta state and bot activity.\n" +
"Profile: " + (v?.ProfileText ?? "Default") + "\nNav: " + (v?.NavText ?? "None") + "Profile: " + (v?.ProfileText ?? "Default") + "\nNav: " + (v?.NavText ?? "None") +
"\nLoot: " + (v?.LootText ?? "None") + "\nMeta: " + (v?.MetaText ?? "None") + "\nLoot: " + (v?.LootText ?? "None") + "\nMeta: " + (v?.MetaText ?? "None") +
"\nBuffs: " + (v?.BuffText ?? "Built-in") +
(right ? "\n\nClick to slide them out (to the right: there's no room on the left)." : "\n\nClick to slide them out."); (right ? "\n\nClick to slide them out (to the right: there's no room on the left)." : "\n\nClick to slide them out.");
} }
@ -50,7 +58,7 @@ internal sealed partial class RynthAiFace
public override float Width(float k) => 230 * k; public override float Width(float k) => 230 * k;
public override float Height(float k) => public override float Height(float k) =>
(Pad + TitleH + 4 + 2 * LineH + 6) * k + 4 * SelRow + 3 * SelGap + Pad * k; (Pad + TitleH + 4 + 2 * LineH + 6) * k + 5 * SelRow + 4 * SelGap + Pad * k;
public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k) public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k)
{ {
@ -76,6 +84,8 @@ internal sealed partial class RynthAiFace
_face.Selector(2, "Loot:", view?.LootText ?? "None", raw.LootProfiles, raw.SelectedLootIdx, 1, x, y, w, raw); _face.Selector(2, "Loot:", view?.LootText ?? "None", raw.LootProfiles, raw.SelectedLootIdx, 1, x, y, w, raw);
y += SelRow + SelGap; y += SelRow + SelGap;
_face.Selector(3, "Meta:", view?.MetaText ?? "None", raw.MetaProfiles, raw.SelectedMetaIdx, 2, x, y, w, null); _face.Selector(3, "Meta:", view?.MetaText ?? "None", raw.MetaProfiles, raw.SelectedMetaIdx, 2, x, y, w, null);
y += SelRow + SelGap;
_face.Selector(4, "Buffs:", view?.BuffText ?? "Built-in", raw.BuffProfiles, raw.SelectedBuffIdx, 4, x, y, w, null, spellsButton: true);
} }
private static void InfoLine(ImDrawListPtr dl, ImFontPtr f, float x, float y, float w, float lh, float labelW, string label, string value) private static void InfoLine(ImDrawListPtr dl, ImFontPtr f, float x, float y, float w, float lh, float labelW, string label, string value)
@ -136,4 +146,81 @@ internal sealed partial class RynthAiFace
finally { ImGuiNET.ImGui.EndChild(); } finally { ImGuiNET.ImGui.EndChild(); }
} }
} }
/// <summary>RynthAi's Mini Remote, drawn by the plugin into this drawer (the Hub launcher's right-click).</summary>
private sealed class RemoteDrawer : DashboardDrawer
{
/// <summary>The plugin surface name, NUL-terminated for the export.</summary>
private static ReadOnlySpan<byte> Surface => "miniremote\0"u8;
// Content bounds in unscaled pixels; the plugin's wish is clamped to them.
private const float MinW = 200, MaxW = 760, MinH = 60, DefaultH = 120;
/// <summary>The content size the plugin last asked for (pixels); zero until it has drawn here.</summary>
private Vector2 _want;
public override string Key => "remote";
public override string Icon => PhosphorIcons.SquaresFour;
public override string Name => "Mini Remote drawer";
public override bool SavedOpen => RynthAiDashboardState.RemoteOpen;
public override void SaveOpen(bool open) => RynthAiDashboardState.SetRemoteOpen(open);
public override string TabTooltip(bool right) =>
"Mini Remote: session rates, attack target, summon, item slots, toggles, bank, rebuff, Translate.\n" +
"Its Options button picks the sections and opens the ILT Hub windows (also: right-click Hub).\n" +
(right ? "Click to slide it out (to the right: there's no room on the left)." : "Click to slide it out.");
public override float Width(float k) =>
Math.Clamp(_want.X > 0 ? _want.X : MinW * k, MinW * k, MaxW * k) + 2 * Pad * k;
public override float Height(float k)
{
float frame = (Pad + TitleH + 4 + Pad) * k;
// Never taller than the screen: the body scrolls instead.
float screen = ImGuiNET.ImGui.GetIO().DisplaySize.Y;
float maxBody = screen > 1 ? MathF.Max(MinH * k, screen - frame - 8 * k) : 900 * k;
return frame + Math.Clamp(_want.Y > 0 ? _want.Y : DefaultH * k, MinH * k, maxBody);
}
public override void DrawPanel(Vector2 origin, float panelW, float panelH, float k)
{
float y = PanelFrame(origin, panelW, panelH, k, PhosphorIcons.SquaresFour, "MINI REMOTE", null, "Hide the Mini Remote drawer");
float x = origin.X + Pad * k;
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y));
Vector2 size = new(panelW - 2 * Pad * k, MathF.Max(1, origin.Y + panelH - Pad * k - y));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero);
bool open = ImGuiNET.ImGui.BeginChild("##remote_body", size, ImGuiChildFlags.None, ImGuiWindowFlags.NoBackground);
ImGuiNET.ImGui.PopStyleVar();
try
{
if (!open) return;
// The plugin's widgets use the default UI font, as in its floating Mini Remote.
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
try
{
int result = PluginManager.RenderEmbed("RynthAi", Surface, size, out Vector2 want);
if (result == PluginManager.EmbedDrawn)
{
if (want.X > 0 && want.Y > 0) _want = want;
}
else
{
_want = Vector2.Zero;
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, DMute);
ImGuiNET.ImGui.TextWrapped(result switch
{
PluginManager.EmbedNoPlugin =>
"This RynthAi can't draw its Mini Remote here (it needs RynthAi 0.5.27 or later). Left-click Hub for the floating Mini Remote.",
PluginManager.EmbedFailed =>
"The Mini Remote failed to draw here (see the log). Left-click Hub for the floating Mini Remote.",
_ => "The Mini Remote shows here once RynthAi is ready: in the world, with plugin windows on (engine.json EnablePluginOverlayWindows).",
});
ImGuiNET.ImGui.PopStyleColor();
}
}
finally { ImGuiNET.ImGui.PopFont(); }
}
finally { ImGuiNET.ImGui.EndChild(); }
}
}
} }

View file

@ -18,7 +18,7 @@
// the buttons above it. // the buttons above it.
// drawers tabs on the left edge (DashboardDrawers.cs), one open at a // drawers tabs on the left edge (DashboardDrawers.cs), one open at a
// time, a window of their own beside the dashboard: Ranges // time, a window of their own beside the dashboard: Ranges
// (RangesSlideOut.cs), Loaded files and Patrol // (RangesSlideOut.cs), Loaded files, Patrol and Mini Remote
// (RynthAiFace.Drawers.cs). Everything that slides out goes // (RynthAiFace.Drawers.cs). Everything that slides out goes
// left; only the bars stay at the bottom (Tom 2026-10-05). // left; only the bars stay at the bottom (Tom 2026-10-05).
// Minimized keeps the title row, the control row and the bars. The window's // Minimized keeps the title row, the control row and the bars. The window's
@ -76,13 +76,14 @@ internal sealed partial class RynthAiFace : IImGuiPanel
// The drawers on the dashboard's left edge (their own window, placed against this one). // The drawers on the dashboard's left edge (their own window, placed against this one).
private readonly DashboardDrawers _drawers; private readonly DashboardDrawers _drawers;
private readonly PatrolDrawer _patrol = new(); private readonly PatrolDrawer _patrol = new();
private readonly RemoteDrawer _remote = new();
// This frame's data, for the drawers. // This frame's data, for the drawers.
private RynthAiView? _view; private RynthAiView? _view;
private RynthAiSnapshot _raw = Empty; private RynthAiSnapshot _raw = Empty;
// Picker toggle: ImGui closes a popup on the press outside it, so remember // Picker toggle: ImGui closes a popup on the press outside it, so remember
// whether it was showing when the selector press began (a second click closes). // whether it was showing when the selector press began (a second click closes).
private readonly int[] _pickerShownFrame = { -10, -10, -10, -10 }; private readonly int[] _pickerShownFrame = { -10, -10, -10, -10, -10 };
private readonly bool[] _pressedWhileOpen = new bool[4]; private readonly bool[] _pressedWhileOpen = new bool[5];
// The content's height (logical units, body padding included), measured each // The content's height (logical units, body padding included), measured each
// frame: the window's minimum height. _fit: resize the window to it once. // frame: the window's minimum height. _fit: resize the window to it once.
private float _contentHeight; private float _contentHeight;
@ -92,7 +93,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
public RynthAiFace() public RynthAiFace()
{ {
// Tab order top to bottom; the first one saved open wins at load. // Tab order top to bottom; the first one saved open wins at load.
_drawers = new DashboardDrawers(new RangesSlideOut(), new FilesDrawer(this), _patrol); _drawers = new DashboardDrawers(new RangesSlideOut(), new FilesDrawer(this), _patrol, _remote);
} }
public Vector2? MinSize => new Vector2(MinWidth, _contentHeight > 0 ? _contentHeight public Vector2? MinSize => new Vector2(MinWidth, _contentHeight > 0 ? _contentHeight
@ -145,6 +146,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
} }
Bars(view, raw, x0, width, boxBg); Bars(view, raw, x0, width, boxBg);
PatrolPopup(); PatrolPopup();
CharMenu();
MeasureAndFit(start.Y); MeasureAndFit(start.Y);
// Last: a window of its own, placed against this one's rect (hidden popped out). // Last: a window of its own, placed against this one's rect (hidden popped out).
_drawers.Draw(); _drawers.Draw();
@ -248,7 +250,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + rowH)); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + rowH));
} }
// ── Header: macro + state (40%) | Profile/Nav/Loot/Meta pickers (60%) ── // ── Header: macro + state (40%) | Profile/Nav/Loot/Meta/Buffs pickers (60%) ──
private void HeaderGrid(RynthAiView? view, RynthAiSnapshot raw, float x0, float width) private void HeaderGrid(RynthAiView? view, RynthAiSnapshot raw, float x0, float width)
{ {
@ -266,7 +268,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + 1), Amber, view?.BotActivityText ?? "Idle"); dl.AddText(f10, f10.FontSize, new Vector2(x0, ly + f10.FontSize + 1), Amber, view?.BotActivityText ?? "Idle");
float leftBottom = ly + 2 * (f10.FontSize + 1); float leftBottom = ly + 2 * (f10.FontSize + 1);
// Right: four selector rows (label 36 px, picker fills, spacing 3). // Right: five selector rows (label 36 px, picker fills, spacing 3).
float rx = x0 + leftW, rw = width - leftW, ry = y0; float rx = x0 + leftW, rw = width - leftW, ry = y0;
// The fold arrow sits at the end of the Profile row, where it always fits. // The fold arrow sits at the end of the Profile row, where it always fits.
const float foldW = 18f; const float foldW = 18f;
@ -280,23 +282,39 @@ internal sealed partial class RynthAiFace : IImGuiPanel
Selector(2, "Loot:", view?.LootText ?? "None", raw.LootProfiles, raw.SelectedLootIdx, 1, rx, ry, rw, raw); Selector(2, "Loot:", view?.LootText ?? "None", raw.LootProfiles, raw.SelectedLootIdx, 1, rx, ry, rw, raw);
ry += 16 + 3; ry += 16 + 3;
Selector(3, "Meta:", view?.MetaText ?? "None", raw.MetaProfiles, raw.SelectedMetaIdx, 2, rx, ry, rw, null); Selector(3, "Meta:", view?.MetaText ?? "None", raw.MetaProfiles, raw.SelectedMetaIdx, 2, rx, ry, rw, null);
ry += 16 + 3;
Selector(4, "Buffs:", view?.BuffText ?? "Built-in", raw.BuffProfiles, raw.SelectedBuffIdx, 4, rx, ry, rw, null, spellsButton: true);
ry += 16; ry += 16;
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, Math.Max(leftBottom, ry) + 4)); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, Math.Max(leftBottom, ry) + 4));
} }
private static readonly string[] SelectorIds = { "##sel_profile", "##sel_nav", "##sel_loot", "##sel_meta" }; private static readonly string[] SelectorIds = { "##sel_profile", "##sel_nav", "##sel_loot", "##sel_meta", "##sel_buff" };
private static readonly string[] PickerIds = { "##pick_profile", "##pick_nav", "##pick_loot", "##pick_meta" }; private static readonly string[] PickerIds = { "##pick_profile", "##pick_nav", "##pick_loot", "##pick_meta", "##pick_buff" };
private static readonly string[] NoneItems = { "None" }; private static readonly string[] NoneItems = { "None" };
/// <summary>
/// One file picker row. <paramref name="kind"/> is RynthPluginSelectProfile's list (0 nav,
/// 1 loot, 2 meta, 3 settings profile, 4 buff profile). <paramref name="lootEdit"/> adds the
/// Loot Editor button, <paramref name="spellsButton"/> the RynthAi Spells window button.
/// </summary>
private void Selector(int slot, string label, string text, string[] items, int selected, int kind, private void Selector(int slot, string label, string text, string[] items, int selected, int kind,
float x, float y, float w, RynthAiSnapshot? lootEdit) float x, float y, float w, RynthAiSnapshot? lootEdit, bool spellsButton = false)
{ {
var dl = ImGuiNET.ImGui.GetWindowDrawList(); var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10), f9 = ImGuiFonts.Get(UiFont.Dash9); ImFontPtr f10 = ImGuiFonts.Get(UiFont.Dash10), f9 = ImGuiFonts.Get(UiFont.Dash9);
dl.AddText(f10, f10.FontSize, new Vector2(x, y + (16 - f10.FontSize) * 0.5f), Mute, label); dl.AddText(f10, f10.FontSize, new Vector2(x, y + (16 - f10.FontSize) * 0.5f), Mute, label);
float editW = 0; float editW = 0;
if (spellsButton)
{
editW = 18;
var ep = new Vector2(x + w - editW, y);
if (IconButton("##buff_spells", ep, new Vector2(editW, 16), PhosphorIcons.Sparkle, UiFont.Dash11, SelectorBg, Mute, 0, 2))
RynthAiCommands.ApplyRemoteCommand("spells", "toggle");
ImGuiNET.ImGui.SetItemTooltip("RynthAi Spells: browse the spell list and build buff profiles.");
editW += 3;
}
if (lootEdit != null) if (lootEdit != null)
{ {
editW = 18; editW = 18;
@ -431,7 +449,8 @@ internal sealed partial class RynthAiFace : IImGuiPanel
RynthAiDashboardState.SetFilesOpen(true); RynthAiDashboardState.SetFilesOpen(true);
ImGuiNET.ImGui.SetItemTooltip("Profile: " + (view?.ProfileText ?? "Default") + "\nNav: " + (view?.NavText ?? "None") + ImGuiNET.ImGui.SetItemTooltip("Profile: " + (view?.ProfileText ?? "Default") + "\nNav: " + (view?.NavText ?? "None") +
"\nLoot: " + (view?.LootText ?? "None") + "\nMeta: " + (view?.MetaText ?? "None") + "\nLoot: " + (view?.LootText ?? "None") + "\nMeta: " + (view?.MetaText ?? "None") +
"\n\nClick to show the Profile, Nav, Loot and Meta pickers."); "\nBuffs: " + (view?.BuffText ?? "Built-in") +
"\n\nClick to show the Profile, Nav, Loot, Meta and Buffs pickers.");
} }
// What the bot is doing, always in view (every mode, minimized too): between the toggles and FR. // What the bot is doing, always in view (every mode, minimized too): between the toggles and FR.
@ -477,7 +496,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel
private void Launchers(float x0, float width) private void Launchers(float x0, float width)
{ {
float y = ImGuiNET.ImGui.GetCursorScreenPos().Y; float y = ImGuiNET.ImGui.GetCursorScreenPos().Y;
const int buttons = 8; const int buttons = 10;
float bw = MathF.Floor((width - buttons * LauncherGap) / buttons); float bw = MathF.Floor((width - buttons * LauncherGap) / buttons);
// Short labels only when every button has room for its icon and label. // Short labels only when every button has room for its icon and label.
bool labels = bw >= 68; bool labels = bw >= 68;
@ -516,6 +535,32 @@ internal sealed partial class RynthAiFace : IImGuiPanel
} }
else _drawers.Toggle(_patrol); else _drawers.Toggle(_patrol);
} }
x += bw + LauncherGap;
// Char and Hub open RynthAi's own ImGui overlay windows (Mini Remote, which is the ILT
// Hub, its section windows, Inventory HUDs). They draw only when the engine hands plugins
// its ImGui context.
Launcher("##l_char", PhosphorIcons.User, "Char",
"Char. Left-click: ILT Hub / Mini Remote (/ra hub show). Right-click: Hub windows, Progression (Skills panel).",
x, y, bw, labels, () => RynthAiCommands.ApplyRemoteCommand("hub", "show"));
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
{
ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetItemRectMin(), ImGuiCond.Always, new Vector2(0, 1));
ImGuiNET.ImGui.OpenPopup("##charmenu");
}
x += bw + LauncherGap;
// Right-click is the Mini Remote drawer, as Patrol's is its drawer; popped out there are
// no drawers, so it shows the floating Mini Remote. Inventory HUDs setup is in the
// Mini Remote's Options menu.
Launcher("##l_hub", PhosphorIcons.SquaresFour, "Hub",
popped ? "Hub. Left-click: floating Mini Remote (/ra remote). Right-click: show the floating Mini Remote."
: "Hub. Left-click: floating Mini Remote (/ra remote). Right-click: the Mini Remote drawer (left), with its Options.",
x, y, bw, labels, () => RynthAiCommands.ApplyRemoteCommand("remote", "toggle"));
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
{
if (popped) RynthAiCommands.ApplyRemoteCommand("remote", "show");
else _drawers.Toggle(_remote);
}
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + LauncherH)); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + LauncherH));
} }
@ -708,6 +753,46 @@ internal sealed partial class RynthAiFace : IImGuiPanel
dl.AddText(font, font.FontSize, new Vector2(x + 4 + CalcWidth(font, icon) + 3, ty), White, bar.Text ?? ""); dl.AddText(font, font.FontSize, new Vector2(x + 4 + CalcWidth(font, icon) + 3, ty), White, bar.Text ?? "");
} }
// ── Char menu (right-click Char): RynthAi's character windows ──────────
/// <summary>ILT Hub section windows: menu label and the "/ra hub open" section name RynthAi parses.</summary>
private static readonly (string Label, string Section)[] HubSections =
{
("Character", "character"), ("Quests", "quests"), ("Pets", "pets"),
("Banking", "banking"), ("Gear", "gear"), ("Games", "games"), ("Guardian", "guardian"),
};
private static void CharMenu()
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(8, 8));
bool open = ImGuiNET.ImGui.BeginPopup("##charmenu");
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor(2);
if (!open) return;
try
{
// The Mini Remote is the ILT Hub; each former Hub tab is its own window (toggled).
if (ImGuiNET.ImGui.MenuItem("Mini Remote (ILT Hub)", "/ra hub"))
RynthAiCommands.ApplyRemoteCommand("hub", "toggle");
ImGuiNET.ImGui.Separator();
foreach ((string label, string section) in HubSections)
{
if (ImGuiNET.ImGui.MenuItem(label, "/ra hub open " + section))
RynthAiCommands.ApplyRemoteCommand("hub", "open " + section + " toggle");
}
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem("Progression (Skills panel)"))
SkillsFace.ShowProgression();
ImGuiNET.ImGui.SetItemTooltip("XP planner, augmentations and enlightenment (ILT worlds)");
}
finally
{
ImGuiNET.ImGui.EndPopup();
}
}
// ── Patrol popup (right-click Patrol, popped out; docked it's the Patrol drawer) ── // ── Patrol popup (right-click Patrol, popped out; docked it's the Patrol drawer) ──
private void PatrolPopup() private void PatrolPopup()

View file

@ -53,14 +53,27 @@ internal sealed class SettingsFace : IImGuiPanel
public bool Active; // the box had keyboard focus last frame public bool Active; // the box had keyboard focus last frame
} }
private readonly Dictionary<SettingRow, NumberEdit> _edits = new(); private readonly Dictionary<SettingRow, NumberEdit> _edits = new();
// Text rows being typed in (the saved value shows again once the box loses focus).
private readonly Dictionary<SettingRow, string> _textEdits = new();
/// <summary>Extra sidebar tab after the schema tabs; drawn from UiSources.Charms, not settings rows.</summary>
private const string CharmsTabName = "Charms Tracking";
private static int CharmsTab => SettingsSchema.Tabs.Length;
private const string CharmsHeader = "Advanced Settings > " + CharmsTabName;
public void OnShown() public void OnShown()
{ {
UiSources.Settings.Subscribe(); UiSources.Settings.Subscribe();
UiSources.Settings.RequestRefresh(); UiSources.Settings.RequestRefresh();
UiSources.Charms.Subscribe();
UiSources.Charms.RequestRefresh();
} }
public void OnHidden() => UiSources.Settings.Unsubscribe(); public void OnHidden()
{
UiSources.Settings.Unsubscribe();
UiSources.Charms.Unsubscribe();
}
public void Draw() public void Draw()
{ {
@ -100,9 +113,9 @@ internal sealed class SettingsFace : IImGuiPanel
var dl = ImGuiNET.ImGui.GetWindowDrawList(); var dl = ImGuiNET.ImGui.GetWindowDrawList();
float w = ImGuiNET.ImGui.GetContentRegionAvail().X; float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
SettingsTab[] tabs = SettingsSchema.Tabs; SettingsTab[] tabs = SettingsSchema.Tabs;
for (int i = 0; i < tabs.Length; i++) for (int i = 0; i <= tabs.Length; i++)
{ {
string tabName = tabs[i].Name; string tabName = i < tabs.Length ? tabs[i].Name : CharmsTabName;
ImGuiNET.ImGui.Dummy(new Vector2(0, 1)); ImGuiNET.ImGui.Dummy(new Vector2(0, 1));
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.PushID(i); ImGuiNET.ImGui.PushID(i);
@ -154,14 +167,23 @@ internal sealed class SettingsFace : IImGuiPanel
float w = ImGuiNET.ImGui.GetContentRegionAvail().X; float w = ImGuiNET.ImGui.GetContentRegionAvail().X;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
if (_tab >= SettingsSchema.Tabs.Length) _tab = 0; if (_tab > CharmsTab) _tab = 0;
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), Headers[_tab]); bool charms = _tab == CharmsTab;
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), charms ? CharmsHeader : Headers[_tab]);
ImGuiNET.ImGui.PopFont(); ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
Vector2 lp = ImGuiNET.ImGui.GetCursorScreenPos(); Vector2 lp = ImGuiNET.ImGui.GetCursorScreenPos();
dl.AddLine(lp, lp + new Vector2(w, 0), BtnBord); dl.AddLine(lp, lp + new Vector2(w, 0), BtnBord);
ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
if (charms)
{
CharmsTabContent(w);
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.EndChild();
return;
}
SettingRow[] rows = SettingsSchema.Tabs[_tab].Rows; SettingRow[] rows = SettingsSchema.Tabs[_tab].Rows;
for (int i = 0; i < rows.Length; i++) for (int i = 0; i < rows.Length; i++)
{ {
@ -189,9 +211,132 @@ internal sealed class SettingsFace : IImGuiPanel
case SettingKind.Spacer: ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); break; case SettingKind.Spacer: ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); break;
case SettingKind.Note: Note(row.Label, w); break; case SettingKind.Note: Note(row.Label, w); break;
case SettingKind.CraftingStatus: CraftingStatus(row); break; case SettingKind.CraftingStatus: CraftingStatus(row); break;
case SettingKind.Button: ButtonRow(row, w); break;
case SettingKind.TraceCategories: TraceCategoriesRow(row, w); break;
case SettingKind.Text: TextRow(row, w); break;
case SettingKind.Status: StatusRow(row, w); break;
} }
} }
// [All on] [All off] [ILT Hub on], then a 3-column grid of square toggles, one per
// RynthAi trace category. Edits the copy's DiagCategories and saves like any other row.
private void TraceCategoriesRow(SettingRow row, float w)
{
var cats = TraceCategoryLevels.Parse(_data.DiagCategories);
if (cats.Count == 0)
{
Note("Waiting for RynthAi...", w);
return;
}
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
if (ImGuiNET.ImGui.Button("All on")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", true));
ImGuiNET.ImGui.SameLine(0, 6);
if (ImGuiNET.ImGui.Button("All off")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", false));
ImGuiNET.ImGui.SameLine(0, 6);
if (ImGuiNET.ImGui.Button("ILT Hub on")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", true, "Ilt"));
Tooltip(row);
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
var dl = ImGuiNET.ImGui.GetWindowDrawList();
float colW = Math.Max(80f, w / 3f);
int perRow = Math.Max(1, (int)(w / colW));
Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos();
for (int i = 0; i < cats.Count; i++)
{
var (name, level) = cats[i];
bool on = level != TraceCategoryLevels.Off;
string label = TraceCategoryLevels.Label(name, level);
var p = start + new Vector2(i % perRow * colW, i / perRow * 18f);
ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.PushID(name);
if (ImGuiNET.ImGui.InvisibleButton("##cat", new Vector2(colW - 4, 16)))
SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, name, !on));
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
ImGuiNET.ImGui.PopID();
dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), on ? ToggleOn : ToggleOff, 2);
dl.PushClipRect(p, p + new Vector2(colW - 4, 16), true);
dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, label);
dl.PopClipRect();
}
int rowsUsed = (cats.Count + perRow - 1) / perRow;
ImGuiNET.ImGui.SetCursorScreenPos(start + new Vector2(0, rowsUsed * 18f));
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
}
private void SaveCategories(string levels)
{
_data.DiagCategories = levels;
SettingsCommands.Save(_data.Clone());
}
// Label, then a full-width box; the value commits on Enter or focus loss (like the number boxes).
private void TextRow(SettingRow row, float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
ImGuiNET.ImGui.TextUnformatted(row.Label);
ImGuiNET.ImGui.PopStyleColor();
Tooltip(row);
string saved = row.GetText?.Invoke(_data) ?? string.Empty;
string text = _textEdits.TryGetValue(row, out string? typing) ? typing : saved;
ImGuiNET.ImGui.SetNextItemWidth(Math.Max(80, w - 4));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, PanelBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 0f);
bool enter = ImGuiNET.ImGui.InputTextWithHint("##text", row.Hint ?? string.Empty, ref text, 512u,
ImGuiInputTextFlags.EnterReturnsTrue);
bool active = ImGuiNET.ImGui.IsItemActive();
bool committed = enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit();
ImGuiNET.ImGui.PopStyleVar(2);
ImGuiNET.ImGui.PopStyleColor(3);
Tooltip(row);
_editing |= active;
if (committed)
{
_textEdits.Remove(row);
if (!string.Equals(text, saved, StringComparison.Ordinal))
{
row.SetText?.Invoke(_data, text);
SettingsCommands.Save(_data.Clone());
}
}
else if (active) _textEdits[row] = text;
else _textEdits.Remove(row);
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
}
// RynthAi's one-line status (teal), wrapped to the column.
private void StatusRow(SettingRow row, float w)
{
string text = row.GetText?.Invoke(_data) ?? string.Empty;
if (text.Length == 0) return;
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Teal);
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w);
ImGuiNET.ImGui.TextUnformatted(text);
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.PopStyleColor();
}
// Label | [caption]; Click posts its own work (never runs plugin code on AC's thread).
private static void ButtonRow(SettingRow row, float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim);
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextUnformatted(row.Label);
ImGuiNET.ImGui.PopStyleColor();
ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, w * 0.45f));
if (ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label))
row.Click?.Invoke();
Tooltip(row);
}
private void Changed(SettingRow row, double value) private void Changed(SettingRow row, double value)
{ {
row.Set!(_data, value); row.Set!(_data, value);
@ -403,6 +548,130 @@ internal sealed class SettingsFace : IImGuiPanel
} }
} }
// ── Charms Tracking tab ───────────────────────────────────────────────
private static readonly uint CharmOn = C(0xFF33FF33), CharmDisabled = C(0xFFFF5555);
/// <summary>Summary line, one table row per ACECustom registry charm, then how each column is known.</summary>
private static void CharmsTabContent(float w)
{
var snap = UiSources.Charms.Current;
if (snap == null)
{
Note("Waiting for RynthAi...", w);
return;
}
CharmsInfo info = snap.Value;
if (!info.Available)
{
Note("Charm tracking is for ILT (Infinite Leaftide / ACECustom) worlds."
+ (info.World.Length > 0 ? " Current world: " + info.World + "." : ""), w);
Note("Use /ra hub force on to treat this world as ILT.", w);
return;
}
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333),
$"{info.AcquiredCount} of {info.Total} acquired | {info.ActiveCount} active");
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.Dummy(new Vector2(0, 4));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.CellPadding, new Vector2(4, 3));
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.TableRowBg, PanelBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.TableRowBgAlt, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.TableHeaderBg, TabActive);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.TableBorderLight, BtnBord);
const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingFixedFit;
if (ImGuiNET.ImGui.BeginTable("##charms", 5, flags, new Vector2(w, 0)))
{
ImGuiNET.ImGui.TableSetupColumn("Charm", ImGuiTableColumnFlags.WidthStretch);
ImGuiNET.ImGui.TableSetupColumn("Acquired", ImGuiTableColumnFlags.WidthFixed, 70);
ImGuiNET.ImGui.TableSetupColumn("Status", ImGuiTableColumnFlags.WidthFixed, 44);
ImGuiNET.ImGui.TableSetupColumn("Tier", ImGuiTableColumnFlags.WidthFixed, 32);
ImGuiNET.ImGui.TableSetupColumn("Server", ImGuiTableColumnFlags.WidthFixed, 56);
ImGuiNET.ImGui.TableHeadersRow();
CharmRow[] rows = info.Charms;
for (int i = 0; i < rows.Length; i++)
{
CharmRow r = rows[i];
ImGuiNET.ImGui.PushID(i);
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn();
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), r.Name);
if (r.Effect.Length > 0) ImGuiNET.ImGui.SetItemTooltip(r.Effect);
ImGuiNET.ImGui.TableNextColumn();
switch (r.Acquired)
{
case "carried":
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), r.Count > 1 ? $"Carried x{r.Count}" : "Carried");
ImGuiNET.ImGui.SetItemTooltip("In your pack or equipped.");
break;
case "seen":
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "Stored");
ImGuiNET.ImGui.SetItemTooltip("Owned but not carried"
+ (r.LastSeen.Length > 0 ? " (last carried " + r.LastSeen + ")" : "")
+ ". The client only sees items you carry.");
break;
default:
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "Not yet");
break;
}
ImGuiNET.ImGui.TableNextColumn();
if (r.Acquired != "carried")
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "-");
else if (r.Active == "on")
ColoredText(CharmOn, "ON");
else if (r.Active == "off")
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "OFF");
else
{
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "?");
ImGuiNET.ImGui.SetItemTooltip("Waiting for the charm's appraisal (requested automatically).");
}
ImGuiNET.ImGui.TableNextColumn();
string tier = r.Tier <= 0 ? "-" : r.MaxTier > 0 ? $"{r.Tier}/{r.MaxTier}" : r.Tier.ToString(CultureInfo.InvariantCulture);
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), tier);
ImGuiNET.ImGui.TableNextColumn();
if (r.Server == "off")
{
ColoredText(CharmDisabled, "Disabled");
ImGuiNET.ImGui.SetItemTooltip("The server refused or reported this charm as disabled.");
}
else if (r.Server == "on")
ColoredText(CharmOn, "Enabled");
else
{
ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "-");
ImGuiNET.ImGui.SetItemTooltip("Not reported. The server only tells players when a charm is refused.");
}
ImGuiNET.ImGui.PopID();
}
ImGuiNET.ImGui.EndTable();
}
ImGuiNET.ImGui.PopStyleColor(4);
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
Note("Double-click a carried charm in your pack to toggle it. Status comes from the charm's appraisal "
+ "(Status: ON/OFF) or your character's ability flag. Charms not carried are inactive.", w);
Note("Stored = carried by this character before; RynthAi remembers it per character.", w);
}
/// <summary>TextUnformatted in a packed ImGui colour.</summary>
private static void ColoredText(uint abgr, string text)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, abgr);
ImGuiNET.ImGui.TextUnformatted(text);
ImGuiNET.ImGui.PopStyleColor();
}
private static bool StepButton(string id, Vector2 pos, string glyph) private static bool StepButton(string id, Vector2 pos, string glyph)
{ {
var dl = ImGuiNET.ImGui.GetWindowDrawList(); var dl = ImGuiNET.ImGui.GetWindowDrawList();
@ -430,6 +699,8 @@ internal sealed class SettingsFace : IImGuiPanel
["Crafting"] = PhosphorIcons.Hammer, ["Crafting"] = PhosphorIcons.Hammer,
["Looting"] = PhosphorIcons.Bag, ["Looting"] = PhosphorIcons.Bag,
["Vendoring"] = PhosphorIcons.Storefront, ["Vendoring"] = PhosphorIcons.Storefront,
["Diagnostics"] = PhosphorIcons.Wrench,
[CharmsTabName] = PhosphorIcons.Gift,
}; };
private static readonly System.Collections.Generic.Dictionary<string, string> TabLabels = new(); private static readonly System.Collections.Generic.Dictionary<string, string> TabLabels = new();

View file

@ -0,0 +1,693 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/SkillsFace.Progression.cs
// The Skills panel's Progression tab, shown on ILT-like worlds only:
// - XP planner: exact XP for the next N raises of every attribute and vital,
// from the client's XP tables (raising stays on the Attributes & Vitals tab).
// - Attribute raiser: infinite attributes past the retail cap. RynthAi reads the
// server's costs ("/xp all") and raises with "/attr", by hand or on a timer from
// unassigned XP, in the order and mode set here. Laid out like UB's Leaftide XP
// tab: "+1 Level" / "+10 Levels" buttons labelled with their (projected) cost.
// - Augmentations: UB's Augs tab - Refresh current (/aug), Current / Target / Inc /
// Luminance / Coins with a totals row, Reset targets, Copy Discord / In-Game.
// - Augmentations / Enlightenment: RynthAi's ILT Hub planners. RynthAi owns the
// math and the saved inputs (UiSources.Progression snapshot); edits and
// actions go back as "prog ..." remote commands. /enl and arming
// auto-enlighten ask here first; the server still shows its own dialog.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.Data;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed partial class SkillsFace
{
private const string ProgConfirmId = "##skills_prog_confirm";
private int _planLevels = 10; // XP planner: raises to price per row
private bool _progSubscribed;
// The confirm the Progression tab asked for; the command is sent only on its Yes button.
private string _progConfirmTitle = "", _progConfirmText = "", _progConfirmYes = "", _progConfirmCommand = "";
private bool _progConfirmOpenRequested;
// Set by ShowProgression (any panel, AC thread); the tab is selected once RynthAi's snapshot
// says it exists (the first poll lands a step after the panel opens).
private static bool _progressionRequested;
/// <summary>RynthAi reports an ILT-like world (its ILT Hub exists and the server has ILT features).</summary>
private static bool ProgressionTabVisible => UiSources.Progression.Current?.Value.Available == true;
/// <summary>Opens the Skills panel (if closed) on the Progression tab. AC thread.</summary>
public static void ShowProgression()
{
_progressionRequested = true;
if (!ImGuiPanelHost.IsOpen(Title)) PanelRouter.Toggle(Title);
}
/// <summary>Draw: applies a pending ShowProgression once the tab exists.</summary>
private void ApplyProgressionRequest()
{
if (!_progressionRequested || !ProgressionTabVisible) return;
_progressionRequested = false;
_tab = 2;
}
private void ProgressionShown()
{
if (_progSubscribed) return;
_progSubscribed = true;
UiSources.Progression.Subscribe();
UiSources.Progression.RequestRefresh();
}
private void ProgressionHidden()
{
_progressionRequested = false;
if (!_progSubscribed) return;
_progSubscribed = false;
UiSources.Progression.Unsubscribe();
}
/// <summary>Sends "prog &lt;value&gt;" to RynthAi; the snapshot re-polls after its next tick applies it.</summary>
private static void SendProg(string value)
{
RynthAiCommands.ApplyRemoteCommand("prog", value);
UiSources.Progression.RequestRefreshAfterPluginTick();
}
private void AskProgConfirm(string title, string text, string yes, string command)
{
_progConfirmTitle = title;
_progConfirmText = text;
_progConfirmYes = yes;
_progConfirmCommand = command;
_progConfirmOpenRequested = true;
}
// ── Body ────────────────────────────────────────────────────────────
private void DrawProgression(float w)
{
ProgressionInfo? info = UiSources.Progression.Current?.Value;
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 4));
try
{
DrawXpPlanner(w);
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
if (info == null || !info.Available)
{
Message("Augmentations and Enlightenment need RynthAi's ILT Hub on an ILT world.", w);
return;
}
DrawAttrRaiser(info.Attr, w);
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
DrawAugPlanner(info.Aug, w);
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
DrawEnlPlanner(info.Enl, w);
ImGuiNET.ImGui.Dummy(new Vector2(0, 8));
}
finally
{
ImGuiNET.ImGui.PopStyleVar();
}
}
private void DrawXpPlanner(float w)
{
Section("XP planner", w);
if (_snap == null || _dat == null || _attributes.Count == 0)
{
Message("Waiting for your character's data...", w);
return;
}
ImGuiNET.ImGui.Indent(8);
long have = _snap.UnassignedXp;
Label($"Unassigned XP: {have:N0}", have > 0 ? Teal : Mute);
ImGuiNET.ImGui.SetNextItemWidth(160);
ImGuiNET.ImGui.SliderInt("Raises to plan##prog_lv", ref _planLevels, 1, 100);
if (ImGuiNET.ImGui.BeginTable("##prog_xp", 4, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
new Vector2(w - 16, 0)))
{
ImGuiNET.ImGui.TableSetupColumn("Stat");
ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 50);
ImGuiNET.ImGui.TableSetupColumn("Next raise", ImGuiTableColumnFlags.WidthFixed, 100);
ImGuiNET.ImGui.TableSetupColumn($"Next {_planLevels}", ImGuiTableColumnFlags.WidthFixed, 120);
ImGuiNET.ImGui.TableHeadersRow();
foreach (Row r in _attributes) PlannerRow(r, have);
foreach (Row r in _vitals) PlannerRow(r, have);
ImGuiNET.ImGui.EndTable();
}
Label("Exact costs from the client's XP tables. Raise on the Attributes & Vitals tab"
+ (ProgressionTabVisible ? ", or past the cap with the Attribute raiser below." : "."), Dim);
ImGuiNET.ImGui.Unindent(8);
}
private void PlannerRow(Row r, long have)
{
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Name);
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Base.ToString(CultureInfo.InvariantCulture));
uint[]? table = r.Table;
int left = table == null ? 0 : Math.Max(0, table.Length - 1 - (int)Math.Min(r.Ranks, (uint)int.MaxValue));
ImGuiNET.ImGui.TableNextColumn();
if (table == null || left == 0) { Label(table == null ? "-" : "max", Dim); ImGuiNET.ImGui.TableNextColumn(); Label("-", Dim); return; }
long one = SkillDat.CostOf(table, r.Ranks, r.Spent, 1);
Label(one >= 0 ? one.ToString("N0", CultureInfo.InvariantCulture) : "-", one >= 0 && one <= have ? Teal : Dim);
ImGuiNET.ImGui.TableNextColumn();
int n = Math.Min(_planLevels, left);
long many = SkillDat.CostOf(table, r.Ranks, r.Spent, n);
string text = many >= 0 ? many.ToString("N0", CultureInfo.InvariantCulture) : "-";
if (n < _planLevels) text += $" ({n} to max)";
Label(text, many >= 0 && many <= have ? Teal : Dim);
}
private static readonly string[] AttrModes =
{
"Priority - top of the order first",
"Round robin - one level each, in order",
"Cheapest next level first",
};
private string? _attrKeepEdit; // reserve box being typed in (null = show RynthAi's value)
private int? _attrEveryEdit; // interval box being typed in
private void DrawAttrRaiser(AttrRaiser? a, float w)
{
Section("Attribute raiser (infinite attributes)", w);
ImGuiNET.ImGui.Indent(8);
float wrap = ImGuiNET.ImGui.GetCursorPosX() + w - 24;
ImGuiNET.ImGui.PushTextWrapPos(wrap);
try
{
if (a == null) { Label("Update RynthAi to use the attribute raiser.", Mute); return; }
if (a.Off) { Label(a.Reason, Mute); return; }
Label(a.XpHeader.Length > 0 ? a.XpHeader : a.Unassigned, Teal);
if (a.XpHeader.Length > 0 && a.Unassigned.Contains("spendable", StringComparison.Ordinal)) Label(a.Unassigned, Dim);
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
if (a.Running)
{
if (Button("##attr_stop", "Stop", p, new Vector2(90, 24), Text, StopBg)) SendProg("attrstop");
}
else if (Button("##attr_run", "Raise now", p, new Vector2(110, 24), Text, StartBg, border: Teal))
SendProg("attrrun");
if (Button("##attr_costs", "Refresh XP", new Vector2(p.X + 116, p.Y), new Vector2(100, 24), Text, BtnFill, enabled: !a.Running))
SendProg("attrcosts");
ImGuiNET.ImGui.SetItemTooltip("Re-reads every next-level cost with /xp all.");
if (a.Updated.Length > 0)
{
ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + 224, p.Y + 4));
Label("Last updated: " + a.Updated, Dim);
}
NextLine(p, 28);
if (a.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(a.Status);
if (a.LastRun.Length > 0) Label("Last run: " + a.LastRun, Dim);
ImGuiNET.ImGui.Separator();
bool auto = a.Auto;
if (ImGuiNET.ImGui.Checkbox("Auto-raise from unassigned XP##attr_auto", ref auto))
SendProg("attrauto " + (auto ? "on" : "off"));
ImGuiNET.ImGui.SameLine();
// Commit on Enter, the +/- buttons or focus loss (not on every keystroke: each send
// restarts the auto-raise timer).
int every = _attrEveryEdit ?? a.Every;
ImGuiNET.ImGui.SetNextItemWidth(90);
bool everyCommit = ImGuiNET.ImGui.InputInt("every (min)##attr_every", ref every, 1, 10, ImGuiInputTextFlags.EnterReturnsTrue);
bool everyActive = ImGuiNET.ImGui.IsItemActive();
if (everyCommit || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_attrEveryEdit = null;
if (every != a.Every) SendProg("attrevery " + Math.Clamp(every, 1, 1440).ToString(CultureInfo.InvariantCulture));
}
else _attrEveryEdit = everyActive ? every : null;
if (a.Auto && a.Next.Length > 0) Label($"Next auto-raise: {a.Next}", Dim);
int mode = Math.Clamp(a.Mode, 0, AttrModes.Length - 1);
ImGuiNET.ImGui.SetNextItemWidth(260);
if (ImGuiNET.ImGui.Combo("Raise order##attr_mode", ref mode, AttrModes, AttrModes.Length))
SendProg("attrmode " + mode.ToString(CultureInfo.InvariantCulture));
// The box holds the exact reserve (KeepFull); it is sent only when the text changed, so an
// Enter on an untouched box can't round the reserve.
string shownKeep = a.KeepFull.Length > 0 ? a.KeepFull : a.Keep;
string keep = _attrKeepEdit ?? shownKeep;
ImGuiNET.ImGui.SetNextItemWidth(140);
bool enter = ImGuiNET.ImGui.InputTextWithHint("Keep in reserve (XP)##attr_keep", "0, 500m, 2b", ref keep, 32u,
ImGuiInputTextFlags.EnterReturnsTrue);
bool keepActive = ImGuiNET.ImGui.IsItemActive();
if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_attrKeepEdit = null;
if (!string.Equals(keep.Trim(), shownKeep, StringComparison.Ordinal))
SendProg("attrkeep " + keep.Replace(" ", "", StringComparison.Ordinal).Replace(",", "", StringComparison.Ordinal));
}
else _attrKeepEdit = keepActive ? keep : null;
ImGuiNET.ImGui.SetItemTooltip("Unassigned XP the raiser never spends. Accepts k / m / b / t suffixes.");
DrawAttrTable(a, w);
Label("Auto: the stats Raise now / auto-raise may spend on; arrows set the order. "
+ "+1 / +10 raise by hand (red = not enough unassigned XP). "
+ "+10 is an estimate (7.7% dearer per level); the server charges the real cost. " + a.CostsAge + ".", Dim);
}
finally
{
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.Unindent(8);
}
}
/// <summary>
/// UB Leaftide XP tab layout: Auto tick, stat, base, then "+1 Level" / "+10 Levels" buttons
/// labelled with what they cost, then the priority arrows.
/// </summary>
private void DrawAttrTable(AttrRaiser a, float w)
{
if (!ImGuiNET.ImGui.BeginTable("##prog_attr", 6, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
new Vector2(w - 16, 0)))
return;
ImGuiNET.ImGui.TableSetupColumn("Auto", ImGuiTableColumnFlags.WidthFixed, 34);
ImGuiNET.ImGui.TableSetupColumn("Stat");
ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 56);
ImGuiNET.ImGui.TableSetupColumn("+1 Level", ImGuiTableColumnFlags.WidthFixed, 84);
ImGuiNET.ImGui.TableSetupColumn("+10 Levels", ImGuiTableColumnFlags.WidthFixed, 84);
ImGuiNET.ImGui.TableSetupColumn("Order", ImGuiTableColumnFlags.WidthFixed, 48);
ImGuiNET.ImGui.TableHeadersRow();
for (int i = 0; i < a.Rows.Length; i++)
{
AttrRow r = a.Rows[i];
ImGuiNET.ImGui.PushID("attr_" + r.Key);
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn();
bool on = r.On;
if (ImGuiNET.ImGui.Checkbox("##on", ref on)) SendProg($"attron {r.Key} {(on ? "on" : "off")}");
ImGuiNET.ImGui.TableNextColumn();
Label($"{i + 1}. {r.Label}", r.On ? Text : Mute);
ImGuiNET.ImGui.TableNextColumn();
int clientBase = ClientBase(r);
Label(clientBase > 0 ? clientBase.ToString("N0", CultureInfo.InvariantCulture)
: r.Base >= 0 ? r.Base.ToString("N0", CultureInfo.InvariantCulture) : "-", Text);
// Older RynthAi sends no cost10 / afford1: plain buttons, the server decides.
bool rich = r.Cost10.Length > 0;
ImGuiNET.ImGui.TableNextColumn();
RaiseButton(a, r, 1, rich ? r.Cost : "+1", rich ? r.Afford1 : true, r.CostFull, rich);
ImGuiNET.ImGui.TableNextColumn();
RaiseButton(a, r, 10, rich ? r.Cost10 : "+10", rich ? r.Afford10 : true, r.Cost10Full, rich);
ImGuiNET.ImGui.TableNextColumn();
ImGuiNET.ImGui.BeginDisabled(i == 0);
if (ImGuiNET.ImGui.ArrowButton("##up", ImGuiDir.Up)) SendProg($"attrmove {r.Key} up");
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SameLine(0, 2);
ImGuiNET.ImGui.BeginDisabled(i == a.Rows.Length - 1);
if (ImGuiNET.ImGui.ArrowButton("##down", ImGuiDir.Down)) SendProg($"attrmove {r.Key} down");
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.PopID();
}
ImGuiNET.ImGui.EndTable();
}
/// <summary>
/// One by-hand raise button filling its cell. Unknown cost ("?") stays clickable (the server
/// checks); a known cost over the unassigned XP is red and disabled.
/// </summary>
private static void RaiseButton(AttrRaiser a, AttrRow r, int levels, string label, bool afford, string exact, bool rich)
{
bool known = rich && r.Known;
bool enabled = !a.Running && (!known || afford);
uint fg = !known ? Text : afford ? Teal : Red;
Vector2 pos = ImGuiNET.ImGui.GetCursorScreenPos();
float width = Math.Max(40f, ImGuiNET.ImGui.GetContentRegionAvail().X);
if (Button("##raise" + levels, label, pos, new Vector2(width, 20), fg, BtnFill, enabled, border: known && afford ? Teal : 0))
SendProg($"attrraise {r.Key} {levels}");
string what = $"{r.Label} +{levels} level{(levels > 1 ? "s" : "")}";
string tip = !known ? $"{what}: cost not read yet (Refresh XP)."
: levels > 1 ? $"{what}: about {exact} XP (estimate)."
: $"{what}: {exact} XP.";
if (known && !afford) tip += " Not enough unassigned XP.";
if (a.Running) tip += " Wait for the raise run to finish.";
ImGuiNET.ImGui.SetItemTooltip(tip);
}
/// <summary>The client's own base value for a raiser row (0 when the snapshot has none).</summary>
private int ClientBase(AttrRow r)
{
List<Row> rows = r.Vital ? _vitals : _attributes;
foreach (Row row in rows)
if (row.Name.Equals(r.Label, StringComparison.OrdinalIgnoreCase)) return row.Base;
return 0;
}
private void DrawAugPlanner(AugPlanner a, float w)
{
Section("Augmentations", w);
ImGuiNET.ImGui.Indent(8);
try
{
if (a.Off) { Label("/aug is not available on this server.", Mute); return; }
// UB Augs tab buttons: Refresh Current, Reset Target, Copy Discord, Copy In-Game.
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float x = p.X;
if (Button("##aug_refresh", "Refresh current", new Vector2(x, p.Y), new Vector2(120, 22), Text, StartBg, border: Teal))
SendProg("augload");
ImGuiNET.ImGui.SetItemTooltip("Reads your augmentation levels with /aug (also done once when this tab first opens).");
x += 124;
if (Button("##aug_reset", "Reset targets", new Vector2(x, p.Y), new Vector2(104, 22), Text, BtnFill))
SendProg("augreset");
ImGuiNET.ImGui.SetItemTooltip("Sets every target back to the current level.");
x += 108;
if (Button("##aug_discord", "Copy Discord", new Vector2(x, p.Y), new Vector2(100, 22), Text, BtnFill, enabled: a.CopyDiscord.Length > 0))
ImGuiNET.ImGui.SetClipboardText(a.CopyDiscord);
ImGuiNET.ImGui.SetItemTooltip("Copies the plan as a Discord code-block table.");
x += 104;
if (Button("##aug_ingame", "Copy in-game", new Vector2(x, p.Y), new Vector2(100, 22), Text, BtnFill, enabled: a.CopyIngame.Length > 0))
ImGuiNET.ImGui.SetClipboardText(a.CopyIngame);
ImGuiNET.ImGui.SetItemTooltip("Copies your current levels as one chat line.");
NextLine(p, 26);
Label("Status: " + a.Status, Dim);
if (ImGuiNET.ImGui.BeginTable("##prog_augs", 6, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
new Vector2(w - 16, 0)))
{
ImGuiNET.ImGui.TableSetupColumn("Aug");
ImGuiNET.ImGui.TableSetupColumn("Current", ImGuiTableColumnFlags.WidthFixed, 56);
ImGuiNET.ImGui.TableSetupColumn("Target", ImGuiTableColumnFlags.WidthFixed, 124);
ImGuiNET.ImGui.TableSetupColumn("Inc", ImGuiTableColumnFlags.WidthFixed, 44);
ImGuiNET.ImGui.TableSetupColumn("Luminance", ImGuiTableColumnFlags.WidthFixed, 76);
ImGuiNET.ImGui.TableSetupColumn("Coins", ImGuiTableColumnFlags.WidthFixed, 56);
ImGuiNET.ImGui.TableHeadersRow();
foreach (AugRow row in a.Rows)
{
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Label);
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Current.ToString("N0", CultureInfo.InvariantCulture));
ImGuiNET.ImGui.TableNextColumn();
DrawAugTarget(row);
int inc = row.Increase > 0 ? row.Increase : Math.Max(0, row.Target - row.Current);
ImGuiNET.ImGui.TableNextColumn(); Label(inc > 0 ? inc.ToString("N0", CultureInfo.InvariantCulture) : "-", inc > 0 ? Teal : Dim);
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Lum);
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(row.Coins > 0 ? row.Coins.ToString("N0", CultureInfo.InvariantCulture) : "-");
}
if (a.TotalLum.Length > 0)
{
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn(); Label("TOTALS", Amber);
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalCurrent.ToString("N0", CultureInfo.InvariantCulture), Amber);
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalTarget.ToString("N0", CultureInfo.InvariantCulture), Amber);
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalIncrease.ToString("N0", CultureInfo.InvariantCulture), Amber);
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalLum, Amber);
ImGuiNET.ImGui.TableNextColumn(); Label(a.TotalCoins.ToString("N0", CultureInfo.InvariantCulture), Amber);
}
ImGuiNET.ImGui.EndTable();
}
// Lum per coin commits on Enter / focus loss, not per keystroke.
string shownLpc = a.LumPerCoin.ToString(CultureInfo.InvariantCulture);
string lpc = _augLpcEdit ?? shownLpc;
ImGuiNET.ImGui.SetNextItemWidth(140);
bool lpcEnter = ImGuiNET.ImGui.InputTextWithHint("Lum per e-coin##prog_lpc", "0 = don't price coins", ref lpc, 24u,
ImGuiInputTextFlags.EnterReturnsTrue);
bool lpcActive = ImGuiNET.ImGui.IsItemActive();
if (lpcEnter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_augLpcEdit = null;
string clean = lpc.Replace(" ", "", StringComparison.Ordinal).Replace(",", "", StringComparison.Ordinal);
if (!string.Equals(clean, shownLpc, StringComparison.Ordinal)) SendProg("lumpercoin " + clean);
}
else _augLpcEdit = lpcActive ? lpc : null;
ImGuiNET.ImGui.SetItemTooltip("Luminance one Enlightened Coin costs you. Accepts k / m / b / t suffixes.");
if (a.CoinsLine.Length > 0)
{
Label(a.CoinsLine, Text);
Label(a.LumToBuy, Text);
}
else
{
Label(a.Total, Amber);
if (a.Short.Length > 0) Label(a.Short, Text);
}
Label(a.Banked, Dim);
if (a.Config != null) DrawAugCostSettings(a.Config, w);
}
finally
{
ImGuiNET.ImGui.Unindent(8);
}
}
private static readonly string[] AugTierNames = { "Below S1", "From S1", "From S2", "From S3", "From S4" };
// Cost-settings boxes being typed in, by box id (committed on Enter / focus loss).
private readonly Dictionary<string, int> _augCfgIntEdit = new(StringComparer.Ordinal);
private readonly Dictionary<string, double> _augCfgDblEdit = new(StringComparer.Ordinal);
/// <summary>
/// Collapsible editor for this world's aug cost rules (RynthAi saves them per world). The
/// defaults are UB's InfiniteLeaftide model; Reset puts a changed world back on them.
/// </summary>
private void DrawAugCostSettings(AugCostConfig cfg, float w)
{
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
string head = $"Cost settings for {cfg.World}" + (cfg.Custom ? " (custom)" : " (InfiniteLeaftide defaults)");
if (!ImGuiNET.ImGui.CollapsingHeader(head + "##aug_cfg")) return;
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w - 24);
Label("Level i costs (Base + (i - 1) x Base x Growth% / 100) x the multiplier of its tier. "
+ "A tier starts at its S level (UB's InfiniteLeaftide model). Changes apply to this world only.", Dim);
ImGuiNET.ImGui.PopTextWrapPos();
// Tier multipliers, one box each.
Label("Tier multipliers", Text);
for (int t = 0; t < AugTierNames.Length && t < cfg.Multipliers.Length; t++)
{
if (t > 0) ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.BeginGroup();
Label(AugTierNames[t], Mute);
ImGuiNET.ImGui.SetNextItemWidth(62);
CfgDouble($"mult{t}", cfg.Multipliers[t], v => $"augmult {t} {v.ToString("R", CultureInfo.InvariantCulture)}");
ImGuiNET.ImGui.EndGroup();
}
// Per-aug rules.
if (ImGuiNET.ImGui.BeginTable("##aug_cfg_rows", 9, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp,
new Vector2(w - 16, 0)))
{
ImGuiNET.ImGui.TableSetupColumn("Aug");
ImGuiNET.ImGui.TableSetupColumn("Base", ImGuiTableColumnFlags.WidthFixed, 74);
ImGuiNET.ImGui.TableSetupColumn("Growth%", ImGuiTableColumnFlags.WidthFixed, 54);
ImGuiNET.ImGui.TableSetupColumn("S1", ImGuiTableColumnFlags.WidthFixed, 46);
ImGuiNET.ImGui.TableSetupColumn("S2", ImGuiTableColumnFlags.WidthFixed, 46);
ImGuiNET.ImGui.TableSetupColumn("S3", ImGuiTableColumnFlags.WidthFixed, 46);
ImGuiNET.ImGui.TableSetupColumn("S4", ImGuiTableColumnFlags.WidthFixed, 46);
ImGuiNET.ImGui.TableSetupColumn("Cap", ImGuiTableColumnFlags.WidthFixed, 50);
ImGuiNET.ImGui.TableSetupColumn("Coins", ImGuiTableColumnFlags.WidthFixed, 42);
ImGuiNET.ImGui.TableHeadersRow();
foreach (AugCostRule r in cfg.Rows)
{
ImGuiNET.ImGui.TableNextRow();
ImGuiNET.ImGui.TableNextColumn(); ImGuiNET.ImGui.TextUnformatted(r.Label);
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.base", (int)Math.Min(r.Base, int.MaxValue), $"augcfg {r.Key} base");
ImGuiNET.ImGui.TableNextColumn(); CfgDouble($"{r.Key}.pct", r.Percent, v => $"augcfg {r.Key} pct {v.ToString("R", CultureInfo.InvariantCulture)}");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s1", r.S1, $"augcfg {r.Key} s1");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s2", r.S2, $"augcfg {r.Key} s2");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s3", r.S3, $"augcfg {r.Key} s3");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.s4", r.S4, $"augcfg {r.Key} s4");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.cap", r.Cap, $"augcfg {r.Key} cap");
ImGuiNET.ImGui.SetItemTooltip("Highest target level; 0 = no limit.");
ImGuiNET.ImGui.TableNextColumn(); CfgInt($"{r.Key}.coins", r.Coins, $"augcfg {r.Key} coins");
ImGuiNET.ImGui.SetItemTooltip("Enlightened Coins per level.");
}
ImGuiNET.ImGui.EndTable();
}
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
if (Button("##aug_cfg_reset", "Reset to InfiniteLeaftide defaults", p, new Vector2(230, 22), Text, BtnFill, enabled: cfg.Custom))
SendProg("augcfgreset");
ImGuiNET.ImGui.SetItemTooltip("Drops this world's changes; it goes back to UB's InfiniteLeaftide rules.");
NextLine(p, 26);
}
/// <summary>Integer box that sends "<paramref name="verb"/> value" on Enter or focus loss.</summary>
private void CfgInt(string id, int value, string verb)
{
int v = _augCfgIntEdit.TryGetValue(id, out int typing) ? typing : value;
ImGuiNET.ImGui.SetNextItemWidth(-1);
bool enter = ImGuiNET.ImGui.InputInt("##cfg_" + id, ref v, 0, 0, ImGuiInputTextFlags.EnterReturnsTrue);
bool active = ImGuiNET.ImGui.IsItemActive();
if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_augCfgIntEdit.Remove(id);
if (v != value) SendProg($"{verb} {Math.Max(0, v).ToString(CultureInfo.InvariantCulture)}");
}
else if (active) _augCfgIntEdit[id] = v;
else _augCfgIntEdit.Remove(id);
}
/// <summary>Decimal box (the caller sets its width) that sends <paramref name="command"/>(value) on Enter or focus loss.</summary>
private void CfgDouble(string id, double value, Func<double, string> command)
{
double v = _augCfgDblEdit.TryGetValue(id, out double typing) ? typing : value;
if (!id.StartsWith("mult", StringComparison.Ordinal)) ImGuiNET.ImGui.SetNextItemWidth(-1);
bool enter = ImGuiNET.ImGui.InputDouble("##cfg_" + id, ref v, 0, 0, "%.6g", ImGuiInputTextFlags.EnterReturnsTrue);
bool active = ImGuiNET.ImGui.IsItemActive();
if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_augCfgDblEdit.Remove(id);
if (Math.Abs(v - value) > 1e-9 && double.IsFinite(v)) SendProg(command(Math.Max(0, v)));
}
else if (active) _augCfgDblEdit[id] = v;
else _augCfgDblEdit.Remove(id);
}
private string? _augLpcEdit; // Lum per coin box being typed in
private readonly Dictionary<string, int> _augTargetEdit = new(StringComparer.Ordinal); // target boxes being typed in
/// <summary>
/// Target cell: -/+ step one level (Ctrl: 100), typing commits on Enter or focus loss so a
/// half-typed number never reaches RynthAi. RynthAi clamps to current..cap.
/// </summary>
private void DrawAugTarget(AugRow row)
{
int tgt = _augTargetEdit.TryGetValue(row.Key, out int typing) ? typing : row.Target;
ImGuiNET.ImGui.SetNextItemWidth(-1);
bool commit = ImGuiNET.ImGui.InputInt("##prog_tgt_" + row.Key, ref tgt, 1, 100, ImGuiInputTextFlags.EnterReturnsTrue);
bool active = ImGuiNET.ImGui.IsItemActive();
if (commit || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
_augTargetEdit.Remove(row.Key);
int clamped = Math.Clamp(tgt, row.Current, Math.Max(row.Cap, row.Current));
if (clamped != row.Target) SendProg($"augtarget {row.Key} {clamped.ToString(CultureInfo.InvariantCulture)}");
}
else if (active) _augTargetEdit[row.Key] = tgt;
else _augTargetEdit.Remove(row.Key);
ImGuiNET.ImGui.SetItemTooltip($"Target {row.Label} level (up to {row.Cap.ToString("N0", CultureInfo.InvariantCulture)}).");
}
private void DrawEnlPlanner(EnlPlanner e, float w)
{
Section("Enlightenment", w);
ImGuiNET.ImGui.Indent(8);
float wrap = ImGuiNET.ImGui.GetCursorPosX() + w - 24; // window-local x
ImGuiNET.ImGui.PushTextWrapPos(wrap);
try
{
if (e.Off) { Label("/enl is not available on this server.", Mute); return; }
Label(e.Header, Text);
Label(e.Next, Teal);
int target = e.Target;
ImGuiNET.ImGui.SetNextItemWidth(100);
if (ImGuiNET.ImGui.InputInt("Plan to level##prog_enlt", ref target))
SendProg("enltarget " + Math.Max(e.Level + 1, target).ToString(CultureInfo.InvariantCulture));
foreach (string line in e.Plan) ImGuiNET.ImGui.BulletText(line);
int coinsPerToken = e.CoinsPerToken;
ImGuiNET.ImGui.SetNextItemWidth(100);
if (ImGuiNET.ImGui.InputInt("Coins per token (shop price)##prog_cpt", ref coinsPerToken))
SendProg("coinspertoken " + Math.Max(0, coinsPerToken).ToString(CultureInfo.InvariantCulture));
if (e.TokensShort.Length > 0) Label(e.TokensShort, Dim);
ImGuiNET.ImGui.Separator();
if (e.Blockers.Length == 0) Label("Client-side checks pass.", Green);
foreach (string b in e.Blockers) Label(b, Amber);
Label(e.ServerChecks, Dim);
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
if (Button("##prog_enl", "Enlighten now...", p, new Vector2(150, 24), Text, BtnFill, border: Teal))
AskProgConfirm("Enlighten",
"Send /enl now?\n\nEnlightening resets your level and wipes unassigned XP.\n"
+ "The server will show its own Yes/No dialog - you must click Yes there.",
"Send /enl", "enlighten");
NextLine(p, 28);
ImGuiNET.ImGui.Separator();
bool auto = e.Auto;
if (ImGuiNET.ImGui.Checkbox("Auto-enlighten when ready##prog_auto", ref auto))
{
if (auto)
AskProgConfirm("Arm auto-enlighten",
"Auto-enlighten will send /enl whenever the checks pass (peace mode, level, materials).\n"
+ "You still have to click Yes in the AC dialog each time.\n\nArm it for this session?",
"Arm", "autoenl on");
else
SendProg("autoenl off");
}
if (e.Auto && !e.Armed)
{
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Arm for this session...##prog_arm"))
AskProgConfirm("Arm auto-enlighten", "Arm auto-enlighten for this session?", "Arm", "autoenl arm");
}
bool spend = e.SpendFirst;
if (ImGuiNET.ImGui.Checkbox("Spend unassigned XP on attributes first##prog_spend", ref spend))
SendProg("spendfirst " + (spend ? "on" : "off"));
int every = e.CheckEvery;
ImGuiNET.ImGui.SetNextItemWidth(100);
if (ImGuiNET.ImGui.InputInt("Check every (s)##prog_every", ref every))
SendProg("checkevery " + Math.Max(10, every).ToString(CultureInfo.InvariantCulture));
Label(e.Armed ? "Armed." : "Disarmed.", e.Armed ? Amber : Dim);
if (e.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(e.Status);
}
finally
{
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.Unindent(8);
}
}
// ── Confirm ─────────────────────────────────────────────────────────
/// <summary>The Progression tab's Yes/No popup (outside the body child, like DrawConfirm).</summary>
private void DrawProgressionConfirm()
{
if (_progConfirmOpenRequested)
{
_progConfirmOpenRequested = false;
ImGuiNET.ImGui.OpenPopup(ProgConfirmId);
}
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(10, 8));
bool open = ImGuiNET.ImGui.BeginPopup(ProgConfirmId);
ImGuiNET.ImGui.PopStyleVar(2);
ImGuiNET.ImGui.PopStyleColor(2);
if (!open) return;
try
{
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11));
Label(_progConfirmTitle, Amber);
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + 320);
Label(_progConfirmText, Text);
ImGuiNET.ImGui.PopTextWrapPos();
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4);
if (Button("##prog_yes", _progConfirmYes, p, new Vector2(120, 24), Text, StartBg))
{
SendProg(_progConfirmCommand);
ImGuiNET.ImGui.CloseCurrentPopup();
}
if (Button("##prog_no", "Cancel", new Vector2(p.X + 126, p.Y), new Vector2(90, 24), Text, BtnFill))
ImGuiNET.ImGui.CloseCurrentPopup();
NextLine(p, 28);
}
finally
{
ImGuiNET.ImGui.EndPopup();
}
}
}

View file

@ -45,7 +45,7 @@ using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels; namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class SkillsFace : IImGuiPanel internal sealed partial class SkillsFace : IImGuiPanel
{ {
public const string Title = "Skills"; public const string Title = "Skills";
@ -127,7 +127,7 @@ internal sealed class SkillsFace : IImGuiPanel
} }
// ── State ─────────────────────────────────────────────────────────── // ── State ───────────────────────────────────────────────────────────
private int _tab; // 0 skills, 1 attributes & vitals private int _tab; // 0 skills, 1 attributes & vitals, 2 progression (ILT worlds)
private SortKey _sort = SortKey.Name; private SortKey _sort = SortKey.Name;
private bool _descending; private bool _descending;
private readonly bool[] _collapsed = { false, false, false, true }; private readonly bool[] _collapsed = { false, false, false, true };
@ -193,18 +193,23 @@ internal sealed class SkillsFace : IImGuiPanel
SkillDat.EnsureLoadQueued(); SkillDat.EnsureLoadQueued();
PortalSpellTable.EnsureLoadQueued(); PortalSpellTable.EnsureLoadQueued();
MasteryFeed.PanelOpened(); // asks only on Aelrynth, and only if the last reply is stale MasteryFeed.PanelOpened(); // asks only on Aelrynth, and only if the last reply is stale
ProgressionShown();
} }
public void OnHidden() => ProgressionHidden();
public void Draw() public void Draw()
{ {
PlayerProgressHooks.Want(); PlayerProgressHooks.Want();
Refresh(); Refresh();
ApplyProgressionRequest();
if (_tab == 2 && !ProgressionTabVisible) _tab = 0;
float w = Begin(out Vector2 origin, out Vector2 size); float w = Begin(out Vector2 origin, out Vector2 size);
DrawSummary(w); DrawSummary(w);
DrawTabs(w); DrawTabs(w);
if (_tab == 0) DrawToolbar(w); if (_tab == 0) DrawToolbar(w);
DrawColumnHeader(w, _tab == 0 ? "Skill" : "Attribute"); if (_tab != 2) DrawColumnHeader(w, _tab == 0 ? "Skill" : "Attribute");
float bodyH = Math.Max(60, Remaining(origin, size) - GripOverlap()); float bodyH = Math.Max(60, Remaining(origin, size) - GripOverlap());
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg); ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
@ -212,7 +217,9 @@ internal sealed class SkillsFace : IImGuiPanel
ImGuiNET.ImGui.BeginChild("##skills_body", new Vector2(w, bodyH)); ImGuiNET.ImGui.BeginChild("##skills_body", new Vector2(w, bodyH));
float bw = ImGuiNET.ImGui.GetContentRegionAvail().X; float bw = ImGuiNET.ImGui.GetContentRegionAvail().X;
EnsureWidths(); EnsureWidths();
if (_snap == null || !_snap.SkillTableRead && !_snap.AttributeCacheRead) if (_tab == 2)
DrawProgression(bw);
else if (_snap == null || !_snap.SkillTableRead && !_snap.AttributeCacheRead)
Message("Waiting for your character's data...", bw); Message("Waiting for your character's data...", bw);
else if (_dat == null) else if (_dat == null)
Message("Loading skill names from the client's portal.dat: " + SkillDat.Status, bw); Message("Loading skill names from the client's portal.dat: " + SkillDat.Status, bw);
@ -228,6 +235,7 @@ internal sealed class SkillsFace : IImGuiPanel
_picker.Draw(); _picker.Draw();
DrawMulti(); DrawMulti();
DrawConfirm(); DrawConfirm();
DrawProgressionConfirm();
} }
// ── Data ──────────────────────────────────────────────────────────── // ── Data ────────────────────────────────────────────────────────────
@ -691,13 +699,18 @@ internal sealed class SkillsFace : IImGuiPanel
private void DrawTabs(float w) private void DrawTabs(float w)
{ {
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float half = (w - 4) * 0.5f; // The Progression tab only exists on ILT-like worlds (RynthAi's snapshot says so).
if (Button("##tab_skills", "Skills", p, new Vector2(half, 22), _tab == 0 ? Teal : Text, _tab == 0 ? Selected : BtnFill, int count = ProgressionTabVisible ? 3 : 2;
float tabW = (w - 4 * (count - 1)) / count;
if (Button("##tab_skills", "Skills", p, new Vector2(tabW, 22), _tab == 0 ? Teal : Text, _tab == 0 ? Selected : BtnFill,
border: _tab == 0 ? Teal : 0)) border: _tab == 0 ? Teal : 0))
_tab = 0; _tab = 0;
if (Button("##tab_attrs", "Attributes & Vitals", new Vector2(p.X + half + 4, p.Y), new Vector2(half, 22), if (Button("##tab_attrs", "Attributes & Vitals", new Vector2(p.X + tabW + 4, p.Y), new Vector2(tabW, 22),
_tab == 1 ? Teal : Text, _tab == 1 ? Selected : BtnFill, border: _tab == 1 ? Teal : 0)) _tab == 1 ? Teal : Text, _tab == 1 ? Selected : BtnFill, border: _tab == 1 ? Teal : 0))
_tab = 1; _tab = 1;
if (count == 3 && Button("##tab_prog", "Progression", new Vector2(p.X + 2 * (tabW + 4), p.Y), new Vector2(tabW, 22),
_tab == 2 ? Teal : Text, _tab == 2 ? Selected : BtnFill, border: _tab == 2 ? Teal : 0))
_tab = 2;
NextLine(p, 26); NextLine(p, 26);
} }

View file

@ -392,6 +392,14 @@ internal static unsafe class Win32Backend
RunOnGameThread<bool>(() => { action(); return true; }); RunOnGameThread<bool>(() => { action(); return true; });
} }
/// <summary>
/// True once the game window is known AND its WndProc is subclassed, i.e.
/// <see cref="RunOnGameThread{T}"/> can actually deliver work to AC's main
/// thread. Knowing the HWND alone is not enough: without the subclass,
/// WM_RYNTH_RUN_ACTION reaches AC's own WndProc, which ignores it.
/// </summary>
public static bool CanRunOnGameThread => _initialized && _gameHwnd != IntPtr.Zero;
/// <summary>Deactivates chat capture. The game HWND retains focus throughout so no /// <summary>Deactivates chat capture. The game HWND retains focus throughout so no
/// Win32 focus transfer is needed.</summary> /// Win32 focus transfer is needed.</summary>
public static void ReturnFocusToGame() => ChatCaptureActive = false; public static void ReturnFocusToGame() => ChatCaptureActive = false;
@ -572,10 +580,11 @@ internal static unsafe class Win32Backend
if (!_initialized) return; if (!_initialized) return;
// Destroy floating panels while our hook can still run on the game // Destroy floating panels while our hook can still run on the game
// thread. LayeredWindow.Dispose only POSTS its destroy, and the game // thread. LayeredWindow.Dispose posts its destroy to the panel itself
// thread usually hasn't reached that post by the time we unhook below — // (handled by the panel's own WndProc, which survives this unhook), but
// AC's own WndProc then drops it and the panel outlives this engine // any panel never disposed would outlive this engine load, frozen and
// load, frozen and unclickable (duplicate RynthAi dashboard after RL). // unclickable (duplicate RynthAi dashboard after RL) — this sweep is the
// synchronous backstop for those.
IntPtr swept = SendMessageTimeout(_gameHwnd, WM_RYNTH_SWEEP_PANELS, new IntPtr(1), IntPtr.Zero, IntPtr swept = SendMessageTimeout(_gameHwnd, WM_RYNTH_SWEEP_PANELS, new IntPtr(1), IntPtr.Zero,
SMTO_NORMAL, 2000, out _); SMTO_NORMAL, 2000, out _);
if (swept == IntPtr.Zero) if (swept == IntPtr.Zero)
@ -991,11 +1000,15 @@ internal static unsafe class Win32Backend
// HUD drag (keeps our SetCapture from fighting NewFrame's). No-op // HUD drag (keeps our SetCapture from fighting NewFrame's). No-op
// unless the HUD is drawn. // unless the HUD is drawn.
if (IsMouseMessage(msg)) if (IsMouseMessage(msg))
{
TrackMouseButtons(msg, wParam); TrackMouseButtons(msg, wParam);
ItemDragBridge.OnGameMouse(msg, wParam, lParam, _heldButtonsBelongToGame);
}
else if (msg == WM_KILLFOCUS) else if (msg == WM_KILLFOCUS)
{ {
_heldMouseButtons = 0; _heldMouseButtons = 0;
_heldButtonsBelongToGame = false; _heldButtonsBelongToGame = false;
ItemDragBridge.Reset();
} }
// ── Avalonia panel hit-test & input forwarding ──────────────── // ── Avalonia panel hit-test & input forwarding ────────────────
@ -1006,7 +1019,7 @@ internal static unsafe class Win32Backend
{ {
// fall through: AC gets the message // fall through: AC gets the message
} }
else if (IsMouseMessage(msg)) else if (IsMouseMessage(msg) && !ImGuiOwnsMouseOverAvalonia())
{ {
bool handled = TryForwardToAvalonia(msg, wParam, lParam); bool handled = TryForwardToAvalonia(msg, wParam, lParam);
if (handled) if (handled)
@ -1097,6 +1110,14 @@ internal static unsafe class Win32Backend
} }
} }
// An AC inventory item dragged onto an ImGui window: AC must not drop it on the
// ground behind the window. It gets the release where the drag began instead.
if (ItemDragBridge.TryRedirectNativeDrop(msg, out IntPtr pressLParam))
{
CallWindowProcA(_originalWndProc, hWnd, WM_MOUSEMOVE, (IntPtr)MK_LBUTTON, pressLParam);
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, pressLParam);
}
// Pass through to original WndProc // Pass through to original WndProc
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam); return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam);
} }
@ -1107,6 +1128,17 @@ internal static unsafe class Win32Backend
} }
} }
/// <summary>
/// ImGui windows are drawn on top of the Avalonia layer, so when the cursor is over
/// an ImGui window (or an ImGui widget is active) mouse input must go to ImGui
/// instead of the Avalonia panel underneath. An Avalonia drag/resize that is already
/// in progress keeps its capture so the release is never lost.
/// </summary>
private static bool ImGuiOwnsMouseOverAvalonia()
{
return _wantCaptureMouse && !AvaloniaOverlay.HasPointerCapture;
}
/// <summary> /// <summary>
/// If the cursor is over the Avalonia shell panel, PostMessage the mouse event to /// If the cursor is over the Avalonia shell panel, PostMessage the mouse event to
/// the off-screen Avalonia HWND and return true (caller should suppress game delivery). /// the off-screen Avalonia HWND and return true (caller should suppress game delivery).

View file

@ -21,6 +21,7 @@
using System; using System;
using System.IO; using System.IO;
using RynthCore.Install;
namespace RynthCore.Engine; namespace RynthCore.Engine;

View file

@ -0,0 +1,245 @@
using System;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine;
/// <summary>
/// Engine log categories. Each one has a configurable emit level (see <see cref="LogSettings"/>).
/// Names are the keys of engine.json "LogCategories" and must stay stable.
/// </summary>
internal enum LogCategory
{
/// <summary>Uncategorised RynthLog.Info lines.</summary>
General = 0,
/// <summary>D3D9: vtable, EndScene, bootstrapper, matrix capture, nav3D.</summary>
D3D9,
/// <summary>Compatibility hooks: client objects, combat, movement, vitals, chat, ...</summary>
Compat,
/// <summary>ImGui rendering: context, DX9 backend, Win32 input, shell.</summary>
Render,
/// <summary>Plugin system, including every line plugins write through the host Log API.</summary>
Plugin,
/// <summary>UI / Avalonia overlay.</summary>
UI,
/// <summary>Verbose detail lines (RynthLog.Verbose / RynthLog.Debug).</summary>
Verbose,
}
/// <summary>
/// Live engine logging configuration, read from %APPDATA%\RynthCore\engine.json:
/// <list type="bullet">
/// <item><c>"LoggingLevel"</c> — global threshold: Off, Error, Warning, Info, Debug, Trace.</item>
/// <item><c>"LogCategories"</c> — per-category emit level: <c>{ "Compat": "Info", "Verbose": "Debug", ... }</c>.
/// The emit level is the level a category's lines are written AT, so a line shows when
/// its emit level is within the global threshold. Setting a Trace/Debug category to
/// Info puts it in the normal (Info) log; Off silences the category entirely.</item>
/// </list>
/// A background thread polls the file's timestamp once a second, so launcher edits apply to a
/// running client without a restart. Errors are always written, even when the level is Off.
/// </summary>
internal static class LogSettings
{
/// <summary>engine.json property holding the per-category levels.</summary>
internal const string CategoriesProperty = "LogCategories";
private const int PollIntervalMs = 1000;
// Default emit level per LogCategory (index = enum value): categories at Info,
// Render off, verbose lines at Debug.
private static readonly EntryPoint.EngineLogLevel[] Defaults =
{
EntryPoint.EngineLogLevel.Info, // General
EntryPoint.EngineLogLevel.Info, // D3D9
EntryPoint.EngineLogLevel.Info, // Compat
EntryPoint.EngineLogLevel.Off, // Render
EntryPoint.EngineLogLevel.Info, // Plugin
EntryPoint.EngineLogLevel.Info, // UI
EntryPoint.EngineLogLevel.Debug, // Verbose
};
// Replaced wholesale on reload (never mutated after publish) so hot-path readers on any
// thread can index it without a lock.
private static EntryPoint.EngineLogLevel[] _levels = (EntryPoint.EngineLogLevel[])Defaults.Clone();
private static readonly object WatcherLock = new();
private static Thread? _watcherThread;
private static ManualResetEventSlim? _stopSignal;
private static DateTime _stampUtc = DateTime.MinValue;
private static string SettingsPath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "engine.json");
/// <summary>Current emit level for a category (cheap; safe on hot paths).</summary>
internal static EntryPoint.EngineLogLevel LevelFor(LogCategory category)
{
EntryPoint.EngineLogLevel[] levels = Volatile.Read(ref _levels);
int i = (int)category;
return (uint)i < (uint)levels.Length ? levels[i] : EntryPoint.EngineLogLevel.Info;
}
/// <summary>True when a line in this category would be written right now.</summary>
internal static bool IsEnabled(LogCategory category) => EntryPoint.ShouldLog(LevelFor(category));
/// <summary>3-char severity tag written into each log line.</summary>
internal static string Tag(EntryPoint.EngineLogLevel level) => level switch
{
EntryPoint.EngineLogLevel.Error => "ERR",
EntryPoint.EngineLogLevel.Warning => "WRN",
EntryPoint.EngineLogLevel.Debug => "DBG",
EntryPoint.EngineLogLevel.Trace => "TRC",
_ => "INF",
};
/// <summary>
/// Reads the global level and category levels from engine.json and publishes them.
/// Called once at init (before the first log line) and again by the watcher on change.
/// Missing or unreadable values fall back to their defaults. Returns a one-line summary.
/// </summary>
internal static string Reload()
{
string? globalText = null;
var levels = (EntryPoint.EngineLogLevel[])Defaults.Clone();
try
{
string path = SettingsPath;
if (File.Exists(path))
{
_stampUtc = File.GetLastWriteTimeUtc(path);
// ReadAllText strips a UTF-8/UTF-16 BOM that JsonDocument would choke on.
using var doc = JsonDocument.Parse(File.ReadAllText(path));
JsonElement root = doc.RootElement;
if (root.TryGetProperty("LoggingLevel", out JsonElement levelEl) && levelEl.ValueKind == JsonValueKind.String)
globalText = levelEl.GetString();
if (root.TryGetProperty(CategoriesProperty, out JsonElement catsEl) && catsEl.ValueKind == JsonValueKind.Object)
{
foreach (JsonProperty p in catsEl.EnumerateObject())
{
if (p.Value.ValueKind != JsonValueKind.String) continue;
if (!Enum.TryParse(p.Name, ignoreCase: true, out LogCategory cat) || !Enum.IsDefined(cat)) continue;
if (TryParseCategoryLevel(p.Value.GetString(), out EntryPoint.EngineLogLevel lvl))
levels[(int)cat] = lvl;
}
}
}
}
catch
{
// Half-written / corrupt file: keep defaults for this pass; the next timestamp change retries.
globalText ??= EngineSettings.LoggingLevel;
}
EntryPoint.LoggingLevel = EntryPoint.ParseLoggingLevel(globalText);
Volatile.Write(ref _levels, levels);
EntryPoint.VerboseLogging = IsEnabled(LogCategory.Verbose);
return Describe();
}
/// <summary>Human-readable "level=Info D3D9=Info Compat=Info ..." summary for the log.</summary>
internal static string Describe()
{
var sb = new StringBuilder();
sb.Append("level=").Append(EntryPoint.LoggingLevel);
EntryPoint.EngineLogLevel[] levels = Volatile.Read(ref _levels);
for (int i = 0; i < levels.Length; i++)
sb.Append(' ').Append((LogCategory)i).Append('=').Append(levels[i]);
return sb.ToString();
}
/// <summary>
/// Categories whose emit level is more verbose than the global level, so none of their lines
/// are written (e.g. every category at Trace with LoggingLevel Info: an almost empty log).
/// Empty when nothing is hidden.
/// </summary>
internal static string HiddenCategoriesWarning()
{
EntryPoint.EngineLogLevel global = EntryPoint.LoggingLevel;
EntryPoint.EngineLogLevel[] levels = Volatile.Read(ref _levels);
var hidden = new StringBuilder();
for (int i = 0; i < levels.Length; i++)
{
if (levels[i] == EntryPoint.EngineLogLevel.Off || levels[i] <= global) continue;
if (hidden.Length > 0) hidden.Append(", ");
hidden.Append((LogCategory)i).Append('=').Append(levels[i]);
}
return hidden.Length == 0 ? ""
: $"LogSettings: {hidden} write above the global LoggingLevel ({global}), so those lines are NOT logged. " +
"Raise LoggingLevel to the most verbose category level, or set the categories to Info.";
}
/// <summary>Starts the once-a-second engine.json poll. Idempotent.</summary>
internal static void StartWatcher()
{
lock (WatcherLock)
{
if (_watcherThread != null) return;
_stopSignal = new ManualResetEventSlim(false);
ManualResetEventSlim stop = _stopSignal;
_watcherThread = new Thread(() => WatchLoop(stop))
{
IsBackground = true,
Name = "RynthCore.LogSettingsWatcher",
};
_watcherThread.Start();
}
}
/// <summary>
/// Stops and joins the poll thread. Called from EngineLifecycle.Shutdown so the thread never
/// runs inside an old engine generation after a hot reload.
/// </summary>
internal static void StopWatcher()
{
Thread? thread;
lock (WatcherLock)
{
thread = _watcherThread;
_stopSignal?.Set();
_watcherThread = null;
}
thread?.Join(2000);
}
private static void WatchLoop(ManualResetEventSlim stop)
{
while (!stop.Wait(PollIntervalMs))
{
try
{
string path = SettingsPath;
if (!File.Exists(path) || File.GetLastWriteTimeUtc(path) == _stampUtc)
continue;
string summary = Reload();
// Bypasses the category levels so a change is visible whenever Info is in range.
if (EntryPoint.ShouldLog(EntryPoint.EngineLogLevel.Info))
EntryPoint.LogTagged("engine", $"LogSettings: engine.json changed - logging reloaded ({summary}).", "INF");
string hidden = HiddenCategoriesWarning();
if (hidden.Length > 0) RynthLog.Warn(hidden);
}
catch
{
// Logging configuration must never take the client down; retry next poll.
}
}
}
/// <summary>
/// Parses a category emit level: Off, Trace, Debug (or Verbose), Info, Warning (or Warn), Error.
/// </summary>
private static bool TryParseCategoryLevel(string? text, out EntryPoint.EngineLogLevel level)
{
level = EntryPoint.EngineLogLevel.Info;
if (string.IsNullOrWhiteSpace(text)) return false;
string t = text.Trim();
if (t.Equals("Verbose", StringComparison.OrdinalIgnoreCase)) { level = EntryPoint.EngineLogLevel.Debug; return true; }
if (t.Equals("Warn", StringComparison.OrdinalIgnoreCase)) { level = EntryPoint.EngineLogLevel.Warning; return true; }
return Enum.TryParse(t, ignoreCase: true, out level) && Enum.IsDefined(level);
}
}

View file

@ -28,9 +28,11 @@ internal static class EngineSettings
private static bool _enableEngine = true; private static bool _enableEngine = true;
private static int _engineHookCount = int.MaxValue; private static int _engineHookCount = int.MaxValue;
private static bool _enableImGuiBackend = true; private static bool _enableImGuiBackend = true;
private static bool _enablePluginOverlayWindows = true;
private static bool _enableHangMinidump = true; private static bool _enableHangMinidump = true;
private static bool _preventIdleLogoff = true; private static bool _preventIdleLogoff = true;
private static bool _closeOnServerDisconnect = true; private static bool _closeOnServerDisconnect = true;
private static string _loggingLevel = "Info";
private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto; private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto;
private static bool _decalInGameImGui = true; private static bool _decalInGameImGui = true;
private static bool _decalStandDown = true; private static bool _decalStandDown = true;
@ -205,6 +207,19 @@ internal static class EngineSettings
} }
} }
/// <summary>When true (default) and the ImGui shell is off, plugins that export
/// RynthPluginRenderOverlay draw their extra ImGui windows (RynthAi: ILT Hub, Item Info)
/// beside the Avalonia UI. engine.json "EnablePluginOverlayWindows": false hides them.
/// Needs <see cref="EnableImGuiBackend"/>.</summary>
public static bool EnablePluginOverlayWindows
{
get
{
EnsureLoaded();
return _enablePluginOverlayWindows;
}
}
/// <summary>When true, MainThreadHangWatchdog writes a minidump to /// <summary>When true, MainThreadHangWatchdog writes a minidump to
/// Logs\dumps\ the first time AC's main thread is confirmed permanently /// Logs\dumps\ the first time AC's main thread is confirmed permanently
/// wedged — a targeted post-mortem to replace always-on procdump (which /// wedged — a targeted post-mortem to replace always-on procdump (which
@ -253,6 +268,18 @@ internal static class EngineSettings
} }
} }
/// <summary>Engine log threshold from engine.json "LoggingLevel", written by the launcher's
/// Logging level box: Error, Warning, Info (default), Debug/Verbose or Trace. Parsed by
/// EntryPoint.ParseLoggingLevel at init; unknown values fall back to Info.</summary>
public static string LoggingLevel
{
get
{
EnsureLoaded();
return _loggingLevel;
}
}
/// <summary>"DecalBridge" in engine.json: Auto (default), On or Off. Only matters when /// <summary>"DecalBridge" in engine.json: Auto (default), On or Off. Only matters when
/// Decal is loaded in the same client (docs/DECAL_BRIDGE_PLAN.md): /// Decal is loaded in the same client (docs/DECAL_BRIDGE_PLAN.md):
/// Auto - bridge mode when the RynthCore Decal bridge is registered and says hello /// Auto - bridge mode when the RynthCore Decal bridge is registered and says hello
@ -522,6 +549,12 @@ internal static class EngineSettings
_enableImGuiBackend = ibEl.GetBoolean(); _enableImGuiBackend = ibEl.GetBoolean();
} }
if (doc.RootElement.TryGetProperty("EnablePluginOverlayWindows", out var powEl) &&
(powEl.ValueKind == JsonValueKind.True || powEl.ValueKind == JsonValueKind.False))
{
_enablePluginOverlayWindows = powEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableHangMinidump", out var hmEl) && if (doc.RootElement.TryGetProperty("EnableHangMinidump", out var hmEl) &&
(hmEl.ValueKind == JsonValueKind.True || hmEl.ValueKind == JsonValueKind.False)) (hmEl.ValueKind == JsonValueKind.True || hmEl.ValueKind == JsonValueKind.False))
{ {
@ -595,6 +628,14 @@ internal static class EngineSettings
_disabledUiHooks.Add(hookName.Trim()); _disabledUiHooks.Add(hookName.Trim());
} }
} }
if (doc.RootElement.TryGetProperty("LoggingLevel", out var logLevelEl) &&
logLevelEl.ValueKind == JsonValueKind.String)
{
string? configuredLevel = logLevelEl.GetString();
if (!string.IsNullOrWhiteSpace(configuredLevel))
_loggingLevel = configuredLevel;
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -627,7 +668,7 @@ internal static class EngineSettings
"EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge", "EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge",
"DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream", "DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream",
"FlightRecorder", "InsertReleasesUi", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix", "FlightRecorder", "InsertReleasesUi", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix",
"MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", "MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", "EnablePluginOverlayWindows", "LoggingLevel",
}; };
private static void Save() private static void Save()
@ -653,8 +694,11 @@ internal static class EngineSettings
w.WriteBoolean("EnableEngine", _enableEngine); w.WriteBoolean("EnableEngine", _enableEngine);
w.WriteNumber("EngineHookCount", _engineHookCount); w.WriteNumber("EngineHookCount", _engineHookCount);
w.WriteBoolean("EnableImGuiBackend", _enableImGuiBackend); w.WriteBoolean("EnableImGuiBackend", _enableImGuiBackend);
w.WriteBoolean("EnablePluginOverlayWindows", _enablePluginOverlayWindows);
w.WriteBoolean("EnableHangMinidump", _enableHangMinidump); w.WriteBoolean("EnableHangMinidump", _enableHangMinidump);
w.WriteBoolean("PreventIdleLogoff", _preventIdleLogoff); w.WriteBoolean("PreventIdleLogoff", _preventIdleLogoff);
// Preserve the launcher-chosen level; dropping it here would reset logging to Info.
w.WriteString("LoggingLevel", _loggingLevel);
if (_decalBridgeMode != DecalBridgeMode.Auto) // default: leave the file as it was if (_decalBridgeMode != DecalBridgeMode.Auto) // default: leave the file as it was
w.WriteString("DecalBridge", _decalBridgeMode.ToString()); w.WriteString("DecalBridge", _decalBridgeMode.ToString());
if (!_decalInGameImGui) // default true: leave the file as it was if (!_decalInGameImGui) // default true: leave the file as it was

View file

@ -54,6 +54,18 @@ internal sealed class LoadedPlugin
public PluginOnEnchantmentRemovedDelegate? OnEnchantmentRemoved { get; set; } public PluginOnEnchantmentRemovedDelegate? OnEnchantmentRemoved { get; set; }
public PluginTickDelegate? Tick { get; set; } public PluginTickDelegate? Tick { get; set; }
public PluginRenderDelegate? Render { get; set; } public PluginRenderDelegate? Render { get; set; }
/// <summary>Optional RynthPluginRenderOverlay: ImGui windows drawn while the ImGui shell is off.</summary>
public PluginRenderDelegate? RenderOverlay { get; set; }
/// <summary>Set after the first RenderOverlay call has been logged (render thread only).</summary>
public bool RenderOverlayLogged { get; set; }
/// <summary>
/// Optional <c>int RynthPluginRenderEmbed(const char* surface, float width, float height,
/// float* wantWidth, float* wantHeight)</c>, Cdecl: the plugin draws a named surface into the
/// engine's current ImGui window (PluginManager.RenderEmbed). Zeroed after it throws.
/// </summary>
public IntPtr RenderEmbedPtr { get; set; }
// ─── v77 UI exports (resolved lazily by PluginManager.ResolveUiExports) ─── // ─── v77 UI exports (resolved lazily by PluginManager.ResolveUiExports) ───
public bool UiExportsResolved { get; set; } public bool UiExportsResolved { get; set; }
@ -85,4 +97,45 @@ internal sealed class LoadedPlugin
public RynthCore.PluginSdk.Manifest.RynthPluginManifest? Manifest { get; set; } public RynthCore.PluginSdk.Manifest.RynthPluginManifest? Manifest { get; set; }
/// <summary>Why the plugin was not started (a required plugin missing or failed); empty otherwise.</summary> /// <summary>Why the plugin was not started (a required plugin missing or failed); empty otherwise.</summary>
public string NotStartedReason { get; set; } = ""; public string NotStartedReason { get; set; } = "";
/// <summary>
/// Drops managed delegates wrapping exports so the native module can fully unload after
/// the host calls FreeLibrary (hot-reload / rescan).
/// </summary>
internal void ClearResolvedDelegates()
{
Init = null;
Shutdown = null;
GetName = null;
GetVersion = null;
OnLoginComplete = null;
OnUIInitialized = null;
OnBusyCountIncremented = null;
OnBusyCountDecremented = null;
OnSelectedTargetChange = null;
OnCombatModeChange = null;
OnSmartBoxEventPtr = IntPtr.Zero;
OnSmartBoxEvent = null;
OnDeleteObject = null;
OnCreateObject = null;
OnUpdateObjectPtr = IntPtr.Zero;
OnUpdateObject = null;
OnUpdateObjectInventory = null;
OnViewObjectContents = null;
OnStopViewingObjectContents = null;
OnVendorOpen = null;
OnVendorClose = null;
OnUpdateHealthPtr = IntPtr.Zero;
OnUpdateHealth = null;
OnChatWindowTextPtr = IntPtr.Zero;
OnChatWindowText = null;
OnChatBarEnter = null;
OnBarAction = null;
OnEnchantmentAdded = null;
OnEnchantmentRemoved = null;
Tick = null;
Render = null;
RenderOverlay = null;
RenderEmbedPtr = IntPtr.Zero;
}
} }

View file

@ -10,7 +10,18 @@
// const char* RynthPluginName() — human-readable name // const char* RynthPluginName() — human-readable name
// const char* RynthPluginVersion() — version string (e.g. "1.0.0") // const char* RynthPluginVersion() — version string (e.g. "1.0.0")
// void RynthPluginTick() — per-frame logic (before render) // void RynthPluginTick() — per-frame logic (before render)
// void RynthPluginRender() — per-frame ImGui drawing // void RynthPluginRender() — per-frame ImGui drawing (ImGui shell on)
// void RynthPluginRenderOverlay() — per-frame ImGui drawing while the ImGui shell is
// off (Avalonia mode): only windows that have no
// Avalonia panel. Gated by engine.json
// "EnablePluginOverlayWindows" (default true).
// int RynthPluginRenderEmbed(const char* surface, float width, float height,
// float* wantWidth, float* wantHeight)
// — draws a named surface (UTF-8, e.g. RynthAi's
// "miniremote") into the engine's current ImGui
// window on AC's render thread, inside a
// width x height child; reports the size it wants.
// 1 = drawn, 0 = not ready / unknown surface.
// void RynthPluginOnServerMessage(uint opcode, byte* data, int length) // void RynthPluginOnServerMessage(uint opcode, byte* data, int length)
// — v78, reassembled server messages the plugin // — v78, reassembled server messages the plugin
// asked for with SetServerMessageInterestFn // asked for with SetServerMessageInterestFn
@ -864,6 +875,15 @@ internal struct RynthCoreAPI
/// Returns 1 sent or queued, 0 refused before sending (bad ids, negative placement), -1 the /// Returns 1 sent or queued, 0 refused before sending (bad ids, negative placement), -1 the
/// sender isn't bound on this client. Requires API v80+.</summary> /// sender isn't bound on this client. Requires API v80+.</summary>
public IntPtr PutItemInContainerFn; public IntPtr PutItemInContainerFn;
/// <summary>v81: <c>int GetMergeStackResult(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs)</c>:
/// outcome of the latest MergeStackInternal(source, target) request: 0 none, 1 queued,
/// 2 sent (amount = units sent), 3 skipped because the target was already full,
/// 4 failed (invalid ids / AC rejected / threw), 5 dropped (main-thread queue full).
/// ageMs = how long ago the outcome was recorded. Either out pointer may be null.
/// The thunk is cdecl. Any thread. Requires API v81+ (it was v77 on QOL-items and v80 on sk
/// before upstream's v77-v80 landed; plugins built against those SDKs must be rebuilt).</summary>
public IntPtr GetMergeStackResultFn;
} }
/// <summary>v79 <see cref="TrainingInfoNative.Flags"/> bits.</summary> /// <summary>v79 <see cref="TrainingInfoNative.Flags"/> bits.</summary>
@ -1654,6 +1674,10 @@ internal unsafe delegate uint VendorSellCallbackDelegate(uint vendorId, uint* it
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetVendorTradeStatusCallbackDelegate(VendorTradeStatusNative* status); internal unsafe delegate int GetVendorTradeStatusCallbackDelegate(VendorTradeStatusNative* status);
// Cdecl is mandatory on every API delegate: without it x86 marshals a stdcall thunk, the callee and
// the cdecl caller both pop the args, and the plugin's stack drifts on every call.
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetMergeStackResultCallbackDelegate(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetVTankStateCallbackDelegate(int* sequence); internal unsafe delegate int GetVTankStateCallbackDelegate(int* sequence);

View file

@ -15,5 +15,6 @@ namespace RynthCore.Engine.Plugins;
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI (and the SDK's RynthCoreApiNative).</summary> /// <summary>Current API version. Bump when adding fields to RynthCoreAPI (and the SDK's RynthCoreApiNative).</summary>
internal static class PluginContractVersion internal static class PluginContractVersion
{ {
public const uint Current = 80; // v81: GetMergeStackResult (was v77 on QOL-items, then v80; renumbered after upstream's v77-v80).
public const uint Current = 81;
} }

View file

@ -89,6 +89,9 @@ internal static class PluginLoader
/// </summary> /// </summary>
public static void Unload(LoadedPlugin plugin) public static void Unload(LoadedPlugin plugin)
{ {
// Release managed thunks first so the module ref-count can drop to zero on FreeLibrary.
plugin.ClearResolvedDelegates();
if (ManagedPlugins.IsManagedHandle(plugin.ModuleHandle)) if (ManagedPlugins.IsManagedHandle(plugin.ModuleHandle))
{ {
ManagedPlugins.Unload(plugin.ModuleHandle); // a managed plugin really goes away ManagedPlugins.Unload(plugin.ModuleHandle); // a managed plugin really goes away
@ -506,6 +509,13 @@ internal static class PluginLoader
if (renderPtr != IntPtr.Zero) if (renderPtr != IntPtr.Zero)
plugin.Render = Marshal.GetDelegateForFunctionPointer<PluginRenderDelegate>(renderPtr); plugin.Render = Marshal.GetDelegateForFunctionPointer<PluginRenderDelegate>(renderPtr);
IntPtr renderOverlayPtr = GetProcAddress(handle, "RynthPluginRenderOverlay");
if (renderOverlayPtr != IntPtr.Zero)
plugin.RenderOverlay = Marshal.GetDelegateForFunctionPointer<PluginRenderDelegate>(renderOverlayPtr);
// Called through a function pointer (PluginManager.RenderEmbed), so no delegate here.
plugin.RenderEmbedPtr = GetProcAddress(handle, "RynthPluginRenderEmbed");
// Read name/version from the plugin if available // Read name/version from the plugin if available
if (plugin.GetName != null) if (plugin.GetName != null)
{ {

View file

@ -271,6 +271,7 @@ internal static partial class PluginManager
private static VendorBuyCallbackDelegate? _vendorBuyCallback; private static VendorBuyCallbackDelegate? _vendorBuyCallback;
private static VendorSellCallbackDelegate? _vendorSellCallback; private static VendorSellCallbackDelegate? _vendorSellCallback;
private static GetVendorTradeStatusCallbackDelegate? _getVendorTradeStatusCallback; private static GetVendorTradeStatusCallbackDelegate? _getVendorTradeStatusCallback;
private static GetMergeStackResultCallbackDelegate? _getMergeStackResultCallback;
private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback; private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback;
private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback; private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback;
private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback; private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback;
@ -1142,6 +1143,154 @@ internal static partial class PluginManager
} }
} }
/// <summary>
/// ImGui-shell-off counterpart of <see cref="RenderAll"/>: calls the optional
/// RynthPluginRenderOverlay export, where a plugin draws only the extra windows that have
/// no Avalonia panel (e.g. RynthAi's ILT Hub). They float beside the Avalonia UI and add to it.
/// A throw switches off just that plugin's overlay windows; the plugin is NOT marked Failed,
/// so its tick/automation and Avalonia panels keep running.
/// </summary>
public static void RenderOverlayAll()
{
_overlayCalls++;
if (!_loginCompleteObserved)
{
if (!_loggedOverlayWaitingForLogin)
{
_loggedOverlayWaitingForLogin = true;
RynthLog.Info("PluginManager: RenderOverlayAll called - waiting for login before drawing overlay windows.");
}
return; // same not-in-world crash zone guard as RenderAll
}
LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot);
// Count plugins that will actually be called; log whenever that set changes.
int bound = 0;
for (int i = 0; i < plugins.Length; i++)
{
var p = plugins[i];
if (p.Initialized && !p.Failed && p.RenderOverlay != null) bound++;
}
_overlayBound = bound;
if (bound != _loggedOverlayBound || plugins.Length != _loggedOverlayTotal)
{
_loggedOverlayBound = bound;
_loggedOverlayTotal = plugins.Length;
var sb = new System.Text.StringBuilder();
for (int i = 0; i < plugins.Length; i++)
{
var p = plugins[i];
if (sb.Length > 0) sb.Append(", ");
sb.Append(p.DisplayName).Append('(')
.Append(p.RenderOverlay != null ? "overlay" : "no-overlay")
.Append(p.Initialized ? "" : ",not-init")
.Append(p.Failed ? ",failed" : "")
.Append(')');
}
RynthLog.Info($"PluginManager: RenderOverlayAll login seen, {bound} of {plugins.Length} plugin(s) will draw overlay windows: {sb}.");
}
for (int i = 0; i < plugins.Length; i++)
{
var plugin = plugins[i];
var overlay = plugin.RenderOverlay;
if (!plugin.Initialized || plugin.Failed || overlay == null)
continue;
if (!plugin.RenderOverlayLogged)
{
// One line per plugin per session: proves the engine is actually driving the overlay export.
plugin.RenderOverlayLogged = true;
RynthLog.Plugin($"PluginManager: first RenderOverlay call for {plugin.DisplayName}.");
}
try
{
overlay();
}
catch (Exception ex)
{
plugin.RenderOverlay = null;
RynthLog.Error($"PluginManager: {plugin.DisplayName} RenderOverlay threw {ex.GetType().Name}: {ex.Message} - overlay windows off for this session (plugin keeps running).");
}
}
}
// RenderOverlayAll diagnostics (render thread only).
private static long _overlayCalls;
private static int _overlayBound;
private static bool _loggedOverlayWaitingForLogin;
private static int _loggedOverlayBound = -1;
private static int _loggedOverlayTotal = -1;
/// <summary>
/// True when an initialized, healthy plugin exports RynthPluginRenderOverlay. Reads the
/// render snapshot only (no lock, no allocation): safe every frame on the render thread.
/// </summary>
internal static bool HasOverlayPlugins
{
get
{
LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot);
for (int i = 0; i < plugins.Length; i++)
{
var p = plugins[i];
if (p.Initialized && !p.Failed && p.RenderOverlay != null) return true;
}
return false;
}
}
/// <summary>Overlay stats for the ImGui heartbeat line.</summary>
internal static string DescribeOverlayState()
=> $"overlayCalls={_overlayCalls} loginSeen={_loginCompleteObserved} overlayPlugins={_overlayBound}";
/// <summary>RenderEmbed results.</summary>
internal const int EmbedDrawn = 1, EmbedNotReady = 0, EmbedNoPlugin = -1, EmbedFailed = -2;
/// <summary>
/// Lets the plugin named <paramref name="pluginName"/> (display name contains it) draw the
/// surface <paramref name="surfaceUtf8"/> (NUL-terminated) into the current ImGui window,
/// through its optional RynthPluginRenderEmbed export. The caller has begun a child of
/// <paramref name="size"/> in the main ImGui context; the plugin draws only inside it and
/// reports the content size it wants in <paramref name="want"/> (zero when it didn't say).
/// Render thread only. Returns <see cref="EmbedDrawn"/>, <see cref="EmbedNotReady"/> (the
/// plugin isn't ready: before login, no ImGui context), <see cref="EmbedNoPlugin"/> (not
/// loaded, or too old to have the export) or <see cref="EmbedFailed"/> (it threw: the export
/// is switched off for this session; the plugin keeps running).
/// </summary>
internal static unsafe int RenderEmbed(string pluginName, ReadOnlySpan<byte> surfaceUtf8, System.Numerics.Vector2 size, out System.Numerics.Vector2 want)
{
want = System.Numerics.Vector2.Zero;
if (!_loginCompleteObserved) return EmbedNotReady; // same not-in-world guard as RenderAll
LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot);
for (int i = 0; i < plugins.Length; i++)
{
LoadedPlugin p = plugins[i];
if (!p.Initialized || p.Failed || !p.DisplayName.Contains(pluginName, StringComparison.OrdinalIgnoreCase))
continue;
IntPtr fn = p.RenderEmbedPtr;
if (fn == IntPtr.Zero) return EmbedNoPlugin;
float w = 0, h = 0;
try
{
int r;
fixed (byte* s = surfaceUtf8)
r = ((delegate* unmanaged[Cdecl]<byte*, float, float, float*, float*, int>)fn)(s, size.X, size.Y, &w, &h);
want = new System.Numerics.Vector2(float.IsFinite(w) ? MathF.Max(0, w) : 0, float.IsFinite(h) ? MathF.Max(0, h) : 0);
return r == 1 ? EmbedDrawn : EmbedNotReady;
}
catch (Exception ex)
{
p.RenderEmbedPtr = IntPtr.Zero;
RynthLog.Error($"PluginManager: {p.DisplayName} RenderEmbed threw {ex.GetType().Name}: {ex.Message} - embedded surfaces off for this session (plugin keeps running).");
return EmbedFailed;
}
}
return EmbedNoPlugin;
}
public static void ShutdownAll() public static void ShutdownAll()
{ {
RynthLog.Plugin($"PluginManager: Shutting down {_plugins.Count} plugin(s)..."); RynthLog.Plugin($"PluginManager: Shutting down {_plugins.Count} plugin(s)...");
@ -2338,6 +2487,14 @@ internal static partial class PluginManager
// %APPDATA%\RynthCore\engine.json. The engine never auto-scans a // %APPDATA%\RynthCore\engine.json. The engine never auto-scans a
// bundled Plugins\ folder — that historically caused stray DLLs to // bundled Plugins\ folder — that historically caused stray DLLs to
// load on next start (or after hot-reload) without the user knowing. // load on next start (or after hot-reload) without the user knowing.
//
// Track DLL file names and canonical paths already staged this generation. engine.json can
// list the same plugin twice (e.g. a stale copy in another folder); a second File.Copy to the
// same shadow file name fails while the first copy is still mapped ("used by another process")
// and breaks hot-reload ordering for later DLLs.
var loadedBasenames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var loadedCanonicalPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var extraPaths = EngineSettings.PluginPaths; var extraPaths = EngineSettings.PluginPaths;
var present = new List<string>(extraPaths.Count); var present = new List<string>(extraPaths.Count);
for (int i = 0; i < extraPaths.Count; i++) for (int i = 0; i < extraPaths.Count; i++)
@ -2398,7 +2555,29 @@ internal static partial class PluginManager
} }
} }
// RenderAll / RenderOverlayAll iterate only this snapshot; without it they see no plugins.
PublishPluginsRenderSnapshot(); PublishPluginsRenderSnapshot();
RynthLog.Plugin($"PluginManager: render snapshot published ({_plugins.Count} plugin(s)).");
}
private static void TryAddCanonicalPath(HashSet<string> set, string path)
{
if (TryGetCanonicalPath(path, out string canon))
set.Add(canon);
}
private static bool TryGetCanonicalPath(string path, out string canonical)
{
try
{
canonical = Path.GetFullPath(path);
return true;
}
catch
{
canonical = string.Empty;
return false;
}
} }
// ── Plugin manifests ───────────────────────────────────────────────── // ── Plugin manifests ─────────────────────────────────────────────────
@ -2796,6 +2975,7 @@ internal static partial class PluginManager
_vendorBuyCallback ??= VendorBuyAction; _vendorBuyCallback ??= VendorBuyAction;
_vendorSellCallback ??= VendorSellAction; _vendorSellCallback ??= VendorSellAction;
_getVendorTradeStatusCallback ??= GetVendorTradeStatusAction; _getVendorTradeStatusCallback ??= GetVendorTradeStatusAction;
_getMergeStackResultCallback ??= GetMergeStackResultAction;
_api.Version = PluginContractVersion.Current; _api.Version = PluginContractVersion.Current;
_api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback); _api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback);
@ -2941,6 +3121,7 @@ internal static partial class PluginManager
_api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback); _api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback);
_api.VendorSellFn = Marshal.GetFunctionPointerForDelegate(_vendorSellCallback); _api.VendorSellFn = Marshal.GetFunctionPointerForDelegate(_vendorSellCallback);
_api.GetVendorTradeStatusFn = Marshal.GetFunctionPointerForDelegate(_getVendorTradeStatusCallback); _api.GetVendorTradeStatusFn = Marshal.GetFunctionPointerForDelegate(_getVendorTradeStatusCallback);
_api.GetMergeStackResultFn = Marshal.GetFunctionPointerForDelegate(_getMergeStackResultCallback);
RouteApiThroughLoader(); RouteApiThroughLoader();
} }
@ -3665,6 +3846,22 @@ internal static partial class PluginManager
return ToAbiBool(ClientHelperHooks.MergeStackInternal(sourceObjectId, targetObjectId)); return ToAbiBool(ClientHelperHooks.MergeStackInternal(sourceObjectId, targetObjectId));
} }
// v68: outcome of the latest MergeStackInternal(source, target) (MergeStackResults codes).
private static unsafe int GetMergeStackResultAction(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs)
{
try
{
int status = MergeStackResults.Get(sourceObjectId, targetObjectId, out int sent, out int age);
if (amount != null) *amount = sent;
if (ageMs != null) *ageMs = age;
return status;
}
catch
{
return MergeStackResults.None;
}
}
private static int GiveObjectTo(uint objectId, uint targetId, int amount) private static int GiveObjectTo(uint objectId, uint targetId, int amount)
{ {
Compatibility.AcActionTrace.Record("GiveObjectTo", objectId, targetId); Compatibility.AcActionTrace.Record("GiveObjectTo", objectId, targetId);

View file

@ -6,6 +6,9 @@
<RuntimeIdentifier>win-x86</RuntimeIdentifier> <RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<!-- Unreachable code (CS0162) is always a bug here: a misplaced statement after a return
once left the plugin render snapshot unpublished and silently disabled every overlay window. -->
<WarningsAsErrors>$(WarningsAsErrors);CS0162</WarningsAsErrors>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<PublishAot>true</PublishAot> <PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib> <NativeLib>Shared</NativeLib>
@ -66,9 +69,9 @@
<PackageReference Include="Avalonia.Desktop" Version="11.2.3" /> <PackageReference Include="Avalonia.Desktop" Version="11.2.3" />
<PackageReference Include="Avalonia.Skia" Version="11.2.3" /> <PackageReference Include="Avalonia.Skia" Version="11.2.3" />
<PackageReference Include="Avalonia.Themes.Simple" Version="11.2.3" /> <PackageReference Include="Avalonia.Themes.Simple" Version="11.2.3" />
<PackageReference Include="Avalonia.AvaloniaEdit" Version="11.2.0" /> <!-- Overrides Avalonia.FreeDesktop transitive Tmds.DBus.Protocol (NU1903 / GHSA-xrw6-gwf8-vvr9). -->
<!-- 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" /> <PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" />
<PackageReference Include="Avalonia.AvaloniaEdit" Version="11.2.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View file

@ -4,73 +4,67 @@ namespace RynthCore.Engine;
/// <summary> /// <summary>
/// Centralised logging — every log call in the Engine routes through here. /// Centralised logging — every log call in the Engine routes through here.
/// Toggle categories on/off at runtime to suppress entire subsystems. /// Each category method writes at that category's emit level (engine.json "LogCategories",
/// Messages keep their existing prefix text (e.g. "D3D9VTable: scanning…"). /// editable live from the launcher; see <see cref="LogSettings"/>), gated by the global
/// "LoggingLevel". Messages keep their existing prefix text (e.g. "D3D9VTable: scanning…").
/// </summary> /// </summary>
internal static class RynthLog internal static class RynthLog
{ {
// ── Category toggles (flip to false to silence a subsystem) ──────────
internal static bool D3D9Enabled = true;
internal static bool CompatEnabled = true;
internal static bool RenderEnabled = false; // ImGui, DX9Backend, Win32Backend
internal static bool PluginEnabled = true;
internal static bool UIEnabled = true;
// ── Category methods ───────────────────────────────────────────────── // ── Category methods ─────────────────────────────────────────────────
/// <summary>D3D9 subsystem: vtable, EndScene, bootstrapper, matrix capture, nav3D.</summary> /// <summary>D3D9 subsystem: vtable, EndScene, bootstrapper, matrix capture, nav3D.</summary>
internal static void D3D9(string msg) internal static void D3D9(string msg) => WriteCategory(LogCategory.D3D9, msg);
{
if (D3D9Enabled) Write(msg);
}
/// <summary>Compatibility hooks: SmartBox, client objects, combat, movement, vitals, chat, etc.</summary> /// <summary>Compatibility hooks: SmartBox, client objects, combat, movement, vitals, chat, etc.</summary>
internal static void Compat(string msg) internal static void Compat(string msg) => WriteCategory(LogCategory.Compat, msg);
{
if (CompatEnabled) Write(msg);
}
/// <summary>ImGui rendering: context, DX9 backend, Win32 input, shell.</summary> /// <summary>ImGui rendering: context, DX9 backend, Win32 input, shell.</summary>
internal static void Render(string msg) internal static void Render(string msg) => WriteCategory(LogCategory.Render, msg);
{
if (RenderEnabled) Write(msg);
}
/// <summary>Plugin system: loader, manager, lifecycle callbacks.</summary> /// <summary>Plugin system: loader, manager, lifecycle callbacks, plugin host Log lines.</summary>
internal static void Plugin(string msg) internal static void Plugin(string msg) => WriteCategory(LogCategory.Plugin, msg);
{
if (PluginEnabled) Write(msg);
}
/// <summary>UI / Avalonia overlay subsystem.</summary> /// <summary>UI / Avalonia overlay subsystem.</summary>
internal static void UI(string msg) internal static void UI(string msg) => WriteCategory(LogCategory.UI, msg);
{
if (UIEnabled) Write(msg);
}
/// <summary>Verbose-only log (any category). Only written when VerboseLogging is on.</summary> /// <summary>Verbose detail (any subsystem). Debug by default; set the Verbose category to Info to see it in the normal log.</summary>
internal static void Verbose(string msg) internal static void Verbose(string msg) => WriteCategory(LogCategory.Verbose, msg);
{
if (EntryPoint.VerboseLogging) Write(msg);
}
/// <summary>Always-on log for critical / uncategorised messages (INFO).</summary> /// <summary>Same as <see cref="Verbose"/>.</summary>
internal static void Info(string msg) => Write(msg); internal static void Debug(string msg) => WriteCategory(LogCategory.Verbose, msg);
/// <summary>Trace-level line: written only when the global level is Trace.</summary>
internal static void Trace(string msg) => WriteAt(EntryPoint.EngineLogLevel.Trace, msg);
/// <summary>Uncategorised line (General category, Info by default).</summary>
internal static void Info(string msg) => WriteCategory(LogCategory.General, msg);
/// <summary>Same as <see cref="Warn"/>.</summary>
internal static void Warning(string msg) => Warn(msg);
// Most recent WRN/ERR text + when, surfaced via the GetEngineStatusJson host bridge so a stuck box // Most recent WRN/ERR text + when, surfaced via the GetEngineStatusJson host bridge so a stuck box
// can be diagnosed remotely without reading the PC log. // can be diagnosed remotely without reading the PC log. Recorded even when the line is filtered.
internal static volatile string? LastIssue; internal static volatile string? LastIssue;
internal static DateTime LastIssueUtc; internal static DateTime LastIssueUtc;
/// <summary>Always-on WARN line — a recoverable problem worth grepping for.</summary> /// <summary>WARN line — a recoverable problem worth grepping for. Hidden only at level Error/Off.</summary>
internal static void Warn(string msg) internal static void Warn(string msg)
{ {
LastIssue = msg; LastIssueUtc = DateTime.UtcNow; LastIssue = msg; LastIssueUtc = DateTime.UtcNow;
EntryPoint.LogTagged("engine", msg, "WRN"); if (EntryPoint.ShouldLog(EntryPoint.EngineLogLevel.Warning))
EntryPoint.LogTagged("engine", msg, "WRN");
} }
/// <summary>Always-on ERROR line — a fault/crash/disable. Triage with grep "[ERR]".</summary> /// <summary>
/// Always-on heartbeat line, written at every LoggingLevel (Off included). The launcher's
/// wedge watchdog reads RynthCore.&lt;pid&gt;.log going quiet for 120 s as a dead engine and
/// kills the client, so this line must never be filtered: on 2026-10-06 LoggingLevel=Info
/// with General=Trace dropped it and healthy in-world clients were killed and relaunched
/// every few minutes.
/// </summary>
internal static void Heartbeat(string msg) => EntryPoint.LogTagged("engine", msg, "INF");
/// <summary>Always-on ERROR line — a fault/crash/disable, written even at level Off. Triage with grep "[ERR]".</summary>
internal static void Error(string msg) internal static void Error(string msg)
{ {
LastIssue = msg; LastIssueUtc = DateTime.UtcNow; LastIssue = msg; LastIssueUtc = DateTime.UtcNow;
@ -154,7 +148,24 @@ internal static class RynthLog
: $"thread {Environment.CurrentManagedThreadId}"; : $"thread {Environment.CurrentManagedThreadId}";
} }
/// <summary>True when a line in <paramref name="category"/> would be written (guard expensive messages).</summary>
internal static bool IsEnabled(LogCategory category) => LogSettings.IsEnabled(category);
// ── Sink ───────────────────────────────────────────────────────────── // ── Sink ─────────────────────────────────────────────────────────────
private static void Write(string message) => EntryPoint.Log(message); /// <summary>Uncategorised line (General category); used by the Move/UseDone traces.</summary>
private static void Write(string? message)
{
if (message != null)
WriteCategory(LogCategory.General, message);
}
private static void WriteCategory(LogCategory category, string message)
=> WriteAt(LogSettings.LevelFor(category), message);
private static void WriteAt(EntryPoint.EngineLogLevel level, string message)
{
if (EntryPoint.ShouldLog(level))
EntryPoint.LogTagged("engine", message, LogSettings.Tag(level));
}
} }

View file

@ -0,0 +1,78 @@
// ============================================================================
// RynthCore.Engine - UI/Data/CharmsData.cs
// RynthAi's ACECustom charm tracker for the Settings panel's "Charms
// Tracking" tab. RynthAi owns the charm registry (WCIDs, ability flags) and
// the per-character "seen" memory; this side only shows the snapshot.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI.Data;
/// <summary>RynthPluginGetCharmsJson's payload.</summary>
internal sealed class CharmsInfo
{
/// <summary>False off ILT-like worlds (or before RynthAi's ILT Hub exists).</summary>
[JsonPropertyName("available")] public bool Available { get; set; }
[JsonPropertyName("world")] public string World { get; set; } = "";
[JsonPropertyName("total")] public int Total { get; set; }
[JsonPropertyName("acquiredCount")] public int AcquiredCount { get; set; }
[JsonPropertyName("activeCount")] public int ActiveCount { get; set; }
[JsonPropertyName("charms")] public CharmRow[] Charms { get; set; } = Array.Empty<CharmRow>();
}
internal sealed class CharmRow
{
[JsonPropertyName("name")] public string Name { get; set; } = "";
[JsonPropertyName("effect")] public string Effect { get; set; } = "";
/// <summary>"carried" (in pack / equipped now), "seen" (carried before, now elsewhere) or "no".</summary>
[JsonPropertyName("acquired")] public string Acquired { get; set; } = "no";
/// <summary>Copies carried right now.</summary>
[JsonPropertyName("count")] public int Count { get; set; }
/// <summary>Best tier carried or last seen; 0 until an appraisal reports it.</summary>
[JsonPropertyName("tier")] public int Tier { get; set; }
[JsonPropertyName("maxTier")] public int MaxTier { get; set; }
/// <summary>Ability toggled on: "on", "off" or "unknown".</summary>
[JsonPropertyName("active")] public string Active { get; set; } = "unknown";
/// <summary>Server-side global switch as far as the client has learned it: "on", "off" or "unknown".</summary>
[JsonPropertyName("server")] public string Server { get; set; } = "unknown";
/// <summary>yyyy-MM-dd the charm was last carried (empty when never).</summary>
[JsonPropertyName("lastSeen")] public string LastSeen { get; set; } = "";
}
[JsonSerializable(typeof(CharmsInfo))]
internal sealed partial class CharmsJsonContext : JsonSerializerContext { }
/// <summary>
/// RynthPluginGetCharmsJson (single static buffer: one caller only) while the Settings panel
/// is open. Every 2 s is plenty: charm state only changes when one is picked up or toggled.
/// </summary>
internal sealed unsafe class CharmsSource : UiSource<CharmsInfo>
{
private delegate* unmanaged[Cdecl]<IntPtr> _getCharmsJson;
public CharmsSource() : base("Charms", periodMs: 2000) { }
protected internal override void Poll()
{
if (_getCharmsJson == null)
_getCharmsJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetCharmsJson");
if (_getCharmsJson == null) return;
IntPtr p = _getCharmsJson();
string json = p == IntPtr.Zero ? "{}" : Marshal.PtrToStringAnsi(p) ?? "{}";
CharmsInfo info;
try { info = JsonSerializer.Deserialize(json, CharmsJsonContext.Default.CharmsInfo) ?? new CharmsInfo(); }
catch (JsonException) { info = new CharmsInfo(); }
Publish(info);
}
protected internal override void Reset()
{
_getCharmsJson = null;
ClearSnapshot();
}
}

View file

@ -604,6 +604,8 @@ internal static class ChatModel
foreach (string t in Volatile.Read(ref _customTabs)) if (seen.Add(t)) tabs.Add(t); foreach (string t in Volatile.Read(ref _customTabs)) if (seen.Add(t)) tabs.Add(t);
foreach (ChatFilterRule rule in Filters) foreach (ChatFilterRule rule in Filters)
if (rule.Enabled && rule.Routes && rule.Tab.Length > 0 && seen.Add(rule.Tab)) tabs.Add(rule.Tab); if (rule.Enabled && rule.Routes && rule.Tab.Length > 0 && seen.Add(rule.Tab)) tabs.Add(rule.Tab);
foreach (string t in RynthCore.Engine.UI.Panels.RynthChatPresets.TargetTabs())
if (seen.Add(t)) tabs.Add(t);
string[] result = tabs.ToArray(); string[] result = tabs.ToArray();
_allTabs = (version, result); _allTabs = (version, result);
return result; return result;
@ -674,6 +676,9 @@ internal static class ChatModel
foreach (ChatFilterRule rule in Filters) foreach (ChatFilterRule rule in Filters)
if (string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase)) if (string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase))
rule.Tab = newName; rule.Tab = newName;
foreach (var preset in RynthCore.Engine.UI.Panels.RynthChatPresets.All)
if (string.Equals(preset.Tab, tab, StringComparison.OrdinalIgnoreCase))
preset.Tab = newName;
if (string.Equals(ActiveChannel, tab, StringComparison.OrdinalIgnoreCase)) ActiveChannel = newName; if (string.Equals(ActiveChannel, tab, StringComparison.OrdinalIgnoreCase)) ActiveChannel = newName;
FiltersChanged(); FiltersChanged();
return true; return true;
@ -690,6 +695,9 @@ internal static class ChatModel
if (rule.Action is ChatRuleAction.Move or ChatRuleAction.Copy if (rule.Action is ChatRuleAction.Move or ChatRuleAction.Copy
&& string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase)) && string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase))
rule.Enabled = false; rule.Enabled = false;
foreach (var preset in RynthCore.Engine.UI.Panels.RynthChatPresets.All)
if (string.Equals(preset.Tab, tab, StringComparison.OrdinalIgnoreCase))
preset.Enabled = false;
FiltersChanged(); FiltersChanged();
} }
@ -1350,6 +1358,16 @@ internal static class ChatModel
&& !IsBaseTab(rule.Tab) && !tabs.Contains(rule.Tab, StringComparer.OrdinalIgnoreCase)) && !IsBaseTab(rule.Tab) && !tabs.Contains(rule.Tab, StringComparer.OrdinalIgnoreCase))
tabs.Add(rule.Tab); tabs.Add(rule.Tab);
} }
foreach (RynthChatPresetDto p in dto.Presets ?? Array.Empty<RynthChatPresetDto>())
{
var preset = p.Id == null ? null : RynthCore.Engine.UI.Panels.RynthChatPresets.Get(p.Id);
if (preset == null) continue; // a preset a later build removed
preset.Enabled = p.Enabled;
preset.Tab = (p.Tab ?? "").Trim();
if (preset.Tab.Length > 0 && !IsBaseTab(preset.Tab)
&& !tabs.Contains(preset.Tab, StringComparer.OrdinalIgnoreCase))
tabs.Add(preset.Tab);
}
_customTabs = tabs.ToArray(); _customTabs = tabs.ToArray();
_filters = rules.ToArray(); _filters = rules.ToArray();
Interlocked.Increment(ref _filtersVersion); Interlocked.Increment(ref _filtersVersion);
@ -1404,6 +1422,11 @@ internal static class ChatModel
LineColors = ChatLineColors.ToJson(), // null (left out) until a colour is set LineColors = ChatLineColors.ToJson(), // null (left out) until a colour is set
CustomTabs = Volatile.Read(ref _customTabs), CustomTabs = Volatile.Read(ref _customTabs),
Filters = Filters.Select(ToDto).ToArray(), Filters = Filters.Select(ToDto).ToArray(),
// Only presets the user touched: new presets in later builds start off.
Presets = RynthCore.Engine.UI.Panels.RynthChatPresets.All
.Where(p => p.Enabled || p.Tab.Length > 0)
.Select(p => new RynthChatPresetDto { Id = p.Id, Enabled = p.Enabled, Tab = p.Tab.Length > 0 ? p.Tab : null })
.ToArray(),
}; };
UiBackgroundWriter.Enqueue("persist chat settings", () => UiBackgroundWriter.Enqueue("persist chat settings", () =>
{ {

View file

@ -292,9 +292,12 @@ internal sealed class ChatRouter
foreach (ChatFilterRule rule in _rules) Volatile.Write(ref rule.Hits, 0); foreach (ChatFilterRule rule in _rules) Volatile.Write(ref rule.Hits, 0);
} }
/// <summary>One step of the editor's test: rule index (-1 = mention) and what it did.</summary> /// <summary>One step of the editor's test: rule index (-1 = mention, -2 = a standard filter) and what it did.</summary>
public readonly record struct Step(int Rule, string What); public readonly record struct Step(int Rule, string What);
/// <summary><see cref="Step.Rule"/> of a standard-filter (RynthChatPresets) step.</summary>
public const int StandardFilterStep = -2;
public ChatRoute Evaluate(ChatLine line, List<Step>? trace) => public ChatRoute Evaluate(ChatLine line, List<Step>? trace) =>
Evaluate(line.Text, line.Channel, line.ChatType, trace); Evaluate(line.Text, line.Channel, line.ChatType, trace);
@ -383,6 +386,28 @@ internal sealed class ChatRouter
trace?.Add(new Step(i, what!.ToString())); trace?.Add(new Step(i, what!.ToString()));
} }
// Standard filters (RynthChatPresets) decide only what the custom rules left undecided.
if (!routed)
{
var preset = RynthCore.Engine.UI.Panels.RynthChatPresets.FirstMatch(text, channel);
if (preset != null)
{
string presetTab = preset.Tab;
routed = true;
if (presetTab.Length == 0)
{
hidden = true;
trace?.Add(new Step(StandardFilterStep, $"standard filter \"{preset.Label}\" hides it"));
}
else
{
inHome = false;
AddTab(ref tabs, presetTab);
trace?.Add(new Step(StandardFilterStep, $"standard filter \"{preset.Label}\" moves it to {presetTab}"));
}
}
}
bool mention = false; bool mention = false;
if (!hidden && _mention != null && ChatModel.MentionEligible(channel, chatType)) if (!hidden && _mention != null && ChatModel.MentionEligible(channel, chatType))
{ {

View file

@ -66,6 +66,16 @@ internal sealed class RynthChatSettingsDto
[JsonPropertyName("historyLines")] public int? HistoryLines { get; set; } [JsonPropertyName("historyLines")] public int? HistoryLines { get; set; }
[JsonPropertyName("customTabs")] public string[]? CustomTabs { get; set; } [JsonPropertyName("customTabs")] public string[]? CustomTabs { get; set; }
[JsonPropertyName("filters")] public RynthChatFilterDto[]? Filters { get; set; } [JsonPropertyName("filters")] public RynthChatFilterDto[]? Filters { get; set; }
/// <summary>Standard filters' user state (RynthChatPresets); absent while none was changed.</summary>
[JsonPropertyName("presets")] public RynthChatPresetDto[]? Presets { get; set; }
}
/// <summary>A standard filter's user state (RynthChatPresets), by preset id.</summary>
internal sealed class RynthChatPresetDto
{
[JsonPropertyName("id")] public string? Id { get; set; }
[JsonPropertyName("enabled")] public bool Enabled { get; set; }
[JsonPropertyName("tab")] public string? Tab { get; set; }
} }
/// <summary>Export / import on the clipboard (the rule editor's Export and Import).</summary> /// <summary>Export / import on the clipboard (the rule editor's Export and Import).</summary>

View file

@ -63,11 +63,14 @@ internal sealed unsafe class ItemsSource : UiSource<ItemsSnapshot>
internal static unsafe class ItemsCommands internal static unsafe class ItemsCommands
{ {
private static delegate* unmanaged[Cdecl]<IntPtr, void> _set; private static delegate* unmanaged[Cdecl]<IntPtr, void> _set;
private static delegate* unmanaged[Cdecl]<void> _addWeapon, _addConsumable; private static delegate* unmanaged[Cdecl]<void> _addWeapon, _addShield, _addConsumable;
/// <summary>ItemRule.Action value the plugin uses for off-hand shields.</summary>
public const string ShieldAction = "Shield";
static ItemsCommands() static ItemsCommands()
{ {
PluginManager.PluginsUnloaded += () => { _set = null; _addWeapon = null; _addConsumable = null; }; PluginManager.PluginsUnloaded += () => { _set = null; _addWeapon = null; _addShield = null; _addConsumable = null; };
} }
public static readonly string[] Elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; public static readonly string[] Elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
@ -94,6 +97,18 @@ internal static unsafe class ItemsCommands
UiSources.Items.RequestRefresh(); UiSources.Items.RequestRefresh();
}); });
/// <summary>
/// Adds the item selected in the inventory as an off-hand shield. RynthAi older than
/// 0.6.20 has no such export: the click is logged and dropped.
/// </summary>
public static void AddSelectedShield() => UiDataHub.Post("Items add shield", () =>
{
if (_addShield == null) _addShield = (delegate* unmanaged[Cdecl]<void>)Export("RynthPluginAddSelectedShield");
if (_addShield != null) _addShield();
else RynthLog.UI("ItemsCommands: Add Selected Shield unavailable - RynthAi 0.6.20 or newer is required.");
UiSources.Items.RequestRefresh();
});
/// <summary>Adds the item selected in the inventory as a consumable.</summary> /// <summary>Adds the item selected in the inventory as a consumable.</summary>
public static void AddSelectedConsumable() => UiDataHub.Post("Items add consumable", () => public static void AddSelectedConsumable() => UiDataHub.Post("Items add consumable", () =>
{ {

View file

@ -40,6 +40,17 @@ internal sealed class NavPayload
public int ActiveNavIndex { get; set; } public int ActiveNavIndex { get; set; }
public List<string> NavFiles { get; set; } = new(); public List<string> NavFiles { get; set; } = new();
public List<NavPoint> Points { get; set; } = new(); public List<NavPoint> Points { get; set; } = new();
/// <summary>RynthAi records (and draws) the walked breadcrumb trail. Older plugins omit it (false).</summary>
public bool TrackBreadcrumbs { get; set; }
/// <summary>RynthAi draws the route overlay (rings / lines, waypoint labels, guide line).</summary>
public bool ShowRouteOverlay { get; set; }
/// <summary>Route recording is on (points are added as you walk). Older plugins omit it.</summary>
public bool IsRecording { get; set; }
/// <summary>Breadcrumb trail size, for "Trail to route" / "Backtrack".</summary>
public int TrailPoints { get; set; }
public double TrailYards { get; set; }
/// <summary>The last route edit's result, for a few seconds after it (empty otherwise).</summary>
public string EditStatus { get; set; } = string.Empty;
/// <summary>A copy a face may change (its own point list); the points themselves are shared.</summary> /// <summary>A copy a face may change (its own point list); the points themselves are shared.</summary>
public NavPayload Clone() public NavPayload Clone()
@ -60,6 +71,12 @@ internal sealed class NavCmd
public int InsertAt { get; set; } = -1; public int InsertAt { get; set; } = -1;
public string NavName { get; set; } = string.Empty; public string NavName { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty; // addChat public string Text { get; set; } = string.Empty; // addChat
public bool On { get; set; } // setBreadcrumbs / setRouteOverlay / setRecording
public List<int>? Indices { get; set; } // movePoints / duplicatePoints / deletePoints
public int Delta { get; set; } // movePoints: -1 up, +1 down
public double Seconds { get; set; } // addPause
public double Yards { get; set; } // simplifyRoute tolerance
public bool Reverse { get; set; } // trailToRoute: backtrack
} }
[JsonSerializable(typeof(NavPayload))] [JsonSerializable(typeof(NavPayload))]
@ -105,6 +122,19 @@ internal static class NavCommands
public static readonly string[] RouteTypes = { "Once", "Circular", "Linear", "Follow" }; public static readonly string[] RouteTypes = { "Once", "Circular", "Linear", "Follow" };
public static readonly string[] AddModes = { "End", "Above", "Below" }; public static readonly string[] AddModes = { "End", "Above", "Below" };
public static readonly double[] PauseSeconds = { 1, 2, 3, 5, 10, 15, 30, 60 };
public static readonly string[] PauseLabels = Array.ConvertAll(PauseSeconds, s => $"Pause {s:0} s");
public static readonly double[] SimplifyYards = { 0.5, 1, 2, 3, 5 };
public static readonly string[] SimplifyLabels =
Array.ConvertAll(SimplifyYards, y => $"Drop points within {y:0.#} yd of a straight line");
public static readonly string[] TrailChoices =
{
"Replace route with the trail (walk it again)",
"Replace route with a backtrack (walk it back)",
};
/// <summary>Route picker index for the plugin's RouteType (1 Circular, 2 Linear, 3 Follow, else Once).</summary> /// <summary>Route picker index for the plugin's RouteType (1 Circular, 2 Linear, 3 Follow, else Once).</summary>
public static int RouteIndex(int routeType) => routeType switch { 1 => 1, 2 => 2, 3 => 3, _ => 0 }; public static int RouteIndex(int routeType) => routeType switch { 1 => 1, 2 => 2, 3 => 3, _ => 0 };

View file

@ -0,0 +1,206 @@
// ============================================================================
// RynthCore.Engine - UI/Data/ProgressionData.cs
// RynthAi's ILT progression planners (augmentations, enlightenment) and the
// infinite-attribute raiser for the Skills panel's Progression tab. RynthAi owns the math and the persisted
// inputs; this side only shows the snapshot and sends "prog ..." remote
// commands (RynthAiCommands.ApplyRemoteCommand) for edits and actions.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI.Data;
/// <summary>RynthPluginGetProgressionJson's payload. Display strings arrive preformatted.</summary>
internal sealed class ProgressionInfo
{
/// <summary>False off ILT-like worlds (or before the ILT Hub exists): the tab is hidden.</summary>
[JsonPropertyName("available")] public bool Available { get; set; }
[JsonPropertyName("world")] public string World { get; set; } = "";
[JsonPropertyName("aug")] public AugPlanner Aug { get; set; } = new();
[JsonPropertyName("enl")] public EnlPlanner Enl { get; set; } = new();
/// <summary>Absent from an older RynthAi: stays empty and the section shows "update RynthAi".</summary>
[JsonPropertyName("attr")] public AttrRaiser? Attr { get; set; }
}
/// <summary>RynthAi's IltAttributeRaiser: server costs ("/xp all") and the raise settings.</summary>
internal sealed class AttrRaiser
{
/// <summary>The raiser can't run here; <see cref="Reason"/> says why.</summary>
[JsonPropertyName("off")] public bool Off { get; set; }
[JsonPropertyName("reason")] public string Reason { get; set; } = "";
[JsonPropertyName("auto")] public bool Auto { get; set; }
/// <summary>Minutes between auto-raise runs.</summary>
[JsonPropertyName("every")] public int Every { get; set; } = 5;
/// <summary>0 priority, 1 round robin, 2 cheapest first.</summary>
[JsonPropertyName("mode")] public int Mode { get; set; }
[JsonPropertyName("running")] public bool Running { get; set; }
/// <summary>XP reserve, preformatted ("0", "1.50B").</summary>
[JsonPropertyName("keep")] public string Keep { get; set; } = "0";
/// <summary>XP reserve in full ("1,234,567"): what the reserve box edits.</summary>
[JsonPropertyName("keepFull")] public string KeepFull { get; set; } = "";
[JsonPropertyName("status")] public string Status { get; set; } = "";
[JsonPropertyName("lastRun")] public string LastRun { get; set; } = "";
[JsonPropertyName("unassigned")] public string Unassigned { get; set; } = "";
/// <summary>Time to the next auto run ("" when auto is off).</summary>
[JsonPropertyName("next")] public string Next { get; set; } = "";
[JsonPropertyName("costsAge")] public string CostsAge { get; set; } = "";
/// <summary>Local time the costs were last read ("-" before the first read; "" from older RynthAi).</summary>
[JsonPropertyName("updated")] public string Updated { get; set; } = "";
/// <summary>"Level N Total XP X Unassigned Y" ("" from older RynthAi).</summary>
[JsonPropertyName("xpHeader")] public string XpHeader { get; set; } = "";
/// <summary>In raise-priority order.</summary>
[JsonPropertyName("rows")] public AttrRow[] Rows { get; set; } = Array.Empty<AttrRow>();
}
internal sealed class AttrRow
{
/// <summary>/attr abbreviation: str end coo qui foc sel hea sta man.</summary>
[JsonPropertyName("key")] public string Key { get; set; } = "";
[JsonPropertyName("label")] public string Label { get; set; } = "";
[JsonPropertyName("vital")] public bool Vital { get; set; }
/// <summary>Ticked: "Raise now" and auto-raise may spend on it.</summary>
[JsonPropertyName("on")] public bool On { get; set; }
/// <summary>Base value RynthAi last saw in a server reply (-1 = unknown; the panel prefers the client's).</summary>
[JsonPropertyName("base")] public int Base { get; set; } = -1;
/// <summary>Next-level cost from "/xp all", preformatted ("?" until read).</summary>
[JsonPropertyName("cost")] public string Cost { get; set; } = "?";
/// <summary>Next level fits the raiser's budget (unassigned minus the reserve).</summary>
[JsonPropertyName("afford")] public bool Afford { get; set; }
/// <summary>The next-level cost has been read (false from older RynthAi too).</summary>
[JsonPropertyName("known")] public bool Known { get; set; }
/// <summary>By hand: +1 fits the unassigned XP (no reserve).</summary>
[JsonPropertyName("afford1")] public bool Afford1 { get; set; }
/// <summary>By hand: the projected +10 fits the unassigned XP.</summary>
[JsonPropertyName("afford10")] public bool Afford10 { get; set; }
/// <summary>Projected cost of ten levels (7.7% growth per level), e.g. "~1.2T"; "" from older RynthAi.</summary>
[JsonPropertyName("cost10")] public string Cost10 { get; set; } = "";
/// <summary>Exact next-level cost with separators, for the tooltip.</summary>
[JsonPropertyName("costFull")] public string CostFull { get; set; } = "";
[JsonPropertyName("cost10Full")] public string Cost10Full { get; set; } = "";
}
internal sealed class AugPlanner
{
/// <summary>The server reports /aug off.</summary>
[JsonPropertyName("off")] public bool Off { get; set; }
[JsonPropertyName("status")] public string Status { get; set; } = "";
[JsonPropertyName("lumPerCoin")] public long LumPerCoin { get; set; }
[JsonPropertyName("rows")] public AugRow[] Rows { get; set; } = Array.Empty<AugRow>();
[JsonPropertyName("total")] public string Total { get; set; } = "";
/// <summary>Empty when the bank holds enough Enlightened Coins.</summary>
[JsonPropertyName("short")] public string Short { get; set; } = "";
[JsonPropertyName("banked")] public string Banked { get; set; } = "";
// Totals row and e-coin summary (all empty / zero from older RynthAi).
[JsonPropertyName("totCur")] public long TotalCurrent { get; set; }
[JsonPropertyName("totTgt")] public long TotalTarget { get; set; }
[JsonPropertyName("totInc")] public long TotalIncrease { get; set; }
[JsonPropertyName("totLum")] public string TotalLum { get; set; } = "";
[JsonPropertyName("totCoins")] public long TotalCoins { get; set; }
[JsonPropertyName("coinsLine")] public string CoinsLine { get; set; } = "";
[JsonPropertyName("lumToBuy")] public string LumToBuy { get; set; } = "";
/// <summary>Ready-made clipboard texts (UB's Copy Discord / Copy In-Game).</summary>
[JsonPropertyName("copyDiscord")] public string CopyDiscord { get; set; } = "";
[JsonPropertyName("copyIngame")] public string CopyIngame { get; set; } = "";
/// <summary>This world's cost rules for the Cost settings editor (null from older RynthAi).</summary>
[JsonPropertyName("cfg")] public AugCostConfig? Config { get; set; }
}
/// <summary>Per-server aug cost rules: level i costs (Base + (i-1)*Base*Pct/100) x the multiplier of its tier.</summary>
internal sealed class AugCostConfig
{
[JsonPropertyName("world")] public string World { get; set; } = "";
/// <summary>The world has its own saved rules (false = UB / InfiniteLeaftide defaults).</summary>
[JsonPropertyName("custom")] public bool Custom { get; set; }
/// <summary>Tier multipliers: below S1, from S1, from S2, from S3, from S4.</summary>
[JsonPropertyName("mults")] public double[] Multipliers { get; set; } = Array.Empty<double>();
[JsonPropertyName("rows")] public AugCostRule[] Rows { get; set; } = Array.Empty<AugCostRule>();
}
internal sealed class AugCostRule
{
[JsonPropertyName("key")] public string Key { get; set; } = "";
[JsonPropertyName("label")] public string Label { get; set; } = "";
[JsonPropertyName("base")] public long Base { get; set; }
/// <summary>Percent of Base added per level.</summary>
[JsonPropertyName("pct")] public double Percent { get; set; }
[JsonPropertyName("coins")] public int Coins { get; set; }
[JsonPropertyName("s1")] public int S1 { get; set; }
[JsonPropertyName("s2")] public int S2 { get; set; }
[JsonPropertyName("s3")] public int S3 { get; set; }
[JsonPropertyName("s4")] public int S4 { get; set; }
/// <summary>Highest target (0 = no limit).</summary>
[JsonPropertyName("cap")] public int Cap { get; set; }
}
internal sealed class AugRow
{
[JsonPropertyName("key")] public string Key { get; set; } = "";
[JsonPropertyName("label")] public string Label { get; set; } = "";
[JsonPropertyName("cur")] public int Current { get; set; }
[JsonPropertyName("tgt")] public int Target { get; set; }
/// <summary>Levels planned (target - current).</summary>
[JsonPropertyName("inc")] public int Increase { get; set; }
/// <summary>Highest target allowed (the aug's cap, or the current level when the server reports more).</summary>
[JsonPropertyName("cap")] public int Cap { get; set; }
[JsonPropertyName("lum")] public string Lum { get; set; } = "-";
[JsonPropertyName("coins")] public long Coins { get; set; }
}
internal sealed class EnlPlanner
{
/// <summary>The server reports /enl off.</summary>
[JsonPropertyName("off")] public bool Off { get; set; }
[JsonPropertyName("header")] public string Header { get; set; } = "";
[JsonPropertyName("next")] public string Next { get; set; } = "";
[JsonPropertyName("enl")] public int Level { get; set; }
[JsonPropertyName("target")] public int Target { get; set; }
[JsonPropertyName("plan")] public string[] Plan { get; set; } = Array.Empty<string>();
[JsonPropertyName("coinsPerToken")] public int CoinsPerToken { get; set; }
[JsonPropertyName("tokensShort")] public string TokensShort { get; set; } = "";
/// <summary>Client-side requirements not yet met; empty = the client checks pass.</summary>
[JsonPropertyName("blockers")] public string[] Blockers { get; set; } = Array.Empty<string>();
[JsonPropertyName("serverChecks")] public string ServerChecks { get; set; } = "";
[JsonPropertyName("auto")] public bool Auto { get; set; }
/// <summary>Auto-enlighten is disarmed every session until confirmed again.</summary>
[JsonPropertyName("armed")] public bool Armed { get; set; }
[JsonPropertyName("spendFirst")] public bool SpendFirst { get; set; }
[JsonPropertyName("checkEvery")] public int CheckEvery { get; set; }
[JsonPropertyName("status")] public string Status { get; set; } = "";
}
[JsonSerializable(typeof(ProgressionInfo))]
internal sealed partial class ProgressionJsonContext : JsonSerializerContext { }
/// <summary>
/// RynthPluginGetProgressionJson (single static buffer: one caller only) while the Skills
/// panel is open, and right after each Progression edit (RequestRefreshAfterPluginTick).
/// </summary>
internal sealed unsafe class ProgressionSource : UiSource<ProgressionInfo>
{
private delegate* unmanaged[Cdecl]<IntPtr> _getProgressionJson;
public ProgressionSource() : base("Progression", periodMs: 1000) { }
protected internal override void Poll()
{
if (_getProgressionJson == null)
_getProgressionJson = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve("RynthAi", "RynthPluginGetProgressionJson");
if (_getProgressionJson == null) return;
IntPtr p = _getProgressionJson();
string json = p == IntPtr.Zero ? "{}" : Marshal.PtrToStringAnsi(p) ?? "{}";
ProgressionInfo info;
try { info = JsonSerializer.Deserialize(json, ProgressionJsonContext.Default.ProgressionInfo) ?? new ProgressionInfo(); }
catch (JsonException) { info = new ProgressionInfo(); }
Publish(info);
}
protected internal override void Reset()
{
_getProgressionJson = null;
ClearSnapshot();
}
}

View file

@ -41,6 +41,11 @@ internal sealed class RynthAiSnapshot
[JsonPropertyName("selectedLootIdx")] public int SelectedLootIdx { get; set; } [JsonPropertyName("selectedLootIdx")] public int SelectedLootIdx { get; set; }
[JsonPropertyName("selectedMetaIdx")] public int SelectedMetaIdx { get; set; } [JsonPropertyName("selectedMetaIdx")] public int SelectedMetaIdx { get; set; }
[JsonPropertyName("selectedProfileIdx")] public int SelectedProfileIdx { get; set; } [JsonPropertyName("selectedProfileIdx")] public int SelectedProfileIdx { get; set; }
// Buff profiles (RynthAi 0.5.31+): "Built-in" first, then BuffProfiles\*.json. Older plugins
// send none, and the Buffs picker then shows "Built-in" with nothing to pick.
[JsonPropertyName("buffProfiles")] public string[] BuffProfiles { get; set; } = Array.Empty<string>();
[JsonPropertyName("currentBuffName")] public string CurrentBuffName { get; set; } = string.Empty;
[JsonPropertyName("selectedBuffIdx")] public int SelectedBuffIdx { get; set; }
[JsonPropertyName("combatEnabled")] public bool CombatEnabled { get; set; } [JsonPropertyName("combatEnabled")] public bool CombatEnabled { get; set; }
[JsonPropertyName("buffingEnabled")] public bool BuffingEnabled { get; set; } [JsonPropertyName("buffingEnabled")] public bool BuffingEnabled { get; set; }
[JsonPropertyName("navigationEnabled")] public bool NavigationEnabled { get; set; } [JsonPropertyName("navigationEnabled")] public bool NavigationEnabled { get; set; }
@ -85,6 +90,8 @@ internal sealed class RynthAiView
public required string NavText { get; init; } public required string NavText { get; init; }
public required string LootText { get; init; } public required string LootText { get; init; }
public required string MetaText { get; init; } public required string MetaText { get; init; }
/// <summary>Buff profile buffing uses ("Built-in" without one).</summary>
public required string BuffText { get; init; }
public required string TargetHeadline { get; init; } public required string TargetHeadline { get; init; }
public required int TargetSegmentsLit { get; init; } public required int TargetSegmentsLit { get; init; }
public required bool ShowTargetSubBars { get; init; } public required bool ShowTargetSubBars { get; init; }
@ -164,6 +171,7 @@ internal sealed unsafe class RynthAiSource : UiSource<RynthAiView>
NavText = Truncate(s.CurrentNavName, 16), NavText = Truncate(s.CurrentNavName, 16),
LootText = Truncate(s.CurrentLootName, 16), LootText = Truncate(s.CurrentLootName, 16),
MetaText = Truncate(s.CurrentMetaName, 16), MetaText = Truncate(s.CurrentMetaName, 16),
BuffText = Truncate(string.IsNullOrWhiteSpace(s.CurrentBuffName) ? "Built-in" : s.CurrentBuffName, 16),
TargetHeadline = Truncate(label, 32), TargetHeadline = Truncate(label, 32),
TargetSegmentsLit = lit, TargetSegmentsLit = lit,
ShowTargetSubBars = showSub, ShowTargetSubBars = showSub,
@ -265,6 +273,7 @@ internal static unsafe class RynthAiCommands
private static delegate* unmanaged[Cdecl]<float, void> _adjustOpacity; private static delegate* unmanaged[Cdecl]<float, void> _adjustOpacity;
private static delegate* unmanaged[Cdecl]<void> _togglePanelLock; private static delegate* unmanaged[Cdecl]<void> _togglePanelLock;
private static delegate* unmanaged[Cdecl]<IntPtr, void> _sendNavCommand; private static delegate* unmanaged[Cdecl]<IntPtr, void> _sendNavCommand;
private static delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void> _applyRemoteCommand;
static RynthAiCommands() static RynthAiCommands()
{ {
@ -272,6 +281,7 @@ internal static unsafe class RynthAiCommands
{ {
_toggleMacro = null; _setSubsystemEnabled = null; _selectProfile = null; _forceRebuff = null; _toggleMacro = null; _setSubsystemEnabled = null; _selectProfile = null; _forceRebuff = null;
_cancelForceRebuff = null; _adjustOpacity = null; _togglePanelLock = null; _sendNavCommand = null; _cancelForceRebuff = null; _adjustOpacity = null; _togglePanelLock = null; _sendNavCommand = null;
_applyRemoteCommand = null;
}; };
} }
@ -341,6 +351,29 @@ internal static unsafe class RynthAiCommands
if (refreshPatrol) UiSources.Patrol.RequestRefresh(); if (refreshPatrol) UiSources.Patrol.RequestRefresh();
UiSources.Nav.RequestRefresh(); // the plugin applied it: the Nav panels show it next poll UiSources.Nav.RequestRefresh(); // the plugin applied it: the Nav panels show it next poll
}); });
/// <summary>
/// RynthPluginApplyRemoteCommand(action, value) - the same (action, value) pairs as the
/// plugin's /ra chat commands ("huds","show"; "remote","toggle"; "hub","show" ...).
/// Older RynthAi builds without the export drop the command (logged once per bind miss).
/// </summary>
public static void ApplyRemoteCommand(string action, string value) => Run("remote command " + action, () =>
{
if (_applyRemoteCommand == null) _applyRemoteCommand = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void>)Export("RynthPluginApplyRemoteCommand");
if (_applyRemoteCommand == null)
{
RynthLog.UI($"RynthAiCommands: RynthPluginApplyRemoteCommand not exported; dropped '{action} {value}'.");
return;
}
IntPtr a = Marshal.StringToHGlobalAnsi(action);
IntPtr b = Marshal.StringToHGlobalAnsi(value);
try { _applyRemoteCommand(a, b); }
finally
{
Marshal.FreeHGlobal(a);
Marshal.FreeHGlobal(b);
}
});
} }
/// <summary>RynthPluginGetPatrolInfoJson's payload (patrol flyout).</summary> /// <summary>RynthPluginGetPatrolInfoJson's payload (patrol flyout).</summary>

View file

@ -11,6 +11,7 @@
// ============================================================================ // ============================================================================
using System; using System;
using System.Collections.Generic;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
@ -47,6 +48,13 @@ internal sealed class RynthAiSettings
// Decal bridge: stop RynthAi's macro when VTank's starts (one bot per client). Default on; // Decal bridge: stop RynthAi's macro when VTank's starts (one bot per client). Default on;
// an older RynthAi doesn't send it, and a missing field must not read as "off". // an older RynthAi doesn't send it, and a missing field must not read as "off".
public bool YieldToVTank { get; set; } = true; public bool YieldToVTank { get; set; } = true;
// Server Features (RynthAi ServerFeatureGate): world names that turn on the ILT Hub, the
// Progression planners and the attribute raiser, plus a manual override. An older RynthAi
// doesn't send them; RynthAi lays a save over its current values, so these defaults are
// only ever shown, never applied. ServerFeaturesStatus is read-only (RynthAi ignores it).
public string FeatureServerNames { get; set; } = "InfiniteLeaftide, *Leaftide*";
public bool ForceServerFeatures { get; set; }
public string ServerFeaturesStatus { get; set; } = string.Empty;
public bool EnableRaycasting { get; set; } public bool EnableRaycasting { get; set; }
public bool UseArcs { get; set; } public bool UseArcs { get; set; }
public float BowArcVelocity { get; set; } = 25f; public float BowArcVelocity { get; set; } = 25f;
@ -219,6 +227,15 @@ internal sealed class RynthAiSettings
public int SalvageSalvageDelayMs { get; set; } = 50; public int SalvageSalvageDelayMs { get; set; } = 50;
public int SalvageResultDelayFirstMs { get; set; } = 1000; public int SalvageResultDelayFirstMs { get; set; } = 1000;
public int SalvageResultDelayFastMs { get; set; } = 250; public int SalvageResultDelayFastMs { get; set; } = 250;
// Ground loot and item info
public bool EnableGroundLoot { get; set; }
// Diagnostics (RynthAi's RynthLog: per PC in Logs\Diagnostics\diagnostics.json, not the profile)
public bool DiagDebugToChat { get; set; }
public bool DiagFileLogAll { get; set; } = true;
/// <summary>"Name=Level" per trace category, ','-joined; Level 0 Off, 1 Trace, 2 Info. See <see cref="TraceCategoryLevels"/>.</summary>
public string DiagCategories { get; set; } = string.Empty;
/// <summary>Read-only (RynthAi ignores it on save): the diagnostics folder.</summary>
public string DiagFolder { get; set; } = string.Empty;
/// <summary>A private copy for a face to edit (all members are values or strings).</summary> /// <summary>A private copy for a face to edit (all members are values or strings).</summary>
public RynthAiSettings Clone() => (RynthAiSettings)MemberwiseClone(); public RynthAiSettings Clone() => (RynthAiSettings)MemberwiseClone();
@ -289,7 +306,60 @@ internal static unsafe class SettingsCommands
// ── Schema ───────────────────────────────────────────────────────────────── // ── Schema ─────────────────────────────────────────────────────────────────
internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus } internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus, Button, TraceCategories, Text, Status }
/// <summary>
/// Reads and edits <see cref="RynthAiSettings.DiagCategories"/> ("Name=Level,..."). The category
/// list comes from RynthAi, so a category it adds shows up without an engine change.
/// </summary>
internal static class TraceCategoryLevels
{
public const int Off = 0, Trace = 1, Info = 2;
/// <summary>The categories in RynthAi's order; malformed entries are skipped.</summary>
public static List<(string Name, int Level)> Parse(string? levels)
{
var list = new List<(string, int)>();
if (string.IsNullOrWhiteSpace(levels)) return list;
foreach (string entry in levels.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
int eq = entry.IndexOf('=');
if (eq <= 0 || !int.TryParse(entry[(eq + 1)..], out int level)) continue;
list.Add((entry[..eq], Math.Clamp(level, Off, Info)));
}
return list;
}
private static string Format(List<(string Name, int Level)> list)
{
var parts = new string[list.Count];
for (int i = 0; i < list.Count; i++) parts[i] = list[i].Name + "=" + list[i].Level;
return string.Join(",", parts);
}
/// <summary>
/// Turns tracing on or off for one category (empty <paramref name="name"/> with a
/// <paramref name="prefix"/>: every category starting with it; both empty: all). On keeps
/// a category already at Info at Info, the same rule as /ra trace.
/// </summary>
public static string Set(string? levels, string name, bool on, string prefix = "")
{
List<(string Name, int Level)> list = Parse(levels);
for (int i = 0; i < list.Count; i++)
{
var (n, level) = list[i];
bool match = name.Length > 0
? string.Equals(n, name, StringComparison.OrdinalIgnoreCase)
: n.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
if (!match) continue;
list[i] = (n, !on ? Off : level == Off ? Trace : level);
}
return Format(list);
}
/// <summary>Checkbox label: the name, plus " +log" at Info (trace lines also go to the normal log).</summary>
public static string Label(string name, int level) => level == Info ? name + " +log" : name;
}
/// <summary> /// <summary>
/// One row of a settings tab. Numeric values go through double (bools as /// One row of a settings tab. Numeric values go through double (bools as
@ -307,7 +377,15 @@ internal sealed record SettingRow(
double Step = 1, double Step = 1,
string[]? Items = null, string[]? Items = null,
Func<RynthAiSettings, bool>? VisibleWhen = null, Func<RynthAiSettings, bool>? VisibleWhen = null,
bool Gates = false) bool Gates = false,
// Button rows: the button's caption (Label is the row label) and its action. Any thread.
string? ButtonText = null,
Action? Click = null,
// Text rows: the string value (committed on Enter / focus loss); Status rows: GetText only.
Func<RynthAiSettings, string>? GetText = null,
Action<RynthAiSettings, string>? SetText = null,
// Text rows: greyed hint shown while the box is empty.
string? Hint = null)
{ {
public bool IsVisible(RynthAiSettings s) => VisibleWhen == null || VisibleWhen(s); public bool IsVisible(RynthAiSettings s) => VisibleWhen == null || VisibleWhen(s);
} }
@ -387,6 +465,17 @@ internal static class SettingsSchema
private static SettingRow Note(string text, Func<RynthAiSettings, bool>? when = null) => private static SettingRow Note(string text, Func<RynthAiSettings, bool>? when = null) =>
new(SettingKind.Note, text, VisibleWhen: when); new(SettingKind.Note, text, VisibleWhen: when);
private static SettingRow Button(string label, string buttonText, Action click, string? tip = null) =>
new(SettingKind.Button, label, tip, ButtonText: buttonText, Click: click);
private static SettingRow Text(string label, Func<RynthAiSettings, string> get, Action<RynthAiSettings, string> set,
string? tip = null, string? hint = null) =>
new(SettingKind.Text, label, tip, GetText: get, SetText: set, Hint: hint);
// A one-line status RynthAi computes (read-only; empty = hidden).
private static SettingRow Status(Func<RynthAiSettings, string> get) =>
new(SettingKind.Status, "", GetText: get, VisibleWhen: s => !string.IsNullOrEmpty(get(s)));
private static SettingRow[] Tiers(Func<RynthAiSettings, int>[] get, Action<RynthAiSettings, int>[] set) private static SettingRow[] Tiers(Func<RynthAiSettings, int>[] get, Action<RynthAiSettings, int>[] set)
{ {
var rows = new SettingRow[get.Length]; var rows = new SettingRow[get.Length];
@ -481,6 +570,12 @@ internal static class SettingsSchema
TextSize("Status", "Status"), TextSize("Status", "Status"),
TextSize("Log", "Log"), TextSize("Log", "Log"),
TextSize("Tracker", "Tracker"), TextSize("Tracker", "Tracker"),
Spacer(),
Section("Item Info"),
Bool("Describe Items When Selected", s => s.ItemInfoOnSelect, (s, v) => s.ItemInfoOnSelect = v,
"Print a Mag-style description of an item in chat when you select it, identifying it\nfirst when needed. Items the bot selects while looting are skipped.\nAlso: /ra iteminfo on|off."),
Button("Item Info Options", "Open...", () => RynthAiCommands.ApplyRemoteCommand("iteminfo", "window"),
"Which fields the description shows and which item types are described on select (/ra iteminfo window)."),
}), }),
new("UI", new[] new("UI", new[]
@ -546,6 +641,17 @@ internal static class SettingsSchema
"With Decal: when VTank's macro starts (/vt start), RynthAi's macro stops, and it won't start while VTank runs.\nOne bot per client. Without Decal this does nothing. Also: /ra vtankyield on|off."), "With Decal: when VTank's macro starts (/vt start), RynthAi's macro stops, and it won't start while VTank runs.\nOne bot per client. Without Decal this does nothing. Also: /ra vtankyield on|off."),
Bool("Enable Raycasting", s => s.EnableRaycasting, (s, v) => s.EnableRaycasting = v), Bool("Enable Raycasting", s => s.EnableRaycasting, (s, v) => s.EnableRaycasting = v),
Spacer(), Spacer(),
Section("Server Features (ILT / infinite attributes)"),
Status(s => s.ServerFeaturesStatus),
Text("Servers", s => s.FeatureServerNames, (s, v) => s.FeatureServerNames = v,
"Comma-separated world names that turn on the ILT Hub, the Skills panel's Progression planners\n" +
"and the attribute raiser. * is a wildcard (*Leaftide* matches any name containing Leaftide).\n" +
"Case does not matter. Saved with the RynthAi profile.",
hint: "InfiniteLeaftide, *Leaftide*"),
Bool("Force enable on this server (manual override)", s => s.ForceServerFeatures, (s, v) => s.ForceServerFeatures = v,
"Turn the features on for whatever world you are on, even if it is not in the list.\n" +
"Each feature still follows what the server reports (for example /xp off keeps the attribute raiser off)."),
Spacer(),
Section("Missile Arc Velocities (m/s)"), Section("Missile Arc Velocities (m/s)"),
Bool("Use Arcs for Missile LoS", s => s.UseArcs, (s, v) => s.UseArcs = v, Bool("Use Arcs for Missile LoS", s => s.UseArcs, (s, v) => s.UseArcs = v,
"A missile target must pass both the straight line and the real arrow arc, ceilings included (dungeons too).\nWhen off, all missile LoS checks are linear (eye-to-eye).", gates: true), "A missile target must pass both the straight line and the real arrow arc, ceilings included (dungeons too).\nWhen off, all missile LoS checks are linear (eye-to-eye).", gates: true),
@ -748,6 +854,8 @@ internal static class SettingsSchema
new("Buffing", Concat( new("Buffing", Concat(
Bool("Enable Buffing", s => s.EnableBuffing, (s, v) => s.EnableBuffing = v), Bool("Enable Buffing", s => s.EnableBuffing, (s, v) => s.EnableBuffing = v),
Button("Buff Profiles", "Spells...", () => RynthAiCommands.ApplyRemoteCommand("spells", "show"),
"Open the RynthAi Spells window: browse the spell list by school, level and target,\nand build the buff profile buffing uses (pick it under Loaded Files > Buffs).\nAlso: /ra spells, /ra buffprofile <name>|none."),
Bool("Rebuff When Idle", s => s.RebuffWhenIdle, (s, v) => s.RebuffWhenIdle = v), Bool("Rebuff When Idle", s => s.RebuffWhenIdle, (s, v) => s.RebuffWhenIdle = v),
Int("Rebuff With (seconds left)", s => s.RebuffSecondsRemaining, (s, v) => s.RebuffSecondsRemaining = v, 30, 1800, 30, Int("Rebuff With (seconds left)", s => s.RebuffSecondsRemaining, (s, v) => s.RebuffSecondsRemaining = v, 30, 1800, 30,
"Recast a self buff when its remaining duration drops below this value.\nDefault 300 (5 minutes). Lower values rebuff more eagerly."), "Recast a self buff when its remaining duration drops below this value.\nDefault 300 (5 minutes). Lower values rebuff more eagerly."),
@ -790,6 +898,8 @@ internal static class SettingsSchema
"Don't start on another corpse when no pack has a free slot (says so once in chat)."), "Don't start on another corpse when no pack has a free slot (says so once in chat)."),
Bool("Jump When Looting", s => s.LootJumpEnabled, (s, v) => s.LootJumpEnabled = v, gates: true), Bool("Jump When Looting", s => s.LootJumpEnabled, (s, v) => s.LootJumpEnabled = v, gates: true),
Int("Jump Height", s => s.LootJumpHeight, (s, v) => s.LootJumpHeight = v, 1, 100, 5, when: s => s.LootJumpEnabled), Int("Jump Height", s => s.LootJumpHeight, (s, v) => s.LootJumpHeight = v, 1, 100, 5, when: s => s.LootJumpEnabled),
Bool("Loot Items On Ground", s => s.EnableGroundLoot, (s, v) => s.EnableGroundLoot = v,
"Pick up loose items on the ground that match your loot profile, within Corpse Max range.\nCorpses always come first. Status and rescan: /ra groundloot."),
Spacer(), Spacer(),
Section("Corpse Ownership"), Section("Corpse Ownership"),
Combo("Loot From", LootOwnershipModes, s => s.LootOwnership, (s, v) => s.LootOwnership = v), Combo("Loot From", LootOwnershipModes, s => s.LootOwnership, (s, v) => s.LootOwnership = v),
@ -799,8 +909,6 @@ internal static class SettingsSchema
"After a death, walk back to where you died with RynthNav (outdoor deaths only),\nfighting on the way as usual, recover the corpse, then carry on. Needs the macro\nrunning and RynthNav loaded. /ra owncorpse stop cancels."), "After a death, walk back to where you died with RynthNav (outdoor deaths only),\nfighting on the way as usual, recover the corpse, then carry on. Needs the macro\nrunning and RynthNav loaded. /ra owncorpse stop cancels."),
Spacer(), Spacer(),
Section("Inventory Management"), Section("Inventory Management"),
Bool("Item Info On Select", s => s.ItemInfoOnSelect, (s, v) => s.ItemInfoOnSelect = v,
"Selecting an item prints its details to chat, Mag-Tools style (/ra iteminfo),\nidentifying it first when needed. Items the bot selects while looting are skipped."),
Bool("Enable Autostack", s => s.EnableAutostack, (s, v) => s.EnableAutostack = v), Bool("Enable Autostack", s => s.EnableAutostack, (s, v) => s.EnableAutostack = v),
Bool("Enable Autocram", s => s.EnableAutocram, (s, v) => s.EnableAutocram = v, Bool("Enable Autocram", s => s.EnableAutocram, (s, v) => s.EnableAutocram = v,
"Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack."), "Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack."),
@ -808,6 +916,8 @@ internal static class SettingsSchema
"After the salvage queue empties, move same-name bags together so the server merges them."), "After the salvage queue empties, move same-name bags together so the server merges them."),
Bool("Combine Bags During Salvage", s => s.CombineBagsDuringSalvage, (s, v) => s.CombineBagsDuringSalvage = v, Bool("Combine Bags During Salvage", s => s.CombineBagsDuringSalvage, (s, v) => s.CombineBagsDuringSalvage = v,
"When salvaging an item, also add any under-full salvage bag of the same material to the salvage panel."), "When salvaging an item, also add any under-full salvage bag of the same material to the salvage panel."),
Button("Floating HUDs", "Inventory HUDs...", () => RynthAiCommands.ApplyRemoteCommand("huds", "show"),
"Opens the item count HUD / Mini Remote setup window (/ra huds)."),
Spacer(), Spacer(),
Section("Loot Timers (ms)"), Section("Loot Timers (ms)"),
Int("Inter-Item Delay", s => s.LootInterItemDelayMs, (s, v) => s.LootInterItemDelayMs = v, 0, 5000, 25), Int("Inter-Item Delay", s => s.LootInterItemDelayMs, (s, v) => s.LootInterItemDelayMs = v, 0, 5000, 25),
@ -850,5 +960,24 @@ internal static class SettingsSchema
Spacer(), Spacer(),
Note("Never sold: equipped, attuned, bonded, retained, tinkered, imbued, inscribed, rare, zero value, packs, or anything a Keep rule could match."), Note("Never sold: equipped, attuned, bonded, retained, tinkered, imbued, inscribed, rare, zero value, packs, or anything a Keep rule could match."),
}), }),
new("Diagnostics", new[]
{
Section("Logging & Debugging"),
Bool("Debug to chat", s => s.DiagDebugToChat, (s, v) => s.DiagDebugToChat = v,
"Echo trace lines and errors from the categories ticked below into the chat window.\nAlso: /ra debug on|off."),
Bool("Daily RynthAi log file", s => s.DiagFileLogAll, (s, v) => s.DiagFileLogAll = v,
"Mirror every RynthAi log line to rynthai_<date>.txt in the log folder (kept 7 days).\nAlso: /ra logs file on|off."),
Button("Log Folder", "Open", () => RynthAiCommands.ApplyRemoteCommand("logs", "open"),
"Open RynthAi's Logs\\Diagnostics folder in Explorer (/ra logs open)."),
Button("Old Log Files", "Prune", () => RynthAiCommands.ApplyRemoteCommand("logs", "prune"),
"Delete diagnostics files past the retention limit now (/ra logs prune)."),
Spacer(),
Section("Trace Per Category"),
new SettingRow(SettingKind.TraceCategories, "Categories",
"Ticked categories write their trace lines to Trace\\<Category>_<date>.txt (/ra trace <category> on|off)."),
Note("+log = the category is at Info: its trace lines also go to the normal log. The launcher's Logging page sets Off, Trace or Info."),
Note("Exceptions always go to exceptions_<date>.txt with full stack traces (throttled). Settings here are for this PC, not the profile."),
}),
}; };
} }

View file

@ -16,6 +16,8 @@ internal static class UiSources
public static readonly TrackerSource Tracker = new(); public static readonly TrackerSource Tracker = new();
public static readonly RynthAiSource RynthAi = new(); public static readonly RynthAiSource RynthAi = new();
public static readonly PatrolSource Patrol = new(); public static readonly PatrolSource Patrol = new();
public static readonly ProgressionSource Progression = new();
public static readonly CharmsSource Charms = new();
public static readonly RadarSource Radar = new(); public static readonly RadarSource Radar = new();
public static readonly SettingsSource Settings = new(); public static readonly SettingsSource Settings = new();
public static readonly MetaSource Meta = new(); public static readonly MetaSource Meta = new();
@ -54,6 +56,8 @@ internal static class UiSources
UiDataHub.Register(Radar); UiDataHub.Register(Radar);
UiDataHub.Register(RynthAi); UiDataHub.Register(RynthAi);
UiDataHub.Register(Patrol); UiDataHub.Register(Patrol);
UiDataHub.Register(Progression);
UiDataHub.Register(Charms);
UiDataHub.Register(PluginStatus); UiDataHub.Register(PluginStatus);
UiDataHub.Register(Log); UiDataHub.Register(Log);
UiDataHub.Register(Tracker); UiDataHub.Register(Tracker);

View file

@ -207,7 +207,7 @@ internal sealed unsafe class LayeredWindow : IDisposable
[DllImport("user32.dll")] private static extern bool BringWindowToTop(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool BringWindowToTop(IntPtr hWnd);
private const uint GW_OWNER = 4; private const uint GW_OWNER = 4;
[DllImport("user32.dll")] private static extern bool ReleaseCapture(); [DllImport("user32.dll")] private static extern bool ReleaseCapture();
[DllImport("user32.dll")] private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", SetLastError = true)] private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")] private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach); [DllImport("user32.dll")] private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
[DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT lpPoint); [DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT lpPoint);
@ -275,15 +275,20 @@ internal sealed unsafe class LayeredWindow : IDisposable
/// DestroyWindow only works there. A window created on the overlay thread /// DestroyWindow only works there. A window created on the overlay thread
/// (not the game thread) could not be destroyed by a destroy posted to the /// (not the game thread) could not be destroyed by a destroy posted to the
/// game thread (ACCESS_DENIED) and stayed on screen: the double dashboard. /// game thread (ACCESS_DENIED) and stayed on screen: the double dashboard.
/// Must not collide with Win32Backend's game-window messages (0x8001-0x8005).
/// </summary> /// </summary>
private const uint WM_RYNTH_SELF_DESTROY = 0x8051; private const uint WM_RYNTH_SELF_DESTROY = 0x8051;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
private static IntPtr StaticWndProc(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam) private static IntPtr StaticWndProc(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam)
{ {
// Handled before the instance lookup: Dispose has already removed the
// instance by the time this posted message is dispatched.
if (msg == WM_RYNTH_SELF_DESTROY) if (msg == WM_RYNTH_SELF_DESTROY)
{ {
DestroyWindow(hwnd); bool destroyed = DestroyWindow(hwnd);
int err = destroyed ? 0 : Marshal.GetLastWin32Error();
RynthCore.Engine.RynthLog.Info($"LayeredWindow: self-destroy DestroyWindow(0x{hwnd.ToInt64():X}) = {destroyed} err={err} on thread=0x{GetCurrentThreadId():X}.");
return IntPtr.Zero; return IntPtr.Zero;
} }
@ -317,12 +322,11 @@ internal sealed unsafe class LayeredWindow : IDisposable
/// FloatingPanelHost's RunOnGameThread) and DestroyWindow only works on /// FloatingPanelHost's RunOnGameThread) and DestroyWindow only works on
/// the owning thread. /// the owning thread.
/// ///
/// Dispose only posts the destroy, and Win32Backend.Shutdown unhooks the /// Synchronous backstop for panels that were never disposed: because the
/// game WndProc ~1 ms after the overlay stops — usually before the game /// engine module is never unloaded, such a panel lives on after shutdown,
/// thread gets to the post. AC's own WndProc then drops it, and because /// frozen on its last frame, deaf to input, and hidden under the next
/// the engine module is never unloaded the panel lives on: frozen on its /// generation's copy of it until that one is moved ("two RynthAi windows").
/// last frame, deaf to input, and hidden under the next generation's copy /// (Disposed panels destroy themselves via WM_RYNTH_SELF_DESTROY.)
/// of it until that one is moved ("two RynthAi windows").
/// ///
/// <paramref name="includeThisGeneration"/>=false spares this engine /// <paramref name="includeThisGeneration"/>=false spares this engine
/// load's own windows (class names carry a per-load Guid) and removes only /// load's own windows (class names carry a per-load Guid) and removes only
@ -367,6 +371,25 @@ internal sealed unsafe class LayeredWindow : IDisposable
} }
} }
/// <summary>
/// The content rects (screen px: left, top, width, height) of every visible panel window.
/// They sit above the game window, so nothing drawn in the game frame can show over them.
/// </summary>
internal static List<(int Left, int Top, int Width, int Height)> VisibleContentRects()
{
LayeredWindow[] windows;
lock (_instancesLock)
{
windows = new LayeredWindow[_instances.Count];
_instances.Values.CopyTo(windows, 0);
}
var rects = new List<(int, int, int, int)>(windows.Length);
foreach (LayeredWindow w in windows)
if (w.IsVisible && w.Width > 0 && w.Height > 0)
rects.Add((w.ScreenLeft, w.ScreenTop, w.Width, w.Height));
return rects;
}
private static readonly HashSet<IntPtr> _sweptLogged = new(); private static readonly HashSet<IntPtr> _sweptLogged = new();
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
@ -1526,4 +1549,43 @@ internal sealed unsafe class LayeredWindow : IDisposable
RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: destroy fallback threw {ex.GetType().Name}: {ex.Message}."); RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: destroy fallback threw {ex.GetType().Name}: {ex.Message}.");
} }
} }
/// <summary>
/// Destroys <paramref name="hwnd"/> on the thread that actually owns it, never
/// blocking the caller. Inline when the caller is the owner; otherwise posts
/// WM_RYNTH_SELF_DESTROY to the window itself so its own WndProc destroys it.
/// Posting to the panel (not the game window) works for panels created on
/// any thread, and still works after Win32Backend has unhooked the game
/// WndProc at shutdown — a post to the game window would be dropped by AC.
/// </summary>
private static void DestroyOnOwnerThread(IntPtr hwnd)
{
uint ownerThread = GetWindowThreadProcessId(hwnd, out _);
uint currentThread = GetCurrentThreadId();
if (ownerThread == 0)
{
// Window already gone (e.g. its owning thread exited, which destroys it).
RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: HWND=0x{hwnd.ToInt64():X} no longer exists — nothing to destroy.");
return;
}
if (ownerThread == currentThread)
{
bool destroyed = DestroyWindow(hwnd);
int err = destroyed ? 0 : Marshal.GetLastWin32Error();
RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: DestroyWindow(0x{hwnd.ToInt64():X}) inline on owner thread=0x{currentThread:X} = {destroyed} err={err}.");
return;
}
if (PostMessage(hwnd, WM_RYNTH_SELF_DESTROY, IntPtr.Zero, IntPtr.Zero))
{
RynthCore.Engine.RynthLog.Info($"LayeredWindow.Dispose: posted self-destroy to HWND=0x{hwnd.ToInt64():X} (owner thread=0x{ownerThread:X}, caller thread=0x{currentThread:X}).");
return;
}
// Post failed (queue full or HWND destroyed in the meantime); a cross-thread
// DestroyWindow would only fail, so report it rather than attempt it.
RynthCore.Engine.RynthLog.Error($"LayeredWindow.Dispose: PostMessage(self-destroy) to HWND=0x{hwnd.ToInt64():X} failed err={Marshal.GetLastWin32Error()} (owner thread=0x{ownerThread:X}).");
}
} }

View file

@ -0,0 +1,72 @@
// ============================================================================
// RynthCore.Engine - UI/OverlayFrameBuffer.cs
// Lock-minimised pixel handoff from the Avalonia UI thread to the D3D9
// render thread. Avalonia submits a captured BGRA frame; EndScene consumes
// it once, uploads to a D3D9 texture, then re-uses that texture until the
// next submit.
//
// Thread model:
// Writer: Avalonia STA thread (DispatcherTimer ~30 fps)
// Reader: D3D9 render thread (EndScene ~60 fps)
//
// The submitted buffer is replaced atomically (pointer swap). The reader
// holds a reference for the duration of the upload, preventing GC collection
// even if the writer has already posted a newer frame.
// ============================================================================
using System;
using System.Threading;
namespace RynthCore.Engine.UI;
internal static class OverlayFrameBuffer
{
private sealed class Frame
{
public readonly byte[] Pixels;
public readonly int Width;
public readonly int Height;
public Frame(byte[] pixels, int w, int h)
{
Pixels = pixels;
Width = w;
Height = h;
}
}
// Written by Avalonia thread, read by D3D9 thread.
// Interlocked.Exchange gives the sequential-consistency guarantee we need.
private static Frame? _pending;
/// <summary>
/// Submit a new BGRA frame from the Avalonia UI thread.
/// The pixel array is copied so the caller can reuse its bitmap lock buffer.
/// </summary>
public static void Submit(IntPtr pixelData, int byteCount, int w, int h)
{
var buf = new byte[byteCount];
System.Runtime.InteropServices.Marshal.Copy(pixelData, buf, 0, byteCount);
Interlocked.Exchange(ref _pending, new Frame(buf, w, h));
}
/// <summary>
/// Consume the latest pending frame from the D3D9 render thread.
/// Returns true if a new frame is available; the caller owns the byte array
/// until the next call (no further synchronisation required).
/// </summary>
public static bool TryConsume(out byte[]? pixels, out int w, out int h)
{
Frame? frame = Interlocked.Exchange(ref _pending, null);
if (frame == null)
{
pixels = null; w = 0; h = 0;
return false;
}
pixels = frame.Pixels;
w = frame.Width;
h = frame.Height;
return true;
}
}

View file

@ -2,8 +2,9 @@
// RynthCore.Engine — UI/Panels/ItemsPanel.cs // RynthCore.Engine — UI/Panels/ItemsPanel.cs
// Avalonia replica of the ImGui Items tab (LegacyWeaponsUi.cs). // Avalonia replica of the ImGui Items tab (LegacyWeaponsUi.cs).
// //
// Three sections: // Four sections:
// Weapons — Name, Element picker, Delete // Weapons — Name, Element picker, Delete (ItemRules with Action != "Shield")
// Shields — Auto-equip toggle, Name, Delete (ItemRules with Action == "Shield")
// Consumables — Name, Type picker, Delete // Consumables — Name, Type picker, Delete
// Mana Stones — Enable tapping toggle, keep count, min mana threshold // Mana Stones — Enable tapping toggle, keep count, min mana threshold
// //
@ -67,6 +68,8 @@ internal static class ItemsPanel
/// it when the payload is saved back. /// it when the payload is saved back.
/// </summary> /// </summary>
[JsonPropertyName("missingIds")] public List<int> MissingIds { get; set; } = new(); [JsonPropertyName("missingIds")] public List<int> MissingIds { get; set; } = new();
// Null when the plugin predates shields (RynthAi < 0.6.20); the plugin then ignores it on write-back.
[JsonPropertyName("autoEquipShield")] public bool? AutoEquipShield { get; set; }
} }
internal sealed class WeaponEntry internal sealed class WeaponEntry
@ -74,6 +77,10 @@ internal static class ItemsPanel
[JsonPropertyName("id")] public int Id { get; set; } [JsonPropertyName("id")] public int Id { get; set; }
[JsonPropertyName("name")] public string Name { get; set; } = string.Empty; [JsonPropertyName("name")] public string Name { get; set; } = string.Empty;
[JsonPropertyName("element")] public string Element { get; set; } = "Slash"; [JsonPropertyName("element")] public string Element { get; set; } = "Slash";
// "Weapon" or "Shield" (older settings may hold "Loot"). Round-tripped untouched.
[JsonPropertyName("action")] public string Action { get; set; } = "Weapon";
public bool IsShield => string.Equals(Action, ItemsCommands.ShieldAction, StringComparison.OrdinalIgnoreCase);
} }
internal sealed class ConsumableEntry internal sealed class ConsumableEntry
@ -212,29 +219,33 @@ internal static class ItemsPanel
{ {
body.Children.Clear(); body.Children.Clear();
// Weapons and shields share the plugin's ItemRules list (state.Data.Weapons);
// rows are split by Action, so deletes remove by reference, not by index.
void DeleteItem(WeaponEntry entry)
{
state.Data.Weapons.Remove(entry);
state.Dirty = true;
PushChanges(state);
Refresh();
}
// ── Weapons ────────────────────────────────────────────────────── // ── Weapons ──────────────────────────────────────────────────────
body.Children.Add(BuildSectionHeader("Weapons")); body.Children.Add(BuildSectionHeader("Weapons"));
if (state.Data.Weapons.Count == 0) var weapons = state.Data.Weapons.Where(w => !w.IsShield).ToList();
if (weapons.Count == 0)
{ {
body.Children.Add(BuildEmptyRow("No weapons configured")); body.Children.Add(BuildEmptyRow("No weapons configured"));
} }
else else
{ {
body.Children.Add(BuildTableHeader(new[] { "Item Name", "Element", "" }, new[] { true, false, false }, new double[] { 0, 100, 46 })); body.Children.Add(BuildTableHeader(new[] { "Item Name", "Element", "" }, new[] { true, false, false }, new double[] { 0, 100, 46 }));
for (int i = 0; i < state.Data.Weapons.Count; i++) for (int i = 0; i < weapons.Count; i++)
{ {
var w = state.Data.Weapons[i]; var w = weapons[i];
int wi = i; body.Children.Add(BuildWeaponRow(w, i % 2 == 0, ShowPicker,
body.Children.Add(BuildWeaponRow(w, wi % 2 == 0, ShowPicker,
onChanged: () => { state.Dirty = true; PushChanges(state); }, onChanged: () => { state.Dirty = true; PushChanges(state); },
onDelete: () => onDelete: () => DeleteItem(w)));
{
state.Data.Weapons.RemoveAt(wi);
state.Dirty = true;
PushChanges(state);
Refresh();
}));
} }
} }
@ -243,6 +254,45 @@ internal static class ItemsPanel
body.Children.Add(BuildDivider()); body.Children.Add(BuildDivider());
// ── Shields (off-hand) ───────────────────────────────────────────
body.Children.Add(BuildSectionHeader("Shields (off-hand)"));
// Plugins older than RynthAi 0.6.20 don't report the setting — hide the toggle then.
if (state.Data.AutoEquipShield is bool autoEquip)
{
body.Children.Add(BuildToggleRow("Auto-equip with one-handed melee weapons", autoEquip,
"On: in melee with a one-handed weapon, combat wields the first shield below unless the monster has its own off-hand (Damage panel or Monsters 'Offhand').\n" +
"Off: only per-monster off-hand choices are equipped.\n" +
"Never used with two-handed weapons, bows, crossbows, atlatls or casters.",
on =>
{
state.Data.AutoEquipShield = on;
state.Dirty = true;
PushChanges(state);
Refresh();
}));
}
var shields = state.Data.Weapons.Where(w => w.IsShield).ToList();
if (shields.Count == 0)
{
body.Children.Add(BuildEmptyRow("No shields configured"));
}
else
{
body.Children.Add(BuildTableHeader(new[] { "Shield Name", "" }, new[] { true, false }, new double[] { 0, 46 }));
for (int i = 0; i < shields.Count; i++)
{
var s = shields[i];
body.Children.Add(BuildShieldRow(s, i % 2 == 0, onDelete: () => DeleteItem(s)));
}
}
body.Children.Add(BuildAddButton("Add Selected Shield", "(select a shield in inventory first)",
ItemsCommands.AddSelectedShield));
body.Children.Add(BuildDivider());
// ── Consumables ────────────────────────────────────────────────── // ── Consumables ──────────────────────────────────────────────────
body.Children.Add(BuildSectionHeader("Consumable Items")); body.Children.Add(BuildSectionHeader("Consumable Items"));
@ -296,7 +346,8 @@ internal static class ItemsPanel
bool consumablesChanged = ConsumablesChanged(state.Data.Consumables, fresh.Consumables); bool consumablesChanged = ConsumablesChanged(state.Data.Consumables, fresh.Consumables);
bool manaChanged = state.Data.EnableManaTapping != fresh.EnableManaTapping bool manaChanged = state.Data.EnableManaTapping != fresh.EnableManaTapping
|| state.Data.ManaTapMinMana != fresh.ManaTapMinMana || state.Data.ManaTapMinMana != fresh.ManaTapMinMana
|| state.Data.ManaStoneKeepCount != fresh.ManaStoneKeepCount; || state.Data.ManaStoneKeepCount != fresh.ManaStoneKeepCount
|| state.Data.AutoEquipShield != fresh.AutoEquipShield;
// UI deep-dive finding P0-4 (2026-07-02): state.Data = fresh used // UI deep-dive finding P0-4 (2026-07-02): state.Data = fresh used
// to run unconditionally, EVERY poll tick, even when the // to run unconditionally, EVERY poll tick, even when the
@ -515,6 +566,80 @@ internal static class ItemsPanel
return grid; return grid;
} }
// ── Shield table row (name + delete; shields have no element) ─────────────
private static Control BuildShieldRow(WeaponEntry s, bool alt, Action onDelete)
{
var grid = new Grid
{
Background = alt ? ColRowAlt : ColPanelBg,
Height = 24,
ColumnDefinitions = new ColumnDefinitions("*, 46"),
};
var nameTb = new TextBlock
{
Text = s.Name,
Foreground = ColTextDim,
FontSize = 10,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(6, 0),
TextTrimming = TextTrimming.CharacterEllipsis,
};
Grid.SetColumn(nameTb, 0);
grid.Children.Add(nameTb);
var del = new Button
{
Content = "Del",
Background = ColBtnFill,
Foreground = ColRed,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
Padding = new Thickness(4, 2),
FontSize = 10,
Margin = new Thickness(2, 2),
};
del.Click += (_, _) => onDelete();
Grid.SetColumn(del, 1);
grid.Children.Add(del);
return grid;
}
// ── Labelled ON/OFF toggle row (same look as the mana-tapping toggle) ─────
private static Control BuildToggleRow(string label, bool value, string tooltip, Action<bool> onToggled)
{
var row = new WrapPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(4, 4, 4, 2) };
var btn = new Button
{
Content = value ? "ON" : "OFF",
Background = value ? new SolidColorBrush(Color.FromRgb(0x10, 0x40, 0x10)) : ColBtnFill,
Foreground = value ? new SolidColorBrush(Color.FromRgb(0x33, 0xFF, 0x33)) : ColMute,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
Padding = new Thickness(8, 2),
FontSize = 10,
Width = 50,
Margin = new Thickness(0, 0, 8, 0),
};
btn.Click += (_, _) => onToggled(!value);
ToolTip.SetTip(btn, tooltip);
row.Children.Add(btn);
var lbl = new TextBlock
{
Text = label,
Foreground = ColTextDim,
FontSize = 10,
VerticalAlignment = VerticalAlignment.Center,
};
ToolTip.SetTip(lbl, tooltip);
row.Children.Add(lbl);
return row;
}
// ── Consumable table row ────────────────────────────────────────────────── // ── Consumable table row ──────────────────────────────────────────────────
private static Control BuildConsumableRow( private static Control BuildConsumableRow(
ConsumableEntry c, bool alt, ConsumableEntry c, bool alt,
@ -745,7 +870,8 @@ internal static class ItemsPanel
{ {
if (a.Count != b.Count) return true; if (a.Count != b.Count) return true;
for (int i = 0; i < a.Count; i++) for (int i = 0; i < a.Count; i++)
if (a[i].Id != b[i].Id || a[i].Name != b[i].Name || a[i].Element != b[i].Element) return true; if (a[i].Id != b[i].Id || a[i].Name != b[i].Name || a[i].Element != b[i].Element
|| !string.Equals(a[i].Action, b[i].Action, StringComparison.OrdinalIgnoreCase)) return true;
return false; return false;
} }

View file

@ -171,9 +171,29 @@ internal static class NavPanel
{ e.Handled = true; picker.Close(); } { e.Handled = true; picker.Close(); }
}; };
// Waypoint list controls live for the panel's lifetime. Rebuild() only refills
// waypointStack: a ScrollViewer recreated (or given a new Content) resets its
// offset to the top, which made the list jump back every poll and impossible to edit.
var waypointStack = new StackPanel { Spacing = 1 };
var waypointScroll = new ScrollViewer
{
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
Content = waypointStack,
};
var waypointHost = new Border { Height = 200, Child = waypointScroll };
// Last plugin JSON the panel was built from. A rebuild from a user action
// (optimistic local edit) clears it so the next poll always resyncs with the plugin.
string lastJson = string.Empty;
bool rebuildFromPoll = false;
void Rebuild() void Rebuild()
{ {
if (!rebuildFromPoll) lastJson = string.Empty;
Vector keepOffset = waypointScroll.Offset;
content.Children.Clear(); content.Children.Clear();
waypointStack.Children.Clear();
var d = state.Data; var d = state.Data;
bool navActive = d.MacroRunning && d.NavigationEnabled; bool navActive = d.MacroRunning && d.NavigationEnabled;
@ -439,7 +459,6 @@ internal static class NavPanel
FontSize = 10, FontSize = 10,
}); });
var waypointStack = new StackPanel { Spacing = 1 };
for (int i = 0; i < d.Points.Count; i++) for (int i = 0; i < d.Points.Count; i++)
{ {
int ci = i; int ci = i;
@ -516,16 +535,10 @@ internal static class NavPanel
waypointStack.Children.Add(row); waypointStack.Children.Add(row);
} }
content.Children.Add(new Border content.Children.Add(waypointHost); // same instance every rebuild — keeps scroll offset
{ // Re-apply after layout too: the re-attach / new row extent can coerce it to 0.
Height = 200, waypointScroll.Offset = keepOffset;
Child = new ScrollViewer Dispatcher.UIThread.Post(() => waypointScroll.Offset = keepOffset, DispatcherPriority.Loaded);
{
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
Content = waypointStack,
},
});
} }
// ── Poll timer ──────────────────────────────────────────────────────── // ── Poll timer ────────────────────────────────────────────────────────
@ -536,6 +549,9 @@ internal static class NavPanel
timer.Tick += (_, _) => timer.Tick += (_, _) =>
{ {
if (picker.ActivePicker != null || state.Typing) return; if (picker.ActivePicker != null || state.Typing) return;
// A rebuild between press and release eats the click on X / row select. seenVersion
// is left alone, so the change is picked up once the pointer leaves the list.
if (waypointHost.IsPointerOver) return;
var snap = UiSources.Nav.Current; var snap = UiSources.Nav.Current;
if (snap == null || snap.Version == seenVersion) return; if (snap == null || snap.Version == seenVersion) return;
seenVersion = snap.Version; seenVersion = snap.Version;

View file

@ -558,7 +558,7 @@ internal static partial class RynthAiPanel
var launcherGrid = new Grid var launcherGrid = new Grid
{ {
ColumnDefinitions = new ColumnDefinitions("*,*,*"), ColumnDefinitions = new ColumnDefinitions("*,*,*"),
RowDefinitions = new RowDefinitions("Auto,Auto"), RowDefinitions = new RowDefinitions("Auto,Auto,Auto"),
Margin = new Thickness(0, 4, 0, 0) Margin = new Thickness(0, 4, 0, 0)
}; };
AddSplitLauncher(launcherGrid, 0, 0, "Meta", "⚙", "Lua", "<>", AddSplitLauncher(launcherGrid, 0, 0, "Meta", "⚙", "Lua", "<>",
@ -567,8 +567,15 @@ internal static partial class RynthAiPanel
AddMonstersLauncher(launcherGrid, 0, 1); AddMonstersLauncher(launcherGrid, 0, 1);
AddLauncher(launcherGrid, 0, 2, "Settings", "⚒", AddLauncher(launcherGrid, 0, 2, "Settings", "⚒",
onClick: () => PanelRouter.Toggle("Settings")); onClick: () => PanelRouter.Toggle("Settings"));
AddSplitLauncher(launcherGrid, 1, 0, "Nav", "➤", "Map", "🗺", // Map: RynthAi's dungeon map is an ImGui overlay window; the right half toggles it like "/ra map".
onLeftClick: () => PanelRouter.Toggle("Nav")); var (_, mapBtn) = AddSplitLauncher(launcherGrid, 1, 0, "Nav", "➤", "Map", "🗺",
onLeftClick: () => PanelRouter.Toggle("Nav"),
onRightClick: () =>
{
ClosePicker();
RynthAiCommands.ApplyRemoteCommand("map", "toggle");
});
ToolTip.SetTip(mapBtn, "Show/hide the dungeon map (/ra map). It appears when you are indoors.");
AddLauncher(launcherGrid, 1, 1, "Items", "🛡", AddLauncher(launcherGrid, 1, 1, "Items", "🛡",
onClick: () => PanelRouter.Toggle("Items")); onClick: () => PanelRouter.Toggle("Items"));
var patrolBtn = AddLauncher(launcherGrid, 1, 2, "Patrol", "⬡", var patrolBtn = AddLauncher(launcherGrid, 1, 2, "Patrol", "⬡",
@ -583,6 +590,33 @@ internal static partial class RynthAiPanel
ShowPatrolFlyout(patrolBtn); ShowPatrolFlyout(patrolBtn);
} }
}; };
// Char: same as typing "/ra hub show". The ILT Hub is an ImGui overlay window with no
// Avalonia panel, so this is the panel's way to open it.
var charBtn = AddLauncher(launcherGrid, 2, 0, "Char", "♥",
onClick: () =>
{
ClosePicker();
RynthAiCommands.ApplyRemoteCommand("hub", "show");
});
ToolTip.SetTip(charBtn, "Open the character hub (ILT Hub) window (/ra hub show).");
// Hub: the Mini Remote and the Inventory HUDs setup are ImGui windows inside RynthAi.
var hudBtn = AddLauncher(launcherGrid, 2, 1, "Hub", "▣",
onClick: () =>
{
ClosePicker();
RynthAiCommands.ApplyRemoteCommand("remote", "toggle");
});
ToolTip.SetTip(hudBtn, "Left-click: show/hide the Mini Remote (/ra remote). Right-click: Inventory HUDs setup (/ra huds).");
hudBtn.PointerPressed += (_, e) =>
{
if (e.GetCurrentPoint(hudBtn).Properties.IsRightButtonPressed)
{
e.Handled = true;
ClosePicker();
RynthAiCommands.ApplyRemoteCommand("huds", "show");
}
};
dash.Children.Add(launcherGrid); dash.Children.Add(launcherGrid);
@ -1201,16 +1235,18 @@ internal static partial class RynthAiPanel
/// by side. Used for Nav | Map so the user can pop the navigation panel /// by side. Used for Nav | Map so the user can pop the navigation panel
/// or the dungeon map independently from the same row slot. /// or the dungeon map independently from the same row slot.
/// </summary> /// </summary>
private static void AddSplitLauncher(Grid grid, int row, int col, /// <returns>The left and right half buttons (e.g. for tooltips).</returns>
private static (Button Left, Button Right) AddSplitLauncher(Grid grid, int row, int col,
string leftLabel, string leftIcon, string rightLabel, string rightIcon, string leftLabel, string leftIcon, string rightLabel, string rightIcon,
Action? onLeftClick = null, Action? onRightClick = null) Action? onLeftClick = null, Action? onRightClick = null)
{ {
var splitGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*") }; var splitGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*") };
AddLauncher(splitGrid, 0, 0, leftLabel, leftIcon, onLeftClick); var left = AddLauncher(splitGrid, 0, 0, leftLabel, leftIcon, onLeftClick);
AddLauncher(splitGrid, 0, 1, rightLabel, rightIcon, onRightClick); var right = AddLauncher(splitGrid, 0, 1, rightLabel, rightIcon, onRightClick);
grid.Children.Add(splitGrid); grid.Children.Add(splitGrid);
Grid.SetRow(splitGrid, row); Grid.SetRow(splitGrid, row);
Grid.SetColumn(splitGrid, col); Grid.SetColumn(splitGrid, col);
return (left, right);
} }
private static Button AddLauncher(Grid grid, int row, int col, string label, string icon, Action? onClick = null) private static Button AddLauncher(Grid grid, int row, int col, string label, string icon, Action? onClick = null)

View file

@ -6,7 +6,10 @@
// //
// Rule semantics (the rules live in ChatModel, UI/Data/ChatData.cs; the ImGui // Rule semantics (the rules live in ChatModel, UI/Data/ChatData.cs; the ImGui
// face is ImGui/Panels/ChatFiltersFace.cs): // face is ImGui/Panels/ChatFiltersFace.cs):
// • Regex, case-insensitive, matched against the formatted line. // • Regex, or plain text Contains / Starts with / Ends with (the mode
// button), case-insensitive.
// • Standard filters (RynthChatPresets) below the rules apply only to
// lines no rule moved or hid.
// • FIRST matching rule wins — order matters, hence the ▲▼ buttons. // • FIRST matching rule wins — order matters, hence the ▲▼ buttons.
// • Tab name set → matching lines MOVE to that tab (and leave All). // • Tab name set → matching lines MOVE to that tab (and leave All).
// • Tab name empty → matching lines are hidden everywhere. // • Tab name empty → matching lines are hidden everywhere.
@ -95,10 +98,24 @@ internal static class RynthChatFiltersPanel
ChatModel.FiltersChanged(); ChatModel.FiltersChanged();
}; };
// Click-to-cycle (no ComboBox: the overlay's popup hosting is unreliable).
var modeBtn = new Button
{
Content = ModeLabels[(int)r.Mode],
FontSize = 10,
Width = 62,
Padding = new Thickness(4, 2),
Background = ButtonBg,
Foreground = Brushes.White,
BorderThickness = new Thickness(0),
VerticalAlignment = VerticalAlignment.Center,
};
ToolTip.SetTip(modeBtn, "How the text is matched: Regex, or plain text Contains / Starts with / Ends with.");
var patternBox = new TextBox var patternBox = new TextBox
{ {
Text = r.Pattern, Text = r.Pattern,
Watermark = "regex (e.g. AutoRun)", Watermark = PatternWatermark(r.Mode),
FontSize = 10, FontSize = 10,
MinWidth = 220, MinWidth = 220,
Height = 24, Height = 24,
@ -118,6 +135,15 @@ internal static class RynthChatFiltersPanel
patternBox.BorderBrush = r.Invalid ? Brushes.IndianRed : FieldBorder; patternBox.BorderBrush = r.Invalid ? Brushes.IndianRed : FieldBorder;
ChatModel.FiltersChanged(); ChatModel.FiltersChanged();
}; };
modeBtn.Click += (_, _) =>
{
r.Mode = (ChatMatchMode)(((int)r.Mode + 1) % ModeLabels.Length);
r.Recompile();
modeBtn.Content = ModeLabels[(int)r.Mode];
patternBox.Watermark = PatternWatermark(r.Mode);
patternBox.BorderBrush = r.Invalid ? Brushes.IndianRed : FieldBorder;
ChatModel.FiltersChanged();
};
var tabBox = new TextBox var tabBox = new TextBox
{ {
@ -180,7 +206,7 @@ internal static class RynthChatFiltersPanel
{ {
Orientation = Orientation.Horizontal, Orientation = Orientation.Horizontal,
Spacing = 4, Spacing = 4,
Children = { enabledCheck, patternBox, tabBox, upBtn, downBtn, delBtn }, Children = { enabledCheck, modeBtn, patternBox, tabBox, upBtn, downBtn, delBtn },
}); });
} }
@ -194,6 +220,80 @@ internal static class RynthChatFiltersPanel
Margin = new Thickness(2, 6), Margin = new Thickness(2, 6),
}); });
} }
AddStandardFilters();
}
// Canned UB-IT-style filters (RynthChatPresets), checked after the rules above.
void AddStandardFilters()
{
rows.Children.Add(new TextBlock
{
Text = "Standard filters — tick to hide; type a tab to move the lines there instead.",
FontSize = 10,
FontWeight = FontWeight.Bold,
Foreground = Brushes.White,
Margin = new Thickness(2, 10, 2, 2),
});
foreach (string group in RynthChatPresets.Groups)
{
rows.Children.Add(new TextBlock
{
Text = group,
FontSize = 10,
Foreground = Brushes.LightSteelBlue,
Margin = new Thickness(2, 6, 2, 0),
});
foreach (var p in RynthChatPresets.All.Where(p => p.Group == group))
rows.Children.Add(PresetRow(p));
}
}
Control PresetRow(RynthChatPresets.Preset p)
{
var check = new CheckBox
{
IsChecked = p.Enabled,
Content = new TextBlock { Text = p.Label, FontSize = 10, Foreground = Brushes.White },
VerticalAlignment = VerticalAlignment.Center,
MinWidth = 220,
};
ToolTip.SetTip(check, $"{p.Description}\nExample: {p.Example}");
check.IsCheckedChanged += (_, _) =>
{
p.Enabled = check.IsChecked == true;
ChatModel.FiltersChanged();
};
var tabBox = new TextBox
{
Text = p.Tab,
Watermark = "tab (empty = hide)",
FontSize = 10,
Width = 120,
Height = 24,
Background = FieldBg,
Foreground = Brushes.White,
BorderBrush = FieldBorder,
BorderThickness = new Thickness(1),
};
ScrollViewer.SetHorizontalScrollBarVisibility(tabBox, ScrollBarVisibility.Disabled);
ScrollViewer.SetVerticalScrollBarVisibility(tabBox, ScrollBarVisibility.Disabled);
tabBox.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true;
tabBox.LostFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = false;
tabBox.TextChanged += (_, _) =>
{
p.Tab = (tabBox.Text ?? "").Trim();
ChatModel.FiltersChanged();
};
return new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 4,
Margin = new Thickness(8, 0, 0, 0),
Children = { check, tabBox },
};
} }
addBtn.Click += (_, _) => addBtn.Click += (_, _) =>
@ -224,4 +324,15 @@ internal static class RynthChatFiltersPanel
RebuildRows(); RebuildRows();
return layout; return layout;
} }
/// <summary>Button captions, indexed by <see cref="ChatMatchMode"/>.</summary>
private static readonly string[] ModeLabels = { "Regex", "Contains", "Starts", "Ends" };
private static string PatternWatermark(ChatMatchMode mode) => mode switch
{
ChatMatchMode.Contains => "text anywhere in the line",
ChatMatchMode.StartsWith => "line starts with...",
ChatMatchMode.EndsWith => "line ends with...",
_ => "regex (e.g. AutoRun)",
};
} }

View file

@ -0,0 +1,250 @@
// ============================================================================
// RynthCore.Engine — UI/Panels/RynthChatPresets.cs
// Canned ("standard") RynthChat filters, modelled on UtilityBelt-IT's
// ChatFilter / Mag ChatFilter categories. Each preset is a tick-box in the
// ChatFilters panel that hides its lines or moves them to a tab.
//
// Presets match the raw line text (no timestamp / sender prefix). Most are
// limited to non-chat channels so a player typing the same words in Local or
// a channel is never eaten. ChatRouter evaluates them on the plugin pump
// (after the custom rules); editors change Enabled / Tab from any thread and
// then call ChatModel.FiltersChanged so every kept line is routed again.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace RynthCore.Engine.UI.Panels;
internal static class RynthChatPresets
{
/// <summary>Which RynthChat channels a preset may match.</summary>
internal enum Scope
{
/// <summary>Anything except Chat / Channels (player-typed text).</summary>
NotPlayerChat,
/// <summary>Only the Combat channel (spell incantations arrive as chat type 0x11 → Combat).</summary>
CombatOnly,
/// <summary>Only the Channels tab (General / Trade / LFG / Roleplay / Society).</summary>
ChannelsOnly,
/// <summary>Every channel.</summary>
Any,
}
internal sealed class Preset
{
internal string Id { get; }
internal string Group { get; }
internal string Label { get; }
internal string Description { get; }
internal string Example { get; }
internal Scope Where { get; }
internal Regex Pattern { get; }
// User state (persisted in rynthchat_settings.json "presets" by ChatModel).
// Volatile: written by an editor, read by the pump's router.
internal volatile bool Enabled;
internal volatile string Tab = ""; // "" = hide matching lines
internal Preset(string id, string group, string label, string description, string example, Scope where, string pattern)
{
Id = id;
Group = group;
Label = label;
Description = description;
Example = example;
Where = where;
Pattern = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(50));
}
/// <summary>True when this preset applies to a line on <paramref name="channel"/> with raw <paramref name="text"/>.</summary>
internal bool Matches(string text, string channel)
{
bool inScope = Where switch
{
Scope.NotPlayerChat => channel is not ("Chat" or "Channels"),
Scope.CombatOnly => channel == "Combat",
Scope.ChannelsOnly => channel == "Channels",
_ => true,
};
if (!inScope) return false;
try { return Pattern.IsMatch(text); }
catch (RegexMatchTimeoutException) { return false; }
}
}
// Kill flavour text (retail/ACE death messages). Damage lines ("... for N points of ...")
// share some verbs, so they are excluded up front.
private const string KillPattern =
@"^(?!.* for \d+ points? of )(?:" +
@"You (?:flatten|knock|split|cleave|slay|bring|beat|run|suffocate|smite|killed) .+!" +
@"|.+ is (?:reduced to cinders|torn to ribbons by your assault|shattered by your assault|incinerated by your assault|liquified by your attack|dessicated by your attack)!" +
@"|.+ catches your attack, with dire consequences!" +
@"|.+'s (?:seared corpse smolders before you|last strength dissolves before you)!" +
@"|Electricity tears .+ apart!|Blistered by lightning, .+ falls!" +
@"|Your killing blow nearly turns .+ inside-out!|The thunder of crushing .+ is followed by the deafening silence of death!" +
@"|Your attack stops .+ cold!)";
// Optional combat prefixes such as "Critical hit! " / "Sneak Attack! ".
private const string HitPrefix = @"^(?:[A-Z][\w ]{2,20}! )*";
private static readonly Preset[] _all =
{
// ── Combat ────────────────────────────────────────────────────────
new("combat.attack_evades", "Combat", "Your attacks evaded",
"A monster evades your melee or missile attack.",
"Drudge Slinker evaded your attack.", Scope.NotPlayerChat, @" evaded your attack\.\s*$"),
new("combat.defense_evades", "Combat", "You evade attacks",
"You evade a monster's attack.",
"You evaded Drudge Slinker!", Scope.NotPlayerChat, @"^You evaded "),
new("combat.damage_dealt", "Combat", "Damage you deal",
"Your melee, missile and war-spell hits (including critical / sneak attack prefixes).",
"You slash Drudge Slinker for 54 points of slashing damage!", Scope.NotPlayerChat, HitPrefix + @"You .+ for \d+ points? of "),
new("combat.damage_taken", "Combat", "Damage you take",
"Monster hits and spell damage landing on you.",
"Drudge Slinker slashes you for 12 points of slashing damage!", Scope.NotPlayerChat, HitPrefix + @"(?!You ).+ you (?:with .+ )?for \d+ points? of "),
new("combat.attack_resists", "Combat", "Your spells resisted",
"A target resists one of your spells.",
"Drudge Slinker resists your spell", Scope.NotPlayerChat, @" resists your spell"),
new("combat.defense_resists", "Combat", "You resist spells",
"You resist a spell, or a caster was out of range / had no valid target.",
"You resist the spell cast by Drudge Sorcerer", Scope.NotPlayerChat,
@"^You resist the spell cast by |^You have no appropriate target.*spell|^You are an invalid target for the spell|tried to cast a spell on you, but was too far away!"),
new("combat.npk", "Combat", "Not-a-PK failures",
"\"You fail to affect X, you are not a player killer!\" and the mirror message.",
"You fail to affect Bob because you are not a player killer!", Scope.NotPlayerChat,
@"^You fail to affect .+ you are not a player killer!|fails to affect you.+ is not a player killer!"),
new("combat.dirty_fighting", "Combat", "Dirty Fighting procs",
"Dirty Fighting assault announcements.",
"Dirty Fighting! Bob delivers a Traumatic Assault to Drudge!", Scope.NotPlayerChat, @"^Dirty Fighting! .+ delivers a "),
new("combat.monster_deaths", "Combat", "Monster death messages",
"Kill flavour text (\"You flatten…\", \"…is reduced to cinders!\").",
"Drudge Slinker is reduced to cinders!", Scope.NotPlayerChat, KillPattern),
// ── Casting ───────────────────────────────────────────────────────
new("cast.mine", "Casting", "Your spell words",
"Your own incantations (\"You say, \\\"Zojak…\\\"\"). Real Local chat is untouched.",
"You say, \"Zojak Equin\"", Scope.CombatOnly, @"^You say, """),
new("cast.others", "Casting", "Others' spell words",
"Incantations from other players and monsters.",
"Bob says, \"Cruath Quareth\"", Scope.CombatOnly, @"^(?!You say).+ says, """),
new("cast.fizzle", "Casting", "Spell fizzles",
"\"Your spell fizzled.\"",
"Your spell fizzled.", Scope.NotPlayerChat, @"^Your spell fizzled\."),
new("cast.components", "Casting", "Component usage",
"\"The spell consumed the following components: …\"",
"The spell consumed the following components: Lead Scarab", Scope.NotPlayerChat, @"^The spell consumed the following components"),
new("cast.self_buffs", "Casting", "Your buff casts",
"\"You cast X on yourself…\" confirmations.",
"You cast Strength Self VII on yourself", Scope.NotPlayerChat, @"^You cast .+ on yourself"),
new("cast.buffs_on_you", "Casting", "Buffs others cast on you",
"\"Bob cast X on you…\" lines from buff bots and fellows.",
"Bob cast Strength Other VII on you", Scope.NotPlayerChat, @"^(?!You ).+ cast .+ on you\b"),
new("cast.expires", "Casting", "Spell expiry",
"\"… has expired.\" — rares (Brilliance / Prodigal / Spectral) are kept.",
"Strength Self VII has expired.", Scope.NotPlayerChat, @"^(?!.*(?:Brilliance|Prodigal|Spectral)).*\b(?:has|have) expired\."),
// ── Items & utility ───────────────────────────────────────────────
new("item.heal_ok", "Items", "Healing kit success",
"\"You heal yourself for N Health points…\"",
"You heal yourself for 80 Health points.", Scope.NotPlayerChat, @"^You .*heal yourself for "),
new("item.heal_fail", "Items", "Healing kit failure",
"\"You fail to heal yourself.\"",
"You fail to heal yourself. ", Scope.NotPlayerChat, @"^You fail to heal yourself\."),
new("item.salvage", "Items", "Salvage results",
"\"You obtain … using your knowledge of …\"",
"You obtain 12 Steel (ws 7.00) using your knowledge of Weapon Tinkering.", Scope.NotPlayerChat, @"^You obtain .+ using your knowledge of "),
new("item.salvage_fail", "Items", "Salvage failures",
"\"Salvaging Failed!\" and unsuitable-item notices.",
"Salvaging Failed!", Scope.NotPlayerChat, @"^Salvaging Failed!|The following were not suitable for salvaging: "),
new("item.craftsman", "Items", "Aura of the Craftsman",
"The +5 skill augmentation notice on every craft.",
"Your Aura of the Craftman augmentation increased your skill by 5!", Scope.NotPlayerChat, @"^Your Aura of the Craftman augmentation increased your skill"),
new("item.mana_stone", "Items", "Mana stone usage",
"Mana stone give / drain / destroyed lines.",
"The Mana Stone gives 4,500 points of mana to the following items:", Scope.NotPlayerChat,
@"^The Mana Stone (?:gives|drains) |^You need .+ more mana to fully charge your items\.\s*$|^The .+ is destroyed\.\s*$"),
new("item.regen", "Items", "Periodic healing ticks",
"\"You receive N points of periodic healing.\"",
"You receive 12 points of periodic healing.", Scope.NotPlayerChat, @"^You receive .+ points of periodic healing"),
// ── Social & trade ────────────────────────────────────────────────
new("social.bot_spam", "Social", "Trade / buff bot spam",
"Lines ending in the bot tags -t- or -b-.",
"BuffBot says, \"Buffs at the Holtburg lifestone -b-\"", Scope.Any, @"-[tb]-""?\s*$"),
new("social.failed_assess", "Social", "Failed assess on you",
"\"Someone tried and failed to assess you!\"",
"Bob tried and failed to assess you!", Scope.NotPlayerChat, @"tried and failed to assess you!\s*$"),
new("social.kill_task", "Social", "Kill task complete",
"\"You have killed N Xs! Your task is complete!\"",
"You have killed 50 Drudges! Your task is complete!", Scope.NotPlayerChat, @"^You have killed \d+ .+Your task is complete!\s*$"),
new("social.general", "Social", "General channel",
"Everything said on General.",
"[General] Bob says, \"hi\"", Scope.ChannelsOnly, @"^\[General\]|says on the General channel"),
new("social.trade", "Social", "Trade channel",
"Everything said on Trade.",
"[Trade] Bob says, \"WTS\"", Scope.ChannelsOnly, @"^\[Trade\]|says on the Trade channel"),
new("social.lfg", "Social", "LFG channel",
"Everything said on LFG.",
"[LFG] Bob says, \"LF fellow\"", Scope.ChannelsOnly, @"^\[LFG\]|says on the LFG channel"),
new("social.roleplay", "Social", "Roleplay channel",
"Everything said on Roleplay.",
"[Roleplay] Bob says, \"…\"", Scope.ChannelsOnly, @"^\[Roleplay\]|says on the Roleplay channel"),
new("social.society", "Social", "Society channel",
"Everything said on your society channel.",
"[Society] Bob says, \"…\"", Scope.ChannelsOnly, @"^\[(?:Society|Celestial Hand|Eldrytch Web|Radiant Blood)\]|says on the (?:Society|Celestial Hand|Eldrytch Web|Radiant Blood) channel"),
// ── NPCs ──────────────────────────────────────────────────────────
new("npc.arbitrator", "NPCs", "Master Arbitrator (Colosseum)",
"All Master Arbitrator speech and the fellowship-lock notice.",
"Master Arbitrator tells you, \"You shall be known…\"", Scope.Any,
@"^Master Arbitrator (?:says|tells you)|^Your fellowship is now locked\..*you have 15 minutes to be recruited"),
// ── Pets (ACE custom combat pets) ─────────────────────────────────
new("pet.hit", "Pets", "Pet hits",
"\"[Pet] … hit …\" outgoing damage.",
"[Pet] Fire Banshee hit Drudge for 40 damage.", Scope.NotPlayerChat, @"^\[Pet\] .+ hit "),
new("pet.evade", "Pets", "Pet attacks evaded",
"\"[Pet] … evaded by …\"",
"[Pet] Fire Banshee's attack was evaded by Drudge.", Scope.NotPlayerChat, @"^\[Pet\] .+ evaded by "),
new("pet.damage_taken", "Pets", "Pet damage taken",
"\"[Pet] … took …\" incoming damage.",
"[Pet] Fire Banshee took 25 damage from Drudge.", Scope.NotPlayerChat, @"^\[Pet\] .+ took "),
new("pet.death", "Pets", "Pet died",
"\"[Pet] Your combat pet … has died.\"",
"[Pet] Your combat pet Fire Banshee has died.", Scope.NotPlayerChat, @"^\[Pet\] Your combat pet .+ has died\.\s*$"),
new("pet.recall_block", "Pets", "Pet recall blocked",
"\"Your pet was in combat recently; you cannot recall it…\"",
"Your pet was in combat recently; you cannot recall it for about 10 seconds.", Scope.NotPlayerChat,
@"^Your pet was in combat recently; you cannot recall it"),
new("pet.overflow", "Pets", "Pet heal overflow",
"\"… receives N excess … from …\" boost overflow.",
"Fire Banshee receives 20 excess health from Heal Other.", Scope.NotPlayerChat, @" receives .+ excess .+ from "),
};
private static readonly Dictionary<string, Preset> _byId =
_all.ToDictionary(p => p.Id, StringComparer.OrdinalIgnoreCase);
/// <summary>Every preset in display order.</summary>
internal static IReadOnlyList<Preset> All => _all;
/// <summary>Group names in display order.</summary>
internal static IEnumerable<string> Groups => _all.Select(p => p.Group).Distinct();
internal static Preset? Get(string id) => _byId.TryGetValue(id, out var p) ? p : null;
/// <summary>First enabled preset that matches the line, or null.</summary>
internal static Preset? FirstMatch(string text, string channel)
{
foreach (var p in _all)
if (p.Enabled && p.Matches(text, channel))
return p;
return null;
}
/// <summary>Tabs named by enabled presets (tab names create tabs implicitly, like custom rules).</summary>
internal static IEnumerable<string> TargetTabs()
=> _all.Where(p => p.Enabled && p.Tab.Length > 0).Select(p => p.Tab);
}

View file

@ -333,6 +333,25 @@ internal static class SettingsPanel
return SectionHeader(row.Label); return SectionHeader(row.Label);
case SettingKind.Spacer: case SettingKind.Spacer:
return Spacer(); return Spacer();
case SettingKind.Button:
return ButtonRow(row.Label, row.ButtonText ?? row.Label, () => row.Click?.Invoke(), row.Tooltip);
case SettingKind.TraceCategories:
return TraceCategoriesRow(state, row);
case SettingKind.Text:
return TextRow(row.Label, row.GetText?.Invoke(d) ?? string.Empty, row.Hint, v =>
{
row.SetText?.Invoke(state.Data, v);
Push(state);
}, row.Tooltip);
case SettingKind.Status:
{
string status = row.GetText?.Invoke(d) ?? string.Empty;
return status.Length == 0 ? null : new TextBlock
{
Text = status, Foreground = ColTeal, FontSize = 11,
TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Thickness(0, 2, 0, 2),
};
}
case SettingKind.Note: case SettingKind.Note:
return new TextBlock return new TextBlock
{ {
@ -416,6 +435,53 @@ internal static class SettingsPanel
return row; return row;
} }
/// <summary>Label above a full-width text box; commits on Enter or focus loss when the text changed.</summary>
private static Control TextRow(string label, string value, string? hint, Action<string> onChange, string? tooltip = null)
{
string committed = value;
var box = new StackPanel { Margin = new Thickness(0, 2, 0, 2) };
box.Children.Add(new TextBlock { Text = label, Foreground = ColTextDim, FontSize = 11, Margin = new Thickness(0, 0, 0, 2) });
var tb = new TextBox
{
Text = value,
Watermark = hint,
FontSize = 11,
Height = 22,
Padding = new Thickness(4, 2),
Background = ColPanelBg,
Foreground = ColAmber,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
VerticalContentAlignment = VerticalAlignment.Center,
};
DisableInnerScroll(tb);
void Commit()
{
string text = tb.Text ?? string.Empty;
if (string.Equals(text, committed, StringComparison.Ordinal)) return;
committed = text;
onChange(text);
}
// Same keyboard gate as the number boxes: typed keys go to Avalonia, not the game.
tb.GotFocus += (_, _) => Win32Backend.AvaloniaTextInputActive = true;
tb.LostFocus += (_, _) =>
{
Win32Backend.AvaloniaTextInputActive = false;
Commit();
};
tb.KeyDown += (_, e) =>
{
if (e.Key == Avalonia.Input.Key.Enter) Commit();
};
box.Children.Add(tb);
if (tooltip != null)
{
ToolTip.SetTip(box, tooltip);
ToolTip.SetShowDelay(box, 400);
}
return box;
}
private static Control IntRow(string label, int value, int min, int max, int step, Action<int> onChange, string? tooltip = null) private static Control IntRow(string label, int value, int min, int max, int step, Action<int> onChange, string? tooltip = null)
{ {
int current = Math.Clamp(value, min, max); int current = Math.Clamp(value, min, max);
@ -699,6 +765,96 @@ internal static class SettingsPanel
return row; return row;
} }
/// <summary>Label on the left, a single action button on the right.</summary>
private static Control ButtonRow(string label, string buttonText, Action onClick, string? tooltip = null)
{
var btn = new Button
{
Content = buttonText,
FontSize = 10,
Height = 20,
MinWidth = 160,
Padding = new Thickness(4, 1),
Background = ColBtnFill,
Foreground = ColTextDim,
BorderBrush = ColBtnBord,
BorderThickness = new Thickness(1),
HorizontalContentAlignment = HorizontalAlignment.Center,
};
btn.Click += (_, _) => onClick();
var row = new Grid
{
ColumnDefinitions = new ColumnDefinitions("*,Auto"),
Margin = new Thickness(0, 2, 0, 2),
Height = 22,
};
var lblBlock = new TextBlock { Text = label, Foreground = ColTextDim, FontSize = 11, VerticalAlignment = VerticalAlignment.Center };
Grid.SetColumn(lblBlock, 0);
Grid.SetColumn(btn, 1);
row.Children.Add(lblBlock);
row.Children.Add(btn);
if (tooltip != null)
{
ToolTip.SetTip(row, tooltip);
ToolTip.SetShowDelay(row, 400);
}
return row;
}
/// <summary>
/// [All on] [All off] [ILT Hub on] over a 3-column grid of toggles, one per RynthAi trace
/// category. Each change edits DiagCategories, saves, and rebuilds the tab so the grid redraws.
/// </summary>
private static Control TraceCategoriesRow(PanelState state, SettingRow row)
{
var cats = TraceCategoryLevels.Parse(state.Data.DiagCategories);
if (cats.Count == 0)
return new TextBlock { Text = "Waiting for RynthAi...", Foreground = ColMute, FontSize = 10, Margin = new Thickness(0, 2, 0, 0) };
void Save(string levels)
{
state.Data.DiagCategories = levels;
Push(state);
state.Rebuild?.Invoke();
}
Button Bulk(string text, Func<string> next)
{
var b = new Button
{
Content = text, FontSize = 10, Height = 20, Padding = new Thickness(6, 1),
Background = ColBtnFill, Foreground = ColTextDim, BorderBrush = ColBtnBord, BorderThickness = new Thickness(1),
};
b.Click += (_, _) => Save(next());
return b;
}
var box = new StackPanel { Margin = new Thickness(0, 2, 0, 2) };
var buttons = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Margin = new Thickness(0, 0, 0, 4) };
buttons.Children.Add(Bulk("All on", () => TraceCategoryLevels.Set(state.Data.DiagCategories, "", true)));
buttons.Children.Add(Bulk("All off", () => TraceCategoryLevels.Set(state.Data.DiagCategories, "", false)));
buttons.Children.Add(Bulk("ILT Hub on", () => TraceCategoryLevels.Set(state.Data.DiagCategories, "", true, "Ilt")));
if (row.Tooltip != null)
{
ToolTip.SetTip(buttons, row.Tooltip);
ToolTip.SetShowDelay(buttons, 400);
}
box.Children.Add(buttons);
var grid = new Avalonia.Controls.Primitives.UniformGrid { Columns = 3 };
foreach (var (name, level) in cats)
{
string catName = name;
bool on = level != TraceCategoryLevels.Off;
grid.Children.Add(BoolRow(TraceCategoryLevels.Label(name, level), on,
v => Save(TraceCategoryLevels.Set(state.Data.DiagCategories, catName, v))));
}
box.Children.Add(grid);
return box;
}
// SimpleTheme wraps TextBox content in a ScrollViewer, and its vertical // SimpleTheme wraps TextBox content in a ScrollViewer, and its vertical
// scrollbar's up RepeatButton is a filled triangle Path. On these short // scrollbar's up RepeatButton is a filled triangle Path. On these short
// (Height=20) single-line numeric fields that scrollbar shows and the // (Height=20) single-line numeric fields that scrollbar shows and the

View file

@ -6,7 +6,8 @@
// minimized|expanded, line 2 unused, line 3 target|notarget, line 4 // minimized|expanded, line 2 unused, line 3 target|notarget, line 4
// vitals|novitals; line 5 filesopen|nofiles, the Loaded files drawer; line 9 // vitals|novitals; line 5 filesopen|nofiles, the Loaded files drawer; line 9
// ranges|noranges, the Ranges drawer; line 10 patrol|nopatrol, the Patrol // ranges|noranges, the Ranges drawer; line 10 patrol|nopatrol, the Patrol
// drawer: the left-edge drawers, ImGui/Panels/DashboardDrawers.cs). Line 2 // drawer; line 11 remote|noremote, the Mini Remote drawer: the left-edge
// drawers, ImGui/Panels/DashboardDrawers.cs). Line 2
// was the Monsters button's Simple/Advanced mode, retired 2026-10-01 with the // was the Monsters button's Simple/Advanced mode, retired 2026-10-01 with the
// basic Monsters panel: it is still written ("advanced") so the lines after // basic Monsters panel: it is still written ("advanced") so the lines after
// it keep their places, and ignored on read. Lines 7 and 8 (the dashboard's // it keep their places, and ignored on read. Lines 7 and 8 (the dashboard's
@ -37,6 +38,7 @@ internal static class RynthAiDashboardState
private static volatile bool _barCollapsed; // the RynthCore bar shows only its grip + expand private static volatile bool _barCollapsed; // the RynthCore bar shows only its grip + expand
private static volatile bool _rangesOpen; // the Ranges drawer beside the dashboard is open private static volatile bool _rangesOpen; // the Ranges drawer beside the dashboard is open
private static volatile bool _patrolOpen; // the Patrol drawer beside the dashboard is open private static volatile bool _patrolOpen; // the Patrol drawer beside the dashboard is open
private static volatile bool _remoteOpen; // the Mini Remote drawer beside the dashboard is open
// Lines 7 and 8, unused since 2026-10-05: written back as read. // Lines 7 and 8, unused since 2026-10-05: written back as read.
private static string _line7 = "-", _line8 = "-"; private static string _line7 = "-", _line8 = "-";
private static bool _loaded; private static bool _loaded;
@ -140,6 +142,19 @@ internal static class RynthAiDashboardState
UiBackgroundWriter.Enqueue("rynthai dashboard state", Save); UiBackgroundWriter.Enqueue("rynthai dashboard state", Save);
} }
/// <summary>The Mini Remote drawer (RynthAi's Mini Remote drawn by the plugin) is open beside the dashboard. Any thread.</summary>
public static bool RemoteOpen
{
get { EnsureLoaded(); return _remoteOpen; }
}
public static void SetRemoteOpen(bool open)
{
EnsureLoaded();
_remoteOpen = open;
UiBackgroundWriter.Enqueue("rynthai dashboard state", Save);
}
/// <summary>Reads the file if it hasn't been read yet. Engine init calls this so AC's thread never does.</summary> /// <summary>Reads the file if it hasn't been read yet. Engine init calls this so AC's thread never does.</summary>
public static void EnsureLoaded() public static void EnsureLoaded()
{ {
@ -163,6 +178,7 @@ internal static class RynthAiDashboardState
if (lines.Length >= 8 && lines[7].Trim().Length > 0) _line8 = lines[7].Trim(); if (lines.Length >= 8 && lines[7].Trim().Length > 0) _line8 = lines[7].Trim();
_rangesOpen = lines.Length >= 9 && lines[8].Trim().Equals("ranges", StringComparison.OrdinalIgnoreCase); _rangesOpen = lines.Length >= 9 && lines[8].Trim().Equals("ranges", StringComparison.OrdinalIgnoreCase);
_patrolOpen = lines.Length >= 10 && lines[9].Trim().Equals("patrol", StringComparison.OrdinalIgnoreCase); _patrolOpen = lines.Length >= 10 && lines[9].Trim().Equals("patrol", StringComparison.OrdinalIgnoreCase);
_remoteOpen = lines.Length >= 11 && lines[10].Trim().Equals("remote", StringComparison.OrdinalIgnoreCase);
} }
} }
catch { /* corrupt cache: start expanded */ } catch { /* corrupt cache: start expanded */ }
@ -180,7 +196,8 @@ internal static class RynthAiDashboardState
+ (_showTargetBar ? "target" : "notarget") + "\n" + (_showVitals ? "vitals" : "novitals") + "\n" + (_showTargetBar ? "target" : "notarget") + "\n" + (_showVitals ? "vitals" : "novitals") + "\n"
+ (_filesOpen ? "filesopen" : "nofiles") + "\n" + (_barCollapsed ? "barcollapsed" : "bar") + "\n" + (_filesOpen ? "filesopen" : "nofiles") + "\n" + (_barCollapsed ? "barcollapsed" : "bar") + "\n"
+ _line7 + "\n" + _line8 + "\n" + _line7 + "\n" + _line8 + "\n"
+ (_rangesOpen ? "ranges" : "noranges") + "\n" + (_patrolOpen ? "patrol" : "nopatrol") + "\n"); + (_rangesOpen ? "ranges" : "noranges") + "\n" + (_patrolOpen ? "patrol" : "nopatrol") + "\n"
+ (_remoteOpen ? "remote" : "noremote") + "\n");
} }
catch { /* best-effort */ } catch { /* best-effort */ }
} }

View file

@ -5,6 +5,7 @@ using System.IO;
using System.Linq; using System.Linq;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using RynthCore.Install;
namespace RynthCore.Injector; namespace RynthCore.Injector;
@ -37,7 +38,7 @@ internal static class LaunchCommand
{ {
// The "bulletproof" private AC copy intended for RynthCore launches — a // The "bulletproof" private AC copy intended for RynthCore launches — a
// separate DAT lock domain from the shared Turbine install. // separate DAT lock domain from the shared Turbine install.
private const string PrivateAcClientPath = @"C:\Games\RynthCore\AcClient\acclient.exe"; private static readonly string PrivateAcClientPath = Path.Combine(RynthInstallPaths.CoreDir, "AcClient", "acclient.exe");
// Matches LaunchAccountProfile.NoneOption — explicit opt-out of auto-login. // Matches LaunchAccountProfile.NoneOption — explicit opt-out of auto-login.
private const string NoneOption = "(None — no auto-login)"; private const string NoneOption = "(None — no auto-login)";

View file

@ -2,6 +2,7 @@ using System;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using RynthCore.Install;
namespace RynthCore.Injector; namespace RynthCore.Injector;

View file

@ -19,6 +19,7 @@ using System;
using System.IO; using System.IO;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading; using System.Threading;
using RynthCore.Install;
namespace RynthCore.Loader; namespace RynthCore.Loader;

View file

@ -165,6 +165,8 @@ public struct RynthCoreApiNative
// v80: real slot order of a container's items, and moves that land at a slot // v80: real slot order of a container's items, and moves that land at a slot
public IntPtr GetContainerOrderFn; // int GetContainerOrder(uint container, int slotKind, uint* ids, int max) -> count, -1 unknown public IntPtr GetContainerOrderFn; // int GetContainerOrder(uint container, int slotKind, uint* ids, int max) -> count, -1 unknown
public IntPtr PutItemInContainerFn; // int PutItemInContainer(uint item, uint container, int placement) -> 1 sent, 0 refused, -1 unbound public IntPtr PutItemInContainerFn; // int PutItemInContainer(uint item, uint container, int placement) -> 1 sent, 0 refused, -1 unbound
// v81: outcome of the latest merge-stack request (cdecl thunk); was v77 on QOL-items, v80 on sk
public IntPtr GetMergeStackResultFn; // int GetMergeStackResult(uint src, uint tgt, int* amount, int* ageMs)
} }
/// <summary> /// <summary>

View file

@ -164,6 +164,8 @@ public readonly unsafe struct RynthCoreHost
/// pack). The sender can still be unbound on an odd client: the call then answers -1.</summary> /// pack). The sender can still be unbound on an odd client: the call then answers -1.</summary>
public bool HasPutItemInContainer => _api.Version >= 80 && _api.PutItemInContainerFn != IntPtr.Zero; public bool HasPutItemInContainer => _api.Version >= 80 && _api.PutItemInContainerFn != IntPtr.Zero;
public bool HasGetPluginExportJson => _api.Version >= 66 && _api.GetPluginExportJsonFn != IntPtr.Zero; public bool HasGetPluginExportJson => _api.Version >= 66 && _api.GetPluginExportJsonFn != IntPtr.Zero;
// Version-checked first: on an older engine the field lies past the end of its API table.
public bool HasGetMergeStackResult => _api.Version >= 81 && _api.GetMergeStackResultFn != IntPtr.Zero;
public bool HasGetPluginInterface => _api.Version >= 68 && _api.GetPluginInterfaceFn != IntPtr.Zero; public bool HasGetPluginInterface => _api.Version >= 68 && _api.GetPluginInterfaceFn != IntPtr.Zero;
public bool HasGetLiveObjectIds => _api.Version >= 69 && _api.GetLiveObjectIdsFn != IntPtr.Zero; public bool HasGetLiveObjectIds => _api.Version >= 69 && _api.GetLiveObjectIdsFn != IntPtr.Zero;
public bool HasGetLastUseDone => _api.Version >= 70 && _api.GetLastUseDoneFn != IntPtr.Zero; public bool HasGetLastUseDone => _api.Version >= 70 && _api.GetLastUseDoneFn != IntPtr.Zero;
@ -570,6 +572,37 @@ public readonly unsafe struct RynthCoreHost
((delegate* unmanaged[Cdecl]<uint, uint, int>)_api.MergeStackInternalFn)(sourceObjectId, targetObjectId) != 0; ((delegate* unmanaged[Cdecl]<uint, uint, int>)_api.MergeStackInternalFn)(sourceObjectId, targetObjectId) != 0;
} }
/// <summary>Outcome codes returned by <see cref="GetMergeStackResult"/>.</summary>
public static class MergeStackStatus
{
public const int None = 0; // no request recorded for this pair (or it aged out)
public const int Queued = 1; // accepted onto AC's main-thread queue, not executed yet
public const int Sent = 2; // merge sent to the server for 'amount' units
public const int TargetFull = 3; // skipped: the target stack was already full
public const int Failed = 4; // invalid ids, merge API unavailable, AC rejected, or threw
public const int QueueFull = 5; // dropped: main-thread queue full
}
/// <summary>
/// What happened to the latest <see cref="MergeStackInternal"/> request for this pair
/// (a <see cref="MergeStackStatus"/> code). <paramref name="amount"/> = units sent
/// (Sent only); <paramref name="ageMs"/> = how long ago the outcome was recorded.
/// Returns <see cref="MergeStackStatus.None"/> on engines older than API v68.
/// </summary>
public int GetMergeStackResult(uint sourceObjectId, uint targetObjectId, out int amount, out int ageMs)
{
amount = 0;
ageMs = 0;
if (!HasGetMergeStackResult)
return MergeStackStatus.None;
int a = 0, age = 0;
int status = ((delegate* unmanaged[Cdecl]<uint, uint, int*, int*, int>)_api.GetMergeStackResultFn)(
sourceObjectId, targetObjectId, &a, &age);
amount = a;
ageMs = age;
return status;
}
/// <summary> /// <summary>
/// Gives an item to an NPC or another player by sending the F7B1 give /// Gives an item to an NPC or another player by sending the F7B1 give
/// GameAction (CM_Inventory::Event_GiveObjectRequest). This is the correct /// GameAction (CM_Inventory::Event_GiveObjectRequest). This is the correct

View file

@ -33,7 +33,7 @@
<PropertyGroup> <PropertyGroup>
<!-- The engine API this SDK knows; tools\PluginManifestTests checks it equals PluginContractVersion.Current. --> <!-- The engine API this SDK knows; tools\PluginManifestTests checks it equals PluginContractVersion.Current. -->
<RynthCoreSdkApiVersion>80</RynthCoreSdkApiVersion> <RynthCoreSdkApiVersion>81</RynthCoreSdkApiVersion>
<_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true</_RynthPluginManifestOn> <_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true</_RynthPluginManifestOn>
</PropertyGroup> </PropertyGroup>

View file

@ -1,5 +1,6 @@
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using RynthCore.Install;
namespace RynthCore.StatusAgent; namespace RynthCore.StatusAgent;

View file

@ -474,11 +474,12 @@ internal static class Program
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.TrainingEntryNative>(f.Name), (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.TrainingEntryNative>(f.Name), "TrainingEntryNative." + f.Name + " offset"); Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.TrainingEntryNative>(f.Name), (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.TrainingEntryNative>(f.Name), "TrainingEntryNative." + f.Name + " offset");
Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits"); Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits");
Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits"); Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits");
// The three v79 slots follow v78's and come right before v80's, in this order. // The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn end the table.
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(2).TakeLast(3).ToArray(); var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).TakeLast(6).ToArray();
Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn" }), "v79 slots before v80's: " + string.Join(",", names)); Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn", "GetContainerOrderFn", "PutItemInContainerFn", "GetMergeStackResultFn" }),
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(2).TakeLast(3).ToArray(); "v79, v80 then v81 slots last: " + string.Join(",", names));
Check(sdkNames.SequenceEqual(names), "SDK v79 slots in the same order"); var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).TakeLast(6).ToArray();
Check(sdkNames.SequenceEqual(names), "SDK v79, v80 and v81 slots in the same order");
} }
// v80: GetContainerOrder and PutItemInContainer are the table's last two slots, engine and SDK alike, // v80: GetContainerOrder and PutItemInContainer are the table's last two slots, engine and SDK alike,
@ -487,8 +488,9 @@ internal static class Program
{ {
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray(); var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray();
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).ToArray(); var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).ToArray();
Check(names.TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots last: " + string.Join(",", names.TakeLast(2))); // v81's GetMergeStackResultFn follows v80's two slots.
Check(sdkNames.TakeLast(2).SequenceEqual(names.TakeLast(2)), "SDK v80 slots in the same order"); Check(names.SkipLast(1).TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots before v81's: " + string.Join(",", names.SkipLast(1).TakeLast(2)));
Check(sdkNames.SkipLast(1).TakeLast(2).SequenceEqual(names.SkipLast(1).TakeLast(2)), "SDK v80 slots in the same order");
Eq(Marshal.SizeOf<RynthCore.PluginSdk.RynthCoreApiNative>(), Marshal.SizeOf<RynthCore.Engine.Plugins.RynthCoreAPI>(), "SDK table size = engine table size"); Eq(Marshal.SizeOf<RynthCore.PluginSdk.RynthCoreApiNative>(), Marshal.SizeOf<RynthCore.Engine.Plugins.RynthCoreAPI>(), "SDK table size = engine table size");
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("PutItemInContainerFn"), Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.RynthCoreApiNative>("PutItemInContainerFn"),
(int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("PutItemInContainerFn"), "PutItemInContainerFn offset"); (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.RynthCoreAPI>("PutItemInContainerFn"), "PutItemInContainerFn offset");