Add multi-viewport support, FPS governor, mana stone looting, and viewport focus fixes

Engine:
- ViewportPlatformBackend: Win32 platform backend for ImGui multi-viewport (pop-out windows)
- ViewportRendererBackend: D3D9 swap chain rendering for viewport windows
- ViewportPlatformBackend: WS_EX_NOACTIVATE + MA_NOACTIVATE always + SW_SHOWNA — viewport
  windows never steal focus; single click works without prior window activation
- ImGuiController/RynthCoreShell: wire multi-viewport callbacks, map always renders
  independent of main dashboard visibility
- Win32Backend: improved input handling for viewport windows
- EndSceneHook: FPS governor (focused/background targets), periodic FPS measurement
- D3D9VTable: vtable discovery improvements
- PluginContract/PluginManager/RynthCoreHost: expose UseObjectOn, GetItemType,
  GetObjectIntProperty to plugins

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
tombohar 2026-04-19 20:29:34 -04:00
commit 0d8579b796
24 changed files with 1876 additions and 38 deletions

View file

@ -70,6 +70,9 @@ internal static class CreateObjectHooks
private static IntPtr CreateObjectDetour(IntPtr thisPtr, uint objectId, IntPtr visualDesc, IntPtr physicsDesc, IntPtr weenieDesc)
{
if (objectId != 0 && visualDesc != IntPtr.Zero)
PaletteCache.ReadFromObjDesc(objectId, visualDesc);
IntPtr result = _originalCreateObject!(thisPtr, objectId, visualDesc, physicsDesc, weenieDesc);
if (result == IntPtr.Zero || objectId == 0)
return result;

View file

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

View file

@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.Compatibility;
// Stores per-object ObjDesc subpalette data captured in CreateObjectDetour.
// ObjDesc (x86 layout, all 4-byte fields):
// +0 vtable ptr (VisualDesc.packObj)
// +4 paletteID
// +8 firstSubpal*
// +12 lastSubpal*
// +16 num_subpalettes
// Subpalette (x86):
// +0 vtable ptr (PackObj)
// +4 subID ← palette DID
// +8 offset ← range start (sorted key)
// +12 numcolors
// +16 prev*
// +20 next*
internal static unsafe class PaletteCache
{
private static readonly Dictionary<uint, (uint SubId, uint Offset)[]> _data = new();
private static readonly object _lock = new();
public static void ReadFromObjDesc(uint objectId, IntPtr objDescPtr)
{
if (objDescPtr == IntPtr.Zero) return;
try
{
byte* p = (byte*)objDescPtr;
int numSubs = *(int*)(p + 16);
if (numSubs <= 0 || numSubs > 128) return;
var list = new (uint SubId, uint Offset)[numSubs];
IntPtr node = *(IntPtr*)(p + 8);
int idx = 0;
while (node != IntPtr.Zero && idx < numSubs)
{
byte* s = (byte*)node;
list[idx++] = (*(uint*)(s + 4), *(uint*)(s + 8));
node = *(IntPtr*)(s + 20);
}
if (idx != numSubs)
Array.Resize(ref list, idx);
Array.Sort(list, (a, b) => a.Offset.CompareTo(b.Offset));
lock (_lock)
_data[objectId] = list;
}
catch { }
}
public static void Remove(uint objectId)
{
lock (_lock)
_data.Remove(objectId);
}
public static int Fill(uint objectId, uint* subIds, uint* offsets, int maxCount)
{
(uint SubId, uint Offset)[]? list;
lock (_lock)
{
if (!_data.TryGetValue(objectId, out list)) return -1;
}
int count = Math.Min(list.Length, maxCount);
for (int i = 0; i < count; i++)
{
subIds[i] = list[i].SubId;
offsets[i] = list[i].Offset;
}
return list.Length;
}
}

View file

@ -0,0 +1,157 @@
// ============================================================================
// RynthCore.Engine - CrashLogger.cs
// Installs a Win32 Vectored Exception Handler so that an AV (uncatchable in
// NativeAOT) is logged with the faulting address + module BEFORE the process
// dies. Without this, silent AVs leave us guessing which call crashed.
// ============================================================================
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine;
internal static class CrashLogger
{
[StructLayout(LayoutKind.Sequential)]
private struct EXCEPTION_RECORD
{
public uint ExceptionCode;
public uint ExceptionFlags;
public IntPtr ExceptionRecord;
public IntPtr ExceptionAddress;
public uint NumberParameters;
// ExceptionInformation[15] follows — not needed for our logging
}
[StructLayout(LayoutKind.Sequential)]
private struct EXCEPTION_POINTERS
{
public IntPtr ExceptionRecord; // EXCEPTION_RECORD*
public IntPtr ContextRecord; // CONTEXT*
}
private delegate int VectoredHandler(IntPtr exceptionInfo);
[DllImport("kernel32.dll")]
private static extern IntPtr AddVectoredExceptionHandler(uint first, VectoredHandler handler);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern uint GetModuleFileNameW(IntPtr hModule, char[] lpFilename, uint nSize);
[DllImport("psapi.dll", SetLastError = true)]
private static extern bool GetModuleInformation(IntPtr hProcess, IntPtr hModule, out MODULEINFO lpmodinfo, uint cb);
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetModuleHandleExW(uint dwFlags, IntPtr lpModuleName, out IntPtr phModule);
[StructLayout(LayoutKind.Sequential)]
private struct MODULEINFO
{
public IntPtr lpBaseOfDll;
public uint SizeOfImage;
public IntPtr EntryPoint;
}
// GetModuleHandleEx flags
private const uint GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS = 0x00000004;
private const uint GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT = 0x00000002;
// Exception codes worth logging — skip the noisy breakpoints / single-steps.
private const uint EXCEPTION_ACCESS_VIOLATION = 0xC0000005;
private const uint EXCEPTION_ILLEGAL_INSTRUCTION = 0xC000001D;
private const uint EXCEPTION_PRIV_INSTRUCTION = 0xC0000096;
private const uint EXCEPTION_INT_DIVIDE_BY_ZERO = 0xC0000094;
private const uint EXCEPTION_STACK_OVERFLOW = 0xC00000FD;
// Return values for VectoredHandler
private const int EXCEPTION_CONTINUE_SEARCH = 0;
// Pin the delegate so it isn't GC'd while Windows holds the function pointer.
private static VectoredHandler? _handler;
private static bool _installed;
public static void Install()
{
if (_installed) return;
try
{
_handler = OnVectoredException;
IntPtr cookie = AddVectoredExceptionHandler(1 /*CALL_FIRST*/, _handler);
if (cookie == IntPtr.Zero)
{
RynthLog.Info($"CrashLogger: AddVectoredExceptionHandler failed (err {Marshal.GetLastWin32Error()})");
return;
}
_installed = true;
RynthLog.Info("CrashLogger: VEH installed.");
}
catch (Exception ex)
{
RynthLog.Info($"CrashLogger: install failed {ex.GetType().Name}: {ex.Message}");
}
}
private static int OnVectoredException(IntPtr pExceptionInfo)
{
try
{
EXCEPTION_POINTERS ep = Marshal.PtrToStructure<EXCEPTION_POINTERS>(pExceptionInfo);
EXCEPTION_RECORD er = Marshal.PtrToStructure<EXCEPTION_RECORD>(ep.ExceptionRecord);
// Only log genuinely fatal categories. Normal operation throws SEH
// exceptions (C++ 0xE06D7363, CLR 0xE0434352, etc.) we should ignore.
bool interesting =
er.ExceptionCode == EXCEPTION_ACCESS_VIOLATION ||
er.ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION ||
er.ExceptionCode == EXCEPTION_PRIV_INSTRUCTION ||
er.ExceptionCode == EXCEPTION_INT_DIVIDE_BY_ZERO ||
er.ExceptionCode == EXCEPTION_STACK_OVERFLOW;
if (!interesting)
return EXCEPTION_CONTINUE_SEARCH;
string module = ResolveModule(er.ExceptionAddress, out IntPtr moduleBase);
long rva = moduleBase != IntPtr.Zero
? er.ExceptionAddress.ToInt64() - moduleBase.ToInt64()
: 0;
RynthLog.Info(
$"CRASH: code=0x{er.ExceptionCode:X8} addr=0x{er.ExceptionAddress.ToInt64():X8} " +
$"module={module} base=0x{moduleBase.ToInt64():X8} rva=0x{rva:X}");
}
catch
{
// Logging must not throw — we're in an exception handler.
}
return EXCEPTION_CONTINUE_SEARCH;
}
private static string ResolveModule(IntPtr address, out IntPtr moduleBase)
{
moduleBase = IntPtr.Zero;
try
{
if (!GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
address, out IntPtr hModule) || hModule == IntPtr.Zero)
{
return "<unknown>";
}
moduleBase = hModule;
char[] buf = new char[512];
uint len = GetModuleFileNameW(hModule, buf, (uint)buf.Length);
if (len == 0) return "<noname>";
return new string(buf, 0, (int)len);
}
catch
{
return "<resolve-failed>";
}
}
}

View file

@ -28,6 +28,7 @@ internal static class DeviceVTableIndex
public const int SetTransform = 44;
public const int GetTransform = 45;
public const int GetRenderTarget = 38;
public const int SetRenderTarget = 37;
public const int SetViewport = 47;
public const int GetViewport = 48;
public const int GetTexture = 64;
@ -77,6 +78,25 @@ internal static class TextureVTableIndex
public const int UnlockRect = 20;
}
/// <summary>
/// IDirect3DSwapChain9 vtable indices.
/// </summary>
internal static class SwapChain9VTableIndex
{
public const int Release = 2;
public const int Present = 3;
// IDirect3DSwapChain9 vtable: 3=Present, 4=GetFrontBufferData, 5=GetBackBuffer.
public const int GetBackBuffer = 5;
}
/// <summary>
/// IDirect3DSurface9 vtable indices.
/// </summary>
internal static class Surface9VTableIndex
{
public const int Release = 2;
}
/// <summary>
/// IDirect3D9 vtable indices.
/// </summary>

