Initial commit
A modern .NET 9 NativeAOT framework for Asheron's Call client modding. Self-contained injection system that hooks D3D9 EndScene to render an ImGui overlay inside the AC client process.
This commit is contained in:
commit
80b71d295d
179 changed files with 52858 additions and 0 deletions
227
src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs
Normal file
227
src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static class D3D9Bootstrapper
|
||||
{
|
||||
private const uint D3DSdkVersion = 32;
|
||||
private const int PollIntervalMs = 50;
|
||||
private const int BootstrapFallbackMs = 15000;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate IntPtr Direct3DCreate9Delegate(uint sdkVersion);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int CreateDeviceDelegate(
|
||||
IntPtr pD3D9,
|
||||
uint adapter,
|
||||
uint deviceType,
|
||||
IntPtr hFocusWindow,
|
||||
uint behaviorFlags,
|
||||
IntPtr pPresentationParameters,
|
||||
out IntPtr ppDevice);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
|
||||
private static extern IntPtr GetModuleHandleA(string? lpModuleName);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
private static int _started;
|
||||
private static bool _d3dCreateHookInstalled;
|
||||
private static bool _createDeviceHookInstalled;
|
||||
private static bool _realDeviceObserved;
|
||||
private static Direct3DCreate9Delegate? _originalDirect3DCreate9;
|
||||
private static Direct3DCreate9Delegate? _direct3DCreate9Detour;
|
||||
private static CreateDeviceDelegate? _originalCreateDevice;
|
||||
private static CreateDeviceDelegate? _createDeviceDetour;
|
||||
private static IntPtr _createDeviceTarget;
|
||||
private static IntPtr _direct3DCreate9Target;
|
||||
|
||||
public static void Start()
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _started, 1, 0) != 0)
|
||||
return;
|
||||
|
||||
var thread = new Thread(BootstrapWorker)
|
||||
{
|
||||
Name = "RynthCore.D3D9Bootstrap",
|
||||
IsBackground = true
|
||||
};
|
||||
thread.Start();
|
||||
}
|
||||
|
||||
private static void BootstrapWorker()
|
||||
{
|
||||
try
|
||||
{
|
||||
// This runs after character login, so d3d9.dll and the game's
|
||||
// device are fully initialized. Use the NULLREF throwaway device
|
||||
// for vtable discovery — it's safe post-login because the
|
||||
// d3d9-on-d3d12 wrapper has finished all its one-time init work.
|
||||
IntPtr earlyModule = GetModuleHandleA("d3d9.dll");
|
||||
if (earlyModule != IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: d3d9.dll loaded — discovering EndScene via NULLREF device.");
|
||||
EndSceneHook.Install("post-login-vtable");
|
||||
return;
|
||||
}
|
||||
|
||||
RynthLog.D3D9("D3D9Bootstrapper: Waiting for d3d9.dll so RynthCore can hook the real device creation path.");
|
||||
DateTime fallbackDeadline = DateTime.UtcNow.AddMilliseconds(BootstrapFallbackMs);
|
||||
|
||||
while (!EndSceneHook.IsInstalled())
|
||||
{
|
||||
IntPtr d3d9Module = GetModuleHandleA("d3d9.dll");
|
||||
if (d3d9Module != IntPtr.Zero)
|
||||
{
|
||||
TryHookDirect3DCreate9(d3d9Module);
|
||||
if (_realDeviceObserved || EndSceneHook.IsInstalled())
|
||||
return;
|
||||
}
|
||||
|
||||
if (DateTime.UtcNow >= fallbackDeadline)
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: Real CreateDevice path was not observed in time. Falling back to shared vtable discovery.");
|
||||
RemoveBootstrapHooks();
|
||||
EndSceneHook.Install();
|
||||
return;
|
||||
}
|
||||
|
||||
Thread.Sleep(PollIntervalMs);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: FATAL bootstrap error: {ex}");
|
||||
if (!EndSceneHook.IsInstalled())
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: Attempting fallback EndScene install after bootstrap failure.");
|
||||
RemoveBootstrapHooks();
|
||||
EndSceneHook.Install();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryHookDirect3DCreate9(IntPtr d3d9Module)
|
||||
{
|
||||
if (_d3dCreateHookInstalled)
|
||||
return;
|
||||
|
||||
IntPtr direct3DCreate9Addr = GetProcAddress(d3d9Module, "Direct3DCreate9");
|
||||
if (direct3DCreate9Addr == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Direct3DCreate9 export unavailable (error {Marshal.GetLastWin32Error()}).");
|
||||
return;
|
||||
}
|
||||
|
||||
_direct3DCreate9Target = direct3DCreate9Addr;
|
||||
_direct3DCreate9Detour = Direct3DCreate9Detour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_direct3DCreate9Detour);
|
||||
|
||||
_originalDirect3DCreate9 = Marshal.GetDelegateForFunctionPointer<Direct3DCreate9Delegate>(MinHook.HookCreate(direct3DCreate9Addr, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(direct3DCreate9Addr);
|
||||
_d3dCreateHookInstalled = true;
|
||||
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Hooked Direct3DCreate9 @ 0x{direct3DCreate9Addr:X8}");
|
||||
}
|
||||
|
||||
private static IntPtr Direct3DCreate9Detour(uint sdkVersion)
|
||||
{
|
||||
IntPtr direct3D9 = _originalDirect3DCreate9!(sdkVersion);
|
||||
|
||||
if (sdkVersion != D3DSdkVersion)
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Direct3DCreate9 called with SDK {sdkVersion} (expected {D3DSdkVersion}).");
|
||||
|
||||
if (direct3D9 == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: Direct3DCreate9 returned null.");
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
TryHookCreateDevice(direct3D9);
|
||||
return direct3D9;
|
||||
}
|
||||
|
||||
private static void TryHookCreateDevice(IntPtr direct3D9)
|
||||
{
|
||||
if (_createDeviceHookInstalled)
|
||||
return;
|
||||
|
||||
IntPtr vtable = Marshal.ReadIntPtr(direct3D9);
|
||||
_createDeviceTarget = Marshal.ReadIntPtr(vtable, D3D9VTableIndex.CreateDevice * IntPtr.Size);
|
||||
if (_createDeviceTarget == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: IDirect3D9::CreateDevice pointer was null.");
|
||||
return;
|
||||
}
|
||||
|
||||
_createDeviceDetour = CreateDeviceDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_createDeviceDetour);
|
||||
|
||||
_originalCreateDevice = Marshal.GetDelegateForFunctionPointer<CreateDeviceDelegate>(MinHook.HookCreate(_createDeviceTarget, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_createDeviceTarget);
|
||||
_createDeviceHookInstalled = true;
|
||||
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Hooked IDirect3D9::CreateDevice @ 0x{_createDeviceTarget:X8}");
|
||||
}
|
||||
|
||||
private static void RemoveBootstrapHooks()
|
||||
{
|
||||
if (_d3dCreateHookInstalled && _direct3DCreate9Target != IntPtr.Zero)
|
||||
{
|
||||
int status = MinHook.MH_DisableHook(_direct3DCreate9Target);
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Disable Direct3DCreate9 hook = {MinHook.StatusString(status)}");
|
||||
status = MinHook.MH_RemoveHook(_direct3DCreate9Target);
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Remove Direct3DCreate9 hook = {MinHook.StatusString(status)}");
|
||||
_d3dCreateHookInstalled = false;
|
||||
}
|
||||
|
||||
if (_createDeviceHookInstalled && _createDeviceTarget != IntPtr.Zero)
|
||||
{
|
||||
int status = MinHook.MH_DisableHook(_createDeviceTarget);
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Disable CreateDevice hook = {MinHook.StatusString(status)}");
|
||||
status = MinHook.MH_RemoveHook(_createDeviceTarget);
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Remove CreateDevice hook = {MinHook.StatusString(status)}");
|
||||
_createDeviceHookInstalled = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static int CreateDeviceDetour(
|
||||
IntPtr pD3D9,
|
||||
uint adapter,
|
||||
uint deviceType,
|
||||
IntPtr hFocusWindow,
|
||||
uint behaviorFlags,
|
||||
IntPtr pPresentationParameters,
|
||||
out IntPtr ppDevice)
|
||||
{
|
||||
int hr = _originalCreateDevice!(
|
||||
pD3D9,
|
||||
adapter,
|
||||
deviceType,
|
||||
hFocusWindow,
|
||||
behaviorFlags,
|
||||
pPresentationParameters,
|
||||
out ppDevice);
|
||||
|
||||
if (hr >= 0 && ppDevice != IntPtr.Zero)
|
||||
{
|
||||
_realDeviceObserved = true;
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Observed real device creation (device=0x{ppDevice:X8}, hwnd=0x{hFocusWindow:X8}, hr=0x{hr:X8}).");
|
||||
RemoveBootstrapHooks();
|
||||
EndSceneHook.InstallFromDevice(ppDevice);
|
||||
}
|
||||
else
|
||||
{
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: CreateDevice returned hr=0x{hr:X8}, device=0x{ppDevice:X8}");
|
||||
}
|
||||
|
||||
return hr;
|
||||
}
|
||||
}
|
||||
593
src/RynthCore.Engine/D3D9/D3D9VTable.cs
Normal file
593
src/RynthCore.Engine/D3D9/D3D9VTable.cs
Normal file
|
|
@ -0,0 +1,593 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/D3D9VTable.cs
|
||||
// Creates a throwaway D3D9 device to harvest vtable function pointers.
|
||||
// The vtable is shared across all IDirect3DDevice9 instances in the process,
|
||||
// so the addresses we read here apply to the game's real device.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
/// <summary>
|
||||
/// IDirect3DDevice9 vtable indices (x86, standard d3d9.h order).
|
||||
/// </summary>
|
||||
internal static class DeviceVTableIndex
|
||||
{
|
||||
public const int Release = 2;
|
||||
public const int GetCreationParameters = 9;
|
||||
public const int CreateAdditionalSwapChain = 13;
|
||||
public const int Reset = 16;
|
||||
public const int GetBackBuffer = 18;
|
||||
public const int CreateTexture = 23;
|
||||
public const int BeginScene = 41;
|
||||
public const int EndScene = 42;
|
||||
public const int Clear = 43;
|
||||
public const int SetTransform = 44;
|
||||
public const int GetTransform = 45;
|
||||
public const int GetRenderTarget = 38;
|
||||
public const int SetViewport = 47;
|
||||
public const int GetViewport = 48;
|
||||
public const int GetTexture = 64;
|
||||
public const int SetRenderState = 57;
|
||||
public const int GetRenderState = 58;
|
||||
public const int SetTexture = 65;
|
||||
public const int GetTextureStageState = 66;
|
||||
public const int SetTextureStageState = 67;
|
||||
public const int GetSamplerState = 68;
|
||||
public const int SetSamplerState = 69;
|
||||
public const int SetScissorRect = 75;
|
||||
public const int GetScissorRect = 76;
|
||||
public const int DrawPrimitive = 81;
|
||||
public const int DrawIndexedPrimitive = 82;
|
||||
public const int DrawPrimitiveUP = 83;
|
||||
public const int DrawIndexedPrimitiveUP = 84;
|
||||
public const int SetFVF = 89;
|
||||
public const int GetFVF = 90;
|
||||
public const int SetVertexShader = 92;
|
||||
public const int GetVertexShader = 93;
|
||||
public const int SetStreamSource = 100;
|
||||
public const int GetStreamSource = 101;
|
||||
public const int SetIndices = 104;
|
||||
public const int GetIndices = 105;
|
||||
public const int SetPixelShader = 107;
|
||||
public const int GetPixelShader = 108;
|
||||
public const int CreateStateBlock = 60;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// IDirect3DStateBlock9 vtable indices.
|
||||
/// </summary>
|
||||
internal static class StateBlockVTableIndex
|
||||
{
|
||||
public const int Release = 2;
|
||||
public const int Capture = 4;
|
||||
public const int Apply = 5;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// IDirect3DTexture9 vtable indices.
|
||||
/// </summary>
|
||||
internal static class TextureVTableIndex
|
||||
{
|
||||
public const int Release = 2;
|
||||
public const int LockRect = 19;
|
||||
public const int UnlockRect = 20;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// IDirect3D9 vtable indices.
|
||||
/// </summary>
|
||||
internal static class D3D9VTableIndex
|
||||
{
|
||||
public const int Release = 2;
|
||||
public const int CreateDevice = 16;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the IDirect3DDevice9 vtable by creating (and immediately releasing)
|
||||
/// a temporary device + hidden window.
|
||||
/// Also provides <see cref="ScanModuleForDeviceVTable"/> which finds the vtable
|
||||
/// by scanning d3d9.dll's module image — no device creation required.
|
||||
/// </summary>
|
||||
internal static unsafe class D3D9VTable
|
||||
{
|
||||
// ─── D3D9 constants ───────────────────────────────────────────────
|
||||
private const uint D3D_SDK_VERSION = 32;
|
||||
private const uint D3DDEVTYPE_HAL = 1;
|
||||
private const uint D3DDEVTYPE_NULLREF = 4;
|
||||
private const uint D3DCREATE_SOFTWARE_VERTEXPROCESSING = 0x00000020;
|
||||
private const uint D3DCREATE_MULTITHREADED = 0x00000004;
|
||||
private const uint D3DFMT_UNKNOWN = 0;
|
||||
private const uint D3DSWAPEFFECT_DISCARD = 1;
|
||||
|
||||
// ─── Win32 ────────────────────────────────────────────────────────
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
private static extern IntPtr CreateWindowExA(
|
||||
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")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool DestroyWindow(IntPtr hWnd);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern IntPtr GetModuleHandleA(string? lpModuleName);
|
||||
|
||||
// ─── D3D9 ─────────────────────────────────────────────────────────
|
||||
[DllImport("d3d9.dll")]
|
||||
private static extern IntPtr Direct3DCreate9(uint SDKVersion);
|
||||
|
||||
// ─── COM Release delegate ─────────────────────────────────────────
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate uint ReleaseDelegate(IntPtr pThis);
|
||||
|
||||
// ─── IDirect3D9::CreateDevice delegate ────────────────────────────
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int CreateDeviceDelegate(
|
||||
IntPtr pD3D9,
|
||||
uint Adapter,
|
||||
uint DeviceType,
|
||||
IntPtr hFocusWindow,
|
||||
uint BehaviorFlags,
|
||||
IntPtr pPresentationParameters,
|
||||
out IntPtr ppDevice);
|
||||
|
||||
// ─── D3DPRESENT_PARAMETERS (x86 layout) ───────────────────────────
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct D3DPRESENT_PARAMETERS
|
||||
{
|
||||
public uint BackBufferWidth;
|
||||
public uint BackBufferHeight;
|
||||
public uint BackBufferFormat; // D3DFORMAT
|
||||
public uint BackBufferCount;
|
||||
public uint MultiSampleType; // D3DMULTISAMPLE_TYPE
|
||||
public uint MultiSampleQuality;
|
||||
public uint SwapEffect; // D3DSWAPEFFECT
|
||||
public IntPtr hDeviceWindow;
|
||||
public int Windowed; // BOOL
|
||||
public int EnableAutoDepthStencil; // BOOL
|
||||
public uint AutoDepthStencilFormat; // D3DFORMAT
|
||||
public uint Flags;
|
||||
public uint FullScreen_RefreshRateInHz;
|
||||
public uint PresentationInterval;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a temp D3D9 device and returns a copy of the device vtable
|
||||
/// (array of function pointers). Returns null on failure.
|
||||
/// </summary>
|
||||
public static IntPtr[]? GetDeviceVTable(int numEntries = 119)
|
||||
{
|
||||
IntPtr hWnd = IntPtr.Zero;
|
||||
IntPtr pD3D9 = IntPtr.Zero;
|
||||
IntPtr pDevice = IntPtr.Zero;
|
||||
|
||||
try
|
||||
{
|
||||
// Create a hidden window
|
||||
hWnd = CreateWindowExA(
|
||||
0, "STATIC", "RynthCore_D3D9_Temp", 0,
|
||||
0, 0, 1, 1,
|
||||
IntPtr.Zero, IntPtr.Zero,
|
||||
GetModuleHandleA(null), IntPtr.Zero);
|
||||
|
||||
if (hWnd == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9VTable: Failed to create temp window.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Create IDirect3D9
|
||||
pD3D9 = Direct3DCreate9(D3D_SDK_VERSION);
|
||||
if (pD3D9 == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9VTable: Direct3DCreate9 failed.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Set up present parameters
|
||||
var pp = new D3DPRESENT_PARAMETERS
|
||||
{
|
||||
BackBufferWidth = 1,
|
||||
BackBufferHeight = 1,
|
||||
BackBufferFormat = D3DFMT_UNKNOWN,
|
||||
BackBufferCount = 1,
|
||||
SwapEffect = D3DSWAPEFFECT_DISCARD,
|
||||
hDeviceWindow = hWnd,
|
||||
Windowed = 1, // TRUE
|
||||
};
|
||||
|
||||
// Call IDirect3D9::CreateDevice via vtable
|
||||
IntPtr d3d9VTable = Marshal.ReadIntPtr(pD3D9); // pD3D9->lpVtbl
|
||||
IntPtr createDeviceAddr = Marshal.ReadIntPtr(d3d9VTable, D3D9VTableIndex.CreateDevice * IntPtr.Size);
|
||||
var createDevice = Marshal.GetDelegateForFunctionPointer<CreateDeviceDelegate>(createDeviceAddr);
|
||||
|
||||
IntPtr ppAlloc = Marshal.AllocHGlobal(Marshal.SizeOf<D3DPRESENT_PARAMETERS>());
|
||||
Marshal.StructureToPtr(pp, ppAlloc, false);
|
||||
|
||||
// Try NULLREF device first — it doesn't touch the GPU, avoiding
|
||||
// race conditions with the game's render thread on the real HAL device.
|
||||
int hr = createDevice(
|
||||
pD3D9,
|
||||
0, // D3DADAPTER_DEFAULT
|
||||
D3DDEVTYPE_NULLREF,
|
||||
hWnd,
|
||||
D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED,
|
||||
ppAlloc,
|
||||
out pDevice);
|
||||
|
||||
if (hr < 0 || pDevice == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: NULLREF device failed (hr=0x{hr:X8}), trying HAL fallback.");
|
||||
Marshal.StructureToPtr(pp, ppAlloc, false);
|
||||
hr = createDevice(
|
||||
pD3D9,
|
||||
0,
|
||||
D3DDEVTYPE_HAL,
|
||||
hWnd,
|
||||
D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED,
|
||||
ppAlloc,
|
||||
out pDevice);
|
||||
}
|
||||
|
||||
Marshal.FreeHGlobal(ppAlloc);
|
||||
|
||||
if (hr < 0 || pDevice == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: CreateDevice failed, HRESULT=0x{hr:X8}");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Read the device vtable
|
||||
IntPtr deviceVTable = Marshal.ReadIntPtr(pDevice); // pDevice->lpVtbl
|
||||
var vtable = new IntPtr[numEntries];
|
||||
for (int i = 0; i < numEntries; i++)
|
||||
vtable[i] = Marshal.ReadIntPtr(deviceVTable, i * IntPtr.Size);
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: Captured {numEntries} entries. " +
|
||||
$"EndScene=0x{vtable[DeviceVTableIndex.EndScene]:X8}");
|
||||
|
||||
return vtable;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: Exception: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Release the temp device and D3D9 object
|
||||
if (pDevice != IntPtr.Zero)
|
||||
{
|
||||
IntPtr vtbl = Marshal.ReadIntPtr(pDevice);
|
||||
IntPtr releaseAddr = Marshal.ReadIntPtr(vtbl, DeviceVTableIndex.Release * IntPtr.Size);
|
||||
var release = Marshal.GetDelegateForFunctionPointer<ReleaseDelegate>(releaseAddr);
|
||||
release(pDevice);
|
||||
}
|
||||
|
||||
if (pD3D9 != IntPtr.Zero)
|
||||
{
|
||||
IntPtr vtbl = Marshal.ReadIntPtr(pD3D9);
|
||||
IntPtr releaseAddr = Marshal.ReadIntPtr(vtbl, D3D9VTableIndex.Release * IntPtr.Size);
|
||||
var release = Marshal.GetDelegateForFunctionPointer<ReleaseDelegate>(releaseAddr);
|
||||
release(pD3D9);
|
||||
}
|
||||
|
||||
if (hWnd != IntPtr.Zero)
|
||||
DestroyWindow(hWnd);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scans the loaded d3d9.dll module image for the IDirect3DDevice9 vtable
|
||||
/// without creating any D3D9 objects. This avoids the thread-safety hazard
|
||||
/// of creating a throwaway device while the game's real device is rendering.
|
||||
/// Returns null if the scan cannot find a valid candidate.
|
||||
/// </summary>
|
||||
public static IntPtr[]? ScanModuleForDeviceVTable(int numEntries = 119)
|
||||
{
|
||||
IntPtr hModule = GetModuleHandleA("d3d9.dll");
|
||||
if (hModule == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9VTable: d3d9.dll not loaded — module scan skipped.");
|
||||
return null;
|
||||
}
|
||||
|
||||
const int MaxReasonableModuleSize = 50 * 1024 * 1024;
|
||||
if (!TryReadModuleImageSize(hModule, out int imageSize) || imageSize < 0x2000 || imageSize > MaxReasonableModuleSize)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: d3d9.dll PE headers unusable (imageSize=0x{imageSize:X}) — module scan skipped.");
|
||||
return null;
|
||||
}
|
||||
|
||||
int baseAddr = hModule.ToInt32();
|
||||
int vtableByteLen = numEntries * 4; // x86 pointer size
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: Reading d3d9.dll (0x{baseAddr:X8}, 0x{imageSize:X} bytes)...");
|
||||
|
||||
// Copy module into managed memory page-by-page, skipping any
|
||||
// uncommitted pages. SizeOfImage can exceed committed memory
|
||||
// and NativeAOT cannot catch the resulting AccessViolationException.
|
||||
byte[] image = new byte[imageSize];
|
||||
int readableBytes = 0;
|
||||
const int PageSize = 0x1000;
|
||||
for (int off = 0; off < imageSize; off += PageSize)
|
||||
{
|
||||
int chunk = Math.Min(PageSize, imageSize - off);
|
||||
IntPtr addr = IntPtr.Add(hModule, off);
|
||||
if (SmartBoxLocator.IsMemoryReadable(addr, chunk))
|
||||
{
|
||||
Marshal.Copy(addr, image, off, chunk);
|
||||
readableBytes += chunk;
|
||||
}
|
||||
}
|
||||
|
||||
if (readableBytes < vtableByteLen + 0x1000)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: Only {readableBytes} readable bytes in d3d9.dll — too small for vtable scan.");
|
||||
return null;
|
||||
}
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: Scanning d3d9.dll ({readableBytes} readable bytes) for {numEntries}-entry device vtable...");
|
||||
|
||||
// Collect ALL candidate vtables. d3d9.dll on Windows 11 can contain
|
||||
// multiple vtables (inner implementation + outer proxy). The game's
|
||||
// device typically uses the LAST one (the outer proxy layer).
|
||||
IntPtr[]? bestCandidate = null;
|
||||
int bestOffset = 0;
|
||||
int candidateCount = 0;
|
||||
|
||||
for (int off = 0x1000; off <= imageSize - vtableByteLen; off += 4)
|
||||
{
|
||||
// Fast reject: first 3 entries (QueryInterface, AddRef, Release) must be in-module
|
||||
int p0 = BitConverter.ToInt32(image, off);
|
||||
if ((uint)(p0 - baseAddr) >= (uint)imageSize) continue;
|
||||
int p1 = BitConverter.ToInt32(image, off + 4);
|
||||
if ((uint)(p1 - baseAddr) >= (uint)imageSize) continue;
|
||||
int p2 = BitConverter.ToInt32(image, off + 8);
|
||||
if ((uint)(p2 - baseAddr) >= (uint)imageSize) continue;
|
||||
|
||||
// QI, AddRef, Release must be distinct functions
|
||||
if (p0 == p1 || p1 == p2) continue;
|
||||
|
||||
// Count in-module pointers across all entries
|
||||
int inModule = 3;
|
||||
for (int i = 3; i < numEntries; i++)
|
||||
{
|
||||
int ptr = BitConverter.ToInt32(image, off + i * 4);
|
||||
if ((uint)(ptr - baseAddr) < (uint)imageSize)
|
||||
inModule++;
|
||||
}
|
||||
|
||||
// Require ≥95% in-module (113 of 119)
|
||||
if (inModule < numEntries * 95 / 100) continue;
|
||||
|
||||
// EndScene (42) and BeginScene (41) must differ
|
||||
int esPtr = BitConverter.ToInt32(image, off + DeviceVTableIndex.EndScene * 4);
|
||||
int bsPtr = BitConverter.ToInt32(image, off + DeviceVTableIndex.BeginScene * 4);
|
||||
if (esPtr == bsPtr) continue;
|
||||
|
||||
// Verify EndScene starts with a hookable function prologue
|
||||
int esOff = esPtr - baseAddr;
|
||||
if ((uint)esOff >= (uint)(imageSize - 3)) continue;
|
||||
if (!IsRecognizedPrologue(image, esOff)) continue;
|
||||
|
||||
candidateCount++;
|
||||
|
||||
// Build candidate array
|
||||
var vtable = new IntPtr[numEntries];
|
||||
for (int i = 0; i < numEntries; i++)
|
||||
vtable[i] = new IntPtr(BitConverter.ToInt32(image, off + i * 4));
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: Candidate #{candidateCount} at d3d9+0x{off:X}: " +
|
||||
$"EndScene=0x{vtable[DeviceVTableIndex.EndScene]:X8} ({inModule}/{numEntries} in-module)");
|
||||
|
||||
bestCandidate = vtable;
|
||||
bestOffset = off;
|
||||
}
|
||||
|
||||
if (bestCandidate != null)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: Using candidate #{candidateCount} (last of {candidateCount}) at d3d9+0x{bestOffset:X}: " +
|
||||
$"EndScene=0x{bestCandidate[DeviceVTableIndex.EndScene]:X8}");
|
||||
return bestCandidate;
|
||||
}
|
||||
|
||||
RynthLog.D3D9("D3D9VTable: Module scan found no device vtable candidates.");
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool IsRecognizedPrologue(byte[] image, int offset)
|
||||
{
|
||||
byte b = image[offset];
|
||||
if (b == 0x55) return true; // push ebp
|
||||
if (b == 0x8B && image[offset + 1] == 0xFF) return true; // mov edi,edi (hot-patch)
|
||||
if (b == 0x83 && image[offset + 1] == 0xEC) return true; // sub esp, imm8
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the game's existing IDirect3DDevice9 by scanning process heap memory
|
||||
/// for a live COM object whose vtable is in d3d9.dll with 119 entries.
|
||||
/// Completely read-only — no D3D9 API calls, no thread-safety hazards.
|
||||
/// Returns null if no device is found.
|
||||
/// </summary>
|
||||
public static IntPtr[]? FindExistingDeviceVTable(int numEntries = 119)
|
||||
{
|
||||
IntPtr d3d9Module = GetModuleHandleA("d3d9.dll");
|
||||
if (d3d9Module == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9VTable: d3d9.dll not loaded — device scan skipped.");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!TryReadModuleImageSize(d3d9Module, out int d3d9Size) || d3d9Size < 0x2000)
|
||||
{
|
||||
RynthLog.D3D9("D3D9VTable: d3d9.dll PE headers unusable — device scan skipped.");
|
||||
return null;
|
||||
}
|
||||
|
||||
int d3d9Base = d3d9Module.ToInt32();
|
||||
int d3d9End = d3d9Base + d3d9Size;
|
||||
int vtableByteLen = numEntries * 4;
|
||||
|
||||
// Pre-read d3d9.dll image so vtable validation reads from safe managed memory
|
||||
byte[] d3d9Image = new byte[d3d9Size];
|
||||
int d3d9Readable = 0;
|
||||
const int PageSize = 0x1000;
|
||||
for (int off = 0; off < d3d9Size; off += PageSize)
|
||||
{
|
||||
int chunk = Math.Min(PageSize, d3d9Size - off);
|
||||
IntPtr addr = IntPtr.Add(d3d9Module, off);
|
||||
if (SmartBoxLocator.IsMemoryReadable(addr, chunk))
|
||||
{
|
||||
Marshal.Copy(addr, d3d9Image, off, chunk);
|
||||
d3d9Readable += chunk;
|
||||
}
|
||||
}
|
||||
|
||||
if (d3d9Readable < vtableByteLen + PageSize)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9VTable: Only {d3d9Readable} readable bytes in d3d9.dll — device scan skipped.");
|
||||
return null;
|
||||
}
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: Scanning process heap for live D3D9 device (d3d9=0x{d3d9Base:X8}, size=0x{d3d9Size:X})...");
|
||||
|
||||
int regionsScanned = 0;
|
||||
long bytesScanned = 0;
|
||||
int d3d9Pointers = 0;
|
||||
|
||||
IntPtr scanAddr = new IntPtr(0x10000);
|
||||
|
||||
while (scanAddr.ToInt32() > 0 && scanAddr.ToInt32() < 0x7FFE0000)
|
||||
{
|
||||
if (!VirtualQueryWrapped(scanAddr, out int regionBase, out int regionSize,
|
||||
out uint state, out uint protect, out uint type))
|
||||
break;
|
||||
|
||||
if (regionSize <= 0) break;
|
||||
IntPtr nextAddr = new IntPtr(regionBase + regionSize);
|
||||
|
||||
// Only scan committed, readable, private (heap) memory
|
||||
bool committed = (state & 0x1000) != 0; // MEM_COMMIT
|
||||
bool readable = protect != 0 && (protect & 0x01) == 0 && (protect & 0x100) == 0; // !NOACCESS, !GUARD
|
||||
bool isPrivate = (type & 0x20000) != 0; // MEM_PRIVATE
|
||||
|
||||
if (!committed || !readable || !isPrivate || regionSize < 128)
|
||||
{
|
||||
scanAddr = nextAddr;
|
||||
continue;
|
||||
}
|
||||
|
||||
regionsScanned++;
|
||||
|
||||
// Safe page-by-page copy of this region
|
||||
byte[] regionData = new byte[regionSize];
|
||||
int regionReadable = 0;
|
||||
for (int off = 0; off < regionSize; off += PageSize)
|
||||
{
|
||||
int chunk = Math.Min(PageSize, regionSize - off);
|
||||
IntPtr pageAddr = new IntPtr(regionBase + off);
|
||||
if (SmartBoxLocator.IsMemoryReadable(pageAddr, chunk))
|
||||
{
|
||||
Marshal.Copy(pageAddr, regionData, off, chunk);
|
||||
regionReadable += chunk;
|
||||
}
|
||||
}
|
||||
|
||||
bytesScanned += regionReadable;
|
||||
|
||||
// Scan each dword for a vtable pointer into d3d9.dll
|
||||
for (int off = 0; off <= regionReadable - 4; off += 4)
|
||||
{
|
||||
int value = BitConverter.ToInt32(regionData, off);
|
||||
if (value < d3d9Base || value >= d3d9End) continue;
|
||||
|
||||
d3d9Pointers++;
|
||||
|
||||
// Check if this is a 119-entry device vtable
|
||||
int vtableOffset = value - d3d9Base;
|
||||
if (vtableOffset + vtableByteLen > d3d9Readable) continue;
|
||||
|
||||
int inModule = 0;
|
||||
for (int i = 0; i < numEntries; i++)
|
||||
{
|
||||
int entry = BitConverter.ToInt32(d3d9Image, vtableOffset + i * 4);
|
||||
if (entry >= d3d9Base && entry < d3d9End)
|
||||
inModule++;
|
||||
}
|
||||
|
||||
if (inModule < numEntries * 95 / 100) continue;
|
||||
|
||||
// BeginScene and EndScene must differ
|
||||
int bs = BitConverter.ToInt32(d3d9Image, vtableOffset + DeviceVTableIndex.BeginScene * 4);
|
||||
int es = BitConverter.ToInt32(d3d9Image, vtableOffset + DeviceVTableIndex.EndScene * 4);
|
||||
if (bs == es) continue;
|
||||
|
||||
// EndScene must have a hookable prologue
|
||||
int esOff = es - d3d9Base;
|
||||
if ((uint)esOff >= (uint)(d3d9Readable - 3)) continue;
|
||||
if (!IsRecognizedPrologue(d3d9Image, esOff)) continue;
|
||||
|
||||
var vtable = new IntPtr[numEntries];
|
||||
for (int i = 0; i < numEntries; i++)
|
||||
vtable[i] = new IntPtr(BitConverter.ToInt32(d3d9Image, vtableOffset + i * 4));
|
||||
|
||||
int objectAddr = regionBase + off;
|
||||
RynthLog.D3D9($"D3D9VTable: Found live device at 0x{objectAddr:X8}, vtable=0x{value:X8} (d3d9+0x{vtableOffset:X}), " +
|
||||
$"EndScene=0x{vtable[DeviceVTableIndex.EndScene]:X8} ({inModule}/{numEntries} in-module)");
|
||||
RynthLog.D3D9($"D3D9VTable: Heap scan stats: {regionsScanned} regions, {bytesScanned / 1024}KB, {d3d9Pointers} d3d9 pointers checked.");
|
||||
return vtable;
|
||||
}
|
||||
|
||||
scanAddr = nextAddr;
|
||||
}
|
||||
|
||||
RynthLog.D3D9($"D3D9VTable: No live device found — {regionsScanned} regions, {bytesScanned / 1024}KB, {d3d9Pointers} d3d9 pointers.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// ─── VirtualQuery wrapper ─────────────────────────────────────────
|
||||
[DllImport("kernel32.dll", SetLastError = false)]
|
||||
private static extern int VirtualQuery(IntPtr lpAddress, byte[] lpBuffer, int dwLength);
|
||||
|
||||
private static bool VirtualQueryWrapped(IntPtr address, out int regionBase, out int regionSize,
|
||||
out uint state, out uint protect, out uint type)
|
||||
{
|
||||
regionBase = 0; regionSize = 0; state = 0; protect = 0; type = 0;
|
||||
byte[] buf = new byte[28]; // MEMORY_BASIC_INFORMATION on x86
|
||||
int result = VirtualQuery(address, buf, 28);
|
||||
if (result == 0) return false;
|
||||
|
||||
regionBase = BitConverter.ToInt32(buf, 0); // BaseAddress
|
||||
regionSize = BitConverter.ToInt32(buf, 12); // RegionSize
|
||||
state = BitConverter.ToUInt32(buf, 16); // State
|
||||
protect = BitConverter.ToUInt32(buf, 20); // Protect
|
||||
type = BitConverter.ToUInt32(buf, 24); // Type
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryReadModuleImageSize(IntPtr moduleBase, out int imageSize)
|
||||
{
|
||||
imageSize = 0;
|
||||
try
|
||||
{
|
||||
if ((ushort)Marshal.ReadInt16(moduleBase) != 0x5A4D) return false; // MZ
|
||||
int peOffset = Marshal.ReadInt32(moduleBase, 0x3C);
|
||||
if (peOffset <= 0) return false;
|
||||
IntPtr ntHeaders = IntPtr.Add(moduleBase, peOffset);
|
||||
if ((uint)Marshal.ReadInt32(ntHeaders) != 0x00004550) return false; // PE\0\0
|
||||
imageSize = Marshal.ReadInt32(ntHeaders, 0x18 + 0x38); // SizeOfImage
|
||||
return imageSize > 0x1000;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
313
src/RynthCore.Engine/D3D9/EndSceneHook.cs
Normal file
313
src/RynthCore.Engine/D3D9/EndSceneHook.cs
Normal file
|
|
@ -0,0 +1,313 @@
|
|||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
using RynthCore.Engine.ImGuiBackend;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static class EndSceneHook
|
||||
{
|
||||
private const int MaxOffscreenSkipLogs = 3;
|
||||
private const int MaxOffscreenSkipsBeforeFallback = 120;
|
||||
private const int OffscreenFallbackDelayMs = 3000;
|
||||
private const int UiInitWarmupFrames = 180;
|
||||
|
||||
// ── FPS Governor — set by plugins via API ───────────────────────
|
||||
internal static bool FpsLimitEnabled;
|
||||
internal static int FpsTargetFocused = 60;
|
||||
internal static int FpsTargetBackground = 30;
|
||||
private static readonly Stopwatch _fpsTimer = Stopwatch.StartNew();
|
||||
private static bool _fpsLimiterLoggedOnce;
|
||||
private static int _fpsDebugCounter;
|
||||
private static long _fpsCounterStart;
|
||||
private static int _fpsCounterFrames;
|
||||
|
||||
[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);
|
||||
|
||||
private static EndSceneDelegate? _originalEndScene;
|
||||
private static EndSceneDelegate? _hookDelegate;
|
||||
private static IntPtr _endSceneAddr;
|
||||
private static bool _installed;
|
||||
private static int _frameCount;
|
||||
private static int _renderCount;
|
||||
private static int _skipCount;
|
||||
private static int _uiFrameCount;
|
||||
private static bool _offscreenFilterDisabled;
|
||||
private static bool _uiActivated;
|
||||
private static bool _warmupLogged;
|
||||
private static long _installTick;
|
||||
private static long _firstOffscreenTick;
|
||||
private static string _installSource = "uninitialized";
|
||||
|
||||
public static void Install()
|
||||
{
|
||||
Install("fallback-vtable");
|
||||
}
|
||||
|
||||
public static void Install(string installSource)
|
||||
{
|
||||
if (_installed)
|
||||
return;
|
||||
|
||||
ResetInstallState(installSource);
|
||||
|
||||
// Vtable discovery uses a NULLREF device to avoid GPU contention
|
||||
// with the game's render thread. Retry once on failure.
|
||||
const int maxAttempts = 2;
|
||||
for (int attempt = 1; attempt <= maxAttempts; attempt++)
|
||||
{
|
||||
RynthLog.D3D9($"EndSceneHook: Discovering D3D9 vtable (attempt {attempt}/{maxAttempts})...");
|
||||
|
||||
if (attempt > 1)
|
||||
System.Threading.Thread.Sleep(500);
|
||||
|
||||
IntPtr[]? vtable = D3D9VTable.GetDeviceVTable();
|
||||
if (vtable != null)
|
||||
{
|
||||
IntPtr endSceneAddress = vtable[DeviceVTableIndex.EndScene];
|
||||
RynthLog.D3D9($"EndSceneHook: EndScene @ 0x{endSceneAddress:X8}");
|
||||
InstallFromEndSceneAddress(endSceneAddress);
|
||||
return;
|
||||
}
|
||||
|
||||
RynthLog.D3D9($"EndSceneHook: Vtable discovery returned null on attempt {attempt}.");
|
||||
}
|
||||
|
||||
RynthLog.D3D9("EndSceneHook: FAILED - could not discover vtable after all attempts.");
|
||||
}
|
||||
|
||||
public static void InstallFromDevice(IntPtr pDevice)
|
||||
{
|
||||
if (_installed)
|
||||
return;
|
||||
|
||||
if (pDevice == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("EndSceneHook: Real-device install skipped because the device pointer was null.");
|
||||
return;
|
||||
}
|
||||
|
||||
ResetInstallState("real-device");
|
||||
|
||||
IntPtr deviceVTable = Marshal.ReadIntPtr(pDevice);
|
||||
IntPtr endSceneAddress = Marshal.ReadIntPtr(deviceVTable, DeviceVTableIndex.EndScene * IntPtr.Size);
|
||||
RynthLog.D3D9($"EndSceneHook: Using real D3D9 device 0x{pDevice:X8}; EndScene @ 0x{endSceneAddress:X8}");
|
||||
InstallFromEndSceneAddress(endSceneAddress);
|
||||
}
|
||||
|
||||
public static void InstallFromAddress(IntPtr endSceneAddress, string installSource)
|
||||
{
|
||||
if (_installed)
|
||||
return;
|
||||
|
||||
if (endSceneAddress == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("EndSceneHook: Address install skipped because EndScene was null.");
|
||||
return;
|
||||
}
|
||||
|
||||
ResetInstallState(installSource);
|
||||
RynthLog.D3D9($"EndSceneHook: Using explicit EndScene address 0x{endSceneAddress:X8} from {installSource}.");
|
||||
InstallFromEndSceneAddress(endSceneAddress);
|
||||
}
|
||||
|
||||
public static bool IsInstalled()
|
||||
{
|
||||
return _installed;
|
||||
}
|
||||
|
||||
public static int GetRenderCount()
|
||||
{
|
||||
return _renderCount;
|
||||
}
|
||||
|
||||
public static void Uninstall()
|
||||
{
|
||||
if (!_installed)
|
||||
return;
|
||||
|
||||
ImGuiController.Shutdown();
|
||||
|
||||
int status = MinHook.MH_DisableHook(_endSceneAddr);
|
||||
RynthLog.D3D9($"EndSceneHook: Disable = {MinHook.StatusString(status)}");
|
||||
|
||||
status = MinHook.MH_RemoveHook(_endSceneAddr);
|
||||
RynthLog.D3D9($"EndSceneHook: Remove = {MinHook.StatusString(status)}");
|
||||
|
||||
_installed = false;
|
||||
_originalEndScene = null;
|
||||
_offscreenFilterDisabled = false;
|
||||
}
|
||||
|
||||
private static void ResetInstallState(string installSource)
|
||||
{
|
||||
_installSource = installSource;
|
||||
_frameCount = 0;
|
||||
_renderCount = 0;
|
||||
_skipCount = 0;
|
||||
_uiFrameCount = 0;
|
||||
_offscreenFilterDisabled = false;
|
||||
_uiActivated = false;
|
||||
_warmupLogged = false;
|
||||
_installTick = Environment.TickCount64;
|
||||
_firstOffscreenTick = 0;
|
||||
}
|
||||
|
||||
private static void InstallFromEndSceneAddress(IntPtr endSceneAddress)
|
||||
{
|
||||
_endSceneAddr = endSceneAddress;
|
||||
|
||||
_hookDelegate = new EndSceneDelegate(EndSceneDetour);
|
||||
IntPtr hookPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate);
|
||||
|
||||
try
|
||||
{
|
||||
_originalEndScene = Marshal.GetDelegateForFunctionPointer<EndSceneDelegate>(MinHook.HookCreate(_endSceneAddr, hookPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_endSceneAddr);
|
||||
_installed = true;
|
||||
|
||||
RynthLog.D3D9($"EndSceneHook: INSTALLED successfully via {_installSource}.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"EndSceneHook: MinHook failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static int EndSceneDetour(IntPtr pDevice)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!_offscreenFilterDisabled && !DX9Backend.IsRenderingToBackBuffer(pDevice))
|
||||
{
|
||||
if (_firstOffscreenTick == 0)
|
||||
_firstOffscreenTick = Environment.TickCount64;
|
||||
|
||||
if (_skipCount < MaxOffscreenSkipLogs)
|
||||
RynthLog.D3D9("EndSceneHook: Skipping offscreen EndScene pass.");
|
||||
_skipCount++;
|
||||
|
||||
long offscreenElapsedMs = Environment.TickCount64 - _firstOffscreenTick;
|
||||
if (_skipCount < MaxOffscreenSkipsBeforeFallback && offscreenElapsedMs < OffscreenFallbackDelayMs)
|
||||
return _originalEndScene!(pDevice);
|
||||
|
||||
_offscreenFilterDisabled = true;
|
||||
RynthLog.D3D9($"EndSceneHook: Falling back to unfiltered EndScene after {_skipCount} skipped offscreen pass(es) over {offscreenElapsedMs}ms.");
|
||||
}
|
||||
|
||||
_renderCount++;
|
||||
_frameCount++;
|
||||
|
||||
if (_renderCount == 1 && _offscreenFilterDisabled && _skipCount > 0)
|
||||
{
|
||||
long installElapsedMs = Environment.TickCount64 - _installTick;
|
||||
RynthLog.D3D9($"EndSceneHook: First render after offscreen fallback ({_skipCount} skip(s), {installElapsedMs}ms since install).");
|
||||
}
|
||||
|
||||
if (_renderCount == 1 && _skipCount > 0)
|
||||
RynthLog.D3D9($"EndSceneHook: First backbuffer frame after skipping {_skipCount} offscreen pass(es).");
|
||||
|
||||
// On first backbuffer frame, verify we hooked the right function by
|
||||
// reading the device's own vtable. A mismatch means the module scan
|
||||
// found an internal/proxy vtable, not the one the game's device uses.
|
||||
if (_renderCount == 1)
|
||||
{
|
||||
IntPtr deviceVtable = Marshal.ReadIntPtr(pDevice);
|
||||
IntPtr actualEndScene = Marshal.ReadIntPtr(deviceVtable, DeviceVTableIndex.EndScene * IntPtr.Size);
|
||||
bool match = actualEndScene == _endSceneAddr;
|
||||
RynthLog.D3D9($"EndSceneHook: Device vtable EndScene=0x{actualEndScene:X8}, hooked=0x{_endSceneAddr:X8} — {(match ? "MATCH" : "MISMATCH")}");
|
||||
|
||||
if (!match && actualEndScene != IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("EndSceneHook: Rehooking at the device's actual EndScene address.");
|
||||
MinHook.MH_DisableHook(_endSceneAddr);
|
||||
MinHook.MH_RemoveHook(_endSceneAddr);
|
||||
_installed = false;
|
||||
|
||||
InstallFromEndSceneAddress(actualEndScene);
|
||||
if (_installed)
|
||||
return _originalEndScene!(pDevice);
|
||||
|
||||
RynthLog.D3D9("EndSceneHook: Rehook failed — continuing with original hook.");
|
||||
// Restore state so we don't keep trying
|
||||
_installed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!_uiActivated)
|
||||
{
|
||||
if (!_warmupLogged)
|
||||
{
|
||||
RynthLog.D3D9($"EndSceneHook: Backbuffer detected. Warming up {UiInitWarmupFrames} frame(s) before UI init.");
|
||||
_warmupLogged = true;
|
||||
}
|
||||
|
||||
if (_renderCount < UiInitWarmupFrames)
|
||||
return _originalEndScene!(pDevice);
|
||||
|
||||
_uiActivated = true;
|
||||
RynthLog.D3D9("EndSceneHook: Warmup complete - initializing ImGui.");
|
||||
}
|
||||
|
||||
ImGuiController.OnEndScene(pDevice);
|
||||
_uiFrameCount++;
|
||||
|
||||
if (_uiFrameCount == 60)
|
||||
RynthLog.D3D9("EndSceneHook: 60 UI frames - ImGui is stable.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (_uiFrameCount < 30)
|
||||
RynthLog.D3D9($"EndSceneHook: Frame {_frameCount} error: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
|
||||
}
|
||||
|
||||
// ── FPS Governor (matches proven NexSuite2 pattern) ─────────
|
||||
if (FpsLimitEnabled)
|
||||
{
|
||||
IntPtr fgWnd = GetForegroundWindow();
|
||||
GetWindowThreadProcessId(fgWnd, out uint fgPid);
|
||||
uint thisPid = GetCurrentProcessId();
|
||||
bool isFocused = fgPid == thisPid;
|
||||
int targetFps = isFocused ? FpsTargetFocused : FpsTargetBackground;
|
||||
double minFrameMs = 1000.0 / Math.Max(targetFps, 1);
|
||||
|
||||
while (_fpsTimer.Elapsed.TotalMilliseconds < minFrameMs)
|
||||
Thread.Sleep(isFocused ? 0 : 1);
|
||||
_fpsTimer.Restart();
|
||||
|
||||
if (!_fpsLimiterLoggedOnce)
|
||||
{
|
||||
_fpsLimiterLoggedOnce = true;
|
||||
RynthLog.D3D9($"EndSceneHook: FPS governor active — max={FpsTargetFocused} focused, max={FpsTargetBackground} background, pid={thisPid}");
|
||||
}
|
||||
|
||||
// Periodic FPS measurement — log every 60 seconds
|
||||
_fpsCounterFrames++;
|
||||
long now = Environment.TickCount64;
|
||||
if (_fpsCounterStart == 0) _fpsCounterStart = now;
|
||||
long elapsedMs = now - _fpsCounterStart;
|
||||
if (elapsedMs >= 60_000)
|
||||
{
|
||||
double measuredFps = _fpsCounterFrames * 1000.0 / elapsedMs;
|
||||
RynthLog.D3D9($"EndSceneHook: FPS={measuredFps:F1} (target={targetFps}, {(isFocused ? "focused" : "background")})");
|
||||
_fpsCounterFrames = 0;
|
||||
_fpsCounterStart = now;
|
||||
}
|
||||
}
|
||||
|
||||
return _originalEndScene!(pDevice);
|
||||
}
|
||||
}
|
||||
286
src/RynthCore.Engine/D3D9/GameMatrixCapture.cs
Normal file
286
src/RynthCore.Engine/D3D9/GameMatrixCapture.cs
Normal file
|
|
@ -0,0 +1,286 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/GameMatrixCapture.cs
|
||||
// Captures the game's camera transform and perspective Projection matrix
|
||||
// for WorldToScreen projection.
|
||||
//
|
||||
// AC sets View=identity and World=identity — it transforms all vertices
|
||||
// on the CPU before sending to D3D9. Only the Projection matrix is real.
|
||||
//
|
||||
// Strategy:
|
||||
// - Hook SetTransform to capture the perspective Projection matrix.
|
||||
// - Read the camera position + rotation from SmartBox memory.
|
||||
// - Build the View matrix manually, then ViewProj = View * Proj.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static unsafe class GameMatrixCapture
|
||||
{
|
||||
private const uint D3DTS_PROJECTION = 3;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTransformD(IntPtr dev, uint state, float* pMatrix);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetViewportD(IntPtr dev, int* pViewport);
|
||||
|
||||
// SetTransform hook
|
||||
private static SetTransformD? _originalSetTransform;
|
||||
private static SetTransformD? _hookDelegate;
|
||||
private static bool _hookInstalled;
|
||||
|
||||
// Viewport
|
||||
private static GetViewportD? _getViewport;
|
||||
private static bool _viewportCached;
|
||||
private static uint _vpWidth;
|
||||
private static uint _vpHeight;
|
||||
private static bool _hasViewport;
|
||||
|
||||
// Captured Projection matrix
|
||||
private static readonly float[] _perspProj = new float[16];
|
||||
private static bool _hasProj;
|
||||
|
||||
// Computed matrices
|
||||
private static readonly float[] _viewMatrix = new float[16];
|
||||
private static readonly float[] _viewProj = new float[16];
|
||||
private static bool _hasValidViewProj;
|
||||
|
||||
// Camera frame from SmartBox memory (same layout as UB Camera.cs)
|
||||
private const int CameraFrameOffset = 0x08;
|
||||
private const int CamRotOffset = 0x18; // 3x3 rotation matrix
|
||||
private const int CamPosOffset = 0x3C; // position (x, y, z)
|
||||
|
||||
// Diagnostics
|
||||
private static int _framesSinceLog;
|
||||
private static bool _loggedFirstCapture;
|
||||
|
||||
public static bool HasCapturedFrame => _hasValidViewProj;
|
||||
public static uint ViewportWidth => _vpWidth;
|
||||
public static uint ViewportHeight => _vpHeight;
|
||||
|
||||
/// <summary>Copy the 4x4 View matrix (row-major) into the destination.</summary>
|
||||
public static void GetViewMatrix(ref float dest)
|
||||
{
|
||||
fixed (float* s = _viewMatrix)
|
||||
fixed (float* d = &dest)
|
||||
{
|
||||
for (int i = 0; i < 16; i++)
|
||||
d[i] = s[i];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Copy the 4x4 Projection matrix (row-major) into the destination.</summary>
|
||||
public static void GetProjectionMatrix(ref float dest)
|
||||
{
|
||||
fixed (float* s = _perspProj)
|
||||
fixed (float* d = &dest)
|
||||
{
|
||||
for (int i = 0; i < 16; i++)
|
||||
d[i] = s[i];
|
||||
}
|
||||
}
|
||||
|
||||
private static int SetTransformDetour(IntPtr dev, uint state, float* pMatrix)
|
||||
{
|
||||
if (pMatrix != null && state == D3DTS_PROJECTION)
|
||||
{
|
||||
bool isPerspective = Math.Abs(pMatrix[11]) > 0.01f;
|
||||
if (isPerspective)
|
||||
{
|
||||
for (int i = 0; i < 16; i++)
|
||||
_perspProj[i] = pMatrix[i];
|
||||
_hasProj = true;
|
||||
}
|
||||
}
|
||||
return _originalSetTransform!(dev, state, pMatrix);
|
||||
}
|
||||
|
||||
public static void CaptureFrame(IntPtr pDevice)
|
||||
{
|
||||
if (pDevice == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
if (!_hookInstalled)
|
||||
InstallHook(pDevice);
|
||||
|
||||
// Read viewport
|
||||
if (!_viewportCached)
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
_getViewport = Marshal.GetDelegateForFunctionPointer<GetViewportD>(
|
||||
Marshal.ReadIntPtr(vtable, DeviceVTableIndex.GetViewport * IntPtr.Size));
|
||||
_viewportCached = true;
|
||||
}
|
||||
|
||||
int* vp = stackalloc int[6];
|
||||
if (_getViewport!(pDevice, vp) >= 0 && vp[2] > 0 && vp[3] > 0)
|
||||
{
|
||||
_vpWidth = (uint)vp[2];
|
||||
_vpHeight = (uint)vp[3];
|
||||
_hasViewport = true;
|
||||
}
|
||||
|
||||
if (_hasProj)
|
||||
BuildViewProjFromCamera();
|
||||
|
||||
_framesSinceLog++;
|
||||
if (_framesSinceLog >= 3000)
|
||||
{
|
||||
_framesSinceLog = 0;
|
||||
RynthLog.D3D9($"GameMatrixCapture: valid={_hasValidViewProj} vp={_vpWidth}x{_vpHeight}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void BuildViewProjFromCamera()
|
||||
{
|
||||
if (!SmartBoxLocator.TryGetSmartBox(out IntPtr smartBox, out _, out _))
|
||||
return;
|
||||
|
||||
IntPtr camFrame = smartBox + CameraFrameOffset;
|
||||
if (!SmartBoxLocator.IsMemoryReadable(camFrame + CamPosOffset, 12))
|
||||
return;
|
||||
|
||||
// Read 3x3 rotation matrix
|
||||
float m11 = ReadFloat(camFrame + CamRotOffset + 0);
|
||||
float m12 = ReadFloat(camFrame + CamRotOffset + 4);
|
||||
float m13 = ReadFloat(camFrame + CamRotOffset + 8);
|
||||
float m21 = ReadFloat(camFrame + CamRotOffset + 12);
|
||||
float m22 = ReadFloat(camFrame + CamRotOffset + 16);
|
||||
float m23 = ReadFloat(camFrame + CamRotOffset + 20);
|
||||
float m31 = ReadFloat(camFrame + CamRotOffset + 24);
|
||||
float m32 = ReadFloat(camFrame + CamRotOffset + 28);
|
||||
float m33 = ReadFloat(camFrame + CamRotOffset + 32);
|
||||
|
||||
// Read position (AC physics: x=EW, y=NS, z=height)
|
||||
float cx = ReadFloat(camFrame + CamPosOffset + 0);
|
||||
float cy = ReadFloat(camFrame + CamPosOffset + 4);
|
||||
float cz = ReadFloat(camFrame + CamPosOffset + 8);
|
||||
|
||||
if (cx == 0f && cy == 0f && cz == 0f)
|
||||
return;
|
||||
|
||||
// View matrix rotation block (D3D Y-up, with AC Y/Z swap).
|
||||
// AC camera rows: row1=Right, row2=Forward, row3=Up
|
||||
// After Y/Z component swap → D3D basis vectors as columns:
|
||||
// col0 = Right_d3d = (m11, m13, m12)
|
||||
// col1 = Up_d3d = (m31, m33, m32)
|
||||
// col2 = Forward_d3d = (m21, m23, m22)
|
||||
_viewMatrix[0] = m11; _viewMatrix[1] = m31; _viewMatrix[2] = m21; _viewMatrix[3] = 0;
|
||||
_viewMatrix[4] = m13; _viewMatrix[5] = m33; _viewMatrix[6] = m23; _viewMatrix[7] = 0;
|
||||
_viewMatrix[8] = m12; _viewMatrix[9] = m32; _viewMatrix[10] = m22; _viewMatrix[11] = 0;
|
||||
|
||||
// Translation = -CamPos_D3D * R_view
|
||||
// CamPos_D3D = (cx, cz, cy) after Y/Z swap
|
||||
float px = cx; // EW
|
||||
float py = cz; // height (D3D Y)
|
||||
float pz = cy; // NS (D3D Z)
|
||||
|
||||
_viewMatrix[12] = -(px * _viewMatrix[0] + py * _viewMatrix[4] + pz * _viewMatrix[8]);
|
||||
_viewMatrix[13] = -(px * _viewMatrix[1] + py * _viewMatrix[5] + pz * _viewMatrix[9]);
|
||||
_viewMatrix[14] = -(px * _viewMatrix[2] + py * _viewMatrix[6] + pz * _viewMatrix[10]);
|
||||
_viewMatrix[15] = 1;
|
||||
|
||||
// ViewProj = View * Projection
|
||||
fixed (float* v = _viewMatrix)
|
||||
fixed (float* p = _perspProj)
|
||||
fixed (float* r = _viewProj)
|
||||
{
|
||||
for (int row = 0; row < 4; row++)
|
||||
for (int col = 0; col < 4; col++)
|
||||
r[row * 4 + col] =
|
||||
v[row * 4 + 0] * p[0 * 4 + col] +
|
||||
v[row * 4 + 1] * p[1 * 4 + col] +
|
||||
v[row * 4 + 2] * p[2 * 4 + col] +
|
||||
v[row * 4 + 3] * p[3 * 4 + col];
|
||||
}
|
||||
|
||||
if (!_loggedFirstCapture)
|
||||
{
|
||||
_loggedFirstCapture = true;
|
||||
RynthLog.D3D9($"GameMatrixCapture: camera pos=({cx:F2},{cy:F2},{cz:F2}) [EW,NS,Z]");
|
||||
RynthLog.D3D9($"GameMatrixCapture: View row0=[{_viewMatrix[0]:F4}, {_viewMatrix[1]:F4}, {_viewMatrix[2]:F4}, {_viewMatrix[3]:F4}]");
|
||||
RynthLog.D3D9($"GameMatrixCapture: View row1=[{_viewMatrix[4]:F4}, {_viewMatrix[5]:F4}, {_viewMatrix[6]:F4}, {_viewMatrix[7]:F4}]");
|
||||
RynthLog.D3D9($"GameMatrixCapture: View row2=[{_viewMatrix[8]:F4}, {_viewMatrix[9]:F4}, {_viewMatrix[10]:F4}, {_viewMatrix[11]:F4}]");
|
||||
RynthLog.D3D9($"GameMatrixCapture: View row3=[{_viewMatrix[12]:F4}, {_viewMatrix[13]:F4}, {_viewMatrix[14]:F4}, {_viewMatrix[15]:F4}]");
|
||||
RynthLog.D3D9($"GameMatrixCapture: viewport={_vpWidth}x{_vpHeight}");
|
||||
}
|
||||
|
||||
_hasValidViewProj = true;
|
||||
}
|
||||
|
||||
private static float ReadFloat(IntPtr address)
|
||||
{
|
||||
int bits = Marshal.ReadInt32(address);
|
||||
return BitConverter.Int32BitsToSingle(bits);
|
||||
}
|
||||
|
||||
public static bool WorldToScreen(float wx, float wy, float wz, out float sx, out float sy)
|
||||
{
|
||||
sx = 0f;
|
||||
sy = 0f;
|
||||
|
||||
if (!_hasValidViewProj || _vpWidth == 0 || _vpHeight == 0)
|
||||
return false;
|
||||
|
||||
float clipX = wx * _viewProj[0] + wy * _viewProj[4] + wz * _viewProj[8] + _viewProj[12];
|
||||
float clipY = wx * _viewProj[1] + wy * _viewProj[5] + wz * _viewProj[9] + _viewProj[13];
|
||||
float clipW = wx * _viewProj[3] + wy * _viewProj[7] + wz * _viewProj[11] + _viewProj[15];
|
||||
|
||||
if (clipW <= 0.001f)
|
||||
return false;
|
||||
|
||||
float ndcX = clipX / clipW;
|
||||
float ndcY = clipY / clipW;
|
||||
|
||||
sx = (ndcX + 1.0f) * 0.5f * _vpWidth;
|
||||
sy = (1.0f - ndcY) * 0.5f * _vpHeight;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static int WorldToScreenCallback(float wx, float wy, float wz, float* sx, float* sy)
|
||||
{
|
||||
bool result = WorldToScreen(wx, wy, wz, out float screenX, out float screenY);
|
||||
*sx = screenX;
|
||||
*sy = screenY;
|
||||
return result ? 1 : 0;
|
||||
}
|
||||
|
||||
public static int GetViewportSizeCallback(uint* width, uint* height)
|
||||
{
|
||||
if (!_hasViewport || _vpWidth == 0 || _vpHeight == 0)
|
||||
return 0;
|
||||
|
||||
*width = _vpWidth;
|
||||
*height = _vpHeight;
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static void InstallHook(IntPtr pDevice)
|
||||
{
|
||||
try
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
IntPtr setTransformAddr = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.SetTransform * IntPtr.Size);
|
||||
|
||||
_hookDelegate = new SetTransformD(SetTransformDetour);
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate);
|
||||
_originalSetTransform = Marshal.GetDelegateForFunctionPointer<SetTransformD>(MinHook.HookCreate(setTransformAddr, detourPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(setTransformAddr);
|
||||
_hookInstalled = true;
|
||||
|
||||
RynthLog.D3D9("GameMatrixCapture: SetTransform hook installed.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"GameMatrixCapture: SetTransform hook FAILED — {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
101
src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs
Normal file
101
src/RynthCore.Engine/D3D9/Nav3DRenderInjector.cs
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/Nav3DRenderInjector.cs
|
||||
// Hooks DrawIndexedPrimitive to inject nav marker rendering at the
|
||||
// 3D→UI boundary. When ZENABLE transitions from 1→0, renders markers
|
||||
// so they appear after the 3D world but before the game's UI pass.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Hooking;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static class Nav3DRenderInjector
|
||||
{
|
||||
private const uint D3DRS_ZENABLE = 7;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int DrawIndexedPrimitiveD(IntPtr dev, uint primitiveType,
|
||||
int baseVertexIndex, uint minVertexIndex, uint numVertices,
|
||||
uint startIndex, uint primCount);
|
||||
|
||||
private static DrawIndexedPrimitiveD? _originalDIP;
|
||||
private static DrawIndexedPrimitiveD? _hookDelegate;
|
||||
private static bool _hookInstalled;
|
||||
private static bool _inRender;
|
||||
|
||||
// Per-frame transition detection
|
||||
private static uint _lastZEnable;
|
||||
private static bool _markersRenderedThisFrame;
|
||||
private static bool _seen3D;
|
||||
|
||||
public static bool RenderedThisFrame => _markersRenderedThisFrame;
|
||||
|
||||
public static void ResetFrame()
|
||||
{
|
||||
_markersRenderedThisFrame = false;
|
||||
_seen3D = false;
|
||||
_lastZEnable = 0;
|
||||
}
|
||||
|
||||
public static void Install(IntPtr pDevice)
|
||||
{
|
||||
if (_hookInstalled) return;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
IntPtr addr = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.DrawIndexedPrimitive * IntPtr.Size);
|
||||
|
||||
_hookDelegate = new DrawIndexedPrimitiveD(Detour);
|
||||
IntPtr hookPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate);
|
||||
_originalDIP = Marshal.GetDelegateForFunctionPointer<DrawIndexedPrimitiveD>(
|
||||
MinHook.HookCreate(addr, hookPtr));
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(addr);
|
||||
_hookInstalled = true;
|
||||
|
||||
RynthLog.D3D9("Nav3DRenderInjector: DrawIndexedPrimitive hook installed.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"Nav3DRenderInjector: Hook install FAILED — {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static int Detour(IntPtr dev, uint primitiveType,
|
||||
int baseVertexIndex, uint minVertexIndex, uint numVertices,
|
||||
uint startIndex, uint primCount)
|
||||
{
|
||||
if (_inRender)
|
||||
return _originalDIP!(dev, primitiveType, baseVertexIndex,
|
||||
minVertexIndex, numVertices, startIndex, primCount);
|
||||
|
||||
ImGuiBackend.DX9Backend.DeviceGetRenderState(dev, D3DRS_ZENABLE, out uint zEnable);
|
||||
|
||||
if (zEnable != 0)
|
||||
_seen3D = true;
|
||||
|
||||
// Detect 3D→UI transition: ZENABLE goes from 1→0 after 3D draws
|
||||
if (!_markersRenderedThisFrame && _seen3D && _lastZEnable != 0 && zEnable == 0)
|
||||
{
|
||||
_markersRenderedThisFrame = true;
|
||||
_inRender = true;
|
||||
try
|
||||
{
|
||||
ImGuiBackend.DX9Backend.RenderNav3D(dev);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
_inRender = false;
|
||||
}
|
||||
|
||||
_lastZEnable = zEnable;
|
||||
|
||||
return _originalDIP!(dev, primitiveType, baseVertexIndex,
|
||||
minVertexIndex, numVertices, startIndex, primCount);
|
||||
}
|
||||
}
|
||||
84
src/RynthCore.Engine/D3D9/Nav3DRenderer.cs
Normal file
84
src/RynthCore.Engine/D3D9/Nav3DRenderer.cs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/Nav3DRenderer.cs
|
||||
// Data store for 3D navigation markers. Plugins submit geometry each frame
|
||||
// via AddRing/AddLine; DX9Backend.RenderNav3D reads it during EndScene.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static class Nav3DRenderer
|
||||
{
|
||||
private const int MaxRings = 128;
|
||||
private const int MaxLines = 128;
|
||||
|
||||
// Ring: center(x,y,z) + radius + thickness + color
|
||||
private static readonly float[] _ringX = new float[MaxRings];
|
||||
private static readonly float[] _ringY = new float[MaxRings];
|
||||
private static readonly float[] _ringZ = new float[MaxRings];
|
||||
private static readonly float[] _ringRadius = new float[MaxRings];
|
||||
private static readonly float[] _ringThick = new float[MaxRings];
|
||||
private static readonly uint[] _ringColor = new uint[MaxRings];
|
||||
private static int _ringCount;
|
||||
|
||||
// Line: endpoints + thickness + color
|
||||
private static readonly float[] _lineX1 = new float[MaxLines];
|
||||
private static readonly float[] _lineY1 = new float[MaxLines];
|
||||
private static readonly float[] _lineZ1 = new float[MaxLines];
|
||||
private static readonly float[] _lineX2 = new float[MaxLines];
|
||||
private static readonly float[] _lineY2 = new float[MaxLines];
|
||||
private static readonly float[] _lineZ2 = new float[MaxLines];
|
||||
private static readonly float[] _lineThick = new float[MaxLines];
|
||||
private static readonly uint[] _lineColor = new uint[MaxLines];
|
||||
private static int _lineCount;
|
||||
|
||||
public static int RingCount => _ringCount;
|
||||
public static int LineCount => _lineCount;
|
||||
|
||||
public static void ClearFrame()
|
||||
{
|
||||
_ringCount = 0;
|
||||
_lineCount = 0;
|
||||
}
|
||||
|
||||
public static void AddRing(float wx, float wy, float wz, float radius, float thickness, uint colorArgb)
|
||||
{
|
||||
if (_ringCount >= MaxRings) return;
|
||||
int i = _ringCount++;
|
||||
_ringX[i] = wx; _ringY[i] = wy; _ringZ[i] = wz;
|
||||
_ringRadius[i] = radius;
|
||||
_ringThick[i] = thickness;
|
||||
_ringColor[i] = colorArgb;
|
||||
}
|
||||
|
||||
public static void AddLine(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb)
|
||||
{
|
||||
if (_lineCount >= MaxLines) return;
|
||||
int i = _lineCount++;
|
||||
_lineX1[i] = x1; _lineY1[i] = y1; _lineZ1[i] = z1;
|
||||
_lineX2[i] = x2; _lineY2[i] = y2; _lineZ2[i] = z2;
|
||||
_lineThick[i] = thickness;
|
||||
_lineColor[i] = colorArgb;
|
||||
}
|
||||
|
||||
public static void GetRing(int i, out float x, out float y, out float z,
|
||||
out float radius, out float thickness, out uint color)
|
||||
{
|
||||
x = _ringX[i]; y = _ringY[i]; z = _ringZ[i];
|
||||
radius = _ringRadius[i]; thickness = _ringThick[i]; color = _ringColor[i];
|
||||
}
|
||||
|
||||
public static void GetLine(int i, out float x1, out float y1, out float z1,
|
||||
out float x2, out float y2, out float z2, out float thickness, out uint color)
|
||||
{
|
||||
x1 = _lineX1[i]; y1 = _lineY1[i]; z1 = _lineZ1[i];
|
||||
x2 = _lineX2[i]; y2 = _lineY2[i]; z2 = _lineZ2[i];
|
||||
thickness = _lineThick[i]; color = _lineColor[i];
|
||||
}
|
||||
|
||||
// C ABI callbacks for plugin contract
|
||||
public static void Nav3DClearCallback() => ClearFrame();
|
||||
public static void Nav3DAddRingCallback(float wx, float wy, float wz, float radius, float thickness, uint color)
|
||||
=> AddRing(wx, wy, wz, radius, thickness, color);
|
||||
public static void Nav3DAddLineCallback(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint color)
|
||||
=> AddLine(x1, y1, z1, x2, y2, z2, thickness, color);
|
||||
}
|
||||
485
src/RynthCore.Engine/D3D9/OverlayTextureRenderer.cs
Normal file
485
src/RynthCore.Engine/D3D9/OverlayTextureRenderer.cs
Normal file
|
|
@ -0,0 +1,485 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - D3D9/OverlayTextureRenderer.cs
|
||||
// Consumes BGRA frames from OverlayFrameBuffer and composites them onto
|
||||
// the D3D9 back buffer as a fullscreen alpha-blended quad.
|
||||
//
|
||||
// Called at the end of OnEndScene, after ImGui has already rendered.
|
||||
// Uses D3DFVF_XYZRHW | D3DFVF_TEX1 (pre-transformed vertices) so no
|
||||
// projection matrix setup is needed.
|
||||
//
|
||||
// Pixel format: Avalonia Bgra8888 == D3DFMT_A8R8G8B8 in memory — no swizzle.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Engine.UI;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static unsafe class OverlayTextureRenderer
|
||||
{
|
||||
private static readonly Guid IID_IDirect3DDevice9Ex = new("B18B10CE-2649-405A-870F-95F777D4313A");
|
||||
// ─── D3D9 constants ───────────────────────────────────────────────────
|
||||
private const uint D3DPT_TRIANGLESTRIP = 5;
|
||||
private const uint D3DUSAGE_RENDERTARGET = 0x00000001;
|
||||
private const uint D3DFMT_A8R8G8B8 = 21;
|
||||
private const uint D3DPOOL_DEFAULT = 0;
|
||||
private const uint D3DPOOL_MANAGED = 1;
|
||||
|
||||
private const uint D3DRS_ALPHABLENDENABLE = 27;
|
||||
private const uint D3DRS_SRCBLEND = 19;
|
||||
private const uint D3DRS_DESTBLEND = 20;
|
||||
private const uint D3DRS_ZENABLE = 7;
|
||||
private const uint D3DRS_CULLMODE = 22;
|
||||
private const uint D3DRS_LIGHTING = 137;
|
||||
private const uint D3DRS_COLORWRITEENABLE = 168;
|
||||
|
||||
private const uint D3DBLEND_SRCALPHA = 5;
|
||||
private const uint D3DBLEND_INVSRCALPHA = 6;
|
||||
private const uint D3DCULL_NONE = 1;
|
||||
|
||||
private const uint D3DTSS_COLOROP = 1;
|
||||
private const uint D3DTSS_COLORARG1 = 2;
|
||||
private const uint D3DTSS_COLORARG2 = 3;
|
||||
private const uint D3DTSS_ALPHAOP = 4;
|
||||
private const uint D3DTSS_ALPHAARG1 = 5;
|
||||
private const uint D3DTSS_ALPHAARG2 = 6;
|
||||
|
||||
private const uint D3DTOP_MODULATE = 4;
|
||||
private const uint D3DTA_TEXTURE = 2;
|
||||
private const uint D3DTA_DIFFUSE = 0;
|
||||
|
||||
private const uint D3DSAMP_MINFILTER = 5;
|
||||
private const uint D3DSAMP_MAGFILTER = 6;
|
||||
private const uint D3DTEXF_LINEAR = 2;
|
||||
private const uint D3DTEXF_POINT = 1;
|
||||
|
||||
// D3DFVF_XYZRHW | D3DFVF_TEX1
|
||||
private const uint FVF = 0x004 | 0x100;
|
||||
|
||||
// ─── Vertex (pre-transformed screen-space + UV) ────────────────────────
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct QuadVertex
|
||||
{
|
||||
public float X, Y, Z, RHW;
|
||||
public float U, V;
|
||||
}
|
||||
|
||||
// ─── D3D9 struct ──────────────────────────────────────────────────────
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct D3DVIEWPORT9
|
||||
{
|
||||
public uint X, Y, Width, Height;
|
||||
public float MinZ, MaxZ;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct D3DLOCKED_RECT
|
||||
{
|
||||
public int Pitch;
|
||||
public IntPtr pBits;
|
||||
}
|
||||
|
||||
// ─── Vtable delegates ─────────────────────────────────────────────────
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int CreateTextureD(IntPtr dev, uint w, uint h, uint levels, uint usage, uint fmt, uint pool, out IntPtr ppTex, IntPtr pShared);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureD(IntPtr dev, uint stage, IntPtr pTex);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureStageStateD(IntPtr dev, uint stage, uint type, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetSamplerStateD(IntPtr dev, uint sampler, uint type, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetFVFD(IntPtr dev, uint fvf);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetRenderStateD(IntPtr dev, uint state, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetRenderStateD(IntPtr dev, uint state, out uint pValue);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetVertexShaderD(IntPtr dev, IntPtr pShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetVertexShaderD(IntPtr dev, out IntPtr ppShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetPixelShaderD(IntPtr dev, IntPtr pShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetPixelShaderD(IntPtr dev, out IntPtr ppShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetViewportD(IntPtr dev, D3DVIEWPORT9* vp);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int DrawPrimitiveUPD(IntPtr dev, uint primType, uint primCount, IntPtr pVtxData, uint vtxStride);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate uint ReleaseD(IntPtr pObj);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int QueryInterfaceD(IntPtr pObj, Guid* riid, out IntPtr ppvObject);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int TexLockRectD(IntPtr pTex, uint level, D3DLOCKED_RECT* pLocked, IntPtr pRect, uint flags);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int TexUnlockRectD(IntPtr pTex, uint level);
|
||||
|
||||
// ─── Cached delegates ─────────────────────────────────────────────────
|
||||
private static CreateTextureD? _createTexture;
|
||||
private static SetTextureD? _setTexture;
|
||||
private static SetTextureStageStateD? _setTexStageState;
|
||||
private static SetSamplerStateD? _setSamplerState;
|
||||
private static SetFVFD? _setFVF;
|
||||
private static SetRenderStateD? _setRenderState;
|
||||
private static GetRenderStateD? _getRenderState;
|
||||
private static SetVertexShaderD? _setVertexShader;
|
||||
private static GetVertexShaderD? _getVertexShader;
|
||||
private static SetPixelShaderD? _setPixelShader;
|
||||
private static GetPixelShaderD? _getPixelShader;
|
||||
private static GetViewportD? _getViewport;
|
||||
private static DrawPrimitiveUPD? _drawPrimitiveUP;
|
||||
private static QueryInterfaceD? _queryInterface;
|
||||
|
||||
// ─── State ────────────────────────────────────────────────────────────
|
||||
private static IntPtr _texture;
|
||||
private static IntPtr _sharedTextureHandle;
|
||||
private static int _texW;
|
||||
private static int _texH;
|
||||
private static bool _delegatesCached;
|
||||
private static bool _sharedInteropProbed;
|
||||
private static bool _sharedInteropSupported;
|
||||
|
||||
// ─── Public entry point ───────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Called from EndScene (D3D9 render thread) after ImGui has rendered.
|
||||
/// Uploads any pending Avalonia frame to the texture and draws it.
|
||||
/// </summary>
|
||||
public static void Render(IntPtr pDevice)
|
||||
{
|
||||
if (pDevice == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
if (!_delegatesCached)
|
||||
{
|
||||
CacheDelegates(pDevice);
|
||||
_delegatesCached = true;
|
||||
}
|
||||
|
||||
// Learn as early as possible whether this game device can consume shared
|
||||
// textures. That lets the producer stay on software submissions only on
|
||||
// unsupported clients instead of discovering it mid-session.
|
||||
if (OverlaySurfaceBridge.ActiveSupportsGpuInterop && !_sharedInteropProbed)
|
||||
EnsureSharedInteropSupport(pDevice);
|
||||
|
||||
// Upload new frame if one is available
|
||||
if (OverlaySurfaceBridge.TryConsume(out OverlaySurfaceFrame? frame) && frame != null)
|
||||
{
|
||||
switch (frame.Kind)
|
||||
{
|
||||
case OverlaySurfaceKind.SoftwareBgra32 when frame.SoftwarePixels != null:
|
||||
UploadFrame(pDevice, frame.SoftwarePixels, frame.Width, frame.Height);
|
||||
break;
|
||||
case OverlaySurfaceKind.AngleSharedTexture when frame.SharedTexture != null:
|
||||
if (!TryUseSharedTexture(pDevice, "ANGLE", frame.SharedTexture.Value))
|
||||
LogSharedTextureStub("ANGLE", frame.SharedTexture);
|
||||
break;
|
||||
case OverlaySurfaceKind.DxgiSharedTexture when frame.SharedTexture != null:
|
||||
if (!TryUseSharedTexture(pDevice, "DXGI", frame.SharedTexture.Value))
|
||||
LogSharedTextureStub("DXGI", frame.SharedTexture);
|
||||
break;
|
||||
case OverlaySurfaceKind.D3D9SharedTexture when frame.SharedTexture != null:
|
||||
if (!TryUseSharedTexture(pDevice, "D3D9Ex", frame.SharedTexture.Value))
|
||||
LogSharedTextureStub("D3D9Ex", frame.SharedTexture);
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (_texture == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
DrawQuad(pDevice);
|
||||
}
|
||||
|
||||
private static void LogSharedTextureStub(string label, OverlaySharedTextureDescriptor? descriptor)
|
||||
{
|
||||
if (descriptor == null)
|
||||
{
|
||||
RynthLog.D3D9($"OverlayTextureRenderer: {label} shared texture frame arrived without a descriptor.");
|
||||
return;
|
||||
}
|
||||
|
||||
RynthLog.D3D9(
|
||||
$"OverlayTextureRenderer: {label} shared texture interop is not implemented yet " +
|
||||
$"(handle=0x{descriptor.Value.SharedHandle:X8}, size={descriptor.Value.Width}x{descriptor.Value.Height}, adapterLuid=0x{descriptor.Value.AdapterLuid:X}).");
|
||||
}
|
||||
|
||||
public static void Shutdown()
|
||||
{
|
||||
ReleaseTexture();
|
||||
_delegatesCached = false;
|
||||
_sharedInteropProbed = false;
|
||||
_sharedInteropSupported = false;
|
||||
}
|
||||
|
||||
// ─── Upload ───────────────────────────────────────────────────────────
|
||||
|
||||
private static void UploadFrame(IntPtr pDevice, byte[] pixels, int w, int h)
|
||||
{
|
||||
// Recreate texture if dimensions changed
|
||||
if (_texture == IntPtr.Zero || w != _texW || h != _texH || _sharedTextureHandle != IntPtr.Zero)
|
||||
{
|
||||
ReleaseTexture();
|
||||
|
||||
int hr = _createTexture!(pDevice, (uint)w, (uint)h, 1, 0,
|
||||
D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, out _texture, IntPtr.Zero);
|
||||
|
||||
if (hr < 0 || _texture == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9($"OverlayTextureRenderer: CreateTexture({w}x{h}) failed HRESULT=0x{hr:X8}");
|
||||
return;
|
||||
}
|
||||
|
||||
_texW = w;
|
||||
_texH = h;
|
||||
RynthLog.D3D9($"OverlayTextureRenderer: Created {w}x{h} overlay texture.");
|
||||
}
|
||||
|
||||
// Lock → copy → unlock
|
||||
var lockRect = GetTexMethod<TexLockRectD>(_texture, TextureVTableIndex.LockRect);
|
||||
var unlockRect = GetTexMethod<TexUnlockRectD>(_texture, TextureVTableIndex.UnlockRect);
|
||||
|
||||
D3DLOCKED_RECT locked;
|
||||
if (lockRect(_texture, 0, &locked, IntPtr.Zero, 0) < 0)
|
||||
return;
|
||||
|
||||
// Avalonia Bgra8888 == D3DFMT_A8R8G8B8 in memory — direct copy, no swizzle
|
||||
int srcStride = w * 4;
|
||||
for (int row = 0; row < h; row++)
|
||||
{
|
||||
IntPtr dst = locked.pBits + row * locked.Pitch;
|
||||
fixed (byte* src = pixels)
|
||||
Buffer.MemoryCopy(src + row * srcStride, (void*)dst, srcStride, srcStride);
|
||||
}
|
||||
|
||||
unlockRect(_texture, 0);
|
||||
}
|
||||
|
||||
private static bool TryUseSharedTexture(IntPtr pDevice, string label, OverlaySharedTextureDescriptor descriptor)
|
||||
{
|
||||
if (descriptor.SharedHandle == IntPtr.Zero)
|
||||
return false;
|
||||
|
||||
if (!EnsureSharedInteropSupport(pDevice))
|
||||
return false;
|
||||
|
||||
if (_texture != IntPtr.Zero &&
|
||||
_sharedTextureHandle == descriptor.SharedHandle &&
|
||||
_texW == descriptor.Width &&
|
||||
_texH == descriptor.Height)
|
||||
{
|
||||
OverlaySurfaceBridge.NotifySharedTextureOpened(descriptor.SharedHandle);
|
||||
return true;
|
||||
}
|
||||
|
||||
IntPtr openedTexture = IntPtr.Zero;
|
||||
IntPtr sharedHandle = descriptor.SharedHandle;
|
||||
uint usage = descriptor.Usage != 0 ? (uint)descriptor.Usage : D3DUSAGE_RENDERTARGET;
|
||||
uint format = descriptor.PixelFormat != 0 ? (uint)descriptor.PixelFormat : D3DFMT_A8R8G8B8;
|
||||
int hr = _createTexture!(
|
||||
pDevice,
|
||||
(uint)descriptor.Width,
|
||||
(uint)descriptor.Height,
|
||||
1,
|
||||
usage,
|
||||
format,
|
||||
D3DPOOL_DEFAULT,
|
||||
out openedTexture,
|
||||
new IntPtr(&sharedHandle));
|
||||
|
||||
if (hr < 0 || openedTexture == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9(
|
||||
$"OverlayTextureRenderer: Failed to open {label} shared texture handle 0x{descriptor.SharedHandle:X8}, HRESULT=0x{hr:X8}.");
|
||||
return false;
|
||||
}
|
||||
|
||||
ReleaseTexture();
|
||||
_texture = openedTexture;
|
||||
_sharedTextureHandle = descriptor.SharedHandle;
|
||||
_texW = descriptor.Width;
|
||||
_texH = descriptor.Height;
|
||||
OverlaySurfaceBridge.NotifySharedTextureOpened(descriptor.SharedHandle);
|
||||
RynthLog.D3D9(
|
||||
$"OverlayTextureRenderer: Opened {label} shared texture handle 0x{descriptor.SharedHandle:X8} ({descriptor.Width}x{descriptor.Height}).");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool EnsureSharedInteropSupport(IntPtr pDevice)
|
||||
{
|
||||
if (_sharedInteropProbed)
|
||||
return _sharedInteropSupported;
|
||||
|
||||
_sharedInteropProbed = true;
|
||||
|
||||
if (_queryInterface == null)
|
||||
{
|
||||
RynthLog.D3D9("OverlayTextureRenderer: Shared-texture probe unavailable because QueryInterface is not cached.");
|
||||
OverlaySurfaceBridge.NotifySharedTextureUnavailable();
|
||||
return false;
|
||||
}
|
||||
|
||||
IntPtr exDevice = IntPtr.Zero;
|
||||
Guid iid = IID_IDirect3DDevice9Ex;
|
||||
int hr = _queryInterface(pDevice, &iid, out exDevice);
|
||||
if (hr >= 0 && exDevice != IntPtr.Zero)
|
||||
{
|
||||
_sharedInteropSupported = true;
|
||||
RynthLog.D3D9("OverlayTextureRenderer: D3D9Ex shared-texture consumption is available on the active game device.");
|
||||
ReleaseComObject(exDevice);
|
||||
return true;
|
||||
}
|
||||
|
||||
RynthLog.D3D9("OverlayTextureRenderer: D3D9Ex shared-texture consumption is unavailable on the active game device; software fallback will remain active.");
|
||||
OverlaySurfaceBridge.NotifySharedTextureUnavailable();
|
||||
return false;
|
||||
}
|
||||
|
||||
// ─── Draw ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void DrawQuad(IntPtr pDevice)
|
||||
{
|
||||
// Get current viewport to size the quad
|
||||
D3DVIEWPORT9 vp;
|
||||
if (_getViewport!(pDevice, &vp) < 0)
|
||||
return;
|
||||
|
||||
float W = vp.Width;
|
||||
float H = vp.Height;
|
||||
|
||||
// Tell the Avalonia thread what the current viewport size is so it can
|
||||
// keep the canvas sized correctly (prevents stretch/scale artifacts).
|
||||
int viewportWidth = (int)W;
|
||||
int viewportHeight = (int)H;
|
||||
bool viewportChanged =
|
||||
AvaloniaOverlay.ViewportWidth != viewportWidth ||
|
||||
AvaloniaOverlay.ViewportHeight != viewportHeight;
|
||||
AvaloniaOverlay.ViewportWidth = viewportWidth;
|
||||
AvaloniaOverlay.ViewportHeight = viewportHeight;
|
||||
if (viewportChanged)
|
||||
AvaloniaOverlay.NotifyGameSurfaceMetricsChanged();
|
||||
|
||||
// Save render states we will change
|
||||
_getRenderState!(pDevice, D3DRS_ALPHABLENDENABLE, out uint savedAlpha);
|
||||
_getRenderState!(pDevice, D3DRS_SRCBLEND, out uint savedSrcBlend);
|
||||
_getRenderState!(pDevice, D3DRS_DESTBLEND, out uint savedDstBlend);
|
||||
_getRenderState!(pDevice, D3DRS_ZENABLE, out uint savedZ);
|
||||
_getRenderState!(pDevice, D3DRS_CULLMODE, out uint savedCull);
|
||||
_getRenderState!(pDevice, D3DRS_LIGHTING, out uint savedLighting);
|
||||
_getRenderState!(pDevice, D3DRS_COLORWRITEENABLE, out uint savedColorWrite);
|
||||
_getVertexShader!(pDevice, out IntPtr savedVS);
|
||||
_getPixelShader!(pDevice, out IntPtr savedPS);
|
||||
|
||||
try
|
||||
{
|
||||
// Set up fixed-function alpha-blended state
|
||||
_setRenderState!(pDevice, D3DRS_ALPHABLENDENABLE, 1);
|
||||
_setRenderState!(pDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
|
||||
_setRenderState!(pDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
|
||||
_setRenderState!(pDevice, D3DRS_ZENABLE, 0);
|
||||
_setRenderState!(pDevice, D3DRS_CULLMODE, D3DCULL_NONE);
|
||||
_setRenderState!(pDevice, D3DRS_LIGHTING, 0);
|
||||
_setRenderState!(pDevice, D3DRS_COLORWRITEENABLE, 0xF);
|
||||
|
||||
_setVertexShader!(pDevice, IntPtr.Zero);
|
||||
_setPixelShader!(pDevice, IntPtr.Zero);
|
||||
|
||||
_setFVF!(pDevice, FVF);
|
||||
_setTexture!(pDevice, 0, _texture);
|
||||
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_COLOROP, D3DTOP_MODULATE);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
|
||||
_setSamplerState!(pDevice, 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
|
||||
_setSamplerState!(pDevice, 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
|
||||
|
||||
QuadVertex* verts = stackalloc QuadVertex[4];
|
||||
verts[0] = new QuadVertex { X = 0, Y = 0, Z = 0, RHW = 1, U = 0, V = 0 };
|
||||
verts[1] = new QuadVertex { X = W, Y = 0, Z = 0, RHW = 1, U = 1, V = 0 };
|
||||
verts[2] = new QuadVertex { X = 0, Y = H, Z = 0, RHW = 1, U = 0, V = 1 };
|
||||
verts[3] = new QuadVertex { X = W, Y = H, Z = 0, RHW = 1, U = 1, V = 1 };
|
||||
|
||||
_drawPrimitiveUP!(pDevice, D3DPT_TRIANGLESTRIP, 2,
|
||||
new IntPtr(verts), (uint)sizeof(QuadVertex));
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Restore changed state
|
||||
_setRenderState!(pDevice, D3DRS_ALPHABLENDENABLE, savedAlpha);
|
||||
_setRenderState!(pDevice, D3DRS_SRCBLEND, savedSrcBlend);
|
||||
_setRenderState!(pDevice, D3DRS_DESTBLEND, savedDstBlend);
|
||||
_setRenderState!(pDevice, D3DRS_ZENABLE, savedZ);
|
||||
_setRenderState!(pDevice, D3DRS_CULLMODE, savedCull);
|
||||
_setRenderState!(pDevice, D3DRS_LIGHTING, savedLighting);
|
||||
_setRenderState!(pDevice, D3DRS_COLORWRITEENABLE, savedColorWrite);
|
||||
_setVertexShader!(pDevice, savedVS);
|
||||
_setPixelShader!(pDevice, savedPS);
|
||||
_setTexture!(pDevice, 0, IntPtr.Zero);
|
||||
|
||||
if (savedVS != IntPtr.Zero) ReleaseComObject(savedVS);
|
||||
if (savedPS != IntPtr.Zero) ReleaseComObject(savedPS);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void ReleaseTexture()
|
||||
{
|
||||
if (_texture == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
var release = GetTexMethod<ReleaseD>(_texture, TextureVTableIndex.Release);
|
||||
release(_texture);
|
||||
_texture = IntPtr.Zero;
|
||||
_sharedTextureHandle = IntPtr.Zero;
|
||||
_texW = 0;
|
||||
_texH = 0;
|
||||
}
|
||||
|
||||
private static void ReleaseComObject(IntPtr pObj)
|
||||
{
|
||||
if (pObj == IntPtr.Zero) return;
|
||||
IntPtr vtbl = Marshal.ReadIntPtr(pObj);
|
||||
var rel = Marshal.GetDelegateForFunctionPointer<ReleaseD>(
|
||||
Marshal.ReadIntPtr(vtbl, 2 * IntPtr.Size));
|
||||
rel(pObj);
|
||||
}
|
||||
|
||||
private static void CacheDelegates(IntPtr pDevice)
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
_createTexture = Get<CreateTextureD>(vtable, DeviceVTableIndex.CreateTexture);
|
||||
_setTexture = Get<SetTextureD>(vtable, DeviceVTableIndex.SetTexture);
|
||||
_setTexStageState = Get<SetTextureStageStateD>(vtable, DeviceVTableIndex.SetTextureStageState);
|
||||
_setSamplerState = Get<SetSamplerStateD>(vtable, DeviceVTableIndex.SetSamplerState);
|
||||
_setFVF = Get<SetFVFD>(vtable, DeviceVTableIndex.SetFVF);
|
||||
_setRenderState = Get<SetRenderStateD>(vtable, DeviceVTableIndex.SetRenderState);
|
||||
_getRenderState = Get<GetRenderStateD>(vtable, DeviceVTableIndex.GetRenderState);
|
||||
_setVertexShader = Get<SetVertexShaderD>(vtable, DeviceVTableIndex.SetVertexShader);
|
||||
_getVertexShader = Get<GetVertexShaderD>(vtable, DeviceVTableIndex.GetVertexShader);
|
||||
_setPixelShader = Get<SetPixelShaderD>(vtable, DeviceVTableIndex.SetPixelShader);
|
||||
_getPixelShader = Get<GetPixelShaderD>(vtable, DeviceVTableIndex.GetPixelShader);
|
||||
_getViewport = Get<GetViewportD>(vtable, DeviceVTableIndex.GetViewport);
|
||||
_drawPrimitiveUP = Get<DrawPrimitiveUPD>(vtable, DeviceVTableIndex.DrawPrimitiveUP);
|
||||
_queryInterface = Get<QueryInterfaceD>(vtable, 0);
|
||||
}
|
||||
|
||||
private static T Get<T>(IntPtr vtable, int index) where T : Delegate
|
||||
{
|
||||
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(addr);
|
||||
}
|
||||
|
||||
private static T GetTexMethod<T>(IntPtr pTex, int index) where T : Delegate
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pTex);
|
||||
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(addr);
|
||||
}
|
||||
}
|
||||
175
src/RynthCore.Engine/D3D9/TestRenderer.cs
Normal file
175
src/RynthCore.Engine/D3D9/TestRenderer.cs
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/TestRenderer.cs
|
||||
// Draws a small colored rectangle in the top-left corner of the game.
|
||||
// Pure D3D9 via vtable calls — no dependencies on any overlay framework.
|
||||
//
|
||||
// Uses pre-transformed vertices (D3DFVF_XYZRHW | D3DFVF_DIFFUSE) so no
|
||||
// world/view/projection matrices needed. The rectangle is screen-space.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static unsafe class TestRenderer
|
||||
{
|
||||
// ─── D3D9 constants ───────────────────────────────────────────────
|
||||
private const uint D3DFVF_XYZRHW = 0x0004;
|
||||
private const uint D3DFVF_DIFFUSE = 0x0040;
|
||||
private const uint D3DFVF_CUSTOM = D3DFVF_XYZRHW | D3DFVF_DIFFUSE;
|
||||
|
||||
private const uint D3DPT_TRIANGLESTRIP = 5;
|
||||
|
||||
// D3DRENDERSTATETYPE
|
||||
private const uint D3DRS_LIGHTING = 137;
|
||||
private const uint D3DRS_ALPHABLENDENABLE = 27;
|
||||
private const uint D3DRS_SRCBLEND = 19;
|
||||
private const uint D3DRS_DESTBLEND = 20;
|
||||
private const uint D3DRS_ZENABLE = 7;
|
||||
private const uint D3DRS_FOGENABLE = 28;
|
||||
|
||||
// D3DBLEND
|
||||
private const uint D3DBLEND_SRCALPHA = 5;
|
||||
private const uint D3DBLEND_INVSRCALPHA = 6;
|
||||
|
||||
// D3DTRANSFORMSTATETYPE
|
||||
private const uint D3DTS_WORLD = 256;
|
||||
private const uint D3DTS_VIEW = 2;
|
||||
private const uint D3DTS_PROJECTION = 3;
|
||||
|
||||
// ─── Vertex structure ─────────────────────────────────────────────
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct Vertex
|
||||
{
|
||||
public float X, Y, Z, RHW;
|
||||
public uint Color; // ARGB
|
||||
|
||||
public Vertex(float x, float y, uint color)
|
||||
{
|
||||
X = x; Y = y; Z = 0f; RHW = 1f;
|
||||
Color = color;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Device method delegates (COM/stdcall) ────────────────────────
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetRenderStateDelegate(IntPtr pDevice, uint state, uint value);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetRenderStateDelegate(IntPtr pDevice, uint state, out uint pValue);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureDelegate(IntPtr pDevice, uint stage, IntPtr pTexture);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetFVFDelegate(IntPtr pDevice, uint fvf);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int DrawPrimitiveUPDelegate(
|
||||
IntPtr pDevice, uint primitiveType, uint primitiveCount,
|
||||
IntPtr pVertexStreamZeroData, uint vertexStreamZeroStride);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetVertexShaderDelegate(IntPtr pDevice, IntPtr pShader);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetPixelShaderDelegate(IntPtr pDevice, IntPtr pShader);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureStageStateDelegate(IntPtr pDevice, uint stage, uint type, uint value);
|
||||
|
||||
// ─── Cached delegates (created once from vtable on first frame) ──
|
||||
private static SetRenderStateDelegate? _setRenderState;
|
||||
private static GetRenderStateDelegate? _getRenderState;
|
||||
private static SetTextureDelegate? _setTexture;
|
||||
private static SetFVFDelegate? _setFVF;
|
||||
private static DrawPrimitiveUPDelegate? _drawPrimitiveUP;
|
||||
private static SetVertexShaderDelegate? _setVertexShader;
|
||||
private static SetPixelShaderDelegate? _setPixelShader;
|
||||
private static SetTextureStageStateDelegate? _setTextureStageState;
|
||||
private static bool _delegatesCached;
|
||||
|
||||
// ─── Rectangle config ─────────────────────────────────────────────
|
||||
// Bright green semi-transparent rectangle, top-left corner
|
||||
private const float RectX = 10f;
|
||||
private const float RectY = 10f;
|
||||
private const float RectW = 120f;
|
||||
private const float RectH = 40f;
|
||||
private const uint RectColor = 0xCC00FF00; // ARGB: green, ~80% opaque
|
||||
|
||||
// ─── Public API ───────────────────────────────────────────────────
|
||||
|
||||
public static void Draw(IntPtr pDevice)
|
||||
{
|
||||
if (pDevice == IntPtr.Zero) return;
|
||||
|
||||
// Cache vtable delegates on first call
|
||||
if (!_delegatesCached)
|
||||
CacheDelegates(pDevice);
|
||||
|
||||
// Save render states we'll modify
|
||||
_getRenderState!(pDevice, D3DRS_LIGHTING, out uint oldLighting);
|
||||
_getRenderState(pDevice, D3DRS_ALPHABLENDENABLE, out uint oldAlphaBlend);
|
||||
_getRenderState(pDevice, D3DRS_SRCBLEND, out uint oldSrcBlend);
|
||||
_getRenderState(pDevice, D3DRS_DESTBLEND, out uint oldDestBlend);
|
||||
_getRenderState(pDevice, D3DRS_ZENABLE, out uint oldZEnable);
|
||||
_getRenderState(pDevice, D3DRS_FOGENABLE, out uint oldFogEnable);
|
||||
|
||||
// Set up for 2D overlay drawing
|
||||
_setRenderState!(pDevice, D3DRS_LIGHTING, 0); // no lighting
|
||||
_setRenderState(pDevice, D3DRS_ZENABLE, 0); // no depth test
|
||||
_setRenderState(pDevice, D3DRS_FOGENABLE, 0); // no fog
|
||||
_setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, 1); // alpha blend on
|
||||
_setRenderState(pDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
|
||||
_setRenderState(pDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
|
||||
|
||||
_setTexture!(pDevice, 0, IntPtr.Zero); // no texture
|
||||
_setVertexShader!(pDevice, IntPtr.Zero); // fixed function
|
||||
_setPixelShader!(pDevice, IntPtr.Zero); // fixed function
|
||||
_setFVF!(pDevice, D3DFVF_CUSTOM);
|
||||
|
||||
// Build quad (triangle strip: TL, TR, BL, BR)
|
||||
var verts = stackalloc Vertex[4];
|
||||
verts[0] = new Vertex(RectX, RectY, RectColor);
|
||||
verts[1] = new Vertex(RectX + RectW, RectY, RectColor);
|
||||
verts[2] = new Vertex(RectX, RectY + RectH, RectColor);
|
||||
verts[3] = new Vertex(RectX + RectW, RectY + RectH, RectColor);
|
||||
|
||||
_drawPrimitiveUP!(pDevice, D3DPT_TRIANGLESTRIP, 2, (IntPtr)verts, (uint)sizeof(Vertex));
|
||||
|
||||
// Restore saved render states
|
||||
_setRenderState(pDevice, D3DRS_LIGHTING, oldLighting);
|
||||
_setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, oldAlphaBlend);
|
||||
_setRenderState(pDevice, D3DRS_SRCBLEND, oldSrcBlend);
|
||||
_setRenderState(pDevice, D3DRS_DESTBLEND, oldDestBlend);
|
||||
_setRenderState(pDevice, D3DRS_ZENABLE, oldZEnable);
|
||||
_setRenderState(pDevice, D3DRS_FOGENABLE, oldFogEnable);
|
||||
}
|
||||
|
||||
// ─── Internals ────────────────────────────────────────────────────
|
||||
|
||||
private static void CacheDelegates(IntPtr pDevice)
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
|
||||
_setRenderState = GetMethod<SetRenderStateDelegate>(vtable, DeviceVTableIndex.SetRenderState);
|
||||
_getRenderState = GetMethod<GetRenderStateDelegate>(vtable, DeviceVTableIndex.GetRenderState);
|
||||
_setTexture = GetMethod<SetTextureDelegate>(vtable, DeviceVTableIndex.SetTexture);
|
||||
_setFVF = GetMethod<SetFVFDelegate>(vtable, DeviceVTableIndex.SetFVF);
|
||||
_drawPrimitiveUP = GetMethod<DrawPrimitiveUPDelegate>(vtable, DeviceVTableIndex.DrawPrimitiveUP);
|
||||
_setVertexShader = GetMethod<SetVertexShaderDelegate>(vtable, DeviceVTableIndex.SetVertexShader);
|
||||
_setPixelShader = GetMethod<SetPixelShaderDelegate>(vtable, DeviceVTableIndex.SetPixelShader);
|
||||
_setTextureStageState = GetMethod<SetTextureStageStateDelegate>(vtable, DeviceVTableIndex.SetTextureStageState);
|
||||
|
||||
_delegatesCached = true;
|
||||
RynthLog.D3D9("TestRenderer: D3D9 delegates cached.");
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue