feat: port aelrynth 2026.9.27.2 snapshot onto GitHub history
Overlay upstream/main (9b5e276) onto BlankenshipG main without rewriting
history. Keep origin-only Decal/plugin/docs trees. Re-apply aelrynth.com
and sibling-fork URL fixes that aelrynth git still has as tombohar links.
Co-authored-by: BlankenshipG <BlankenshipG@users.noreply.github.com>
This commit is contained in:
parent
ac0d743e16
commit
4ddbb52eb2
244 changed files with 59710 additions and 3067 deletions
|
|
@ -312,23 +312,64 @@ internal static unsafe class DX9Backend
|
|||
private static SetIndicesD? _setIndices;
|
||||
private static GetIndicesD? _getIndices;
|
||||
private static IntPtr _fontTexture;
|
||||
/// <summary>
|
||||
/// True once <see cref="InitCore"/> has cached the D3D9 vtable delegates.
|
||||
/// Required by <see cref="RenderNav3D"/>, <see cref="DeviceSetRenderState"/>,
|
||||
/// and any non-ImGui render path. Independent of <see cref="_initialized"/>
|
||||
/// (which means "ImGui-specific resources also ready").
|
||||
/// </summary>
|
||||
private static bool _coreInitialized;
|
||||
/// <summary>
|
||||
/// True once <see cref="InitImGui"/> has built the font texture and the
|
||||
/// backend is fully ready for <see cref="RenderDrawData"/>. Implies
|
||||
/// <see cref="_coreInitialized"/>.
|
||||
/// </summary>
|
||||
private static bool _initialized;
|
||||
|
||||
// ─── Public API ───────────────────────────────────────────────────
|
||||
|
||||
public static bool Init(IntPtr pDevice)
|
||||
/// <summary>
|
||||
/// Caches the D3D9 device function pointers that every render path here
|
||||
/// (ImGui draw, Nav3D markers, callers like Nav3DRenderInjector) relies on.
|
||||
/// Idempotent. Safe to call when ImGui is disabled — does NOT touch the
|
||||
/// font texture or any ImGui state.
|
||||
/// </summary>
|
||||
public static bool InitCore(IntPtr pDevice)
|
||||
{
|
||||
if (_initialized) return true;
|
||||
if (_coreInitialized) return true;
|
||||
if (pDevice == IntPtr.Zero) return false;
|
||||
|
||||
CacheDelegates(pDevice);
|
||||
_coreInitialized = true;
|
||||
RynthLog.Render("DX9Backend: Core delegates cached.");
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the ImGui font texture and marks the backend ready for
|
||||
/// <see cref="RenderDrawData"/>. Calls <see cref="InitCore"/> first if it
|
||||
/// hasn't run. Idempotent.
|
||||
/// </summary>
|
||||
public static bool InitImGui(IntPtr pDevice)
|
||||
{
|
||||
if (_initialized) return true;
|
||||
if (!InitCore(pDevice)) return false;
|
||||
|
||||
if (!CreateFontTexture(pDevice))
|
||||
return false;
|
||||
|
||||
_initialized = true;
|
||||
RynthLog.Render("DX9Backend: Initialized.");
|
||||
RynthLog.Render("DX9Backend: ImGui resources initialized.");
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Backward-compat wrapper — initializes both core delegates and ImGui
|
||||
/// resources. Prefer <see cref="InitCore"/> + <see cref="InitImGui"/>
|
||||
/// directly so callers can skip the ImGui half when not needed.
|
||||
/// </summary>
|
||||
public static bool Init(IntPtr pDevice) => InitImGui(pDevice);
|
||||
|
||||
public static void Shutdown()
|
||||
{
|
||||
if (_fontTexture != IntPtr.Zero)
|
||||
|
|
@ -338,6 +379,7 @@ internal static unsafe class DX9Backend
|
|||
_fontTexture = IntPtr.Zero;
|
||||
}
|
||||
_initialized = false;
|
||||
_coreInitialized = false;
|
||||
}
|
||||
|
||||
public static void NewFrame()
|
||||
|
|
@ -988,6 +1030,24 @@ internal static unsafe class DX9Backend
|
|||
private static bool _navTrigReady;
|
||||
private static int _nav3DLogCount;
|
||||
|
||||
// Persistent heap buffer for batched triangle rendering. Filled once per
|
||||
// RenderNav3D call with every Nav3D triangle, then drawn in one
|
||||
// DrawPrimitiveUP — avoids the 4000+ draw-call cost of doing one call per
|
||||
// triangle (the cost showed up as motion-related flicker at high radii).
|
||||
// Grown on demand; never freed until process exit.
|
||||
private static IntPtr _navTriBatch;
|
||||
private static int _navTriBatchCapacityVerts;
|
||||
|
||||
private static void EnsureNavTriBatch(int neededVerts)
|
||||
{
|
||||
if (neededVerts <= _navTriBatchCapacityVerts) return;
|
||||
int newCap = _navTriBatchCapacityVerts == 0 ? 1024 : _navTriBatchCapacityVerts;
|
||||
while (newCap < neededVerts) newCap *= 2;
|
||||
if (_navTriBatch != IntPtr.Zero) Marshal.FreeHGlobal(_navTriBatch);
|
||||
_navTriBatch = Marshal.AllocHGlobal(newCap * sizeof(NavVertex));
|
||||
_navTriBatchCapacityVerts = newCap;
|
||||
}
|
||||
|
||||
private static void EnsureNavTrig()
|
||||
{
|
||||
if (_navTrigReady) return;
|
||||
|
|
@ -1002,9 +1062,12 @@ internal static unsafe class DX9Backend
|
|||
|
||||
public static void RenderNav3D(IntPtr pDevice)
|
||||
{
|
||||
if (!_initialized || pDevice == IntPtr.Zero) return;
|
||||
// Nav3D only needs the cached function pointers + nav trig + GameMatrixCapture;
|
||||
// it doesn't touch the ImGui font texture / vertex buffers. Gate on the
|
||||
// core init flag so this path runs even when EnableImGuiBackend=false.
|
||||
if (!_coreInitialized || pDevice == IntPtr.Zero) return;
|
||||
if (!D3D9.GameMatrixCapture.HasCapturedFrame) return;
|
||||
if (D3D9.Nav3DRenderer.RingCount == 0 && D3D9.Nav3DRenderer.LineCount == 0) return;
|
||||
if (D3D9.Nav3DRenderer.RingCount == 0 && D3D9.Nav3DRenderer.LineCount == 0 && D3D9.Nav3DRenderer.TriangleCount == 0) return;
|
||||
|
||||
EnsureNavTrig();
|
||||
|
||||
|
|
@ -1095,7 +1158,31 @@ internal static unsafe class DX9Backend
|
|||
_setTransform!(pDevice, D3DTS_VIEW, &viewMat);
|
||||
_setTransform!(pDevice, D3DTS_PROJECTION, &projMat);
|
||||
|
||||
// Draw lines first (behind rings)
|
||||
// Draw triangles first (terrain-conforming faces, sit beneath
|
||||
// everything else). All triangles are packed into one heap-backed
|
||||
// vertex buffer and submitted in a single DrawPrimitiveUP — at
|
||||
// high slope-radius settings we can have 4000+ triangles per
|
||||
// frame, and one DP-UP per triangle was visibly frame-dropping.
|
||||
int triCount = D3D9.Nav3DRenderer.TriangleCount;
|
||||
if (triCount > 0)
|
||||
{
|
||||
EnsureNavTriBatch(triCount * 3);
|
||||
NavVertex* batch = (NavVertex*)_navTriBatch;
|
||||
for (int i = 0; i < triCount; i++)
|
||||
{
|
||||
D3D9.Nav3DRenderer.GetTriangle(i,
|
||||
out float x1, out float y1, out float z1,
|
||||
out float x2, out float y2, out float z2,
|
||||
out float x3, out float y3, out float z3, out uint color);
|
||||
int b = i * 3;
|
||||
batch[b ].X = x1; batch[b ].Y = y1; batch[b ].Z = z1; batch[b ].Col = color;
|
||||
batch[b + 1].X = x2; batch[b + 1].Y = y2; batch[b + 1].Z = z2; batch[b + 1].Col = color;
|
||||
batch[b + 2].X = x3; batch[b + 2].Y = y3; batch[b + 2].Z = z3; batch[b + 2].Col = color;
|
||||
}
|
||||
_drawPrimUP!(pDevice, D3DPT_TRIANGLELIST, (uint)triCount, (IntPtr)batch, (uint)sizeof(NavVertex));
|
||||
}
|
||||
|
||||
// Draw lines (extruded XZ-plane quads — for edges/strips)
|
||||
for (int i = 0; i < D3D9.Nav3DRenderer.LineCount; i++)
|
||||
{
|
||||
D3D9.Nav3DRenderer.GetLine(i, out float x1, out float y1, out float z1,
|
||||
|
|
@ -1107,8 +1194,8 @@ internal static unsafe class DX9Backend
|
|||
for (int i = 0; i < D3D9.Nav3DRenderer.RingCount; i++)
|
||||
{
|
||||
D3D9.Nav3DRenderer.GetRing(i, out float x, out float y, out float z,
|
||||
out float radius, out float thick, out uint color);
|
||||
DrawNavRing(pDevice, x, y, z, radius, thick, color);
|
||||
out float radius, out float thick, out float height, out uint color);
|
||||
DrawNavRing(pDevice, x, y, z, radius, thick, height, color);
|
||||
}
|
||||
|
||||
if (_nav3DLogCount == 0)
|
||||
|
|
@ -1160,19 +1247,20 @@ internal static unsafe class DX9Backend
|
|||
}
|
||||
}
|
||||
|
||||
private const float NavCylinderHeight = 0.5f; // world units tall
|
||||
|
||||
private static void DrawNavRing(IntPtr pDevice, float cx, float cy, float cz,
|
||||
float radius, float thickness, uint color)
|
||||
float radius, float thickness, float height, uint color)
|
||||
{
|
||||
// Outer cylinder wall: triangle strip alternating top/bottom vertices
|
||||
// Outer cylinder wall: triangle strip alternating top/bottom vertices.
|
||||
// Wall height comes from the per-ring Height field (set via the Ex
|
||||
// submission) so thickness and height tune independently — a thin
|
||||
// but tall ring is what makes the radar range visible at a glance.
|
||||
int wallVertCount = (NavRingSegments + 1) * 2;
|
||||
NavVertex* wallVerts = stackalloc NavVertex[wallVertCount];
|
||||
|
||||
// Fade top edge to transparent for a nicer look
|
||||
uint colorTop = (color & 0x00FFFFFF) | 0x10000000; // ~6% alpha at top
|
||||
float yBottom = cy;
|
||||
float yTop = cy + NavCylinderHeight;
|
||||
float yTop = cy + MathF.Max(height, 0.1f);
|
||||
|
||||
for (int i = 0; i <= NavRingSegments; i++)
|
||||
{
|
||||
|
|
@ -1253,4 +1341,20 @@ internal static unsafe class DX9Backend
|
|||
wall[3].X = x2; wall[3].Y = y2; wall[3].Z = z2; wall[3].Col = color;
|
||||
_drawPrimUP!(pDevice, D3DPT_TRIANGLESTRIP, 2, (IntPtr)wall, (uint)sizeof(NavVertex));
|
||||
}
|
||||
|
||||
// Filled 3D triangle in world space — vertices passed straight through to
|
||||
// the device. Cull mode is already NONE in RenderNav3D so the triangle
|
||||
// shows from either face winding, which spares the plugin from having to
|
||||
// produce CCW vertex order.
|
||||
private static void DrawNavTriangle(IntPtr pDevice,
|
||||
float x1, float y1, float z1,
|
||||
float x2, float y2, float z2,
|
||||
float x3, float y3, float z3, uint color)
|
||||
{
|
||||
NavVertex* verts = stackalloc NavVertex[3];
|
||||
verts[0].X = x1; verts[0].Y = y1; verts[0].Z = z1; verts[0].Col = color;
|
||||
verts[1].X = x2; verts[1].Y = y2; verts[1].Z = z2; verts[1].Col = color;
|
||||
verts[2].X = x3; verts[2].Y = y3; verts[2].Z = z3; verts[2].Col = color;
|
||||
_drawPrimUP!(pDevice, D3DPT_TRIANGLELIST, 1, (IntPtr)verts, (uint)sizeof(NavVertex));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
582
src/RynthCore.Engine/ImGui/EngineFrameController.cs
Normal file
582
src/RynthCore.Engine/ImGui/EngineFrameController.cs
Normal file
|
|
@ -0,0 +1,582 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - ImGui/EngineFrameController.cs
|
||||
// Top-level orchestrator: drives the per-frame engine pipeline from EndScene.
|
||||
//
|
||||
// Per-frame work splits into two layers:
|
||||
// * Always-on (when EndScene fires): GameMatrixCapture, Nav3DRenderInjector
|
||||
// install/reset, PluginManager init/pending/delete/tick, DX9Backend.RenderNav3D
|
||||
// fallback. These run regardless of EngineSettings.EnableImGuiBackend so
|
||||
// world→screen, nav markers, and plugin lifecycle stay alive even when
|
||||
// the ImGui surface is disabled.
|
||||
// * ImGui-gated (only when EngineSettings.EnableImGuiBackend is true):
|
||||
// Win32Backend.NewFrame / DX9Backend.NewFrame, ImGui.NewFrame/EndFrame/
|
||||
// Render, RynthCoreShell + plugin RenderAll, DX9Backend.RenderDrawData,
|
||||
// mouse/keyboard capture flag updates, multi-viewport platform pump.
|
||||
//
|
||||
// Renamed 2026-05-10 from ImGuiController — the type now owns more than
|
||||
// ImGui's frame; the ImGui block is just one branch of its work.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.D3D9;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
internal static class EngineFrameController
|
||||
{
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern uint GetCurrentProcessId();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool GetClientRect(IntPtr hWnd, out ClientRect lpRect);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool ClientToScreen(IntPtr hWnd, ref ClientPoint lpPoint);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct ClientRect { public int Left, Top, Right, Bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct ClientPoint { public int X, Y; }
|
||||
|
||||
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
|
||||
|
||||
private static bool _imguiInitialized;
|
||||
private static bool _imguiInitFailed;
|
||||
private static bool _coreResolved;
|
||||
private static bool _pluginsInitialized;
|
||||
private static IntPtr _context;
|
||||
private static IntPtr _gameHwnd;
|
||||
|
||||
/// <summary>
|
||||
/// Live D3D9 device pointer, published by <see cref="OnEndScene"/> on AC's
|
||||
/// render thread and consumed by <see cref="PumpPluginFrame"/> on the
|
||||
/// dedicated plugin pump thread. Zero until the first real backbuffer
|
||||
/// frame — the pump no-ops until then (we need the HWND/core resolved and
|
||||
/// a device to hand plugins). Volatile: written by render thread, read by
|
||||
/// pump thread; IntPtr writes are atomic on this platform.
|
||||
/// </summary>
|
||||
internal static volatile IntPtr CachedDevice;
|
||||
private static int _pluginPumpInFrame; // re-entrancy guard for the pump
|
||||
private static long _lastFrameTicks;
|
||||
private static int _frameCount;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the AC game HWND (via the D3D9 device, falling back to
|
||||
/// EnumWindows) and seeds <see cref="EntryPoint.GameHwnd"/>. Required by
|
||||
/// the always-on path (Nav3DRenderInjector + DX9Backend core delegates)
|
||||
/// and by the ImGui init path. Idempotent — safe to call every frame.
|
||||
/// </summary>
|
||||
public static bool EnsureCore(IntPtr pDevice)
|
||||
{
|
||||
if (_coreResolved && _gameHwnd != IntPtr.Zero)
|
||||
return true;
|
||||
|
||||
// Prefer the actual D3D device window so startup does not latch onto a splash/loading HWND.
|
||||
_gameHwnd = DX9Backend.GetDeviceWindow(pDevice);
|
||||
if (_gameHwnd == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Render("EngineFrameController: D3D device window unavailable, falling back to EnumWindows.");
|
||||
_gameHwnd = FindGameWindow();
|
||||
}
|
||||
|
||||
if (_gameHwnd == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Render("EngineFrameController: Could not find game window.");
|
||||
return false;
|
||||
}
|
||||
|
||||
RynthLog.Render($"EngineFrameController: Game HWND = 0x{_gameHwnd:X8}");
|
||||
EntryPoint.GameHwnd = _gameHwnd;
|
||||
_coreResolved = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool Init(IntPtr pDevice)
|
||||
{
|
||||
if (_imguiInitialized)
|
||||
return true;
|
||||
|
||||
if (!EnsureCore(pDevice))
|
||||
return false;
|
||||
|
||||
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
|
||||
if (previousContext != IntPtr.Zero)
|
||||
RynthLog.Render($"EngineFrameController: Existing ImGui context detected (0x{previousContext:X8}) - isolating RynthCore context.");
|
||||
|
||||
_context = ImGuiNET.ImGui.CreateContext();
|
||||
bool initSucceeded = false;
|
||||
try
|
||||
{
|
||||
ImGuiNET.ImGui.SetCurrentContext(_context);
|
||||
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
|
||||
// Pin imgui.ini to a stable absolute path so window positions/sizes
|
||||
// persist across plugin reloads (RL) and AC restarts. The default
|
||||
// ImGui behavior writes to the working directory which can differ
|
||||
// between launches. Allocated once, kept alive for the process lifetime.
|
||||
try
|
||||
{
|
||||
const string iniPath = @"C:\Games\RynthSuite\RynthAi\imgui.ini";
|
||||
System.IO.Directory.CreateDirectory(@"C:\Games\RynthSuite\RynthAi");
|
||||
IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath);
|
||||
unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; }
|
||||
RynthLog.Render($"EngineFrameController: imgui.ini pinned to {iniPath}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Render($"EngineFrameController: failed to pin imgui.ini path - {ex.Message}");
|
||||
}
|
||||
|
||||
io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;
|
||||
// ViewportsEnable was enabling ImGui multi-viewport platform/renderer
|
||||
// callbacks against a cimgui.dll that is NOT built with
|
||||
// IMGUI_ENABLE_VIEWPORTS. The platform/renderer callback chain then
|
||||
// recursed (Platform → Renderer → Platform → ...) on AC's render
|
||||
// thread, eating the 1MB stack in ~17s and AV'ing in ntdll mid-push.
|
||||
// CLAUDE.md flags this: Multi-viewport "requires cimgui built with
|
||||
// IMGUI_ENABLE_VIEWPORTS" — flag re-introduced this in the engine
|
||||
// and triggered the silent stack-overflow on every login.
|
||||
// io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable;
|
||||
// Popped-out plugin windows use WS_EX_TOOLWINDOW so they don't show
|
||||
// up as extra "Asheron's Call" entries in the taskbar — critical for
|
||||
// users running many clients side by side.
|
||||
io.ConfigViewportsNoTaskBarIcon = true;
|
||||
ImGuiNET.ImGui.StyleColorsDark();
|
||||
|
||||
// One-shot offset probe for diagnostics — safe to keep installed.
|
||||
ViewportProbe.Run();
|
||||
|
||||
if (!Win32Backend.Init(_gameHwnd))
|
||||
return false;
|
||||
|
||||
if (!DX9Backend.InitImGui(pDevice))
|
||||
return false;
|
||||
|
||||
// Viewport backends only run when ViewportsEnable is on. Installing
|
||||
// their callbacks on PlatformIO without the flag has no upside and
|
||||
// just expands the crash surface.
|
||||
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
|
||||
{
|
||||
bool platformOk = ViewportPlatformBackend.Init(_gameHwnd);
|
||||
bool rendererOk = platformOk && ViewportRendererBackend.Init(pDevice);
|
||||
if (!platformOk || !rendererOk)
|
||||
{
|
||||
RynthLog.Render($"EngineFrameController: viewport init failed (platform={platformOk}, renderer={rendererOk}) — disabling ViewportsEnable.");
|
||||
io.ConfigFlags &= ~ImGuiConfigFlags.ViewportsEnable;
|
||||
}
|
||||
ViewportPlatformBackend.ImGuiContext = _context;
|
||||
}
|
||||
|
||||
_lastFrameTicks = Stopwatch.GetTimestamp();
|
||||
_imguiInitialized = true;
|
||||
initSucceeded = true;
|
||||
|
||||
RynthLog.Render("EngineFrameController: Fully initialized - RynthCore shell active.");
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!initSucceeded && _context != IntPtr.Zero)
|
||||
{
|
||||
ImGuiNET.ImGui.DestroyContext(_context);
|
||||
_context = IntPtr.Zero;
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.SetCurrentContext(previousContext);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Shutdown()
|
||||
{
|
||||
if (!_imguiInitialized)
|
||||
return;
|
||||
|
||||
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
|
||||
IntPtr contextToDestroy = _context;
|
||||
|
||||
try
|
||||
{
|
||||
ImGuiNET.ImGui.SetCurrentContext(contextToDestroy);
|
||||
|
||||
// Zero the WndProc context guard BEFORE DestroyContext so any
|
||||
// deferred OS messages that arrive at viewport HWNDs during or
|
||||
// after teardown don't try to call into freed ImGui memory.
|
||||
ViewportPlatformBackend.ImGuiContext = IntPtr.Zero;
|
||||
PluginManager.ShutdownAll();
|
||||
OverlayTextureRenderer.Shutdown();
|
||||
ViewportRendererBackend.Shutdown();
|
||||
ViewportPlatformBackend.Shutdown();
|
||||
DX9Backend.Shutdown();
|
||||
// Do NOT call Win32Backend.Shutdown() here. EngineLifecycle.Shutdown
|
||||
// owns that step explicitly, AFTER AvaloniaOverlay.Stop — floating
|
||||
// panels can only be destroyed on the game thread by our subclass
|
||||
// WndProc (Win32Backend.Shutdown sweeps any still open before it
|
||||
// unhooks), so restoring AC's original WndProc this early sends
|
||||
// those destroys to AC's proc, which ignores them, and the orphaned
|
||||
// panel HWND outlives the engine load.
|
||||
ImGuiNET.ImGui.DestroyContext(contextToDestroy);
|
||||
|
||||
_imguiInitialized = false;
|
||||
_coreResolved = false;
|
||||
_context = IntPtr.Zero;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.SetCurrentContext(previousContext == contextToDestroy ? IntPtr.Zero : previousContext);
|
||||
}
|
||||
}
|
||||
|
||||
public static void OnEndScene(IntPtr pDevice)
|
||||
{
|
||||
// ── Always-on engine pipeline ────────────────────────────────────
|
||||
// These run on every EndScene tick, regardless of
|
||||
// EngineSettings.EnableImGuiBackend, so world→screen capture, nav-
|
||||
// marker rendering, and plugin lifecycle stay alive when the ImGui
|
||||
// surface is disabled.
|
||||
try
|
||||
{
|
||||
// Resolve game HWND and seed EntryPoint.GameHwnd. Required even
|
||||
// in ImGui-off mode so Avalonia owner-window binding works.
|
||||
EnsureCore(pDevice);
|
||||
|
||||
// Cache the D3D9 device function pointers used by Nav3DRenderInjector,
|
||||
// RenderNav3D, and the always-on render path. This is a strict subset
|
||||
// of what InitImGui needs and is safe to run without ImGui state.
|
||||
DX9Backend.InitCore(pDevice);
|
||||
|
||||
// Install the DrawIndexedPrimitive hook that injects Nav3D markers at
|
||||
// the 3D→UI ZENABLE transition so they render BEHIND AC's UI. Idempotent
|
||||
// (installs once); placed here because its Detour reads the device
|
||||
// delegates InitCore (above) just cached. WITHOUT THIS the injector never
|
||||
// accumulates, RenderedThisFrame stays false on every frame, and the
|
||||
// end-of-frame fallback below paints markers OVER the UI. This call was
|
||||
// dropped in the v0.19 Nav3D double-buffer refactor — restored here.
|
||||
D3D9.Nav3DRenderInjector.Install(pDevice);
|
||||
|
||||
// Capture the game's View/Projection matrices before ImGui touches them
|
||||
GameMatrixCapture.CaptureFrame(pDevice);
|
||||
|
||||
// Refresh the player-skill snapshot on AC's main thread (this
|
||||
// EndScene runs on it). The plugin tick is pumped off-thread and
|
||||
// can't read skills live (TryGetObjectQualitiesPtr fail-closes);
|
||||
// without this it gets (0,0) → tier-1 casts and never buffs.
|
||||
// Throttled internally.
|
||||
Compatibility.ClientObjectHooks.PrefetchPlayerSkills();
|
||||
// Same rationale + same main-thread guard: snapshot the spellbook
|
||||
// so the off-thread pump can resolve tiers against spells the char
|
||||
// actually knows (throttled internally).
|
||||
Compatibility.ClientObjectHooks.PrefetchKnownSpells();
|
||||
// Same main-thread guard + rationale: snapshot AC's real
|
||||
// ObjectIsAttackable for every live object so the off-thread pump
|
||||
// can tell NPC/vendor (attackable=false) from monster. Without it
|
||||
// the pump got hardcoded true and the classifier promoted NPCs to
|
||||
// attackable creatures → war magic cast at NPCs (throttled
|
||||
// internally).
|
||||
Compatibility.ClientObjectHooks.PrefetchAttackable();
|
||||
// Same main-thread guard + rationale: snapshot object names and
|
||||
// item types for every live object so the off-thread plugin pump
|
||||
// can classify objects without walking AC's live CObjectMaint
|
||||
// table (0x0067E779 READ-AV class; throttled internally at 3 s).
|
||||
Compatibility.ClientObjectHooks.PrefetchObjectIdentity();
|
||||
// Same main-thread guard: snapshot every live object's POSITION so the
|
||||
// off-thread plugin pump reads position from cache instead of resolving
|
||||
// _getWeenieObject live — that resolution is AC's CObjectMaint walk and
|
||||
// is the dump-verified 0x0067E779 READ-AV when done on the pump thread.
|
||||
// Sampled every frame (positions are volatile), zero-alloc.
|
||||
Compatibility.ClientObjectHooks.PrefetchPositions();
|
||||
// Same main-thread guard: snapshot XP/luminance/deaths/vitae (main-thread-only
|
||||
// Inq* reads) so the GetEngineStatusJson host bridge can serve them off-thread (throttled).
|
||||
Compatibility.ClientObjectHooks.PrefetchPlayerStats();
|
||||
|
||||
// Cold-login object backfill on the SAME AC main thread as the
|
||||
// skill prefetch above: deliver objects already present at login
|
||||
// (the incremental CreateObject hook only catches NEW spawns, so
|
||||
// login-present mobs were never reaching the plugin — proven via
|
||||
// per-id ClassifyTrace). One-shot per login, IsOnMainThread-gated
|
||||
// and attempt-bounded internally; reuses the guarded
|
||||
// QueueCreateObject delivery path. EndScene is a build-independent
|
||||
// anchor (D3D9 hook, not string-resolved like SmartBox).
|
||||
try { Plugins.PluginManager.TrySeedLiveObjectsFromCObjectMaintOnce(); }
|
||||
catch (Exception ex) { RynthLog.Plugin($"CObjectMaint seed threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
|
||||
// P1: drain off-thread bot actions (UseObject / ChangeCombatMode / melee /
|
||||
// missile / movement / jump) here on AC's MAIN thread. The pump enqueues
|
||||
// them instead of calling AC directly, so AC mutates its single-threaded
|
||||
// object/animation (CSequence) state on the same thread that updates it —
|
||||
// closing the off-thread-mutation corruption class (the CSequence::
|
||||
// update_internal AV captured 2026-06-03, the 0x0055FA24 range-list AV, etc).
|
||||
// CastSpell is deliberately NOT routed here (stays off-thread + SEH).
|
||||
try { Compatibility.AcMainThreadQueue.Drain(); }
|
||||
catch (Exception ex) { RynthLog.Plugin($"AcMainThreadQueue.Drain threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
|
||||
// Nav3DRenderInjector fires mid-frame at the 3D→UI ZENABLE
|
||||
// transition — that's the only pipeline position where markers
|
||||
// can render BEHIND AC's UI (the UI pass draws after ZENABLE
|
||||
// turns off, and the end-of-frame fallback is past it entirely).
|
||||
//
|
||||
// The injector accumulates state per-frame via DrawIndexedPrimitive
|
||||
// callbacks during AC's draws (which fire before this EndScene),
|
||||
// so by the time we check RenderedThisFrame here, its decision
|
||||
// for the current frame is final. ResetFrame at the END of
|
||||
// OnEndScene primes it for the next frame's accumulation.
|
||||
//
|
||||
// Historically the engine forced the end-of-frame fallback ONLY
|
||||
// because the injector's hit-rate varied across motion, producing
|
||||
// flicker when some frames painted at the 3D→UI boundary and
|
||||
// others at end-of-frame. We accept that risk here: the user
|
||||
// wants markers behind the UI, and a frame the injector misses
|
||||
// simply doesn't render markers (less jarring than a Z-order flip).
|
||||
bool nav3DAlreadyRendered = D3D9.Nav3DRenderInjector.RenderedThisFrame;
|
||||
|
||||
// Publish the live device pointer for the off-render-thread plugin
|
||||
// pump (see PumpPluginFrame). The D3D9 device is a stable COM
|
||||
// pointer for the session, so caching it is safe; the pump only
|
||||
// passes it opaquely to plugins (RynthAi in Avalonia-only mode
|
||||
// never dereferences it). Atomic IntPtr write; volatile read.
|
||||
CachedDevice = pDevice;
|
||||
|
||||
// NOTE (2026-05-16): PluginManager.InitPlugins / ProcessPendingActions
|
||||
// / FlushPendingDeletes / TickAll are NO LONGER called here. The
|
||||
// 2026-05-10 refactor put them on this EndScene reverse-P/Invoke
|
||||
// (AC's D3D9 render thread); a GC during the plugin tick on that
|
||||
// AC-owned thread fail-fasts in NativeAOT's
|
||||
// RhpReversePInvokeAttachOrTrapThread2 (proven from the
|
||||
// 2026-05-16 09:39 dump). They now run on the dedicated managed
|
||||
// plugin pump thread (EntryPoint.StartNormalPluginPump →
|
||||
// PumpPluginFrame), which mirrors the proven DecalCoexistence
|
||||
// pump. EXACTLY ONE TickAll driver: this render path no longer
|
||||
// calls it at all.
|
||||
|
||||
// ── ImGui-gated work ─────────────────────────────────────────
|
||||
if (Plugins.EngineSettings.EnableImGuiBackend)
|
||||
RunImGuiFrame(pDevice);
|
||||
|
||||
// Fallback render — only fires when the injector missed this
|
||||
// frame's 3D→UI transition. _coreInitialized is enough — this
|
||||
// does not touch font / vertex buffer state.
|
||||
if (!nav3DAlreadyRendered)
|
||||
DX9Backend.RenderNav3D(pDevice);
|
||||
|
||||
// Custom D3D9 vital HUD (Health/Stamina/Mana). Always-on (independent
|
||||
// of EnableImGuiBackend) so it shows even in Avalonia-only mode; drawn
|
||||
// last so it sits on top of the world + AC UI. Reads the vitals
|
||||
// snapshot maintained on this same (AC main) thread and does its own
|
||||
// device state save/restore. No-op until vitals are seeded.
|
||||
if (Plugins.EngineSettings.DrawCustomVitalBars)
|
||||
D3D9.VitalHud.Draw(pDevice);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Info($"EngineFrameController: frame {_frameCount} engine error: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Prime the injector for the next frame's DIP accumulation.
|
||||
// Without this, _markersRenderedThisFrame latches true after
|
||||
// the first 3D→UI transition in the session and the injector
|
||||
// never fires again — every subsequent frame falls back to the
|
||||
// end-of-frame draw (which paints over the UI).
|
||||
D3D9.Nav3DRenderInjector.ResetFrame();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The plugin lifecycle/tick work that used to run inline in
|
||||
/// <see cref="OnEndScene"/>. Driven by the dedicated managed plugin pump
|
||||
/// thread (EntryPoint.StartNormalPluginPump) — NOT AC's render thread —
|
||||
/// so a GC during the plugin tick can't fail-fast NativeAOT's reverse-
|
||||
/// P/Invoke transition on an AC-owned thread (the 2026-05-16 root cause).
|
||||
///
|
||||
/// No-ops until the render path has resolved the game HWND and published
|
||||
/// a device (CachedDevice != 0). Single-threaded by contract: only the
|
||||
/// one pump thread calls this; the render path no longer touches
|
||||
/// PluginManager at all, so there is exactly one TickAll driver. The
|
||||
/// re-entrancy guard is belt-and-braces against an accidental second
|
||||
/// caller.
|
||||
/// </summary>
|
||||
public static void PumpPluginFrame()
|
||||
{
|
||||
IntPtr device = CachedDevice;
|
||||
if (device == IntPtr.Zero || _gameHwnd == IntPtr.Zero)
|
||||
return; // render path hasn't established core state yet
|
||||
|
||||
if (System.Threading.Interlocked.Exchange(ref _pluginPumpInFrame, 1) != 0)
|
||||
return; // never re-enter PluginManager from two stacks
|
||||
try
|
||||
{
|
||||
if (!_pluginsInitialized)
|
||||
{
|
||||
_pluginsInitialized = true;
|
||||
PluginManager.InitPlugins(_context, device, _gameHwnd);
|
||||
}
|
||||
|
||||
PluginManager.ProcessPendingActions(_context, device, _gameHwnd);
|
||||
PluginManager.FlushPendingDeletes(); // closes the create→delete race window
|
||||
PluginManager.TickAll();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Plugin($"EngineFrameController.PumpPluginFrame: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
System.Threading.Interlocked.Exchange(ref _pluginPumpInFrame, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the ImGui-specific portion of the per-frame pipeline:
|
||||
/// backend NewFrame plumbing, ImGui frame open/close, RynthCore shell +
|
||||
/// plugin RenderAll, draw-data submission, capture flag update, and the
|
||||
/// multi-viewport platform pump. Bypassed entirely when
|
||||
/// EngineSettings.EnableImGuiBackend is false.
|
||||
/// </summary>
|
||||
private static void RunImGuiFrame(IntPtr pDevice)
|
||||
{
|
||||
if (_imguiInitFailed) return;
|
||||
|
||||
if (!_imguiInitialized)
|
||||
{
|
||||
if (!Init(pDevice))
|
||||
{
|
||||
_imguiInitFailed = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
|
||||
ImGuiNET.ImGui.SetCurrentContext(_context);
|
||||
bool frameStarted = false;
|
||||
bool frameEnded = false;
|
||||
|
||||
try
|
||||
{
|
||||
_frameCount++;
|
||||
DX9Backend.NewFrame();
|
||||
Win32Backend.NewFrame();
|
||||
|
||||
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
|
||||
// Fallback: if Win32Backend could not determine display size, read from the D3D9 viewport.
|
||||
if (io.DisplaySize.X <= 1 || io.DisplaySize.Y <= 1)
|
||||
{
|
||||
DX9Backend.GetViewportSize(pDevice, out int vpW, out int vpH);
|
||||
if (vpW > 1 && vpH > 1)
|
||||
io.DisplaySize = new System.Numerics.Vector2(vpW, vpH);
|
||||
}
|
||||
|
||||
long now = Stopwatch.GetTimestamp();
|
||||
float dt = (float)(now - _lastFrameTicks) / Stopwatch.Frequency;
|
||||
_lastFrameTicks = now;
|
||||
io.DeltaTime = dt > 0f ? dt : 1f / 60f;
|
||||
|
||||
// With ViewportsEnable on, ImGui routes mouse and window positions in
|
||||
// absolute screen coords. The main viewport's Pos must equal the game
|
||||
// client's screen origin so clicks over the main viewport map to the
|
||||
// correct windows, and popped-out viewports share a coord system with
|
||||
// the main one.
|
||||
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
|
||||
{
|
||||
int screenX = 0, screenY = 0;
|
||||
if (_gameHwnd != IntPtr.Zero)
|
||||
{
|
||||
ClientPoint p = new ClientPoint { X = 0, Y = 0 };
|
||||
if (ClientToScreen(_gameHwnd, ref p)) { screenX = p.X; screenY = p.Y; }
|
||||
}
|
||||
ImGuiViewportPtr mainVp = ImGuiNET.ImGui.GetMainViewport();
|
||||
mainVp.Pos = new System.Numerics.Vector2(screenX, screenY);
|
||||
mainVp.Size = io.DisplaySize;
|
||||
mainVp.WorkPos = new System.Numerics.Vector2(screenX, screenY);
|
||||
mainVp.WorkSize = io.DisplaySize;
|
||||
}
|
||||
|
||||
ImGuiNET.ImGui.NewFrame();
|
||||
frameStarted = true;
|
||||
// EnableImGuiShell gates the in-AC ImGui surface as a whole: both the
|
||||
// RynthCore overlay bar and any plugin-drawn ImGui windows. Plugins
|
||||
// still load, init, and tick when this is off — they just don't
|
||||
// draw, so Avalonia panels can drive them via the plugin's C exports.
|
||||
if (Plugins.EngineSettings.EnableImGuiShell)
|
||||
{
|
||||
RynthCoreShell.Render(_frameCount);
|
||||
PluginManager.RenderAll();
|
||||
}
|
||||
|
||||
bool captureMouse =
|
||||
ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow) ||
|
||||
ImGuiNET.ImGui.IsAnyItemActive();
|
||||
bool captureKeyboard = ImGuiNET.ImGui.IsAnyItemActive();
|
||||
|
||||
ImGuiNET.ImGui.EndFrame();
|
||||
frameEnded = true;
|
||||
ImGuiNET.ImGui.Render();
|
||||
Win32Backend.UpdateCaptureFlags(captureMouse, captureKeyboard);
|
||||
|
||||
ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
|
||||
|
||||
DX9Backend.RenderDrawData(drawData, pDevice);
|
||||
// OverlayTextureRenderer.Render is now driven from EndSceneHook.EndSceneDetour
|
||||
// directly so the Avalonia compositor runs even when EnableImGuiBackend=false.
|
||||
// Leaving it out of this call site avoids double-blit when ImGui is also active.
|
||||
|
||||
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
|
||||
{
|
||||
ImGuiNET.ImGui.UpdatePlatformWindows();
|
||||
ImGuiNET.ImGui.RenderPlatformWindowsDefault();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Keep Dear ImGui's frame state balanced so the next frame does not assert.
|
||||
if (frameStarted && !frameEnded && ImGuiNET.ImGui.GetCurrentContext() == _context)
|
||||
ImGuiNET.ImGui.EndFrame();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
RynthLog.Info($"EngineFrameController: frame {_frameCount} ImGui error: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
ImGuiNET.ImGui.SetCurrentContext(previousContext);
|
||||
}
|
||||
}
|
||||
|
||||
internal static IntPtr FindGameWindow()
|
||||
{
|
||||
uint pid = GetCurrentProcessId();
|
||||
IntPtr found = IntPtr.Zero;
|
||||
|
||||
EnumWindows((hWnd, _) =>
|
||||
{
|
||||
GetWindowThreadProcessId(hWnd, out uint windowPid);
|
||||
if (windowPid == pid && IsWindowVisible(hWnd))
|
||||
{
|
||||
found = hWnd;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}, IntPtr.Zero);
|
||||
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
|
@ -52,9 +52,25 @@ internal static class RynthCoreShell
|
|||
private static Vector2 _barPosition = new(12f, 12f);
|
||||
private static bool _barPositionInitialized;
|
||||
private static bool _barResetRequested = true;
|
||||
/// <summary>Previous frame's in-world state, tracked in <see cref="Render"/>
|
||||
/// so the logout→login rising edge can re-assert the remembered bar
|
||||
/// position (ImGui silently clamps the inactive bar window while logged
|
||||
/// out if AC's DisplaySize shrinks during the login transition).</summary>
|
||||
private static bool _wasInWorld;
|
||||
private static long _lastBarSaveTick;
|
||||
private static Vector2 _lastSavedBarPosition;
|
||||
|
||||
/// <summary>Set from outside AC's render thread (the /rc resetbar chat
|
||||
/// command, or the launcher's Reset Overlay Bar button via dispatch.txt)
|
||||
/// to drag the bar back on-screen. Consumed at the top of
|
||||
/// <see cref="RenderControlBar"/>. Volatile: written by a worker thread,
|
||||
/// read by the render thread.</summary>
|
||||
private static volatile bool _externalResetPending;
|
||||
|
||||
/// <summary>Serializes the two cross-thread writers of the bar cfg file:
|
||||
/// the render-thread throttled save vs. the worker-thread external reset.</summary>
|
||||
private static readonly object BarCfgLock = new();
|
||||
|
||||
private static readonly string BarPositionPath = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
|
||||
"RynthCore.bar.cfg");
|
||||
|
|
@ -73,6 +89,12 @@ internal static class RynthCoreShell
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>Set by the ERl click handler so the shell skips rendering for a
|
||||
/// few frames before the engine actually tears down. Otherwise the last
|
||||
/// drawn frame (with the ERl tooltip) gets stranded in the bar's viewport
|
||||
/// HWND backbuffer and stays visible after reload.</summary>
|
||||
internal static volatile bool SuppressDraw;
|
||||
|
||||
public static void Render(int frameCount)
|
||||
{
|
||||
ApplyTheme();
|
||||
|
|
@ -83,9 +105,26 @@ internal static class RynthCoreShell
|
|||
// during that window has been observed to crash D3D9 because plugin
|
||||
// controls reach into half-released game data.
|
||||
bool inWorld = LoginLifecycleHooks.HasObservedLoginComplete;
|
||||
|
||||
// Logout→login rising edge. While logged out the bar window is not
|
||||
// submitted (early-return below); if AC's DisplaySize transiently
|
||||
// shrinks during the login transition (D3D9 device reset / login
|
||||
// screen) ImGui clamps the inactive bar window toward a corner. On
|
||||
// re-login the FirstUseEver SetNextWindowPos is a no-op, so without
|
||||
// this the bar would reappear wherever ImGui parked it and that
|
||||
// position would then be saved over the good one. Re-assert the
|
||||
// remembered position authoritatively for one frame; the user can
|
||||
// still freely drag it afterwards.
|
||||
if (inWorld && !_wasInWorld)
|
||||
_barResetRequested = true;
|
||||
_wasInWorld = inWorld;
|
||||
|
||||
if (!inWorld)
|
||||
return;
|
||||
|
||||
if (SuppressDraw)
|
||||
return;
|
||||
|
||||
RenderControlBar(frameCount);
|
||||
|
||||
if (_showDemoWindow)
|
||||
|
|
@ -102,6 +141,12 @@ internal static class RynthCoreShell
|
|||
|
||||
if (_showPacketSnifferWindow)
|
||||
RenderPacketSnifferWindow();
|
||||
|
||||
// Deep-audit finding #25: sync AFTER the render call (not before), since
|
||||
// RenderPacketSnifferWindow's ImGui.Begin can flip _showPacketSnifferWindow
|
||||
// false this same frame (the window's X button) — Track() should stop
|
||||
// allocating the instant the panel closes, not one frame late.
|
||||
RawOpcodeTracker.Active = _showPacketSnifferWindow;
|
||||
}
|
||||
|
||||
private static void ApplyTheme()
|
||||
|
|
@ -152,6 +197,19 @@ internal static class RynthCoreShell
|
|||
|
||||
private static void RenderControlBar(int frameCount)
|
||||
{
|
||||
if (_externalResetPending)
|
||||
{
|
||||
// Recovered via /rc resetbar (chat) or the launcher button. The
|
||||
// cfg file was already rewritten to 12,12 by RequestExternalReset;
|
||||
// mark initialized so the load-from-cfg branch below can't restore
|
||||
// the stale off-screen value, and force a hard reposition.
|
||||
_externalResetPending = false;
|
||||
_barPositionInitialized = true;
|
||||
_barPosition = new Vector2(12f, 12f);
|
||||
_lastSavedBarPosition = _barPosition;
|
||||
_barResetRequested = true;
|
||||
}
|
||||
|
||||
if (!_barPositionInitialized)
|
||||
{
|
||||
_barPosition = LoadBarPosition();
|
||||
|
|
@ -161,7 +219,7 @@ internal static class RynthCoreShell
|
|||
|
||||
// With ViewportsEnable, ImGui expects absolute screen coords. We store
|
||||
// the bar position as client-relative, so offset by the main viewport's
|
||||
// origin (which ImGuiController sets to ClientToScreen(0,0) each frame).
|
||||
// origin (which EngineFrameController sets to ClientToScreen(0,0) each frame).
|
||||
Vector2 viewportOrigin = ImGui.GetMainViewport().Pos;
|
||||
Vector2 screenPos = _barPosition + viewportOrigin;
|
||||
|
||||
|
|
@ -284,6 +342,40 @@ internal static class RynthCoreShell
|
|||
ResetBarPosition();
|
||||
ShowTooltip("Reset the bar to the top-left corner.");
|
||||
|
||||
ImGui.SameLine();
|
||||
if (ImGui.SmallButton("Sd"))
|
||||
{
|
||||
// Spawn a background thread so the EndScene detour returns before
|
||||
// EngineLifecycle.Shutdown disables the EndScene hook itself.
|
||||
new System.Threading.Thread(() =>
|
||||
{
|
||||
try { EngineLifecycle.Shutdown(); }
|
||||
catch (Exception ex) { RynthLog.Info($"Shutdown trigger failed: {ex}"); }
|
||||
})
|
||||
{ IsBackground = true, Name = "RynthCore.Shutdown" }.Start();
|
||||
}
|
||||
ShowTooltip("Engine shutdown (debug): tear down hooks/overlay/plugins. Engine stays loaded but goes silent.");
|
||||
|
||||
ImGui.SameLine();
|
||||
if (ImGui.SmallButton("ERl"))
|
||||
{
|
||||
RynthLog.Info("ERl button clicked — suppressing shell draw, then signaling reload.");
|
||||
// Suppress the shell from rendering for the next few frames so
|
||||
// the bar's separate viewport HWND presents a blank backbuffer
|
||||
// before we destroy it — otherwise the still-drawn ERl tooltip
|
||||
// pixels get stranded in that swap chain and stay visible after
|
||||
// the engine reloads.
|
||||
SuppressDraw = true;
|
||||
new System.Threading.Thread(() =>
|
||||
{
|
||||
System.Threading.Thread.Sleep(120);
|
||||
bool ok = EngineLifecycle.SignalReload();
|
||||
RynthLog.Info($"ERl: SignalReload returned {ok}.");
|
||||
})
|
||||
{ IsBackground = true, Name = "RynthCore.ERl" }.Start();
|
||||
}
|
||||
ShowTooltip("Engine reload: shut down, FreeLibrary, reload from disk, re-init. Picks up new engine builds without restarting AC.");
|
||||
|
||||
ImGui.End();
|
||||
ImGui.PopStyleVar(3);
|
||||
}
|
||||
|
|
@ -321,6 +413,21 @@ internal static class RynthCoreShell
|
|||
SaveBarPosition();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// External, thread-safe request to put the bar back at the top-left
|
||||
/// corner. Safe to call from any thread (chat-command dispatch thread,
|
||||
/// ChatFileDispatcher timer). The live in-memory move happens on the next
|
||||
/// rendered frame via <see cref="_externalResetPending"/>; the persisted
|
||||
/// cfg is rewritten immediately so a relaunch is clean too, even if the
|
||||
/// bar is not currently rendering (e.g. not yet in-world).
|
||||
/// </summary>
|
||||
internal static void RequestExternalReset()
|
||||
{
|
||||
RynthLog.Info("RynthCoreShell: external bar-position reset requested.");
|
||||
_externalResetPending = true;
|
||||
WriteBarPosition(new Vector2(12f, 12f));
|
||||
}
|
||||
|
||||
private static Vector2 LoadBarPosition()
|
||||
{
|
||||
try
|
||||
|
|
@ -350,13 +457,21 @@ internal static class RynthCoreShell
|
|||
}
|
||||
|
||||
private static void SaveBarPosition()
|
||||
{
|
||||
_lastBarSaveTick = Environment.TickCount64;
|
||||
_lastSavedBarPosition = _barPosition;
|
||||
WriteBarPosition(_barPosition);
|
||||
}
|
||||
|
||||
private static void WriteBarPosition(Vector2 pos)
|
||||
{
|
||||
try
|
||||
{
|
||||
_lastBarSaveTick = Environment.TickCount64;
|
||||
_lastSavedBarPosition = _barPosition;
|
||||
File.WriteAllText(BarPositionPath,
|
||||
$"{_barPosition.X.ToString(CultureInfo.InvariantCulture)},{_barPosition.Y.ToString(CultureInfo.InvariantCulture)}");
|
||||
lock (BarCfgLock)
|
||||
{
|
||||
File.WriteAllText(BarPositionPath,
|
||||
$"{pos.X.ToString(CultureInfo.InvariantCulture)},{pos.Y.ToString(CultureInfo.InvariantCulture)}");
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -616,7 +616,7 @@ internal static unsafe class ViewportPlatformBackend
|
|||
private static void ViewportUpdate(ImGuiViewport* vp)
|
||||
{
|
||||
// No-op on Win32 — imgui_impl_win32 handles monitor updates and other
|
||||
// housekeeping elsewhere. We refresh monitors from ImGuiController.
|
||||
// housekeeping elsewhere. We refresh monitors from EngineFrameController.
|
||||
}
|
||||
|
||||
private static bool TryGetState(ImGuiViewport* vp, out ViewportState state)
|
||||
|
|
@ -629,11 +629,17 @@ internal static unsafe class ViewportPlatformBackend
|
|||
|
||||
private static IntPtr ViewportWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
|
||||
{
|
||||
// If the ImGui context has been torn down (Shutdown already ran), don't
|
||||
// touch any ImGui API — the context memory is freed and any call into it
|
||||
// is a use-after-free. Just forward to the default handler.
|
||||
if (ImGuiContext == IntPtr.Zero)
|
||||
return DefWindowProcW(hWnd, msg, wParam, lParam);
|
||||
|
||||
// OS delivers messages (WM_GETICON, WM_PAINT, etc.) asynchronously outside
|
||||
// of EndScene. By then our saved context has been restored → GImGui is null,
|
||||
// and any ImGui call here AVs. Temporarily set our context for the message.
|
||||
IntPtr saved = ImGuiNET.ImGui.GetCurrentContext();
|
||||
if (ImGuiContext != IntPtr.Zero && saved != ImGuiContext)
|
||||
if (saved != ImGuiContext)
|
||||
ImGuiNET.ImGui.SetCurrentContext(ImGuiContext);
|
||||
|
||||
try
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using ImGuiNET;
|
||||
using RynthCore.Engine.D3D9;
|
||||
using RynthCore.Engine.UI;
|
||||
|
|
@ -17,6 +18,7 @@ internal static unsafe class Win32Backend
|
|||
{
|
||||
// ─── Win32 messages ───────────────────────────────────────────────
|
||||
private const uint WM_MOUSEMOVE = 0x0200;
|
||||
private const uint WM_NCMOUSEMOVE = 0x00A0;
|
||||
private const uint WM_SETFOCUS = 0x0007;
|
||||
private const uint WM_KILLFOCUS = 0x0008;
|
||||
private const uint WM_ACTIVATE = 0x0006;
|
||||
|
|
@ -39,23 +41,77 @@ internal static unsafe class Win32Backend
|
|||
private const uint WM_SETCURSOR = 0x0020;
|
||||
private const uint WM_XBUTTONDOWN = 0x020B;
|
||||
private const uint WM_XBUTTONUP = 0x020C;
|
||||
private const uint WM_CLOSE = 0x0010;
|
||||
|
||||
// Set on the first WM_CLOSE so we kick off the engine teardown exactly
|
||||
// once even if AC reposts WM_CLOSE during its shutdown sequence.
|
||||
private static int _wmCloseSeen;
|
||||
|
||||
/// <summary>Arms the post-close mouse/cursor input swallow without running the
|
||||
/// WM_CLOSE pump-stop/shutdown block (the caller has already quiesced). Used by
|
||||
/// GameTickHooks when AC exits via a path that never delivers WM_CLOSE (in-game
|
||||
/// exit / logout-quit) — late WM_MOUSEMOVE/WM_SETCURSOR otherwise reach
|
||||
/// ClientUISystem::UpdateCursorState after AC frees the combat-system singleton
|
||||
/// (the 0x0056547B close AV).</summary>
|
||||
internal static void MarkCloseInFlight() => Interlocked.Exchange(ref _wmCloseSeen, 1);
|
||||
|
||||
private const int GWL_WNDPROC = -4;
|
||||
private const uint GA_ROOT = 2;
|
||||
private const int HTCLIENT = 1;
|
||||
|
||||
/// <summary>Posted by AvaloniaSubclassWndProc when Avalonia acquires focus.
|
||||
/// Handled here (game thread) so SetFocus is always same-thread — no cross-thread wait.</summary>
|
||||
public const uint WM_RYNTH_RESTORE_FOCUS = 0x8001;
|
||||
|
||||
/// <summary>Sent by RunOnGameThread to execute a queued Action on the game's
|
||||
/// main thread (where AC's WndProc dispatches). Used to create top-level HWNDs
|
||||
/// like floating panels' LayeredWindow on AC's thread instead of Avalonia's UI
|
||||
/// thread, so WS_EX_NOACTIVATE + mouse delivery work as documented (cross-thread
|
||||
/// HWNDs drop WM_LBUTTONDOWN on Win11 in some focus states).</summary>
|
||||
public const uint WM_RYNTH_RUN_ACTION = 0x8002;
|
||||
|
||||
/// <summary>UI deep-dive finding P0-1 belt-and-braces (2026-07-02):
|
||||
/// posted (not sent) by LayeredWindow.Dispose to destroy an HWND on the
|
||||
/// game thread without blocking the calling thread — DestroyWindow must
|
||||
/// run on the owning thread, but the caller (often the Avalonia UI
|
||||
/// thread, e.g. redocking a panel) doesn't need to wait for it to
|
||||
/// finish. wParam carries the HWND to destroy.</summary>
|
||||
public const uint WM_RYNTH_DESTROY_HWND = 0x8003;
|
||||
|
||||
/// <summary>Destroys floating-panel HWNDs on the game thread (their owner).
|
||||
/// wParam != 0 includes this engine load's own panels (sent synchronously by
|
||||
/// Shutdown before unhooking); wParam == 0 removes only panels an earlier
|
||||
/// load left behind (posted by Init). See LayeredWindow.DestroyThreadPanelWindows.</summary>
|
||||
public const uint WM_RYNTH_SWEEP_PANELS = 0x8004;
|
||||
|
||||
private const int VK_CONTROL = 0x11;
|
||||
private const int VK_SHIFT = 0x10;
|
||||
private const int VK_MENU = 0x12; // Alt
|
||||
private const int VK_LWIN = 0x5B;
|
||||
private const int VK_RWIN = 0x5C;
|
||||
private const int VK_INSERT = 0x2D;
|
||||
private const int VK_RETURN = 0x0D;
|
||||
private const int VK_BACK = 0x08;
|
||||
private const int VK_ESCAPE = 0x1B;
|
||||
private const int VK_LEFT = 0x25;
|
||||
private const int VK_UP = 0x26;
|
||||
private const int VK_RIGHT = 0x27;
|
||||
private const int VK_DOWN = 0x28;
|
||||
private const int VK_HOME = 0x24;
|
||||
private const int VK_END = 0x23;
|
||||
private const int VK_DELETE = 0x2E;
|
||||
// lParam bit 24: extended key flag. Set for numpad Enter, right-side Ctrl/Alt.
|
||||
// Used to distinguish numpad Enter (extended) from the main keyboard Enter (not extended).
|
||||
private static bool IsExtendedKey(IntPtr lParam) => ((int)(long)lParam & 0x01000000) != 0;
|
||||
|
||||
// ─── Win32 P/Invoke ───────────────────────────────────────────────
|
||||
// On x86, SetWindowLongPtr doesn't exist — use SetWindowLong
|
||||
[DllImport("user32.dll", EntryPoint = "SetWindowLongA", SetLastError = true)]
|
||||
private static extern IntPtr SetWindowLong32(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
|
||||
|
||||
[DllImport("user32.dll", EntryPoint = "GetWindowLongA", SetLastError = true)]
|
||||
private static extern IntPtr GetWindowLong32(IntPtr hWnd, int nIndex);
|
||||
|
||||
[DllImport("user32.dll", EntryPoint = "CallWindowProcA")]
|
||||
private static extern IntPtr CallWindowProcA(IntPtr lpPrevWndFunc, IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
|
||||
|
||||
|
|
@ -93,12 +149,47 @@ internal static unsafe class Win32Backend
|
|||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
|
||||
|
||||
private const uint SMTO_NORMAL = 0x0000;
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
private static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam,
|
||||
uint fuFlags, uint uTimeout, out IntPtr lpdwResult);
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool DestroyWindow(IntPtr hWnd);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern uint GetCurrentThreadId();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr SetFocus(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr SetCapture(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool ReleaseCapture();
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
||||
private static extern int GetClassNameW(IntPtr hWnd, System.Text.StringBuilder lpClassName, int nMaxCount);
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
||||
private static extern int GetWindowTextW(IntPtr hWnd, System.Text.StringBuilder lpString, int nMaxCount);
|
||||
|
||||
private static string DescribeHwnd(IntPtr hwnd)
|
||||
{
|
||||
if (hwnd == IntPtr.Zero) return "null";
|
||||
var cls = new System.Text.StringBuilder(128);
|
||||
var txt = new System.Text.StringBuilder(128);
|
||||
GetClassNameW(hwnd, cls, cls.Capacity);
|
||||
GetWindowTextW(hwnd, txt, txt.Capacity);
|
||||
return $"class='{cls}' title='{txt}'";
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct RECT { public int Left, Top, Right, Bottom; }
|
||||
|
||||
|
|
@ -152,10 +243,36 @@ internal static unsafe class Win32Backend
|
|||
|
||||
/// <summary>Custom WM_USER message for deferred chat command dispatch.</summary>
|
||||
internal const uint WM_RYNTHCORE_CHAT = 0x0400 + 0x5243; // WM_USER + "RC"
|
||||
// Chat's Tell button (Avalonia UI thread) asks for "/tell <selected>, " to be started;
|
||||
// posted so the selection and its name are read on AC's main thread.
|
||||
internal const uint WM_RYNTHCORE_TELL = 0x0400 + 0x5244;
|
||||
|
||||
/// <summary>Fired on the game thread when the Tell button asks to address the selected object.</summary>
|
||||
public static Action? OnChatTellSelected;
|
||||
|
||||
/// <summary>Callable from any thread: runs <see cref="OnChatTellSelected"/> on AC's main thread.</summary>
|
||||
public static void RequestTellSelected()
|
||||
{
|
||||
if (_gameHwnd != IntPtr.Zero)
|
||||
PostMessage(_gameHwnd, WM_RYNTHCORE_TELL, IntPtr.Zero, IntPtr.Zero);
|
||||
}
|
||||
|
||||
/// <summary>The game's main window handle.</summary>
|
||||
public static IntPtr GameHwnd => _gameHwnd;
|
||||
|
||||
/// <summary>
|
||||
/// Populate <see cref="GameHwnd"/> from outside the ImGui Init path.
|
||||
/// Used by Avalonia-only overlay mode where ImGui is disabled but Avalonia
|
||||
/// panels still need the game HWND for owner-window binding. Idempotent —
|
||||
/// the WndProc subclass that <see cref="Init"/> installs is *not* set up by
|
||||
/// this call, so don't use this if ImGui is going to init too.
|
||||
/// </summary>
|
||||
public static void SetGameHwndExternal(IntPtr hwnd)
|
||||
{
|
||||
if (hwnd != IntPtr.Zero && _gameHwnd == IntPtr.Zero)
|
||||
_gameHwnd = hwnd;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a message directly to the game's original WndProc, bypassing our subclass.
|
||||
/// </summary>
|
||||
|
|
@ -163,8 +280,127 @@ internal static unsafe class Win32Backend
|
|||
{
|
||||
if (_originalWndProc == IntPtr.Zero || _gameHwnd == IntPtr.Zero)
|
||||
return IntPtr.Zero;
|
||||
// Diag (diag/logoff-origin): engine-synthesised input bypasses the subclass.
|
||||
Compatibility.LogoffOriginProbe.RecordWndMsg(msg, wParam, lParam, synthetic: true);
|
||||
return CallWindowProcA(_originalWndProc, _gameHwnd, msg, wParam, lParam);
|
||||
}
|
||||
|
||||
private static readonly object _gameThreadLock = new();
|
||||
private static volatile Action? _pendingGameThreadAction;
|
||||
|
||||
/// <summary>
|
||||
/// Runs <paramref name="action"/> synchronously on AC's main thread (the one
|
||||
/// that dispatches the hooked game WndProc), and returns its result. Used so
|
||||
/// HWNDs that must dispatch input on the game thread — most notably the
|
||||
/// floating-panel LayeredWindows — can be created from any thread (e.g.
|
||||
/// Avalonia's UI thread) without ending up cross-thread to AC. Without
|
||||
/// same-thread ownership, Win11's WS_EX_NOACTIVATE silently drops
|
||||
/// WM_LBUTTONDOWN in some focus states (the docked panels work because they
|
||||
/// already live on the game thread via the EndScene-driven path).
|
||||
///
|
||||
/// Implementation: a single shared action slot serialized by a lock; the
|
||||
/// action is delivered via SendMessage(WM_RYNTH_RUN_ACTION) which blocks
|
||||
/// until the game thread's WndProc has handled it. Game-thread callers
|
||||
/// bypass the marshal and invoke inline.
|
||||
/// </summary>
|
||||
public static T RunOnGameThread<T>(Func<T> action)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(action);
|
||||
if (_gameHwnd == IntPtr.Zero)
|
||||
throw new InvalidOperationException("RunOnGameThread called before Win32Backend.Init.");
|
||||
|
||||
GetWindowThreadProcessId(_gameHwnd, out uint gameThreadId);
|
||||
if (gameThreadId == GetCurrentThreadId())
|
||||
return action();
|
||||
|
||||
lock (_gameThreadLock)
|
||||
{
|
||||
T result = default!;
|
||||
Exception? caught = null;
|
||||
_pendingGameThreadAction = () =>
|
||||
{
|
||||
try { result = action(); }
|
||||
catch (Exception ex) { caught = ex; }
|
||||
};
|
||||
|
||||
// UI deep-dive finding P0-1 belt-and-braces (2026-07-02): a plain
|
||||
// SendMessage here blocks with no visibility if the game thread's
|
||||
// WndProc is ever stuck (the AB-BA class the OnInput fix above
|
||||
// closes, or any future one). SendMessageTimeout with a 2s
|
||||
// budget logs loudly the instant a stall crosses that threshold
|
||||
// — a concrete timestamped log line to correlate against a user
|
||||
// report, instead of silence.
|
||||
//
|
||||
// Deliberately does NOT retry the send on timeout: this shared
|
||||
// single-slot design (_pendingGameThreadAction) has no way to
|
||||
// tell a stale delivery from a fresh one, and Win32 doesn't
|
||||
// guarantee a second SendMessage call coalesces with a still-
|
||||
// pending first one rather than queuing a second delivery — a
|
||||
// retry risks the action firing twice (e.g. creating a
|
||||
// LayeredWindow, twice) once the game thread unblocks. Logging
|
||||
// and returning the default result is a strictly better failure
|
||||
// mode than today's silent, undiagnosed, permanent hang: if
|
||||
// we're 2s+ into this wait, something is already badly wrong,
|
||||
// and a caller getting a default/null result it can react to
|
||||
// beats every thread being frozen with nothing in the log.
|
||||
IntPtr sendResult = SendMessageTimeout(_gameHwnd, WM_RYNTH_RUN_ACTION, IntPtr.Zero, IntPtr.Zero,
|
||||
SMTO_NORMAL, 2000, out _);
|
||||
if (sendResult == IntPtr.Zero)
|
||||
{
|
||||
try { RynthLog.Info($"Win32Backend: RunOnGameThread stalled >2s waiting on game thread (hwnd=0x{_gameHwnd.ToInt64():X}) — giving up this wait; result will be default."); }
|
||||
catch { }
|
||||
}
|
||||
_pendingGameThreadAction = null;
|
||||
if (caught != null)
|
||||
throw caught;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Void overload of <see cref="RunOnGameThread{T}"/>.</summary>
|
||||
public static void RunOnGameThread(Action action)
|
||||
{
|
||||
RunOnGameThread<bool>(() => { action(); return true; });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UI deep-dive finding P0-1 (2026-07-02): posts (does not block on) a
|
||||
/// DestroyWindow for <paramref name="hwnd"/> onto the game thread.
|
||||
/// DestroyWindow must run on the HWND's owning thread, but unlike
|
||||
/// RunOnGameThread this never needs the caller to observe a result — so
|
||||
/// it uses a dedicated PostMessage instead of the shared
|
||||
/// RunOnGameThread action slot, avoiding any risk of blocking the
|
||||
/// caller (e.g. LayeredWindow.Dispose called from the Avalonia UI
|
||||
/// thread while redocking a panel) on the game thread's WndProc.
|
||||
/// </summary>
|
||||
public static void PostDestroyWindow(IntPtr hwnd)
|
||||
{
|
||||
if (hwnd == IntPtr.Zero) return;
|
||||
if (_gameHwnd == IntPtr.Zero)
|
||||
{
|
||||
// No game thread to marshal to (e.g. very early/late in
|
||||
// lifecycle) — best-effort inline as LayeredWindow.Dispose's own
|
||||
// fallback already does for the RunOnGameThread-unavailable case.
|
||||
DestroyWindow(hwnd);
|
||||
return;
|
||||
}
|
||||
|
||||
GetWindowThreadProcessId(_gameHwnd, out uint gameThreadId);
|
||||
if (gameThreadId == GetCurrentThreadId())
|
||||
{
|
||||
DestroyWindow(hwnd);
|
||||
return;
|
||||
}
|
||||
|
||||
PostMessage(_gameHwnd, WM_RYNTH_DESTROY_HWND, hwnd, IntPtr.Zero);
|
||||
}
|
||||
|
||||
/// <summary>Deactivates chat capture. The game HWND retains focus throughout so no
|
||||
/// Win32 focus transfer is needed.</summary>
|
||||
public static void ReturnFocusToGame() => ChatCaptureActive = false;
|
||||
/// <summary>Called by AvaloniaSubclassWndProc when WM_LBUTTONUP arrives via the
|
||||
/// SetCapture route so _avPanelMouseDown doesn't get stuck true.</summary>
|
||||
internal static void ClearPanelMouseDown() => _avPanelMouseDown = false;
|
||||
private static readonly bool[] _mouseButtons = new bool[5];
|
||||
private static readonly object _inputLock = new();
|
||||
private static readonly Queue<QueuedInputMessage> _pendingInput = new();
|
||||
|
|
@ -176,6 +412,50 @@ internal static unsafe class Win32Backend
|
|||
private static bool _focusInitialized;
|
||||
private static bool _insertWasDown;
|
||||
private static bool _avaloniaHasMouse; // cursor is currently over the Avalonia panel
|
||||
/// <summary>While true, WM_CHAR / special keys are consumed for the chat input TextBox
|
||||
/// instead of passing to the game. Focus stays on the game HWND.</summary>
|
||||
public static volatile bool ChatCaptureActive;
|
||||
|
||||
/// <summary>While true, an Avalonia panel TextBox currently has keyboard focus and
|
||||
/// the WM_SETFOCUS hijack in <see cref="UI.AvaloniaOverlay"/>'s subclass WndProc
|
||||
/// must NOT immediately PostMessage focus back to the game window — doing so
|
||||
/// yanks focus off the TextBox ~50 ms after the user clicks it, making it
|
||||
/// impossible to type. Set true on Avalonia TextBox.GotFocus, false on
|
||||
/// LostFocus. (ChatCaptureActive uses a completely different pipeline:
|
||||
/// the game HWND keeps focus and WM_CHAR is routed to the chat callbacks,
|
||||
/// so it doesn't help for normal panels that genuinely need Avalonia focus.)</summary>
|
||||
public static volatile bool AvaloniaTextInputActive;
|
||||
|
||||
/// <summary>Set when we consume the VK_RETURN/VK_ESCAPE that ends chat capture, so the
|
||||
/// trailing WM_CHAR ('\r') + WM_KEYUP of that same keystroke are eaten too and never
|
||||
/// leak to the game (a lone '\r' can spuriously re-open AC's native chat bar).</summary>
|
||||
private static bool _swallowEnterTail;
|
||||
|
||||
// ── Chat input callbacks (set by RynthChatPanel) ─────────────────────
|
||||
/// <summary>Fired when Enter in-game activates chat (UI thread dispatch optional).</summary>
|
||||
public static Action? OnChatCaptureActivated;
|
||||
/// <summary>Fired for each printable character (≥ 0x20) while capture is active.</summary>
|
||||
public static Action<char>? OnChatChar;
|
||||
/// <summary>Fired on VK_BACK while capture is active.</summary>
|
||||
public static Action? OnChatBackspace;
|
||||
/// <summary>Fired on VK_DELETE while capture is active.</summary>
|
||||
public static Action? OnChatDelete;
|
||||
/// <summary>Fired on VK_RETURN while capture is active (ChatCaptureActive already false).</summary>
|
||||
public static Action? OnChatSend;
|
||||
/// <summary>Fired on VK_ESCAPE while capture is active (ChatCaptureActive already false).</summary>
|
||||
public static Action? OnChatCancel;
|
||||
/// <summary>Fired on VK_LEFT while capture is active.</summary>
|
||||
public static Action? OnChatLeft;
|
||||
/// <summary>Fired on VK_RIGHT while capture is active.</summary>
|
||||
public static Action? OnChatRight;
|
||||
/// <summary>Fired on VK_HOME while capture is active.</summary>
|
||||
public static Action? OnChatHome;
|
||||
/// <summary>Fired on VK_END while capture is active.</summary>
|
||||
public static Action? OnChatEnd;
|
||||
/// <summary>Fired on VK_UP while capture is active (history previous).</summary>
|
||||
public static Action? OnChatUp;
|
||||
/// <summary>Fired on VK_DOWN while capture is active (history next).</summary>
|
||||
public static Action? OnChatDown;
|
||||
private static int _lastPanelClientX; // last game-client pos over the panel (for wheel)
|
||||
private static int _lastPanelClientY;
|
||||
|
||||
|
|
@ -185,6 +465,12 @@ internal static unsafe class Win32Backend
|
|||
private static bool _avIsResizing;
|
||||
private static bool _avIsButtonCapture;
|
||||
private static bool _avHasNativeCapture;
|
||||
// Set when a left-button press lands on an opened Avalonia panel (not the
|
||||
// bar). While set, every mouse event is forwarded to Avalonia regardless
|
||||
// of whether the cursor is still over the panel rect — without this,
|
||||
// a fast drag where the cursor outpaces the panel-position update lands
|
||||
// outside IsOverPanel and the drag drops.
|
||||
private static bool _avPanelMouseDown;
|
||||
private static int _avPrevPhysX;
|
||||
private static int _avPrevPhysY;
|
||||
private static double _avDragResidualX;
|
||||
|
|
@ -201,6 +487,7 @@ internal static unsafe class Win32Backend
|
|||
public static bool Init(IntPtr hWnd)
|
||||
{
|
||||
if (_initialized) return true;
|
||||
_forwardOnly = false; // re-arming in this generation — stop any pass-through latch
|
||||
_gameHwnd = hWnd;
|
||||
_uiCaptureEnabled = true;
|
||||
_hasFocus = false;
|
||||
|
|
@ -208,11 +495,16 @@ internal static unsafe class Win32Backend
|
|||
_wantCaptureMouse = false;
|
||||
_wantCaptureKeyboard = false;
|
||||
_insertWasDown = false;
|
||||
_swallowEnterTail = false;
|
||||
|
||||
// Subclass the window
|
||||
_wndProcDelegate = WndProcHook;
|
||||
IntPtr hookPtr = Marshal.GetFunctionPointerForDelegate(_wndProcDelegate);
|
||||
_installedWndProcPtr = hookPtr;
|
||||
_originalWndProc = SetWindowLong32(hWnd, GWL_WNDPROC, hookPtr);
|
||||
// RynthLog.UI (not .Render — RenderEnabled is false) so chain
|
||||
// composition across generations is reconstructible from the log.
|
||||
RynthLog.UI($"Win32Backend: subclass installed — hook=0x{hookPtr:X8}, previous WndProc=0x{_originalWndProc:X8}.");
|
||||
|
||||
if (_originalWndProc == IntPtr.Zero)
|
||||
{
|
||||
|
|
@ -223,15 +515,60 @@ internal static unsafe class Win32Backend
|
|||
_initialized = true;
|
||||
RynthLog.Render("Win32Backend: Initialized (WndProc subclassed).");
|
||||
RynthLog.Render("Win32Backend: UI capture ENABLED by default (Insert to release).");
|
||||
|
||||
// A previous engine load may have left floating panels behind (its
|
||||
// teardown predates the synchronous sweep in Shutdown, or the game
|
||||
// thread was stalled past the timeout) — clear them now, while
|
||||
// sparing this load's own.
|
||||
PostMessage(_gameHwnd, WM_RYNTH_SWEEP_PANELS, IntPtr.Zero, IntPtr.Zero);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static IntPtr _installedWndProcPtr;
|
||||
private static volatile bool _forwardOnly;
|
||||
|
||||
public static void Shutdown()
|
||||
{
|
||||
if (!_initialized) return;
|
||||
|
||||
// Restore original WndProc
|
||||
SetWindowLong32(_gameHwnd, GWL_WNDPROC, _originalWndProc);
|
||||
// Destroy floating panels while our hook can still run on the game
|
||||
// thread. LayeredWindow.Dispose only POSTS its destroy, and the game
|
||||
// thread usually hasn't reached that post by the time we unhook below —
|
||||
// AC's own WndProc then drops it and the panel outlives this engine
|
||||
// load, frozen and unclickable (duplicate RynthAi dashboard after RL).
|
||||
IntPtr swept = SendMessageTimeout(_gameHwnd, WM_RYNTH_SWEEP_PANELS, new IntPtr(1), IntPtr.Zero,
|
||||
SMTO_NORMAL, 2000, out _);
|
||||
if (swept == IntPtr.Zero)
|
||||
RynthLog.Info($"Win32Backend: Shutdown — panel sweep didn't run on the game thread (err={Marshal.GetLastWin32Error()}); the next engine load clears what's left.");
|
||||
|
||||
// Restore the original WndProc ONLY if we are still the head of the
|
||||
// chain. If something subclassed on top of us after Init (Decal /
|
||||
// DINPUT8 re-hooks, a newer engine generation), a blind restore RIPS
|
||||
// their hook out of the chain — DirectInput's hook proc then
|
||||
// dereferences a freed per-window record on AC's main thread and the
|
||||
// render pump never recovers (the 2026-06-11 DINPUT8+0x20CCC reload
|
||||
// wedge). Leaving the chain intact is always safe: our thunk stays
|
||||
// valid because engine module pages are intentionally leaked across
|
||||
// reloads, and a no-longer-initialized backend just forwards.
|
||||
IntPtr currentProc = GetWindowLong32(_gameHwnd, GWL_WNDPROC);
|
||||
if (currentProc == _installedWndProcPtr || currentProc == IntPtr.Zero)
|
||||
{
|
||||
SetWindowLong32(_gameHwnd, GWL_WNDPROC, _originalWndProc);
|
||||
RynthLog.UI("Win32Backend: Shutdown — WndProc restored (we were chain head).");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Become a pure pass-through instead: a frozen generation that
|
||||
// keeps PROCESSING input swallows WM_CHAR and kills AC's chat
|
||||
// after a reload (the historic stacking bug the unconditional
|
||||
// restore was originally added for). Forward-only keeps the
|
||||
// foreign chain intact AND keeps this generation inert.
|
||||
_forwardOnly = true;
|
||||
// A hit on this line positively confirms a foreign subclasser
|
||||
// stacks above us in live sessions — the blind-restore wedge's
|
||||
// missing precondition. Must be visible in the log.
|
||||
RynthLog.UI($"Win32Backend: Shutdown — chain head is 0x{currentProc:X8}, not ours (0x{_installedWndProcPtr:X8}); leaving the chain intact, hook now forward-only.");
|
||||
}
|
||||
lock (_inputLock)
|
||||
_pendingInput.Clear();
|
||||
Array.Clear(_mouseButtons, 0, _mouseButtons.Length);
|
||||
|
|
@ -250,6 +587,7 @@ internal static unsafe class Win32Backend
|
|||
_avIsDragging = false;
|
||||
_avIsResizing = false;
|
||||
_avIsButtonCapture = false;
|
||||
_avPanelMouseDown = false;
|
||||
ReleaseAvaloniaNativeCapture();
|
||||
_avDragResidualX = 0;
|
||||
_avDragResidualY = 0;
|
||||
|
|
@ -268,6 +606,9 @@ internal static unsafe class Win32Backend
|
|||
|
||||
public static void NewFrame()
|
||||
{
|
||||
// Deferred focus restore: AvaloniaSubclassWndProc sets this flag when
|
||||
// WM_SETFOCUS lands on the off-screen Avalonia HWND. We reclaim focus
|
||||
// here (game thread owns _gameHwnd) so there's no cross-thread wait.
|
||||
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
|
||||
|
||||
// Update display size
|
||||
|
|
@ -288,7 +629,7 @@ internal static unsafe class Win32Backend
|
|||
}
|
||||
|
||||
// If GetClientRect returns 0x0 or 1x1, the HWND might be wrong.
|
||||
// DisplaySize will be set from D3D viewport in ImGuiController instead.
|
||||
// DisplaySize will be set from D3D viewport in EngineFrameController instead.
|
||||
if (w > 1 && h > 1)
|
||||
io.DisplaySize = new System.Numerics.Vector2(w, h);
|
||||
|
||||
|
|
@ -340,20 +681,274 @@ internal static unsafe class Win32Backend
|
|||
|
||||
private static IntPtr WndProcHook(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
|
||||
{
|
||||
// Post-shutdown pass-through: Shutdown could not restore the chain
|
||||
// (someone subclassed after us) — this generation must be inert.
|
||||
if (_forwardOnly)
|
||||
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam);
|
||||
|
||||
try
|
||||
{
|
||||
_wndProcLogCount++;
|
||||
|
||||
// ── Game-thread executor: run a queued Action on this thread ──
|
||||
// Sent by RunOnGameThread via SendMessage (synchronous, blocks the
|
||||
// caller until this returns). Keep this near the top — must dispatch
|
||||
// before any chat / focus / mouse paths so callers waiting on a
|
||||
// CreateWindowExW etc. aren't stuck behind unrelated input handling.
|
||||
if (msg == WM_RYNTH_RUN_ACTION)
|
||||
{
|
||||
Action? a = _pendingGameThreadAction;
|
||||
if (a != null)
|
||||
{
|
||||
try { a(); }
|
||||
catch (Exception ex) { RynthLog.Info($"Win32Backend: WM_RYNTH_RUN_ACTION threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
if (msg == WM_RYNTH_DESTROY_HWND)
|
||||
{
|
||||
IntPtr target = wParam;
|
||||
try
|
||||
{
|
||||
bool destroyed = DestroyWindow(target);
|
||||
int err = destroyed ? 0 : Marshal.GetLastWin32Error();
|
||||
RynthLog.Info($"Win32Backend: WM_RYNTH_DESTROY_HWND DestroyWindow(0x{target.ToInt64():X}) = {destroyed} err={err}.");
|
||||
}
|
||||
catch (Exception ex) { RynthLog.Info($"Win32Backend: WM_RYNTH_DESTROY_HWND threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
if (msg == WM_RYNTH_SWEEP_PANELS)
|
||||
{
|
||||
try { UI.LayeredWindow.DestroyThreadPanelWindows(includeThisGeneration: wParam != IntPtr.Zero); }
|
||||
catch (Exception ex) { RynthLog.Info($"Win32Backend: WM_RYNTH_SWEEP_PANELS threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
// Diag (diag/logoff-origin): ring of recent key/click/focus/close messages,
|
||||
// dumped when the client requests a logoff. Filters first; never throws.
|
||||
Compatibility.LogoffOriginProbe.RecordWndMsg(msg, wParam, lParam, synthetic: false);
|
||||
|
||||
// ── User clicked X / Alt+F4 on AC window — tear our overlay down NOW ──
|
||||
// AC's own shutdown takes 20-30 s (network logout, save, etc.) before
|
||||
// it finally calls ExitProcess and triggers ProcessExitHooks. During
|
||||
// that gap EndScene keeps firing and the floating LayeredWindows
|
||||
// (RynthAi panel etc.) stay visible on the OS desktop, which looks
|
||||
// like the overlay is "stuck up" long after the close click. Running
|
||||
// EngineLifecycle.Shutdown here uninstalls the EndScene hook and
|
||||
// closes every floating panel immediately; the later ExitProcess
|
||||
// detour is a no-op (interlocked guard inside Shutdown). Run on a
|
||||
// background thread so the join on the Avalonia STA doesn't block
|
||||
// AC's own message pump during its shutdown.
|
||||
if (msg == WM_CLOSE && Interlocked.Exchange(ref _wmCloseSeen, 1) == 0)
|
||||
{
|
||||
RynthLog.UI("Win32Backend: WM_CLOSE on AC window — quiescing plugin pump, then kicking engine shutdown.");
|
||||
// AC is about to free the ClientUISystem singleton — drop the
|
||||
// busy watchdog's cached pointer so no force-clear can run
|
||||
// against freed memory during the teardown window.
|
||||
try { Compatibility.BusyCountHooks.ResetSession(); }
|
||||
catch { }
|
||||
// Stop the off-thread plugin pump FIRST, synchronously, on AC's main
|
||||
// thread — we run here BEFORE falling through to AC's own WndProc (which
|
||||
// starts AC's object teardown). The pump's in-flight frame finishes on
|
||||
// still-valid AC objects and then it exits; otherwise it keeps ticking
|
||||
// into DestroyObjectCaches and races AC's frees -> the recurring on-close
|
||||
// AVs (BusyCountHooks.ForceResetBusyCount / PlayerPhysicsHooks.TryGetPlayerPose
|
||||
// -> AC, e.g. acclient+0x16547B null+0x1C; EIP->heap). Bounded ~2s inside
|
||||
// StopTickPumpAndJoin; the background EngineLifecycle.Shutdown below then
|
||||
// finds the pump already stopped (its TickPump.StopAndJoin is a no-op).
|
||||
try { EntryPoint.StopTickPumpAndJoin(); }
|
||||
catch (Exception ex) { RynthLog.UI($"Win32Backend: WM_CLOSE pump-stop threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
|
||||
new Thread(() =>
|
||||
{
|
||||
try { EngineLifecycle.Shutdown(); }
|
||||
catch (Exception ex) { RynthLog.UI($"Win32Backend: WM_CLOSE shutdown threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
})
|
||||
{ Name = "RynthCore.WmCloseShutdown", IsBackground = true }.Start();
|
||||
// Fall through to AC's original WndProc so AC starts its own
|
||||
// shutdown sequence in parallel with ours.
|
||||
}
|
||||
|
||||
// ── Once close is in flight, stop feeding mouse/cursor input to AC ──
|
||||
// After WM_CLOSE, AC tears down its world — including the combat-system
|
||||
// singleton. AC's ClientUISystem::UpdateCursorState (acclient 0x005653D0)
|
||||
// runs on every mouse-move / cursor refresh and dereferences
|
||||
// GetCombatSystem()->[+0x1C]; once the singleton is freed that's an AV at
|
||||
// acclient 0x0056547B reading [null+0x1C]. The user is actively moving the
|
||||
// mouse toward the close control, so a trailing WM_MOUSEMOVE / WM_SETCURSOR
|
||||
// lands right after the free. THIS subclass is the one installed on the
|
||||
// game window (AvaloniaSubclassWndProc carries a matching block, but it is
|
||||
// installed on the off-screen Avalonia HWND and never sees AC's mouse
|
||||
// traffic). WM_CLOSE / WM_DESTROY / paint still fall through so the window
|
||||
// closes normally.
|
||||
if (Volatile.Read(ref _wmCloseSeen) != 0)
|
||||
{
|
||||
switch (msg)
|
||||
{
|
||||
case WM_MOUSEMOVE:
|
||||
case WM_NCMOUSEMOVE:
|
||||
case WM_MOUSEWHEEL:
|
||||
case WM_LBUTTONDOWN:
|
||||
case WM_LBUTTONUP:
|
||||
case WM_RBUTTONDOWN:
|
||||
case WM_RBUTTONUP:
|
||||
case WM_MBUTTONDOWN:
|
||||
case WM_MBUTTONUP:
|
||||
return IntPtr.Zero;
|
||||
case WM_SETCURSOR:
|
||||
return (IntPtr)1; // handled — halt AC's cursor-update chain
|
||||
}
|
||||
}
|
||||
|
||||
// ── Chat capture: consume all key input for the chat TextBox ────
|
||||
// Game HWND keeps Win32 focus throughout; callbacks dispatch Text
|
||||
// updates to the panel on Avalonia's UI thread — no Avalonia focus needed.
|
||||
if (ChatCaptureActive && IsKeyMessage(msg))
|
||||
{
|
||||
if (msg == WM_CHAR)
|
||||
{
|
||||
int ch = (int)wParam;
|
||||
if (ch >= 0x20) // printable characters only
|
||||
OnChatChar?.Invoke((char)ch);
|
||||
}
|
||||
else if (msg == WM_KEYDOWN)
|
||||
{
|
||||
int vk = (int)wParam;
|
||||
if (vk == VK_RETURN && !IsExtendedKey(lParam)) { ChatCaptureActive = false; _swallowEnterTail = true; PostMessage(_gameHwnd, WM_RYNTHCORE_CHAT, IntPtr.Zero, IntPtr.Zero); }
|
||||
else if (vk == VK_ESCAPE) { ChatCaptureActive = false; _swallowEnterTail = true; OnChatCancel?.Invoke(); }
|
||||
else if (vk == VK_BACK) { OnChatBackspace?.Invoke(); }
|
||||
else if (vk == VK_DELETE) { OnChatDelete?.Invoke(); }
|
||||
else if (vk == VK_LEFT) { OnChatLeft?.Invoke(); }
|
||||
else if (vk == VK_RIGHT) { OnChatRight?.Invoke(); }
|
||||
else if (vk == VK_HOME) { OnChatHome?.Invoke(); }
|
||||
else if (vk == VK_END) { OnChatEnd?.Invoke(); }
|
||||
else if (vk == VK_UP) { OnChatUp?.Invoke(); }
|
||||
else if (vk == VK_DOWN) { OnChatDown?.Invoke(); }
|
||||
}
|
||||
return IntPtr.Zero; // eat all key messages while chat is active
|
||||
}
|
||||
|
||||
// ── Swallow the tail of the send/cancel keystroke ─────────────
|
||||
// The block above ends chat capture on VK_RETURN/VK_ESCAPE but eats
|
||||
// only the WM_KEYDOWN. The OS still delivers the matching WM_CHAR
|
||||
// ('\r') and WM_KEYUP; with ChatCaptureActive now false they'd fall
|
||||
// through to the game, and a lone '\r' can spuriously re-open AC's
|
||||
// native chat bar (which then sits open, hidden by suppress, eating
|
||||
// input until it resets — a multi-second dead window for chat).
|
||||
if (_swallowEnterTail)
|
||||
{
|
||||
if (msg == WM_CHAR)
|
||||
return IntPtr.Zero;
|
||||
if ((msg == WM_KEYUP || msg == WM_SYSKEYUP) &&
|
||||
((int)wParam == VK_RETURN || (int)wParam == VK_ESCAPE) &&
|
||||
!IsExtendedKey(lParam))
|
||||
{
|
||||
_swallowEnterTail = false;
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
if (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN)
|
||||
_swallowEnterTail = false; // a new keystroke began; stop guarding
|
||||
}
|
||||
|
||||
// ── Deferred chat send ────────────────────────────────────────
|
||||
// The send Enter (handled above) posts WM_RYNTHCORE_CHAT instead of
|
||||
// dispatching inline. We fire OnChatSend here, on a *fresh* game-thread
|
||||
// message dispatch — after the Enter's WM_CHAR/WM_KEYUP tail has been
|
||||
// consumed and outside the original keystroke's WndProc frame. This
|
||||
// matters because OnChatSend → RynthChatSendLine → ChatCommandDispatcher
|
||||
// .SimulateChatInput drives CallWindowProcA back into AC's window proc;
|
||||
// doing that reentrantly inside the Enter keystroke left AC's chat bar
|
||||
// misaligned after the first send ("worked once, then stopped"). The
|
||||
// dispatch must stay on the game thread (it owns the window), so a posted
|
||||
// message — not a worker-thread tick — is the right deferral.
|
||||
if (msg == WM_RYNTHCORE_CHAT)
|
||||
{
|
||||
OnChatSend?.Invoke();
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
if (msg == WM_RYNTHCORE_TELL)
|
||||
{
|
||||
OnChatTellSelected?.Invoke();
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
// ── Chat: Enter in-game activates the chat TextBox ───────────
|
||||
// Numpad Enter (extended key, lParam bit 24) is reserved for AC functions — never capture it.
|
||||
// !AvaloniaTextInputActive: while the user is typing in a docked
|
||||
// panel TextBox this branch otherwise runs BEFORE the text-input
|
||||
// forwarding block and hijacks Enter into chat capture — stealing
|
||||
// the TextBox's own commit handler and every subsequent keystroke.
|
||||
// RynthChatOwnsChat: only while RynthChat is open AND hiding the retail chatbox —
|
||||
// whichever chat is visible gets Enter. Otherwise Enter belongs to AC's own chat,
|
||||
// which used to be unusable whenever RynthChat was installed, even closed.
|
||||
if (msg == WM_KEYDOWN && (int)wParam == VK_RETURN && !IsExtendedKey(lParam) && !ChatCaptureActive && !AvaloniaTextInputActive
|
||||
&& RynthCore.Engine.Compatibility.ChatHooks.RynthChatOwnsChat)
|
||||
{
|
||||
if (OnChatCaptureActivated != null)
|
||||
{
|
||||
ChatCaptureActive = true;
|
||||
OnChatCaptureActivated.Invoke();
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Restore focus to game when Avalonia acquires it ───────────
|
||||
if (msg == WM_RYNTH_RESTORE_FOCUS)
|
||||
{
|
||||
IntPtr prev = SetFocus(_gameHwnd);
|
||||
IntPtr fg = GetForegroundWindow();
|
||||
RynthLog.Info($"Win32Backend: WM_RYNTH_RESTORE_FOCUS → SetFocus(gameHwnd) prev=0x{prev.ToInt64():X} fg=0x{fg.ToInt64():X} game=0x{_gameHwnd.ToInt64():X}.");
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
// ── Diag: game-window focus transitions (driven by clicks on Avalonia panels) ──
|
||||
if (msg == WM_SETFOCUS)
|
||||
RynthLog.Info($"Win32Backend: game WM_SETFOCUS (from hwnd=0x{wParam.ToInt64():X} {DescribeHwnd(wParam)}).");
|
||||
else if (msg == WM_KILLFOCUS)
|
||||
RynthLog.Info($"Win32Backend: game WM_KILLFOCUS (to hwnd=0x{wParam.ToInt64():X} {DescribeHwnd(wParam)}).");
|
||||
|
||||
// ── Vital HUD drag/resize ─────────────────────────────────────
|
||||
// Give the custom vital-bar HUD first crack at mouse input: a click
|
||||
// landing on it moves/resizes the HUD and is swallowed so it never
|
||||
// reaches AC (no camera spin) or the Avalonia panels. Placed before
|
||||
// the ImGui EnqueueInput/capture-eat below so ImGui never tracks the
|
||||
// HUD drag (keeps our SetCapture from fighting NewFrame's). No-op
|
||||
// unless the HUD is drawn.
|
||||
if (IsMouseMessage(msg) && VitalHud.TryHandleMouse(hWnd, msg, wParam, lParam))
|
||||
return IntPtr.Zero;
|
||||
|
||||
// ── Avalonia panel hit-test & input forwarding ────────────────
|
||||
if (IsMouseMessage(msg))
|
||||
// Only in the world: between characters the overlay isn't drawn, so its
|
||||
// panels mustn't take clicks meant for character select.
|
||||
bool overlayLive = RynthCore.Engine.Compatibility.LoginLifecycleHooks.HasObservedLoginComplete;
|
||||
if (!overlayLive)
|
||||
{
|
||||
// fall through: AC gets the message
|
||||
}
|
||||
else if (IsMouseMessage(msg))
|
||||
{
|
||||
bool handled = TryForwardToAvalonia(msg, wParam, lParam);
|
||||
if (handled)
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
else if (IsKeyMessage(msg) && _avaloniaHasMouse)
|
||||
else if (IsKeyMessage(msg) && AvaloniaTextInputActive)
|
||||
{
|
||||
// Keyboard goes to Avalonia only while the cursor is over the panel.
|
||||
// Keys go to Avalonia only when a TextBox actually holds keyboard focus.
|
||||
// Gating on mouse-hover instead was wrong: a held game key whose KEYUP
|
||||
// landed while the cursor was over a panel got swallowed, leaving AC's
|
||||
// edge-driven input state latched (character kept moving until the user
|
||||
// tapped again with the mouse elsewhere).
|
||||
//
|
||||
// CRITICAL: forward only WM_KEYDOWN/WM_KEYUP (and SYS variants). Do NOT
|
||||
// forward WM_CHAR — Avalonia's own message pump calls TranslateMessage on
|
||||
// the WM_KEYDOWN we just posted and synthesises its own WM_CHAR. If we
|
||||
// also post WM_CHAR directly, Avalonia receives the character twice and
|
||||
// every keypress shows up doubled in TextBoxes.
|
||||
if (msg == WM_CHAR)
|
||||
return IntPtr.Zero;
|
||||
|
||||
IntPtr avHwnd = AvaloniaOverlay.AvaloniaHwnd;
|
||||
if (avHwnd != IntPtr.Zero)
|
||||
{
|
||||
|
|
@ -364,6 +959,8 @@ internal static unsafe class Win32Backend
|
|||
}
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
|
||||
// Only enqueue if we did NOT already forward to Avalonia above.
|
||||
// (When AvaloniaTextInputActive is true and a key fires, we returned early.)
|
||||
if (IsMouseMessage(msg) || IsKeyMessage(msg) || IsFocusMessage(msg))
|
||||
EnqueueInput(msg, wParam, lParam);
|
||||
|
||||
|
|
@ -380,10 +977,12 @@ internal static unsafe class Win32Backend
|
|||
return CallWindowProcA(_originalWndProc, hWnd, msg, (IntPtr)1, lParam);
|
||||
|
||||
// WM_ACTIVATE WA_INACTIVE fires when focus moves to another window in the SAME
|
||||
// process (e.g. an ImGui viewport popup). WM_ACTIVATEAPP doesn't fire in that case,
|
||||
// so AC would see its window go inactive and may idle-throttle its render loop.
|
||||
// Intercept and lie: tell AC its window is still active.
|
||||
if (msg == WM_ACTIVATE && EndSceneHook.FpsLimitEnabled)
|
||||
// process (e.g. an ImGui viewport popup, the DComp overlay bar). WM_ACTIVATEAPP
|
||||
// doesn't fire in that case, so AC would see its window go inactive and idle-
|
||||
// throttle its render loop. Always intercept same-process activations — this is
|
||||
// unconditionally correct for an injected overlay and must not be gated on
|
||||
// FpsLimitEnabled (DComp overlay clicks cause 8fps without this fix).
|
||||
if (msg == WM_ACTIVATE)
|
||||
{
|
||||
int activationCode = (int)((long)wParam & 0xFFFF);
|
||||
if (activationCode == WA_INACTIVE && lParam != IntPtr.Zero)
|
||||
|
|
@ -473,6 +1072,12 @@ internal static unsafe class Win32Backend
|
|||
AvaloniaOverlay.ActivateBarButton(releasedButtonTitle!);
|
||||
}
|
||||
|
||||
// Persist bar position on drag-end. All the live moves were
|
||||
// applied via MoveBarByPhys; CommitDrag(0,0) saves the final
|
||||
// canvas position without applying any additional delta.
|
||||
if (_avIsDragging)
|
||||
AvaloniaOverlay.CommitDrag(0, 0);
|
||||
|
||||
AvaloniaOverlay.IsDragInProgress = false;
|
||||
_avIsDragging = false;
|
||||
_avIsResizing = false;
|
||||
|
|
@ -519,16 +1124,62 @@ internal static unsafe class Win32Backend
|
|||
_avaloniaHasMouse = over;
|
||||
}
|
||||
|
||||
// While the left button is held down on a panel, keep forwarding
|
||||
// even if the cursor wanders off the panel rect — Avalonia's drag
|
||||
// handler needs uninterrupted PointerMoved + PointerReleased to
|
||||
// commit/release the drag. The latch clears on WM_LBUTTONUP.
|
||||
if (_avPanelMouseDown)
|
||||
{
|
||||
_lastPanelClientX = overlayPoint.X;
|
||||
_lastPanelClientY = overlayPoint.Y;
|
||||
AvaloniaMessagePoint heldPoint = ClientToAvaloniaMessagePoint(overlayPoint.X, overlayPoint.Y);
|
||||
_lastAvaloniaMessageX = heldPoint.X;
|
||||
_lastAvaloniaMessageY = heldPoint.Y;
|
||||
PostOverlayMouseMessage(avHwnd, msg, wParam, heldPoint.X, heldPoint.Y);
|
||||
if (msg == WM_LBUTTONUP)
|
||||
{
|
||||
_avPanelMouseDown = false;
|
||||
AvaloniaOverlay.SetDockedPanelPointerCaptureActive(false);
|
||||
}
|
||||
if (msg != WM_MOUSEMOVE || AvaloniaOverlay.ShouldUseCustomSkiaProducer)
|
||||
AvaloniaOverlay.RequestCapture();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!over)
|
||||
{
|
||||
if (msg == WM_LBUTTONUP)
|
||||
_pendingBarButtonTitle = null;
|
||||
|
||||
// An open Flyout / ContextMenu / dropdown is embedded in the
|
||||
// overlay window, but a click on the game world is never
|
||||
// forwarded, so Avalonia's light-dismiss never sees it. Close
|
||||
// it here; the click still goes to AC.
|
||||
if ((msg == WM_LBUTTONDOWN || msg == WM_RBUTTONDOWN || msg == WM_MBUTTONDOWN)
|
||||
&& AvaloniaOverlay.HasOpenLightDismissPopup)
|
||||
{
|
||||
AvaloniaOverlay.DismissLightDismissPopups();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
_lastPanelClientX = overlayPoint.X;
|
||||
_lastPanelClientY = overlayPoint.Y;
|
||||
|
||||
// A docked press is starting (over a docked panel/bar). Assert no
|
||||
// floating panel is still marked as the shared-HWND SetCapture
|
||||
// coordinate owner: a stale FloatingPanelHost.PointerCapturingHost
|
||||
// (left set when a floating WM_LBUTTONUP never reached
|
||||
// AvaloniaSubclassWndProc — swallowed by the DockedPanelPointer-
|
||||
// CaptureActive early-return, or a redock/close mid-press) would
|
||||
// make this docked interaction's capture-routed move/release get
|
||||
// remapped into the floating panel's off-bounds space — the docked
|
||||
// click is eaten / needs a double-click. A WM_LBUTTONDOWN means the
|
||||
// button was up before, so any prior floating press already ended;
|
||||
// clearing here cannot truncate a live floating interaction.
|
||||
if (msg == WM_LBUTTONDOWN)
|
||||
FloatingPanelHost.PointerCapturingHost = null;
|
||||
|
||||
if (AvaloniaOverlay.TryGetBarButtonTitleAt(overlayPoint.X, overlayPoint.Y, out string? barButtonTitle))
|
||||
{
|
||||
if (msg == WM_LBUTTONDOWN)
|
||||
|
|
@ -627,8 +1278,17 @@ internal static unsafe class Win32Backend
|
|||
_lastAvaloniaMessageX = messagePoint.X;
|
||||
_lastAvaloniaMessageY = messagePoint.Y;
|
||||
if (msg == WM_LBUTTONDOWN)
|
||||
{
|
||||
LogAvaloniaPointerDebug("forward-down", cx, cy, overlayPoint.X, overlayPoint.Y, messagePoint.X, messagePoint.Y);
|
||||
_avPanelMouseDown = true;
|
||||
AvaloniaOverlay.SetDockedPanelPointerCaptureActive(true);
|
||||
}
|
||||
PostOverlayMouseMessage(avHwnd, msg, wParam, messagePoint.X, messagePoint.Y);
|
||||
if (msg == WM_LBUTTONUP)
|
||||
{
|
||||
_avPanelMouseDown = false;
|
||||
AvaloniaOverlay.SetDockedPanelPointerCaptureActive(false);
|
||||
}
|
||||
if (msg != WM_MOUSEMOVE || AvaloniaOverlay.ShouldUseCustomSkiaProducer)
|
||||
AvaloniaOverlay.RequestCapture();
|
||||
return true;
|
||||
|
|
@ -799,7 +1459,10 @@ internal static unsafe class Win32Backend
|
|||
|
||||
private static void LogAvaloniaPointerDebug(string phase, int clientX, int clientY, int overlayX, int overlayY, int? messageX = null, int? messageY = null)
|
||||
{
|
||||
// Suppressed — these diagnostics are no longer needed for stable operation.
|
||||
if (messageX.HasValue)
|
||||
RynthLog.Info($"AvaloniaPtr [{phase}] client=({clientX},{clientY}) overlay=({overlayX},{overlayY}) msg=({messageX},{messageY}).");
|
||||
else
|
||||
RynthLog.Info($"AvaloniaPtr [{phase}] client=({clientX},{clientY}) overlay=({overlayX},{overlayY}).");
|
||||
}
|
||||
|
||||
private static void AcquireAvaloniaNativeCapture()
|
||||
|
|
@ -820,10 +1483,28 @@ internal static unsafe class Win32Backend
|
|||
_avHasNativeCapture = false;
|
||||
}
|
||||
|
||||
// UI deep-dive finding P0-2 / TL;DR #2 (2026-07-02): every mouse/key/
|
||||
// focus message was enqueued here unconditionally, all session, but
|
||||
// FlushQueuedInput only ever drains it from inside the ImGui NewFrame
|
||||
// path (line ~599 above) — which never runs when EngineSettings.
|
||||
// EnableImGuiBackend is false (the daily-driver config: "Avalonia-only"
|
||||
// mode, bar + plugin ImGui hidden). Tens to hundreds of MB accumulate
|
||||
// over a session on this stack's 32-bit VA budget. Guard on the backend
|
||||
// actually running; cap regardless as defense-in-depth (e.g. a brief
|
||||
// startup window before the flag is known, or a future caller).
|
||||
private const int MaxPendingInput = 4096;
|
||||
|
||||
private static void EnqueueInput(uint msg, IntPtr wParam, IntPtr lParam)
|
||||
{
|
||||
if (!RynthCore.Engine.Plugins.EngineSettings.EnableImGuiBackend)
|
||||
return;
|
||||
|
||||
lock (_inputLock)
|
||||
{
|
||||
if (_pendingInput.Count >= MaxPendingInput)
|
||||
_pendingInput.Dequeue(); // drop oldest — a stale mouse-move/key is harmless to lose
|
||||
_pendingInput.Enqueue(new QueuedInputMessage(msg, wParam, lParam));
|
||||
}
|
||||
}
|
||||
|
||||
private static void FlushQueuedInput(ImGuiIOPtr io)
|
||||
|
|
|
|||
Loading…
Reference in a new issue