View file

@ -27,12 +27,6 @@ internal static class EndSceneHook
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
[DllImport("kernel32.dll")]
private static extern uint GetCurrentProcessId();
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int EndSceneDelegate(IntPtr pDevice);
@ -278,9 +272,8 @@ internal static class EndSceneHook
if (FpsLimitEnabled)
{
IntPtr fgWnd = GetForegroundWindow();
GetWindowThreadProcessId(fgWnd, out uint fgPid);
uint thisPid = GetCurrentProcessId();
bool isFocused = fgPid == thisPid;
// Only "focused" when the AC game window itself is foreground — not viewport popups.
bool isFocused = fgWnd != IntPtr.Zero && fgWnd == Win32Backend.GameHwnd;
int targetFps = isFocused ? FpsTargetFocused : FpsTargetBackground;
double minFrameMs = 1000.0 / Math.Max(targetFps, 1);
@ -291,7 +284,7 @@ internal static class EndSceneHook
if (!_fpsLimiterLoggedOnce)
{
_fpsLimiterLoggedOnce = true;
RynthLog.D3D9($"EndSceneHook: FPS governor active — max={FpsTargetFocused} focused, max={FpsTargetBackground} background, pid={thisPid}");
RynthLog.D3D9($"EndSceneHook: FPS governor active — max={FpsTargetFocused} focused, max={FpsTargetBackground} background, gameHwnd=0x{Win32Backend.GameHwnd.ToInt64():X}");
}
// Periodic FPS measurement — log every 60 seconds

View file

@ -44,6 +44,7 @@ public static class EntryPoint
try
{
RynthLog.Info($"RynthCoreInit called (build {BuildStamp}) - spawning init thread...");
CrashLogger.Install();
RunInitStep("early multi-client hooks", MultiClientHooks.Initialize);
var thread = new Thread(InitWorker)

View file

@ -29,6 +29,17 @@ internal static class ImGuiController
[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 _initialized;
@ -73,14 +84,37 @@ internal static class ImGuiController
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;
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.Init(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($"ImGuiController: viewport init failed (platform={platformOk}, renderer={rendererOk}) — disabling ViewportsEnable.");
io.ConfigFlags &= ~ImGuiConfigFlags.ViewportsEnable;
}
ViewportPlatformBackend.ImGuiContext = _context;
}
_lastFrameTicks = Stopwatch.GetTimestamp();
_initialized = true;
initSucceeded = true;
@ -114,6 +148,8 @@ internal static class ImGuiController
PluginManager.ShutdownAll();
OverlayTextureRenderer.Shutdown();
ViewportRendererBackend.Shutdown();
ViewportPlatformBackend.Shutdown();
DX9Backend.Shutdown();
Win32Backend.Shutdown();
ImGuiNET.ImGui.DestroyContext(contextToDestroy);
@ -192,6 +228,26 @@ internal static class ImGuiController
// Plugin tick (per-frame logic, before ImGui drawing)
PluginManager.TickAll();
// 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;
RynthCoreShell.Render(_frameCount);
@ -210,16 +266,11 @@ internal static class ImGuiController
Win32Backend.UpdateCaptureFlags(captureMouse, captureKeyboard);
ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
// Frame diagnostics suppressed — ImGui is stable.
// Nav markers were rendered by Nav3DRenderInjector at the 3D→UI
// transition. Fallback to EndScene if transition wasn't detected.
if (!nav3DAlreadyRendered)
DX9Backend.RenderNav3D(pDevice);
DX9Backend.RenderDrawData(drawData, pDevice);
// Composite the Avalonia overlay frame on top of ImGui
OverlayTextureRenderer.Render(pDevice);
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
@ -240,7 +291,7 @@ internal static class ImGuiController
{
}
RynthLog.Render($"ImGuiController: frame {_frameCount} error: {ex.GetType().Name}: {ex.Message}");
RynthLog.Info($"ImGuiController: frame {_frameCount} error: {ex.GetType().Name}: {ex.Message}");
}
finally
{

View file

@ -149,17 +149,27 @@ internal static class RynthCoreShell
_barPositionInitialized = true;
}
// 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).
Vector2 viewportOrigin = ImGui.GetMainViewport().Pos;
Vector2 screenPos = _barPosition + viewportOrigin;
if (_barResetRequested)
{
ImGui.SetNextWindowPos(_barPosition, ImGuiCond.Always);
ImGui.SetNextWindowPos(screenPos, ImGuiCond.Always);
_barResetRequested = false;
}
else
{
ImGui.SetNextWindowPos(_barPosition, ImGuiCond.FirstUseEver);
ImGui.SetNextWindowPos(screenPos, ImGuiCond.FirstUseEver);
}
ImGui.SetNextWindowBgAlpha(1.0f);
// Pin the bar to the main viewport so it stays anchored inside the game
// client even with ViewportsEnable on. Plugin windows can still pop out
// into their own OS windows — this pin only applies to the bar.
ImGui.SetNextWindowViewport(ImGui.GetMainViewport().ID);
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(6f, 4f));
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4f, 3f));
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(5f, 2f));
@ -276,7 +286,8 @@ internal static class RynthCoreShell
return;
_barPosition = clamped;
ImGui.SetWindowPos(_barPosition);
// _barPosition is client-relative; translate to screen coords for ImGui.
ImGui.SetWindowPos(_barPosition + ImGui.GetMainViewport().Pos);
}
private static Vector2 ClampToDisplay(Vector2 position, Vector2 windowSize, Vector2 displaySize)
@ -342,7 +353,9 @@ internal static class RynthCoreShell
private static void UpdateBarPositionFromWindow()
{
_barPosition = ImGui.GetWindowPos();
// GetWindowPos returns screen coords with ViewportsEnable — convert back
// to client-relative so the stored position is viewport-independent.
_barPosition = ImGui.GetWindowPos() - ImGui.GetMainViewport().Pos;
EnsureBarVisible();
SaveBarPositionThrottled();
}

View file

@ -0,0 +1,53 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — ImGui/ViewportOffsets.cs
// Byte offsets of ImGuiPlatformIO callback fields in the cimgui.dll shipped
// with ImGui.NET 1.91.6.1 (docking branch).
//
// WARNING: these do NOT match ImGui.NET's compiled struct layout. ImGui.NET
// prepends 36 bytes of clipboard/IME/OpenInShell fields that this cimgui.dll
// build does not have. Writing via ImGui.NET's ref properties lands 36 bytes
// past the native field, so the native library sees NULL and asserts
// "Platform init didn't install handlers".
//
// Source of truth (disassembled cimgui.dll 1.91.6.1, x86):
// ImGuiPlatformIO_Set_Platform_GetWindowPos → mov [pio+0x10], shim
// ImGuiPlatformIO_Set_Platform_GetWindowSize → mov [pio+0x18], shim
// igUpdatePlatformWindows first callback dispatch → call [g+0x37B8]
// with ImGuiContext PlatformIO offset → pio field 0 = Platform_CreateWindow
//
// Struct size (from constructor memset): 0x74 (116 bytes). Fields 0x00..0x5F
// hold 24 callback pointers; 0x60..0x73 hold Monitors + Viewports ImVectors.
// ═══════════════════════════════════════════════════════════════════════════
namespace RynthCore.Engine.ImGuiBackend;
internal static class ViewportOffsets
{
// Platform_* (18 callbacks — this cimgui.dll build lacks GetWindowWorkAreaInsets)
public const int PlatformCreateWindow = 0;
public const int PlatformDestroyWindow = 4;
public const int PlatformShowWindow = 8;
public const int PlatformSetWindowPos = 12;
public const int PlatformGetWindowPos = 16; // confirmed via _Set_ helper disasm
public const int PlatformSetWindowSize = 20;
public const int PlatformGetWindowSize = 24; // confirmed via _Set_ helper disasm
public const int PlatformSetWindowFocus = 28;
public const int PlatformGetWindowFocus = 32;
public const int PlatformGetWindowMinimized = 36;
public const int PlatformSetWindowTitle = 40;
public const int PlatformSetWindowAlpha = 44;
public const int PlatformUpdateWindow = 48;
public const int PlatformRenderWindow = 52;
public const int PlatformSwapBuffers = 56;
public const int PlatformGetWindowDpiScale = 60;
public const int PlatformOnChangedViewport = 64;
public const int PlatformCreateVkSurface = 68;
// Renderer_* (5 callbacks) — RendererCreateWindow at +72 confirmed by
// igUpdatePlatformWindows disasm: [ebx+0x3800] = [pio + 0x48] = +72.
public const int RendererCreateWindow = 72;
public const int RendererDestroyWindow = 76;
public const int RendererSetWindowSize = 80;
public const int RendererRenderWindow = 84;
public const int RendererSwapBuffers = 88;
}

View file

@ -0,0 +1,813 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — ImGui/ViewportPlatformBackend.cs
// Win32 platform backend for Dear ImGui multi-viewport (equivalent of
// imgui_impl_win32's viewport-capable portion). Installs Platform_* callbacks
// into the native ImGuiPlatformIO struct, registers a window class for
// popped-out ImGui windows, and proxies the required Win32 calls.
//
// Input for viewport HWNDs is forwarded into the existing Dear ImGui IO
// event queue via a dedicated WndProc.
// ═══════════════════════════════════════════════════════════════════════════
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Runtime.InteropServices;
using ImGuiNET;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class ViewportPlatformBackend
{
// ── Delegate types (cdecl; ImGui callbacks on x86 use the default C ABI) ──
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportVoidDelegate(ImGuiViewport* vp);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportGetVec2Delegate(ImGuiViewport* vp, Vector2* outVec);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportSetVec2Delegate(ImGuiViewport* vp, Vector2 value);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate byte ViewportGetBoolDelegate(ImGuiViewport* vp);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportSetStringDelegate(ImGuiViewport* vp, IntPtr str);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportSetFloatDelegate(ImGuiViewport* vp, float value);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern ushort RegisterClassExW(ref WNDCLASSEXW lpwcx);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr CreateWindowExW(
uint dwExStyle, string lpClassName, string lpWindowName, uint dwStyle,
int X, int Y, int nWidth, int nHeight,
IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);
[DllImport("user32.dll")]
private static extern bool DestroyWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter,
int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
private static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int SetWindowTextW(IntPtr hWnd, string lpString);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern IntPtr SetWindowLongW(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll")]
private static extern IntPtr GetWindowLongW(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern bool SetLayeredWindowAttributes(IntPtr hWnd, uint crKey, byte bAlpha, uint dwFlags);
[DllImport("user32.dll")]
private static extern IntPtr DefWindowProcW(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool AdjustWindowRectEx(ref RECT lpRect, uint dwStyle, bool bMenu, uint dwExStyle);
[DllImport("user32.dll")]
private static extern bool PostMessageW(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint);
[DllImport("user32.dll")]
private static extern IntPtr SetCapture(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ReleaseCapture();
[StructLayout(LayoutKind.Sequential)]
private struct POINT { public int X, Y; }
[DllImport("kernel32.dll")]
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
[DllImport("user32.dll")]
private static extern IntPtr LoadCursorW(IntPtr hInstance, IntPtr lpCursorName);
[DllImport("user32.dll")]
private static extern int GetSystemMetrics(int nIndex);
[DllImport("user32.dll")]
private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip, MonitorEnumProc lpfnEnum, IntPtr dwData);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern bool GetMonitorInfoW(IntPtr hMonitor, ref MONITORINFO lpmi);
private delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData);
[StructLayout(LayoutKind.Sequential)]
private struct MONITORINFO
{
public uint cbSize;
public RECT rcMonitor;
public RECT rcWork;
public uint dwFlags;
}
private const int SM_CXSCREEN = 0;
private const int SM_CYSCREEN = 1;
private const uint MONITORINFOF_PRIMARY = 0x00000001;
// ImGuiPlatformIO Monitors ImVector (native cimgui.dll layout).
// Native has 18 Platform_* + 5 Renderer_* = 23 callback pointers = 92 bytes,
// then Monitors ImVector{ int Size; int Capacity; void* Data; } at +92..+103,
// then Viewports ImVector at +104..+115. (ImGui.NET's compiled layout adds
// GetWindowWorkAreaInsets and so puts Monitors at +96 — do NOT use that.)
// Confirmed by probe dump showing Viewports.Size=1, Cap=8, Data=ptr at
// +104..+115 when native had just seeded the main viewport.
private const int MonitorsSize = 92;
private const int MonitorsCapacity = 96;
private const int MonitorsData = 100;
// ImGuiPlatformMonitor is 40 bytes (confirmed by cimgui.dll ctor "push 28h"):
// +0 MainPos (ImVec2, 8)
// +8 MainSize (ImVec2, 8)
// +16 WorkPos (ImVec2, 8)
// +24 WorkSize (ImVec2, 8)
// +32 DpiScale (float, 4)
// +36 PlatformHandle (void*, 4)
private const int MonitorStructSize = 40;
private static IntPtr _monitorArrayPtr;
private static int _monitorCount;
private delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct WNDCLASSEXW
{
public uint cbSize;
public uint style;
public IntPtr lpfnWndProc;
public int cbClsExtra;
public int cbWndExtra;
public IntPtr hInstance;
public IntPtr hIcon;
public IntPtr hCursor;
public IntPtr hbrBackground;
[MarshalAs(UnmanagedType.LPWStr)] public string? lpszMenuName;
[MarshalAs(UnmanagedType.LPWStr)] public string? lpszClassName;
public IntPtr hIconSm;
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT { public int Left, Top, Right, Bottom; }
// Win32 constants
private const int GWL_STYLE = -16;
private const int GWL_EXSTYLE = -20;
private const int SW_SHOWNA = 8;
private const int SW_HIDE = 0;
private const uint SWP_NOMOVE = 0x0002;
private const uint SWP_NOSIZE = 0x0001;
private const uint SWP_NOZORDER = 0x0004;
private const uint SWP_NOACTIVATE = 0x0010;
private const uint WS_POPUP = 0x80000000;
private const uint WS_OVERLAPPEDWINDOW = 0x00CF0000;
private const uint WS_CLIPCHILDREN = 0x02000000;
private const uint WS_CLIPSIBLINGS = 0x04000000;
private const uint WS_EX_TOOLWINDOW = 0x00000080;
private const uint WS_EX_LAYERED = 0x00080000;
private const uint WS_EX_APPWINDOW = 0x00040000;
private const uint WS_EX_TOPMOST = 0x00000008;
private const uint WS_EX_NOACTIVATE = 0x08000000;
private const uint LWA_ALPHA = 0x00000002;
private const uint WM_CLOSE = 0x0010;
private const uint WM_MOVE = 0x0003;
private const uint WM_SIZE = 0x0005;
private const uint WM_MOUSEACTIVATE = 0x0021;
private const uint WM_NCHITTEST = 0x0084;
private const uint WM_MOUSEMOVE = 0x0200;
private const uint WM_LBUTTONDOWN = 0x0201;
private const uint WM_LBUTTONUP = 0x0202;
private const uint WM_LBUTTONDBLCLK = 0x0203;
private const uint WM_RBUTTONDOWN = 0x0204;
private const uint WM_RBUTTONUP = 0x0205;
private const uint WM_RBUTTONDBLCLK = 0x0206;
private const uint WM_MBUTTONDOWN = 0x0207;
private const uint WM_MBUTTONUP = 0x0208;
private const uint WM_MBUTTONDBLCLK = 0x0209;
private const uint WM_MOUSEWHEEL = 0x020A;
private const uint WM_XBUTTONDOWN = 0x020B;
private const uint WM_XBUTTONUP = 0x020C;
private const uint WM_MOUSEHWHEEL = 0x020E;
private const uint WM_KEYDOWN = 0x0100;
private const uint WM_KEYUP = 0x0101;
private const uint WM_CHAR = 0x0102;
private const uint WM_SYSKEYDOWN = 0x0104;
private const uint WM_SYSKEYUP = 0x0105;
private const int MA_NOACTIVATE = 3;
private const int HTCLIENT = 1;
private const IntPtr IDC_ARROW = 0x7F00; // MAKEINTRESOURCE(32512)
private const string WindowClassName = "RynthCoreImGuiViewport";
// Pinned delegate instances — prevent GC while ImGui holds function pointers.
private static readonly List<Delegate> _delegateRoots = new();
private static WndProcDelegate? _viewportWndProc;
private static IntPtr _viewportWndProcPtr;
private static bool _initialized;
private static bool _classRegistered;
private static IntPtr _hInstance;
private static IntPtr _mainHwnd;
// Per-viewport state kept on the managed side.
// Keyed by the native ImGuiViewport* pointer.
private static readonly Dictionary<IntPtr, ViewportState> _viewports = new();
private class ViewportState
{
public IntPtr Hwnd;
public bool HwndOwned;
public uint DwStyle;
public uint DwExStyle;
}
public static bool Init(IntPtr mainHwnd)
{
if (_initialized) return true;
_mainHwnd = mainHwnd;
_hInstance = GetModuleHandleW(null);
if (!EnsureWindowClassRegistered())
{
RynthLog.Info($"ViewportPlatform: RegisterClassEx failed (err {Marshal.GetLastWin32Error()})");
return false;
}
ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO();
InstallCallbacks(pio);
PopulateMonitors(pio);
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
io.BackendFlags |= ImGuiBackendFlags.PlatformHasViewports;
// Do NOT set HasMouseHoveredViewport: that flag tells ImGui the backend
// will route hovered-viewport info via AddMouseViewportEvent each frame.
// We don't call that, so setting the flag causes mouse input to drop on
// the floor (IsWindowHovered returns false for every window).
// The main viewport's PlatformHandle points to the game window; store it
// so the very first frame doesn't try to create a new HWND for viewport 0.
ImGuiViewportPtr mainViewport = ImGuiNET.ImGui.GetMainViewport();
mainViewport.PlatformHandle = _mainHwnd;
mainViewport.PlatformHandleRaw = _mainHwnd;
_viewports[(IntPtr)mainViewport.NativePtr] = new ViewportState
{
Hwnd = _mainHwnd,
HwndOwned = false,
DwStyle = unchecked((uint)(long)GetWindowLongW(_mainHwnd, GWL_STYLE)),
DwExStyle = unchecked((uint)(long)GetWindowLongW(_mainHwnd, GWL_EXSTYLE)),
};
_initialized = true;
RynthLog.Info("ViewportPlatform: initialized.");
return true;
}
public static void Shutdown()
{
if (!_initialized) return;
// Destroy any viewport windows we created.
foreach (var kv in _viewports)
{
if (kv.Value.HwndOwned && kv.Value.Hwnd != IntPtr.Zero)
DestroyWindow(kv.Value.Hwnd);
}
_viewports.Clear();
// Clear the Monitors ImVector pointer in PlatformIO before freeing our
// backing buffer — native ImGui otherwise keeps a stale Data pointer.
if (_monitorArrayPtr != IntPtr.Zero)
{
try
{
ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO();
IntPtr pioNative = (IntPtr)pio.NativePtr;
Marshal.WriteInt32(pioNative, MonitorsSize, 0);
Marshal.WriteInt32(pioNative, MonitorsCapacity, 0);
Marshal.WriteIntPtr(pioNative, MonitorsData, IntPtr.Zero);
}
catch { /* context may already be torn down */ }
Marshal.FreeHGlobal(_monitorArrayPtr);
_monitorArrayPtr = IntPtr.Zero;
_monitorCount = 0;
}
_initialized = false;
}
// Dear ImGui asserts Monitor.Size > 0 before the first UpdatePlatformWindows
// call when ViewportsEnable is on. Populate the Monitors ImVector with the
// primary (and any secondary) displays so windows can pop out correctly.
private static void PopulateMonitors(ImGuiPlatformIOPtr pio)
{
var rects = new List<(RECT mon, RECT work, bool primary)>();
MonitorEnumProc cb = (IntPtr hMon, IntPtr hdc, ref RECT r, IntPtr _) =>
{
MONITORINFO mi = default;
mi.cbSize = (uint)Marshal.SizeOf<MONITORINFO>();
if (GetMonitorInfoW(hMon, ref mi))
rects.Add((mi.rcMonitor, mi.rcWork, (mi.dwFlags & MONITORINFOF_PRIMARY) != 0));
return true;
};
if (!EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, cb, IntPtr.Zero) || rects.Count == 0)
{
// Fallback: single primary display via GetSystemMetrics.
int w = GetSystemMetrics(SM_CXSCREEN);
int h = GetSystemMetrics(SM_CYSCREEN);
RECT r = new RECT { Left = 0, Top = 0, Right = w > 0 ? w : 1920, Bottom = h > 0 ? h : 1080 };
rects.Add((r, r, true));
}
GC.KeepAlive(cb);
_monitorCount = rects.Count;
_monitorArrayPtr = Marshal.AllocHGlobal(_monitorCount * MonitorStructSize);
// Primary monitor must be at index 0 for Dear ImGui's viewport code.
rects.Sort((a, b) => (b.primary ? 1 : 0) - (a.primary ? 1 : 0));
for (int i = 0; i < _monitorCount; i++)
{
var (mon, work, _) = rects[i];
IntPtr mp = _monitorArrayPtr + i * MonitorStructSize;
WriteFloat(mp, 0, mon.Left);
WriteFloat(mp, 4, mon.Top);
WriteFloat(mp, 8, mon.Right - mon.Left);
WriteFloat(mp, 12, mon.Bottom - mon.Top);
WriteFloat(mp, 16, work.Left);
WriteFloat(mp, 20, work.Top);
WriteFloat(mp, 24, work.Right - work.Left);
WriteFloat(mp, 28, work.Bottom - work.Top);
WriteFloat(mp, 32, 1.0f);
Marshal.WriteIntPtr(mp, 36, IntPtr.Zero);
}
IntPtr pioNative = (IntPtr)pio.NativePtr;
Marshal.WriteInt32(pioNative, MonitorsSize, _monitorCount);
Marshal.WriteInt32(pioNative, MonitorsCapacity, _monitorCount);
Marshal.WriteIntPtr(pioNative, MonitorsData, _monitorArrayPtr);
RynthLog.Info($"ViewportPlatform: populated {_monitorCount} monitor(s) at 0x{_monitorArrayPtr.ToInt64():X8}");
}
private static bool EnsureWindowClassRegistered()
{
if (_classRegistered) return true;
_viewportWndProc = ViewportWndProc;
_viewportWndProcPtr = Marshal.GetFunctionPointerForDelegate(_viewportWndProc);
WNDCLASSEXW wc = default;
wc.cbSize = (uint)Marshal.SizeOf<WNDCLASSEXW>();
wc.style = 0x0020 /*CS_OWNDC*/ | 0x0002 /*CS_HREDRAW*/ | 0x0001 /*CS_VREDRAW*/;
wc.lpfnWndProc = _viewportWndProcPtr;
wc.hInstance = _hInstance;
wc.hCursor = LoadCursorW(IntPtr.Zero, IDC_ARROW);
wc.hbrBackground = IntPtr.Zero;
wc.lpszClassName = WindowClassName;
ushort atom = RegisterClassExW(ref wc);
if (atom == 0)
{
int err = Marshal.GetLastWin32Error();
// 1410 = ERROR_CLASS_ALREADY_EXISTS; fine if we were re-initialized.
if (err != 1410) return false;
}
_classRegistered = true;
return true;
}
// ─── Callback installation ────────────────────────────────────────────
private static void InstallCallbacks(ImGuiPlatformIOPtr pio)
{
IntPtr pioNative = (IntPtr)pio.NativePtr;
IntPtr createPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportCreate);
IntPtr destroyPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportDestroy);
IntPtr showPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportShow);
IntPtr setPosPtr = RootAndGetPointer<ViewportSetVec2Delegate>(ViewportSetPos);
IntPtr setSizePtr = RootAndGetPointer<ViewportSetVec2Delegate>(ViewportSetSize);
IntPtr setFocusPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportSetFocus);
IntPtr getFocusPtr = RootAndGetPointer<ViewportGetBoolDelegate>(ViewportGetFocus);
IntPtr getMinPtr = RootAndGetPointer<ViewportGetBoolDelegate>(ViewportGetMinimized);
IntPtr setTitlePtr = RootAndGetPointer<ViewportSetStringDelegate>(ViewportSetTitle);
IntPtr setAlphaPtr = RootAndGetPointer<ViewportSetFloatDelegate>(ViewportSetAlpha);
IntPtr updatePtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportUpdate);
// Direct writes at native cimgui.dll offsets (NOT ImGui.NET's compiled
// layout offsets — those are off by 36 bytes). Void-return and
// small-return callbacks match the cdecl ABI naturally.
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformCreateWindow, createPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformDestroyWindow, destroyPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformShowWindow, showPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowPos, setPosPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowSize, setSizePtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowFocus, setFocusPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformGetWindowFocus, getFocusPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformGetWindowMinimized, getMinPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowTitle, setTitlePtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowAlpha, setAlphaPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformUpdateWindow, updatePtr);
// GetWindowPos / GetWindowSize return ImVec2 by value (x86 cdecl struct
// return — hidden first arg on stack). Our C# delegates take an out-ptr
// instead; cimgui ships a wrapper helper that adapts the ABI and writes
// the wrapper at the right offset for us. Must install via helper, not
// Marshal.WriteIntPtr, or native crashes on the first call.
IntPtr getPosPtr = RootAndGetPointer<ViewportGetVec2Delegate>(ViewportGetPos);
IntPtr getSizePtr = RootAndGetPointer<ViewportGetVec2Delegate>(ViewportGetSize);
ImGuiNative.ImGuiPlatformIO_Set_Platform_GetWindowPos(pio.NativePtr, getPosPtr);
ImGuiNative.ImGuiPlatformIO_Set_Platform_GetWindowSize(pio.NativePtr, getSizePtr);
// Read back and log so a silent mismatch surfaces as a log line, not an IM_ASSERT.
IntPtr verifyCreate = Marshal.ReadIntPtr(pioNative, ViewportOffsets.PlatformCreateWindow);
IntPtr verifyGetPos = Marshal.ReadIntPtr(pioNative, ViewportOffsets.PlatformGetWindowPos);
RynthLog.Info($"ViewportPlatform: installed handlers (CreateWindow readback=0x{verifyCreate.ToInt64():X8}, expected=0x{createPtr.ToInt64():X8}, GetWindowPos shim=0x{verifyGetPos.ToInt64():X8})");
}
private static IntPtr RootAndGetPointer<TDelegate>(TDelegate del) where TDelegate : Delegate
{
_delegateRoots.Add(del);
return Marshal.GetFunctionPointerForDelegate<TDelegate>(del);
}
private static void WriteFloat(IntPtr basePtr, int offset, float value)
{
Marshal.WriteInt32(basePtr, offset, BitConverter.SingleToInt32Bits(value));
}
// ─── Callback implementations ─────────────────────────────────────────
private static void ViewportCreate(ImGuiViewport* vp)
{
uint flags = unchecked((uint)vp->Flags);
bool noDecoration = (flags & (uint)ImGuiViewportFlags.NoDecoration) != 0;
bool noTaskbarIcon = (flags & (uint)ImGuiViewportFlags.NoTaskBarIcon) != 0;
bool topMost = (flags & (uint)ImGuiViewportFlags.TopMost) != 0;
uint dwStyle = noDecoration
? WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS
: WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
uint dwExStyle = noTaskbarIcon ? WS_EX_TOOLWINDOW : WS_EX_APPWINDOW;
if (topMost) dwExStyle |= WS_EX_TOPMOST;
dwExStyle |= WS_EX_NOACTIVATE;
// Compute outer window rect that yields the requested client size.
RECT rect;
rect.Left = (int)vp->Pos.X;
rect.Top = (int)vp->Pos.Y;
rect.Right = rect.Left + (int)vp->Size.X;
rect.Bottom = rect.Top + (int)vp->Size.Y;
AdjustWindowRectEx(ref rect, dwStyle, false, dwExStyle);
IntPtr hwnd = CreateWindowExW(
dwExStyle, WindowClassName, "RynthCore Viewport", dwStyle,
rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top,
_mainHwnd, IntPtr.Zero, _hInstance, IntPtr.Zero);
if (hwnd == IntPtr.Zero)
{
RynthLog.Info($"ViewportPlatform: CreateWindowEx failed (err {Marshal.GetLastWin32Error()})");
return;
}
var state = new ViewportState { Hwnd = hwnd, HwndOwned = true, DwStyle = dwStyle, DwExStyle = dwExStyle };
_viewports[(IntPtr)vp] = state;
vp->PlatformHandle = (void*)hwnd;
vp->PlatformHandleRaw = (void*)hwnd;
}
private static void ViewportDestroy(ImGuiViewport* vp)
{
IntPtr key = (IntPtr)vp;
if (_viewports.TryGetValue(key, out var state))
{
if (state.HwndOwned && state.Hwnd != IntPtr.Zero)
DestroyWindow(state.Hwnd);
_viewports.Remove(key);
}
vp->PlatformHandle = (void*)IntPtr.Zero;
vp->PlatformHandleRaw = (void*)IntPtr.Zero;
}
private static void ViewportShow(ImGuiViewport* vp)
{
if (!TryGetState(vp, out var state)) return;
ShowWindow(state.Hwnd, SW_SHOWNA);
}
private static void ViewportSetPos(ImGuiViewport* vp, Vector2 pos)
{
if (!TryGetState(vp, out var state)) return;
RECT rect;
rect.Left = (int)pos.X;
rect.Top = (int)pos.Y;
rect.Right = rect.Left;
rect.Bottom = rect.Top;
AdjustWindowRectEx(ref rect, state.DwStyle, false, state.DwExStyle);
SetWindowPos(state.Hwnd, IntPtr.Zero, rect.Left, rect.Top, 0, 0,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
private static void ViewportSetSize(ImGuiViewport* vp, Vector2 size)
{
if (!TryGetState(vp, out var state)) return;
RECT rect;
rect.Left = 0; rect.Top = 0;
rect.Right = (int)size.X;
rect.Bottom = (int)size.Y;
AdjustWindowRectEx(ref rect, state.DwStyle, false, state.DwExStyle);
SetWindowPos(state.Hwnd, IntPtr.Zero, 0, 0,
rect.Right - rect.Left, rect.Bottom - rect.Top,
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
}
private static void ViewportGetPos(ImGuiViewport* vp, Vector2* outPos)
{
*outPos = new Vector2(0, 0);
if (!TryGetState(vp, out var state)) return;
// Return the CLIENT-area origin in screen coords, not the outer window
// rect. ImGui's hit-testing uses this as the viewport origin; if we
// include the title-bar height, every click misses by that offset.
POINT p = new POINT { X = 0, Y = 0 };
if (!ClientToScreen(state.Hwnd, ref p)) return;
*outPos = new Vector2(p.X, p.Y);
}
private static void ViewportGetSize(ImGuiViewport* vp, Vector2* outSize)
{
*outSize = new Vector2(0, 0);
if (!TryGetState(vp, out var state)) return;
if (!GetClientRect(state.Hwnd, out RECT r)) return;
*outSize = new Vector2(r.Right - r.Left, r.Bottom - r.Top);
}
private static void ViewportSetFocus(ImGuiViewport* vp)
{
if (!TryGetState(vp, out var state)) return;
SetForegroundWindow(state.Hwnd);
}
private static byte ViewportGetFocus(ImGuiViewport* vp)
{
if (!TryGetState(vp, out var state)) return 0;
return GetForegroundWindow() == state.Hwnd ? (byte)1 : (byte)0;
}
private static byte ViewportGetMinimized(ImGuiViewport* vp)
{
if (!TryGetState(vp, out var state)) return 0;
return IsIconic(state.Hwnd) ? (byte)1 : (byte)0;
}
private static void ViewportSetTitle(ImGuiViewport* vp, IntPtr strPtr)
{
if (!TryGetState(vp, out var state)) return;
string title = Marshal.PtrToStringUTF8(strPtr) ?? "RynthCore Viewport";
SetWindowTextW(state.Hwnd, title);
}
private static void ViewportSetAlpha(ImGuiViewport* vp, float alpha)
{
if (!TryGetState(vp, out var state)) return;
IntPtr exStyle = GetWindowLongW(state.Hwnd, GWL_EXSTYLE);
long exs = (long)exStyle;
if (alpha < 1.0f)
SetWindowLongW(state.Hwnd, GWL_EXSTYLE, (IntPtr)(exs | WS_EX_LAYERED));
byte a = (byte)Math.Clamp((int)(alpha * 255f + 0.5f), 0, 255);
SetLayeredWindowAttributes(state.Hwnd, 0, a, LWA_ALPHA);
}
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.
}
private static bool TryGetState(ImGuiViewport* vp, out ViewportState state)
{
return _viewports.TryGetValue((IntPtr)vp, out state!);
}
// ─── WndProc for viewport HWNDs ───────────────────────────────────────
internal static IntPtr ImGuiContext;
private static IntPtr ViewportWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr 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)
ImGuiNET.ImGui.SetCurrentContext(ImGuiContext);
try
{
ImGuiViewportPtr vp = ImGuiNET.ImGui.FindViewportByPlatformHandle(hWnd);
if (vp.NativePtr == null)
return DefWindowProcW(hWnd, msg, wParam, lParam);
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
// ── Mouse position: forward in screen coords (multi-viewport) ────
if (msg == WM_MOUSEMOVE || msg == WM_LBUTTONDOWN || msg == WM_LBUTTONUP
|| msg == WM_LBUTTONDBLCLK || msg == WM_RBUTTONDOWN || msg == WM_RBUTTONUP
|| msg == WM_RBUTTONDBLCLK || msg == WM_MBUTTONDOWN || msg == WM_MBUTTONUP
|| msg == WM_MBUTTONDBLCLK || msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP)
{
short cx = (short)((long)lParam & 0xFFFF);
short cy = (short)(((long)lParam >> 16) & 0xFFFF);
POINT pt = new POINT { X = cx, Y = cy };
ClientToScreen(hWnd, ref pt);
io.AddMouseSourceEvent(ImGuiMouseSource.Mouse);
io.AddMousePosEvent(pt.X, pt.Y);
}
switch (msg)
{
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
if (SetCapture(hWnd) == IntPtr.Zero) { /* ignore */ }
io.AddMouseButtonEvent(0, true);
return IntPtr.Zero;
case WM_LBUTTONUP:
io.AddMouseButtonEvent(0, false);
ReleaseCapture();
return IntPtr.Zero;
case WM_RBUTTONDOWN:
case WM_RBUTTONDBLCLK:
SetCapture(hWnd);
io.AddMouseButtonEvent(1, true);
return IntPtr.Zero;
case WM_RBUTTONUP:
io.AddMouseButtonEvent(1, false);
ReleaseCapture();
return IntPtr.Zero;
case WM_MBUTTONDOWN:
case WM_MBUTTONDBLCLK:
SetCapture(hWnd);
io.AddMouseButtonEvent(2, true);
return IntPtr.Zero;
case WM_MBUTTONUP:
io.AddMouseButtonEvent(2, false);
ReleaseCapture();
return IntPtr.Zero;
case WM_XBUTTONDOWN:
{
int btn = (((int)(long)wParam >> 16) & 0xFFFF) == 1 ? 3 : 4;
SetCapture(hWnd);
io.AddMouseButtonEvent(btn, true);
return IntPtr.Zero;
}
case WM_XBUTTONUP:
{
int btn = (((int)(long)wParam >> 16) & 0xFFFF) == 1 ? 3 : 4;
io.AddMouseButtonEvent(btn, false);
ReleaseCapture();
return IntPtr.Zero;
}
case WM_MOUSEWHEEL:
io.AddMouseWheelEvent(0f, (short)(((long)wParam >> 16) & 0xFFFF) / 120f);
return IntPtr.Zero;
case WM_MOUSEHWHEEL:
io.AddMouseWheelEvent((short)(((long)wParam >> 16) & 0xFFFF) / 120f, 0f);
return IntPtr.Zero;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
{
ImGuiKey key = VkToImGuiKey((int)(long)wParam);
if (key != ImGuiKey.None) io.AddKeyEvent(key, true);
// Let DefWindowProc run so system keys still function (Alt+F4 etc.).
break;
}
case WM_KEYUP:
case WM_SYSKEYUP:
{
ImGuiKey key = VkToImGuiKey((int)(long)wParam);
if (key != ImGuiKey.None) io.AddKeyEvent(key, false);
break;
}
case WM_CHAR:
{
uint ch = (uint)(long)wParam;
if (ch > 0 && ch < 0x10000) io.AddInputCharacter(ch);
return IntPtr.Zero;
}
case WM_CLOSE:
vp.PlatformRequestClose = true;
return IntPtr.Zero;
case WM_MOVE:
vp.PlatformRequestMove = true;
break;
case WM_SIZE:
vp.PlatformRequestResize = true;
break;
case WM_MOUSEACTIVATE:
return new IntPtr(MA_NOACTIVATE);
case WM_NCHITTEST:
{
uint flags = unchecked((uint)vp.Flags);
if ((flags & (uint)ImGuiViewportFlags.NoInputs) != 0)
return new IntPtr(-1 /*HTTRANSPARENT*/);
break;
}
}
}
catch (Exception ex)
{
RynthLog.Info($"ViewportPlatform.WndProc: {ex.GetType().Name}: {ex.Message}");
}
finally
{
if (ImGuiContext != IntPtr.Zero && saved != ImGuiContext)
ImGuiNET.ImGui.SetCurrentContext(saved);
}
return DefWindowProcW(hWnd, msg, wParam, lParam);
}
private static ImGuiKey VkToImGuiKey(int vk)
{
return vk switch
{
0x09 => ImGuiKey.Tab,
0x25 => ImGuiKey.LeftArrow,
0x27 => ImGuiKey.RightArrow,
0x26 => ImGuiKey.UpArrow,
0x28 => ImGuiKey.DownArrow,
0x21 => ImGuiKey.PageUp,
0x22 => ImGuiKey.PageDown,
0x24 => ImGuiKey.Home,
0x23 => ImGuiKey.End,
0x2D => ImGuiKey.Insert,
0x2E => ImGuiKey.Delete,
0x08 => ImGuiKey.Backspace,
0x20 => ImGuiKey.Space,
0x0D => ImGuiKey.Enter,
0x1B => ImGuiKey.Escape,
0xBE => ImGuiKey.Period,
0xBC => ImGuiKey.Comma,
0xBD => ImGuiKey.Minus,
0xBB => ImGuiKey.Equal,
0xBA => ImGuiKey.Semicolon,
0xBF => ImGuiKey.Slash,
0xC0 => ImGuiKey.GraveAccent,
0xDB => ImGuiKey.LeftBracket,
0xDC => ImGuiKey.Backslash,
0xDD => ImGuiKey.RightBracket,
0xDE => ImGuiKey.Apostrophe,
>= 0x30 and <= 0x39 => ImGuiKey._0 + (vk - 0x30),
>= 0x41 and <= 0x5A => ImGuiKey.A + (vk - 0x41),
>= 0x60 and <= 0x69 => ImGuiKey.Keypad0 + (vk - 0x60),
>= 0x70 and <= 0x7B => ImGuiKey.F1 + (vk - 0x70),
0x10 => ImGuiKey.LeftShift,
0x11 => ImGuiKey.LeftCtrl,
0x12 => ImGuiKey.LeftAlt,
_ => ImGuiKey.None,
};
}
}

View file

@ -0,0 +1,200 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — ImGui/ViewportProbe.cs
// One-shot diagnostic run at startup. Determines the byte offsets of each
// ImGuiPlatformIO callback field in the running cimgui.dll, so that we can
// install Win32/DX9 platform callbacks by writing IntPtrs directly into
// the native struct (ImGui.NET exposes callback fields as get-only).
//
// Remove/gate this once offsets are documented and wired into a static table.
// ═══════════════════════════════════════════════════════════════════════════
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using ImGuiNET;
namespace RynthCore.Engine.ImGuiBackend;
internal static class ViewportProbe
{
// Every Platform_* and Renderer_* callback field ImGui.NET exposes.
// Probing strategy: write a unique sentinel at each 4-byte slot, read
// every getter, record which getter sees the sentinel, restore the slot.
private static readonly string[] FieldsToProbe =
{
"Platform_CreateWindow",
"Platform_DestroyWindow",
"Platform_ShowWindow",
"Platform_SetWindowPos",
"Platform_GetWindowPos",
"Platform_SetWindowSize",
"Platform_GetWindowSize",
"Platform_SetWindowFocus",
"Platform_GetWindowFocus",
"Platform_GetWindowMinimized",
"Platform_SetWindowTitle",
"Platform_SetWindowAlpha",
"Platform_UpdateWindow",
"Platform_RenderWindow",
"Platform_SwapBuffers",
"Platform_GetWindowDpiScale",
"Platform_OnChangedViewport",
"Platform_GetWindowWorkAreaInsets",
"Platform_CreateVkSurface",
"Renderer_CreateWindow",
"Renderer_DestroyWindow",
"Renderer_SetWindowSize",
"Renderer_RenderWindow",
"Renderer_SwapBuffers",
};
// ImGuiViewport fields worth locating so we know where ImGui.NET reads from
// vs the authoritative bytes. These are read-back tests — no writes.
private static readonly string[] ViewportFieldsToLog =
{
"ID",
"Flags",
"Pos",
"Size",
"WorkPos",
"WorkSize",
"DpiScale",
"ParentViewportId",
"DrawData",
"RendererUserData",
"PlatformUserData",
"PlatformHandle",
"PlatformHandleRaw",
"PlatformWindowCreated",
"PlatformRequestMove",
"PlatformRequestResize",
"PlatformRequestClose",
};
private const int ScanBytes = 768;
public static void Run()
{
try
{
RynthLog.Info("ViewportProbe: ---- begin ----");
RunPlatformIOProbe();
RunMainViewportDump();
RynthLog.Info("ViewportProbe: ---- end ----");
}
catch (Exception ex)
{
RynthLog.Info($"ViewportProbe: FAILED {ex.GetType().Name}: {ex.Message}");
}
}
private static unsafe void RunPlatformIOProbe()
{
ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO();
IntPtr pioNative = (IntPtr)pio.NativePtr;
RynthLog.Info($"ViewportProbe: PlatformIO native = 0x{pioNative.ToInt64():X8}");
// Log what each getter returns BEFORE probing, so we can see the stock zero state.
var propertyCache = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);
Type ptrType = typeof(ImGuiPlatformIOPtr);
foreach (string name in FieldsToProbe)
{
PropertyInfo? prop = ptrType.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
bool intptrLike = prop != null && (
prop.PropertyType == typeof(IntPtr) ||
(prop.PropertyType.IsByRef && prop.PropertyType.GetElementType() == typeof(IntPtr)));
if (intptrLike)
{
propertyCache[name] = prop!;
}
else
{
RynthLog.Info($"ViewportProbe: {name}: NOT FOUND on ImGuiPlatformIOPtr (type={prop?.PropertyType.Name ?? "null"})");
}
}
var discovered = new Dictionary<string, int>(StringComparer.Ordinal);
for (int off = 0; off < ScanBytes; off += 4)
{
IntPtr orig = Marshal.ReadIntPtr(pioNative, off);
IntPtr sentinel = new IntPtr(unchecked((int)0xAB000000) | off);
Marshal.WriteIntPtr(pioNative, off, sentinel);
foreach (var kv in propertyCache)
{
IntPtr read;
try
{
read = (IntPtr)kv.Value.GetValue(pio)!;
}
catch
{
continue;
}
if (read == sentinel && !discovered.ContainsKey(kv.Key))
{
discovered[kv.Key] = off;
}
}
Marshal.WriteIntPtr(pioNative, off, orig);
}
// Emit in ascending offset order so the mapping is obvious in the log.
var sorted = new List<KeyValuePair<string, int>>(discovered);
sorted.Sort((a, b) => a.Value.CompareTo(b.Value));
RynthLog.Info($"ViewportProbe: discovered {sorted.Count}/{propertyCache.Count} offsets:");
foreach (var kv in sorted)
RynthLog.Info($"ViewportProbe: +{kv.Value,4} {kv.Key}");
foreach (string name in FieldsToProbe)
{
if (propertyCache.ContainsKey(name) && !discovered.ContainsKey(name))
RynthLog.Info($"ViewportProbe: MISSING {name} (getter exists but sentinel never matched)");
}
// Hex dump of the first chunk so we can visually scan for anomalies.
DumpRange(pioNative, 0, 256, "PlatformIO");
}
private static unsafe void RunMainViewportDump()
{
ImGuiViewportPtr main = ImGuiNET.ImGui.GetMainViewport();
IntPtr vp = (IntPtr)main.NativePtr;
RynthLog.Info($"ViewportProbe: MainViewport native = 0x{vp.ToInt64():X8}");
Type vptrType = typeof(ImGuiViewportPtr);
foreach (string name in ViewportFieldsToLog)
{
PropertyInfo? prop = vptrType.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
if (prop == null)
{
RynthLog.Info($"ViewportProbe: MainViewport.{name}: (no such property)");
continue;
}
object? val;
try { val = prop.GetValue(main); }
catch (Exception ex) { val = $"<throw {ex.GetType().Name}>"; continue; }
RynthLog.Info($"ViewportProbe: MainViewport.{name} ({prop.PropertyType.Name}) = {val}");
}
DumpRange(vp, 0, 160, "MainViewport");
}
private static void DumpRange(IntPtr basePtr, int startOffset, int length, string label)
{
for (int off = startOffset; off < startOffset + length; off += 16)
{
uint w0 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 0));
uint w1 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 4));
uint w2 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 8));
uint w3 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 12));
RynthLog.Info($"ViewportProbe: {label} +{off,4} {w0:X8} {w1:X8} {w2:X8} {w3:X8}");
}
}
}

View file

@ -0,0 +1,367 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — ImGui/ViewportRendererBackend.cs
// Per-viewport D3D9 renderer backend for ImGui multi-viewport.
// Installs Renderer_* callbacks on ImGuiPlatformIO: for each viewport we
// create an additional swap chain on the game's device, render the viewport's
// ImDrawData into that swap chain's back buffer, and Present it so the
// viewport's OS window displays the ImGui content.
// ═══════════════════════════════════════════════════════════════════════════
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using ImGuiNET;
using RynthCore.Engine.D3D9;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class ViewportRendererBackend
{
// ─── D3D9 constants ───────────────────────────────────────────────
private const uint D3DFMT_UNKNOWN = 0;
private const uint D3DFMT_A8R8G8B8 = 21;
private const uint D3DFMT_X8R8G8B8 = 22;
private const uint D3DSWAPEFFECT_DISCARD = 1;
private const uint D3DBACKBUFFER_TYPE_MONO = 0;
private const uint D3DCLEAR_TARGET = 0x00000001;
private const uint D3DPRESENT_INTERVAL_IMMEDIATE = 0x80000000;
[StructLayout(LayoutKind.Sequential)]
private struct D3DPRESENT_PARAMETERS
{
public uint BackBufferWidth;
public uint BackBufferHeight;
public uint BackBufferFormat;
public uint BackBufferCount;
public uint MultiSampleType;
public uint MultiSampleQuality;
public uint SwapEffect;
public IntPtr hDeviceWindow;
public int Windowed; // BOOL
public int EnableAutoDepthStencil; // BOOL
public uint AutoDepthStencilFormat;
public uint Flags;
public uint FullScreen_RefreshRateInHz;
public uint PresentationInterval;
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT { public int L, T, R, B; }
// ─── Device method delegates ──────────────────────────────────────
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int CreateAdditionalSwapChainD(IntPtr pDevice, D3DPRESENT_PARAMETERS* pp, out IntPtr ppSwapChain);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetRenderTargetD(IntPtr pDevice, uint rtIndex, IntPtr pSurface);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetRenderTargetD(IntPtr pDevice, uint rtIndex, out IntPtr ppSurface);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int ClearD(IntPtr pDevice, uint count, RECT* pRects, uint flags, uint color, float z, uint stencil);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseD(IntPtr pObj);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SwapChainGetBackBufferD(IntPtr pSwapChain, uint backBufIdx, uint type, out IntPtr ppBackBuffer);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SwapChainPresentD(IntPtr pSwapChain, RECT* src, RECT* dest, IntPtr hDestWnd, IntPtr dirtyRgn, uint flags);
// ─── Callback delegates (must match imgui types) ──────────────────
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportCallbackD(ImGuiViewport* vp);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportSizeCallbackD(ImGuiViewport* vp, System.Numerics.Vector2 size);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportRenderD(ImGuiViewport* vp, IntPtr renderArg);
// ─── State ────────────────────────────────────────────────────────
private sealed class ViewportGpuState
{
public IntPtr SwapChain;
public int Width;
public int Height;
}
private static IntPtr _device;
private static CreateAdditionalSwapChainD? _createAdditionalSwapChain;
private static SetRenderTargetD? _setRenderTarget;
private static GetRenderTargetD? _getRenderTarget;
private static ClearD? _clear;
private static readonly Dictionary<IntPtr, ViewportGpuState> _viewports = new();
private static readonly List<Delegate> _delegateRoots = new();
private static bool _initialized;
// Diagnostic one-shot logging counters — limited to a few calls so log doesn't explode.
private static int _logCreate;
private static int _logRender;
private static int _logSwap;
private const int MaxLog = 3;
public static bool Init(IntPtr pDevice)
{
if (_initialized) return true;
if (pDevice == IntPtr.Zero)
{
RynthLog.Info("ViewportRenderer: Init called with null device.");
return false;
}
_device = pDevice;
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
_createAdditionalSwapChain = GetMethod<CreateAdditionalSwapChainD>(vtable, DeviceVTableIndex.CreateAdditionalSwapChain);
_setRenderTarget = GetMethod<SetRenderTargetD>(vtable, DeviceVTableIndex.SetRenderTarget);
_getRenderTarget = GetMethod<GetRenderTargetD>(vtable, DeviceVTableIndex.GetRenderTarget);
_clear = GetMethod<ClearD>(vtable, DeviceVTableIndex.Clear);
InstallCallbacks();
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
io.BackendFlags |= ImGuiBackendFlags.RendererHasViewports;
_initialized = true;
RynthLog.Info("ViewportRenderer: initialized.");
return true;
}
public static void Shutdown()
{
foreach (var kv in _viewports)
{
if (kv.Value.SwapChain != IntPtr.Zero)
ReleaseCom(kv.Value.SwapChain);
}
_viewports.Clear();
_delegateRoots.Clear();
_initialized = false;
}
private static void InstallCallbacks()
{
ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO();
IntPtr pioNative = (IntPtr)pio.NativePtr;
ViewportCallbackD createFn = RendererCreateWindow;
ViewportCallbackD destroyFn = RendererDestroyWindow;
ViewportSizeCallbackD setSizeFn = RendererSetWindowSize;
ViewportRenderD renderFn = RendererRenderWindow;
ViewportRenderD swapFn = RendererSwapBuffers;
_delegateRoots.Add(createFn);
_delegateRoots.Add(destroyFn);
_delegateRoots.Add(setSizeFn);
_delegateRoots.Add(renderFn);
_delegateRoots.Add(swapFn);
IntPtr createPtr = Marshal.GetFunctionPointerForDelegate(createFn);
IntPtr destroyPtr = Marshal.GetFunctionPointerForDelegate(destroyFn);
IntPtr setSizePtr = Marshal.GetFunctionPointerForDelegate(setSizeFn);
IntPtr renderPtr = Marshal.GetFunctionPointerForDelegate(renderFn);
IntPtr swapPtr = Marshal.GetFunctionPointerForDelegate(swapFn);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererCreateWindow, createPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererDestroyWindow, destroyPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererSetWindowSize, setSizePtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererRenderWindow, renderPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererSwapBuffers, swapPtr);
IntPtr verify = Marshal.ReadIntPtr(pioNative, ViewportOffsets.RendererRenderWindow);
RynthLog.Info($"ViewportRenderer: installed handlers (RenderWindow readback=0x{verify.ToInt64():X8}, expected=0x{renderPtr.ToInt64():X8})");
}
// ─── Callback implementations ─────────────────────────────────────
private static void RendererCreateWindow(ImGuiViewport* vp)
{
IntPtr key = (IntPtr)vp;
if (_viewports.ContainsKey(key)) return;
var state = new ViewportGpuState();
_viewports[key] = state;
int w = Math.Max(1, (int)vp->Size.X);
int h = Math.Max(1, (int)vp->Size.Y);
CreateSwapChainForViewport(vp, state, w, h);
if (_logCreate++ < MaxLog)
{
IntPtr hwnd = (IntPtr)vp->PlatformHandleRaw;
if (hwnd == IntPtr.Zero) hwnd = (IntPtr)vp->PlatformHandle;
RynthLog.Info($"ViewportRenderer: CreateWindow vp=0x{key.ToInt64():X8} hwnd=0x{hwnd.ToInt64():X8} size={w}x{h} swapChain=0x{state.SwapChain.ToInt64():X8}");
}
}
private static void RendererDestroyWindow(ImGuiViewport* vp)
{
IntPtr key = (IntPtr)vp;
if (!_viewports.TryGetValue(key, out var state)) return;
if (state.SwapChain != IntPtr.Zero)
{
ReleaseCom(state.SwapChain);
state.SwapChain = IntPtr.Zero;
}
_viewports.Remove(key);
}
private static void RendererSetWindowSize(ImGuiViewport* vp, System.Numerics.Vector2 size)
{
IntPtr key = (IntPtr)vp;
if (!_viewports.TryGetValue(key, out var state)) return;
int w = Math.Max(1, (int)size.X);
int h = Math.Max(1, (int)size.Y);
if (w == state.Width && h == state.Height) return;
if (state.SwapChain != IntPtr.Zero)
{
ReleaseCom(state.SwapChain);
state.SwapChain = IntPtr.Zero;
}
CreateSwapChainForViewport(vp, state, w, h);
}
private static void RendererRenderWindow(ImGuiViewport* vp, IntPtr renderArg)
{
IntPtr key = (IntPtr)vp;
bool diag = _logRender < MaxLog;
if (!_viewports.TryGetValue(key, out var state))
{
if (diag) { RynthLog.Info($"ViewportRenderer: RenderWindow vp=0x{key.ToInt64():X8} NO STATE"); _logRender++; }
return;
}
if (state.SwapChain == IntPtr.Zero)
{
if (diag) { RynthLog.Info($"ViewportRenderer: RenderWindow vp=0x{key.ToInt64():X8} NO SWAPCHAIN"); _logRender++; }
return;
}
if (_setRenderTarget == null || _getRenderTarget == null || _clear == null)
{
if (diag) { RynthLog.Info("ViewportRenderer: RenderWindow device methods null"); _logRender++; }
return;
}
// Get the swap chain's back-buffer surface
var getBB = GetMethodFromObj<SwapChainGetBackBufferD>(state.SwapChain, SwapChain9VTableIndex.GetBackBuffer);
int hrBB = getBB(state.SwapChain, 0, D3DBACKBUFFER_TYPE_MONO, out IntPtr backBuffer);
if (hrBB < 0 || backBuffer == IntPtr.Zero)
{
if (diag) { RynthLog.Info($"ViewportRenderer: GetBackBuffer failed hr=0x{hrBB:X8}"); _logRender++; }
return;
}
IntPtr oldRenderTarget = IntPtr.Zero;
int cmdCount = 0;
float ddW = 0, ddH = 0, ddX = 0, ddY = 0;
try
{
_getRenderTarget(_device, 0, out oldRenderTarget);
int hrSRT = _setRenderTarget(_device, 0, backBuffer);
// Clear unless the ImGui viewport asked us not to.
uint flags = unchecked((uint)vp->Flags);
if ((flags & (uint)ImGuiViewportFlags.NoRendererClear) == 0)
{
_clear(_device, 0, null, D3DCLEAR_TARGET, 0x00000000u, 1.0f, 0);
}
// Render the viewport's own draw data through the main DX9 backend,
// which already handles full state save/restore.
ImDrawDataPtr draw = new ImDrawDataPtr((ImDrawData*)vp->DrawData);
if ((IntPtr)draw.NativePtr != IntPtr.Zero)
{
IntPtr dd = (IntPtr)draw.NativePtr;
cmdCount = Marshal.ReadInt32(dd, 4);
ddX = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 20));
ddY = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 24));
ddW = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 28));
ddH = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 32));
DX9Backend.RenderDrawData(draw, _device);
}
if (diag)
{
RynthLog.Info($"ViewportRenderer: RenderWindow vp=0x{key.ToInt64():X8} setRT=0x{hrSRT:X8} bb=0x{backBuffer.ToInt64():X8} cmds={cmdCount} ddPos=({ddX},{ddY}) ddSize=({ddW},{ddH})");
_logRender++;
}
}
finally
{
if (oldRenderTarget != IntPtr.Zero)
{
_setRenderTarget(_device, 0, oldRenderTarget);
ReleaseCom(oldRenderTarget);
}
ReleaseCom(backBuffer);
}
}
private static void RendererSwapBuffers(ImGuiViewport* vp, IntPtr renderArg)
{
IntPtr key = (IntPtr)vp;
if (!_viewports.TryGetValue(key, out var state)) return;
if (state.SwapChain == IntPtr.Zero) return;
var present = GetMethodFromObj<SwapChainPresentD>(state.SwapChain, SwapChain9VTableIndex.Present);
int hr = present(state.SwapChain, null, null, IntPtr.Zero, IntPtr.Zero, 0);
if (_logSwap++ < MaxLog)
RynthLog.Info($"ViewportRenderer: SwapBuffers vp=0x{key.ToInt64():X8} Present hr=0x{hr:X8}");
}
// ─── Helpers ──────────────────────────────────────────────────────
private static void CreateSwapChainForViewport(ImGuiViewport* vp, ViewportGpuState state, int w, int h)
{
if (_createAdditionalSwapChain == null) return;
IntPtr hwnd = (IntPtr)vp->PlatformHandleRaw;
if (hwnd == IntPtr.Zero) hwnd = (IntPtr)vp->PlatformHandle;
if (hwnd == IntPtr.Zero)
{
RynthLog.Info("ViewportRenderer: viewport has no HWND — cannot create swap chain.");
return;
}
var pp = new D3DPRESENT_PARAMETERS
{
BackBufferWidth = (uint)w,
BackBufferHeight = (uint)h,
BackBufferFormat = D3DFMT_UNKNOWN, // match device default
BackBufferCount = 1,
SwapEffect = D3DSWAPEFFECT_DISCARD,
hDeviceWindow = hwnd,
Windowed = 1,
// Don't wait for vblank — each popped viewport adds another Present
// per frame, and stacking vsyncs cuts the effective frame rate.
PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE,
};
int hr = _createAdditionalSwapChain(_device, &pp, out IntPtr swapChain);
if (hr < 0 || swapChain == IntPtr.Zero)
{
RynthLog.Info($"ViewportRenderer: CreateAdditionalSwapChain failed (hr=0x{hr:X8}) for {w}x{h} hwnd=0x{hwnd:X}");
return;
}
state.SwapChain = swapChain;
state.Width = w;
state.Height = h;
}
private static T GetMethod<T>(IntPtr vtable, int index) where T : Delegate
{
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
return Marshal.GetDelegateForFunctionPointer<T>(addr);
}
private static T GetMethodFromObj<T>(IntPtr pObj, int index) where T : Delegate
{
IntPtr vtable = Marshal.ReadIntPtr(pObj);
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
return Marshal.GetDelegateForFunctionPointer<T>(addr);
}
private static void ReleaseCom(IntPtr pObj)
{
if (pObj == IntPtr.Zero) return;
IntPtr vtable = Marshal.ReadIntPtr(pObj);
IntPtr addr = Marshal.ReadIntPtr(vtable, 2 * IntPtr.Size); // Release is index 2
var release = Marshal.GetDelegateForFunctionPointer<ReleaseD>(addr);
release(pObj);
}
}

View file

@ -19,7 +19,10 @@ internal static unsafe class Win32Backend
private const uint WM_MOUSEMOVE = 0x0200;
private const uint WM_SETFOCUS = 0x0007;
private const uint WM_KILLFOCUS = 0x0008;
private const uint WM_ACTIVATE = 0x0006;
private const uint WM_ACTIVATEAPP = 0x001C;
private const int WA_INACTIVE = 0;
private const int WA_ACTIVE = 1;
private const uint WM_LBUTTONDOWN = 0x0201;
private const uint WM_LBUTTONUP = 0x0202;
private const uint WM_RBUTTONDOWN = 0x0204;
@ -59,6 +62,12 @@ internal static unsafe class Win32Backend
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("kernel32.dll")]
private static extern uint GetCurrentProcessId();
[DllImport("user32.dll")]
private static extern IntPtr GetAncestor(IntPtr hWnd, uint gaFlags);
@ -68,6 +77,9 @@ internal static unsafe class Win32Backend
[DllImport("user32.dll")]
private static extern bool ScreenToClient(IntPtr hWnd, ref POINT lpPoint);
[DllImport("user32.dll")]
private static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint);
[DllImport("user32.dll")]
private static extern bool GetCursorPos(out POINT lpPoint);
@ -282,9 +294,12 @@ internal static unsafe class Win32Backend
FlushQueuedInput(io);
// Always refresh the cursor position relative to the device window.
// Refresh the cursor position. With ViewportsEnable, ImGui expects
// absolute screen coords so it can route clicks to the correct viewport.
// Without it, client-relative coords are the simpler contract.
GetCursorPos(out POINT cursorPos);
ScreenToClient(_gameHwnd, ref cursorPos);
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) == 0)
ScreenToClient(_gameHwnd, ref cursorPos);
io.AddMousePosEvent(cursorPos.X, cursorPos.Y);
SyncFocusState(io);
@ -364,6 +379,21 @@ internal static unsafe class Win32Backend
if (msg == WM_ACTIVATEAPP && EndSceneHook.FpsLimitEnabled)
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)
{
int activationCode = (int)((long)wParam & 0xFFFF);
if (activationCode == WA_INACTIVE && lParam != IntPtr.Zero)
{
GetWindowThreadProcessId(lParam, out uint newActivePid);
if (newActivePid == GetCurrentProcessId())
return CallWindowProcA(_originalWndProc, hWnd, msg, (IntPtr)WA_ACTIVE, lParam);
}
}
// Pass through to original WndProc
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam);
}
@ -692,7 +722,16 @@ internal static unsafe class Win32Backend
{
short x = (short)((long)lParam & 0xFFFF);
short y = (short)(((long)lParam >> 16) & 0xFFFF);
io.AddMousePosEvent(x, y);
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
{
POINT p = new POINT { X = x, Y = y };
ClientToScreen(_gameHwnd, ref p);
io.AddMousePosEvent(p.X, p.Y);
}
else
{
io.AddMousePosEvent(x, y);
}
}
private static void UpdateMouseButton(ImGuiIOPtr io, int buttonIndex, int virtualKey)

View file

@ -455,6 +455,12 @@ internal struct RynthCoreAPI
/// Force-resets the client's ClientUISystem busy count to zero.
/// Use after portal teleports that interrupt actions and leave the hourglass cursor stuck.</summary>
public IntPtr ForceResetBusyCountFn;
/// <summary>Function pointer: int GetObjectPalettes(uint objectId, uint* subIds, uint* offsets, int maxCount)
/// Fills subIds and offsets with the item's ObjDesc subpalette data (sorted by offset).
/// Returns total subpalette count, or -1 if no data was captured for this object.
/// subIds[i] is the palette DID; offsets[i] is the range-start offset (used as slot index).</summary>
public IntPtr GetObjectPalettesFn;
}
@ -462,7 +468,7 @@ internal struct RynthCoreAPI
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI.</summary>
internal static class PluginContractVersion
{
public const uint Current = 49;
public const uint Current = 50;
}
internal static class ClientActionHookFlags
@ -846,3 +852,6 @@ internal delegate uint GetObjectBitfieldCallbackDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void ForceResetBusyCountCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetObjectPalettesCallbackDelegate(uint objectId, uint* subIds, uint* offsets, int maxCount);

View file

@ -188,6 +188,7 @@ internal static class PluginManager
private static GetObjectMotionOnCallbackDelegate? _getObjectMotionOnCallback;
private static GetObjectStateCallbackDelegate? _getObjectStateCallback;
private static GetObjectBitfieldCallbackDelegate? _getObjectBitfieldCallback;
private static GetObjectPalettesCallbackDelegate? _getObjectPalettesCallback;
private static IntPtr _accountNameScratchPtr;
private static IntPtr _worldNameScratchPtr;
[ThreadStatic] private static IntPtr _objectNameScratchPtr;
@ -1836,6 +1837,8 @@ internal static class PluginManager
_api.GetObjectStateFn = Marshal.GetFunctionPointerForDelegate(_getObjectStateCallback);
_api.GetObjectBitfieldFn = Marshal.GetFunctionPointerForDelegate(_getObjectBitfieldCallback);
_api.ForceResetBusyCountFn = Marshal.GetFunctionPointerForDelegate(_forceResetBusyCountCallback);
_getObjectPalettesCallback ??= GetObjectPalettesAction;
_api.GetObjectPalettesFn = Marshal.GetFunctionPointerForDelegate(_getObjectPalettesCallback);
}
private static void ProbeClientHooks()
@ -2362,6 +2365,12 @@ internal static class PluginManager
return ClientObjectHooks.TryGetObjectBitfield(objectId, out uint bitfield) ? bitfield : 0u;
}
private static unsafe int GetObjectPalettesAction(uint objectId, uint* subIds, uint* offsets, int maxCount)
{
if (subIds == null || offsets == null || maxCount <= 0) return -1;
return PaletteCache.Fill(objectId, subIds, offsets, maxCount);
}
private static int HasAppraisalDataAction(uint objectId)
{
return AppraisalHooks.HasAppraisalData(objectId) ? 1 : 0;

View file

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0-windows</TargetFramework>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>