feat: port aelrynth 2026.9.27.2 snapshot onto GitHub history
Overlay upstream/main (9b5e276) onto BlankenshipG main without rewriting
history. Keep origin-only Decal/plugin/docs trees. Re-apply aelrynth.com
and sibling-fork URL fixes that aelrynth git still has as tombohar links.
Co-authored-by: BlankenshipG <BlankenshipG@users.noreply.github.com>
This commit is contained in:
parent
ac0d743e16
commit
4ddbb52eb2
244 changed files with 59710 additions and 3067 deletions
168
src/RynthCore.Engine/D3D9/BitmapFont.cs
Normal file
168
src/RynthCore.Engine/D3D9/BitmapFont.cs
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/BitmapFont.cs
|
||||
// Dependency-free 5x7 bitmap font, ported from RynthCore2's bitmap_font.cpp.
|
||||
//
|
||||
// Standard 5x7 glyph cells. Each glyph is 7 rows; the low 5 bits of each row
|
||||
// are the columns, bit 4 = leftmost. A set bit is a lit pixel cell. Lit cells
|
||||
// are emitted as rectangles through a caller-supplied sink so the renderer
|
||||
// (VitalHud) can turn each into a colored quad. No allocation, no texture.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static class BitmapFont
|
||||
{
|
||||
/// <summary>Receives one lit pixel cell as an inclusive-exclusive rect.</summary>
|
||||
internal delegate void CellSink(int x0, int y0, int x1, int y1);
|
||||
|
||||
public const int GlyphW = 5;
|
||||
public const int GlyphH = 7;
|
||||
private const int Advance = GlyphW + 1; // one-cell gap between glyphs
|
||||
|
||||
// Glyph table row, in a fixed order; IndexOf maps a character to a row.
|
||||
// 0 = space
|
||||
// 1..10 = '0'..'9'
|
||||
// 11..36 = 'A'..'Z'
|
||||
// 37..45 = '/' ':' '.' ',' '-' '+' '%' '(' ')'
|
||||
private const int GSpace = 0;
|
||||
private const int GDigit0 = 1;
|
||||
private const int GLetterA = 11;
|
||||
private const int GSlash = 37;
|
||||
private const int GColon = 38;
|
||||
private const int GDot = 39;
|
||||
private const int GComma = 40;
|
||||
private const int GDash = 41;
|
||||
private const int GPlus = 42;
|
||||
private const int GPercent = 43;
|
||||
private const int GLParen = 44;
|
||||
private const int GRParen = 45;
|
||||
|
||||
// 5x7 cells, bit 4 leftmost — transcribed verbatim from bitmap_font.cpp.
|
||||
private static readonly byte[][] Glyphs =
|
||||
[
|
||||
/* space */ [0, 0, 0, 0, 0, 0, 0],
|
||||
/* 0 */ [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110],
|
||||
/* 1 */ [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
|
||||
/* 2 */ [0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111],
|
||||
/* 3 */ [0b11111, 0b00010, 0b00100, 0b00010, 0b00001, 0b10001, 0b01110],
|
||||
/* 4 */ [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010],
|
||||
/* 5 */ [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110],
|
||||
/* 6 */ [0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110],
|
||||
/* 7 */ [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000],
|
||||
/* 8 */ [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110],
|
||||
/* 9 */ [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100],
|
||||
/* A */ [0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
|
||||
/* B */ [0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110],
|
||||
/* C */ [0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110],
|
||||
/* D */ [0b11100, 0b10010, 0b10001, 0b10001, 0b10001, 0b10010, 0b11100],
|
||||
/* E */ [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111],
|
||||
/* F */ [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000],
|
||||
/* G */ [0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01111],
|
||||
/* H */ [0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
|
||||
/* I */ [0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
|
||||
/* J */ [0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100],
|
||||
/* K */ [0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001],
|
||||
/* L */ [0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111],
|
||||
/* M */ [0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001],
|
||||
/* N */ [0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001],
|
||||
/* O */ [0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
|
||||
/* P */ [0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000],
|
||||
/* Q */ [0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101],
|
||||
/* R */ [0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001],
|
||||
/* S */ [0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110],
|
||||
/* T */ [0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100],
|
||||
/* U */ [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
|
||||
/* V */ [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100],
|
||||
/* W */ [0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b10101, 0b01010],
|
||||
/* X */ [0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001],
|
||||
/* Y */ [0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100],
|
||||
/* Z */ [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111],
|
||||
/* / */ [0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000],
|
||||
/* : */ [0b00000, 0b00100, 0b00100, 0b00000, 0b00100, 0b00100, 0b00000],
|
||||
/* . */ [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b01100, 0b01100],
|
||||
/* , */ [0b00000, 0b00000, 0b00000, 0b00000, 0b01100, 0b00100, 0b01000],
|
||||
/* - */ [0b00000, 0b00000, 0b00000, 0b11111, 0b00000, 0b00000, 0b00000],
|
||||
/* + */ [0b00000, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0b00000],
|
||||
/* % */ [0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011],
|
||||
/* ( */ [0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010],
|
||||
/* ) */ [0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000],
|
||||
];
|
||||
|
||||
// Maps an ASCII character to a glyph row, or -1 if unsupported (advance blank).
|
||||
private static int IndexOf(char c)
|
||||
{
|
||||
if (c >= '0' && c <= '9') return GDigit0 + (c - '0');
|
||||
if (c >= 'A' && c <= 'Z') return GLetterA + (c - 'A');
|
||||
if (c >= 'a' && c <= 'z') return GLetterA + (c - 'a'); // fold to uppercase
|
||||
return c switch
|
||||
{
|
||||
' ' => GSpace,
|
||||
'/' => GSlash,
|
||||
':' => GColon,
|
||||
'.' => GDot,
|
||||
',' => GComma,
|
||||
'-' => GDash,
|
||||
'+' => GPlus,
|
||||
'%' => GPercent,
|
||||
'(' => GLParen,
|
||||
')' => GRParen,
|
||||
_ => -1,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Pixel height of a glyph at the given cell size.</summary>
|
||||
public static int Height(int cellPx)
|
||||
{
|
||||
if (cellPx < 1) cellPx = 1;
|
||||
return GlyphH * cellPx;
|
||||
}
|
||||
|
||||
/// <summary>Pixel width of a rendered string at the given cell size. Takes a
|
||||
/// span so callers can measure stack-formatted text without allocating.</summary>
|
||||
public static int MeasureWidth(ReadOnlySpan<char> s, int cellPx)
|
||||
{
|
||||
if (s.IsEmpty) return 0;
|
||||
if (cellPx < 1) cellPx = 1;
|
||||
int n = s.Length;
|
||||
// n glyphs, each GlyphW wide, with (n-1) single-cell gaps between them.
|
||||
return (n * GlyphW + (n - 1)) * cellPx;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emits the lit cells of <paramref name="s"/> at (x, y) at the given cell
|
||||
/// size by invoking <paramref name="sink"/> once per lit cell. Takes a span
|
||||
/// (string literals convert implicitly) so it stays allocation-free; the sink
|
||||
/// is a cached delegate on the caller side.
|
||||
/// </summary>
|
||||
public static void Emit(ReadOnlySpan<char> s, int x, int y, int cellPx, CellSink sink)
|
||||
{
|
||||
if (s.IsEmpty || sink == null) return;
|
||||
if (cellPx < 1) cellPx = 1;
|
||||
|
||||
int penX = x;
|
||||
foreach (char ch in s)
|
||||
{
|
||||
int gi = IndexOf(ch);
|
||||
if (gi >= 0 && gi != GSpace)
|
||||
{
|
||||
byte[] rows = Glyphs[gi];
|
||||
for (int r = 0; r < GlyphH; r++)
|
||||
{
|
||||
int bits = rows[r];
|
||||
for (int c = 0; c < GlyphW; c++)
|
||||
{
|
||||
if (((bits >> (GlyphW - 1 - c)) & 1) != 0)
|
||||
{
|
||||
int x0 = penX + c * cellPx;
|
||||
int y0 = y + r * cellPx;
|
||||
sink(x0, y0, x0 + cellPx, y0 + cellPx);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
penX += Advance * cellPx;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -132,18 +132,35 @@ internal static class D3D9Bootstrapper
|
|||
|
||||
private static IntPtr Direct3DCreate9Detour(uint sdkVersion)
|
||||
{
|
||||
// The call-through happens unconditionally, outside any try/catch —
|
||||
// it must always run so the game gets its real IDirect3D9 regardless
|
||||
// of what our own bootstrapping below does.
|
||||
IntPtr direct3D9 = _originalDirect3DCreate9!(sdkVersion);
|
||||
|
||||
if (sdkVersion != D3DSdkVersion)
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Direct3DCreate9 called with SDK {sdkVersion} (expected {D3DSdkVersion}).");
|
||||
|
||||
if (direct3D9 == IntPtr.Zero)
|
||||
// Deep-audit finding #11 (2026-06-18): everything past the
|
||||
// call-through is a delegate-marshalled reverse-P/Invoke callback
|
||||
// with no try/catch. TryHookCreateDevice can throw
|
||||
// InvalidOperationException out of MinHook.HookCreate/Enable — an
|
||||
// escaping exception here fail-fasts the whole client. Wrapped for
|
||||
// parity even though the logging above it can't realistically throw.
|
||||
try
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: Direct3DCreate9 returned null.");
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
if (sdkVersion != D3DSdkVersion)
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: Direct3DCreate9 called with SDK {sdkVersion} (expected {D3DSdkVersion}).");
|
||||
|
||||
TryHookCreateDevice(direct3D9);
|
||||
if (direct3D9 == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: Direct3DCreate9 returned null.");
|
||||
return direct3D9;
|
||||
}
|
||||
|
||||
TryHookCreateDevice(direct3D9);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.D3D9($"D3D9Bootstrapper: Direct3DCreate9Detour post-processing threw {ex.GetType().Name}: {ex.Message} — degrading to no CreateDevice hook."); }
|
||||
catch { }
|
||||
}
|
||||
return direct3D9;
|
||||
}
|
||||
|
||||
|
|
@ -152,23 +169,35 @@ internal static class D3D9Bootstrapper
|
|||
if (_createDeviceHookInstalled)
|
||||
return;
|
||||
|
||||
IntPtr vtable = Marshal.ReadIntPtr(direct3D9);
|
||||
_createDeviceTarget = Marshal.ReadIntPtr(vtable, D3D9VTableIndex.CreateDevice * IntPtr.Size);
|
||||
if (_createDeviceTarget == IntPtr.Zero)
|
||||
// Genuinely unguarded path per the audit: MinHook.HookCreate/Enable can
|
||||
// throw InvalidOperationException. Log and swallow — the caller already
|
||||
// has the real direct3D9 pointer from the call-through, so degrading to
|
||||
// "no CreateDevice hook installed" is a safe no-op, not a crash.
|
||||
try
|
||||
{
|
||||
RynthLog.D3D9("D3D9Bootstrapper: IDirect3D9::CreateDevice pointer was null.");
|
||||
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}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { RynthLog.D3D9($"D3D9Bootstrapper: TryHookCreateDevice threw {ex.GetType().Name}: {ex.Message} — CreateDevice hook not installed."); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
_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()
|
||||
|
|
@ -201,6 +230,8 @@ internal static class D3D9Bootstrapper
|
|||
IntPtr pPresentationParameters,
|
||||
out IntPtr ppDevice)
|
||||
{
|
||||
// Call-through happens unconditionally, outside any try/catch, same
|
||||
// rationale as Direct3DCreate9Detour above.
|
||||
int hr = _originalCreateDevice!(
|
||||
pD3D9,
|
||||
adapter,
|
||||
|
|
@ -210,16 +241,28 @@ internal static class D3D9Bootstrapper
|
|||
pPresentationParameters,
|
||||
out ppDevice);
|
||||
|
||||
if (hr >= 0 && ppDevice != IntPtr.Zero)
|
||||
// Deep-audit finding #11: wrapped for parity with Direct3DCreate9Detour.
|
||||
// This path is already pre-contained by InstallFromDevice ->
|
||||
// InstallFromEndSceneAddress's own try/catch, but a throw from
|
||||
// RemoveBootstrapHooks (MinHook calls) before that point was not.
|
||||
try
|
||||
{
|
||||
_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);
|
||||
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}");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"D3D9Bootstrapper: CreateDevice returned hr=0x{hr:X8}, device=0x{ppDevice:X8}");
|
||||
try { RynthLog.D3D9($"D3D9Bootstrapper: CreateDeviceDetour post-processing threw {ex.GetType().Name}: {ex.Message}."); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
return hr;
|
||||
|
|
|
|||
|
|
@ -25,9 +25,27 @@ internal static class EndSceneHook
|
|||
private static long _fpsCounterStart;
|
||||
private static int _fpsCounterFrames;
|
||||
|
||||
/// <summary>
|
||||
/// Last measured EndScene frames-per-second, refreshed once per second.
|
||||
/// Updated whether or not the FPS governor is enabled — UI panels (the
|
||||
/// RynthAi footer) read this for a live frame-rate display. Volatile
|
||||
/// because writes happen on the AC pump thread and reads happen on the
|
||||
/// Avalonia dispatcher thread (10 Hz panel tick); double-word atomic on
|
||||
/// x86 and we don't need a tear-free guarantee on this value.
|
||||
/// </summary>
|
||||
internal static volatile float MeasuredFps;
|
||||
private static long _liveFpsCounterStart;
|
||||
private static int _liveFpsCounterFrames;
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetForegroundWindow();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint lpdwProcessId);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern uint GetCurrentProcessId();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int EndSceneDelegate(IntPtr pDevice);
|
||||
|
||||
|
|
@ -133,11 +151,18 @@ internal static class EndSceneHook
|
|||
if (!_installed)
|
||||
return;
|
||||
|
||||
ImGuiController.Shutdown();
|
||||
|
||||
// Order is critical: disable the detour FIRST so AC's render thread
|
||||
// stops entering our code, then drain in-flight calls, THEN tear down
|
||||
// ImGui. If we destroyed the context first, an in-flight EndScene call
|
||||
// would assert on `GImGui != NULL`.
|
||||
int status = MinHook.MH_DisableHook(_endSceneAddr);
|
||||
RynthLog.D3D9($"EndSceneHook: Disable = {MinHook.StatusString(status)}");
|
||||
|
||||
// Let the render thread return through the trampoline.
|
||||
Thread.Sleep(80);
|
||||
|
||||
EngineFrameController.Shutdown();
|
||||
|
||||
status = MinHook.MH_RemoveHook(_endSceneAddr);
|
||||
RynthLog.D3D9($"EndSceneHook: Remove = {MinHook.StatusString(status)}");
|
||||
|
||||
|
|
@ -184,6 +209,10 @@ internal static class EndSceneHook
|
|||
|
||||
private static int EndSceneDetour(IntPtr pDevice)
|
||||
{
|
||||
// Liveness beacon for MainThreadHangWatchdog — this detour runs on AC's
|
||||
// main/render thread every frame (even with the ImGui backend disabled),
|
||||
// so a stalled beat means the main thread is wedged. Must never throw.
|
||||
try { MainThreadHangWatchdog.MainThreadBeat(); } catch { }
|
||||
try
|
||||
{
|
||||
if (!_offscreenFilterDisabled && !DX9Backend.IsRenderingToBackBuffer(pDevice))
|
||||
|
|
@ -208,6 +237,10 @@ internal static class EndSceneHook
|
|||
|
||||
// Per-frame chatbox visibility assertion (no-op unless plugin enables suppression).
|
||||
try { ChatHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
|
||||
// Per-frame retail-radar visibility assertion (no-op unless plugin enables suppression).
|
||||
try { RadarHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
|
||||
// Per-frame retail-powerbar visibility assertion (no-op unless plugin enables suppression).
|
||||
try { PowerbarHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
|
||||
|
||||
if (_renderCount == 1 && _offscreenFilterDisabled && _skipCount > 0)
|
||||
{
|
||||
|
|
@ -230,17 +263,38 @@ internal static class EndSceneHook
|
|||
|
||||
if (!match && actualEndScene != IntPtr.Zero)
|
||||
{
|
||||
// Deep-audit finding #8 (2026-06-18): the old sequence
|
||||
// disabled+REMOVED the old hook (freeing the trampoline
|
||||
// _originalEndScene points at) BEFORE attempting the new
|
||||
// install. If the new MH_CreateHook then threw,
|
||||
// _originalEndScene was never reassigned — it still bound
|
||||
// the now-freed trampoline — yet the code force-set
|
||||
// _installed=true and this function's bottom called
|
||||
// through it: a use-after-free. Fixed order: only remove
|
||||
// the OLD hook after the NEW one is confirmed installed;
|
||||
// on failure, re-enable the OLD hook and keep using its
|
||||
// still-valid trampoline instead of a dangling one.
|
||||
RynthLog.D3D9("EndSceneHook: Rehooking at the device's actual EndScene address.");
|
||||
MinHook.MH_DisableHook(_endSceneAddr);
|
||||
MinHook.MH_RemoveHook(_endSceneAddr);
|
||||
_installed = false;
|
||||
IntPtr oldAddr = _endSceneAddr;
|
||||
EndSceneDelegate? oldOriginal = _originalEndScene;
|
||||
MinHook.MH_DisableHook(oldAddr);
|
||||
|
||||
InstallFromEndSceneAddress(actualEndScene);
|
||||
if (_installed)
|
||||
{
|
||||
// New hook confirmed live — safe to free the old
|
||||
// trampoline now.
|
||||
MinHook.MH_RemoveHook(oldAddr);
|
||||
return _originalEndScene!(pDevice);
|
||||
}
|
||||
|
||||
RynthLog.D3D9("EndSceneHook: Rehook failed — continuing with original hook.");
|
||||
// Restore state so we don't keep trying
|
||||
RynthLog.D3D9("EndSceneHook: Rehook failed — restoring original hook.");
|
||||
// New install failed (InstallFromEndSceneAddress leaves
|
||||
// _installed=false on failure). Restore the OLD hook
|
||||
// rather than trust a dangling delegate.
|
||||
_endSceneAddr = oldAddr;
|
||||
_originalEndScene = oldOriginal;
|
||||
MinHook.Enable(oldAddr);
|
||||
_installed = true;
|
||||
}
|
||||
}
|
||||
|
|
@ -260,11 +314,39 @@ internal static class EndSceneHook
|
|||
RynthLog.D3D9("EndSceneHook: Warmup complete - initializing ImGui.");
|
||||
}
|
||||
|
||||
ImGuiController.OnEndScene(pDevice);
|
||||
// EngineFrameController.OnEndScene runs the always-on engine work
|
||||
// (matrix capture, plugin tick, nav rendering, pending action drains)
|
||||
// every frame. The EnableImGuiBackend gate moved INSIDE the
|
||||
// controller so it scopes only the ImGui-specific block; this call
|
||||
// site no longer needs to gate it.
|
||||
EngineFrameController.OnEndScene(pDevice);
|
||||
_uiFrameCount++;
|
||||
|
||||
if (_uiFrameCount == 60)
|
||||
if (_uiFrameCount == 60 && RynthCore.Engine.Plugins.EngineSettings.EnableImGuiBackend)
|
||||
RynthLog.D3D9("EndSceneHook: 60 UI frames - ImGui is stable.");
|
||||
if (_renderCount == UiInitWarmupFrames && !RynthCore.Engine.Plugins.EngineSettings.EnableImGuiBackend)
|
||||
RynthLog.D3D9("EndSceneHook: ImGui backend disabled via engine.json (EnableImGuiBackend=false). Always-on engine work still runs; only ImGui draw calls are skipped.");
|
||||
|
||||
// Avalonia compositor: independent of ImGui. Reads the latest
|
||||
// Avalonia surface from OverlaySurfaceBridge and blits it as a
|
||||
// fullscreen alpha-blended quad onto AC's back buffer. Runs every
|
||||
// frame regardless of EnableImGuiBackend so the Avalonia overlay
|
||||
// is visible even when ImGui per-frame work is disabled. Driven
|
||||
// here exclusively — EngineFrameController.OnEndScene intentionally
|
||||
// does NOT call it (avoids double-blit / TryConsume races).
|
||||
// The UI hides between characters: nothing is drawn at character select or
|
||||
// on the way out, and it's back the moment login completes (an engine
|
||||
// reload synthesises login for a player already in the world).
|
||||
try
|
||||
{
|
||||
if (Compatibility.LoginLifecycleHooks.HasObservedLoginComplete)
|
||||
OverlayTextureRenderer.Render(pDevice);
|
||||
}
|
||||
catch (Exception ovEx)
|
||||
{
|
||||
if (_uiFrameCount < 30)
|
||||
RynthLog.D3D9($"EndSceneHook: OverlayTextureRenderer.Render error: {ovEx.GetType().Name}: {ovEx.Message}");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -272,12 +354,32 @@ internal static class EndSceneHook
|
|||
RynthLog.D3D9($"EndSceneHook: Frame {_frameCount} error: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
|
||||
}
|
||||
|
||||
// ── Always-on FPS measurement for UI footer ──────────────────
|
||||
// Runs whether or not the governor is enabled so the RynthAi
|
||||
// footer can show a live FPS even when the user hasn't capped.
|
||||
// Cheap: one increment + a once-per-second division.
|
||||
_liveFpsCounterFrames++;
|
||||
long liveNow = Environment.TickCount64;
|
||||
if (_liveFpsCounterStart == 0) _liveFpsCounterStart = liveNow;
|
||||
long liveElapsed = liveNow - _liveFpsCounterStart;
|
||||
if (liveElapsed >= 1000)
|
||||
{
|
||||
MeasuredFps = (float)(_liveFpsCounterFrames * 1000.0 / liveElapsed);
|
||||
_liveFpsCounterFrames = 0;
|
||||
_liveFpsCounterStart = liveNow;
|
||||
}
|
||||
|
||||
// ── FPS Governor (matches proven NexSuite2 pattern) ─────────
|
||||
if (FpsLimitEnabled)
|
||||
{
|
||||
IntPtr fgWnd = GetForegroundWindow();
|
||||
// Only "focused" when the AC game window itself is foreground — not viewport popups.
|
||||
bool isFocused = fgWnd != IntPtr.Zero && fgWnd == Win32Backend.GameHwnd;
|
||||
// Focused when AC itself is foreground, OR when any window belonging
|
||||
// to our process is foreground (covers DComp overlay, any Avalonia
|
||||
// child window, etc.). PID comparison is reliable regardless of how
|
||||
// the owner chain was established (GWL_HWNDPARENT vs CreateWindow).
|
||||
GetWindowThreadProcessId(fgWnd, out uint fgPid);
|
||||
bool isFocused = fgWnd != IntPtr.Zero &&
|
||||
(fgWnd == Win32Backend.GameHwnd || fgPid == GetCurrentProcessId());
|
||||
int targetFps = isFocused ? FpsTargetFocused : FpsTargetBackground;
|
||||
double minFrameMs = 1000.0 / Math.Max(targetFps, 1);
|
||||
|
||||
|
|
|
|||
|
|
@ -51,10 +51,19 @@ internal static unsafe class GameMatrixCapture
|
|||
private static readonly float[] _viewProj = new float[16];
|
||||
private static bool _hasValidViewProj;
|
||||
|
||||
// Camera frame from SmartBox memory (same layout as UB Camera.cs)
|
||||
// Camera frame from SmartBox memory.
|
||||
// AC's Position struct: PackObj.vfptr (4) + objcell_id (4) + Frame (...).
|
||||
// Frame is qw,qx,qy,qz (16) + m_fl2gv[9] (36) + m_fOrigin (12) = 64 bytes.
|
||||
// So at Position start (+0x08 from SmartBox):
|
||||
// +0x00 PackObj.vfptr (4)
|
||||
// +0x04 objcell_id (4) ← real viewer cellId
|
||||
// +0x08 Frame.qw,qx,qy,qz (16)
|
||||
// +0x18 Frame.m_fl2gv[9] (36) ← cached 3x3 rotation matrix
|
||||
// +0x3C Frame.m_fOrigin (12) ← camera position (x, y, z)
|
||||
private const int CameraFrameOffset = 0x08;
|
||||
private const int CamRotOffset = 0x18; // 3x3 rotation matrix
|
||||
private const int CamPosOffset = 0x3C; // position (x, y, z)
|
||||
private const int CamCellIdOffset = 0x04; // viewer cellId (skips PackObj.vfptr)
|
||||
private const int CamRotOffset = 0x18;
|
||||
private const int CamPosOffset = 0x3C;
|
||||
|
||||
// Diagnostics
|
||||
private static int _framesSinceLog;
|
||||
|
|
@ -165,6 +174,85 @@ internal static unsafe class GameMatrixCapture
|
|||
if (cx == 0f && cy == 0f && cz == 0f)
|
||||
return;
|
||||
|
||||
// The camera's pose is stored landblock-local: as the camera orbits
|
||||
// across a landblock boundary, AC re-anchors the viewer to the new
|
||||
// landblock and (cx, cy) jumps to that landblock's frame. Plugins
|
||||
// submitting Nav3D markers around the player are in the PLAYER's
|
||||
// landblock frame, so we shift the camera back into that frame here.
|
||||
// Without this, every marker visually leaps 192 m when the camera
|
||||
// crosses a landblock boundary even though the player hasn't moved.
|
||||
//
|
||||
// Guards: the viewer cellId can briefly hold uninitialized / mid-
|
||||
// teleport junk (e.g. landblock 0x0001 while the world isn't loaded)
|
||||
// that gives a multi-thousand-meter "delta" and produces a wildly
|
||||
// wrong view matrix. Only apply the shift when both landblocks look
|
||||
// like real outdoor world landblocks AND the delta is within ±4
|
||||
// landblocks (no legitimate camera frustum reaches further).
|
||||
float rawCx = cx, rawCy = cy;
|
||||
bool shiftApplied = false;
|
||||
int dXBlocks = 0, dYBlocks = 0;
|
||||
uint viewerLbForLog = 0, playerLbForLog = 0;
|
||||
bool guardBlocked = false;
|
||||
string guardReason = "";
|
||||
|
||||
uint viewerCellId = unchecked((uint)Marshal.ReadInt32(camFrame + CamCellIdOffset));
|
||||
uint viewerLandblock = viewerCellId >> 16;
|
||||
viewerLbForLog = viewerLandblock;
|
||||
|
||||
// Prefer the landblock the plugin tick LOCKED IN when it submitted
|
||||
// its Nav3D geometry (see Nav3DRenderer.ClearFrame). If we use the
|
||||
// CURRENT player landblock instead, render and triangles disagree
|
||||
// for the frames between the player crossing a boundary and the next
|
||||
// plugin tick re-submitting — geometry jumps to the adjacent
|
||||
// landblock for ~1 s and snaps back. Fall back to current player
|
||||
// landblock when no submission frame is published (zero).
|
||||
uint submissionLandblock = Nav3DRenderer.ReadyPlayerLandblock;
|
||||
bool havePose;
|
||||
uint playerCellId;
|
||||
if (submissionLandblock != 0)
|
||||
{
|
||||
havePose = true;
|
||||
playerCellId = submissionLandblock << 16;
|
||||
}
|
||||
else
|
||||
{
|
||||
havePose = PlayerPhysicsHooks.TryGetPlayerPose(out playerCellId, out _, out _, out _,
|
||||
out _, out _, out _, out _);
|
||||
}
|
||||
if (viewerLandblock != 0 && havePose && (playerCellId >> 16) != 0)
|
||||
{
|
||||
uint playerLandblock = playerCellId >> 16;
|
||||
playerLbForLog = playerLandblock;
|
||||
int viewerLbX = (int)((viewerLandblock >> 8) & 0xFF);
|
||||
int viewerLbY = (int)(viewerLandblock & 0xFF);
|
||||
int playerLbX = (int)((playerLandblock >> 8) & 0xFF);
|
||||
int playerLbY = (int)(playerLandblock & 0xFF);
|
||||
dXBlocks = viewerLbX - playerLbX;
|
||||
dYBlocks = viewerLbY - playerLbY;
|
||||
if (Math.Abs(dXBlocks) <= 4 && Math.Abs(dYBlocks) <= 4 &&
|
||||
viewerLbX != 0 && viewerLbY != 0)
|
||||
{
|
||||
cx += dXBlocks * 192f; // EW shift back into player-landblock frame
|
||||
cy += dYBlocks * 192f; // NS
|
||||
shiftApplied = (dXBlocks != 0 || dYBlocks != 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
guardBlocked = (dXBlocks != 0 || dYBlocks != 0);
|
||||
guardReason = $"dx={dXBlocks},dy={dYBlocks},vLbX={viewerLbX},vLbY={viewerLbY}";
|
||||
}
|
||||
}
|
||||
|
||||
// Log when a non-zero shift fires (camera crossed a landblock) or when
|
||||
// the guard blocked one. Helps catch "paintings move with camera"
|
||||
// without spamming when player and viewer landblocks agree.
|
||||
if (shiftApplied || guardBlocked)
|
||||
{
|
||||
RynthLog.D3D9($"GameMatrixCapture: viewer lb=0x{viewerLbForLog:X4} player lb=0x{playerLbForLog:X4} " +
|
||||
$"d=({dXBlocks},{dYBlocks}) raw=({rawCx:F1},{rawCy:F1}) adj=({cx:F1},{cy:F1}) " +
|
||||
$"{(shiftApplied ? "SHIFTED" : "GUARD-BLOCKED " + guardReason)}");
|
||||
}
|
||||
|
||||
// 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:
|
||||
|
|
|
|||
|
|
@ -1,84 +1,221 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// 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.
|
||||
// Data store for 3D navigation markers. Plugins submit geometry every plugin
|
||||
// tick via AddRing/AddLine/AddTriangle; DX9Backend.RenderNav3D reads it
|
||||
// during EndScene.
|
||||
//
|
||||
// Double-buffered to keep the render thread (60 Hz, AC's EndScene) from
|
||||
// reading a half-rewritten buffer while the plugin pump thread (~30 Hz) is
|
||||
// mid Clear → Submit. Without this, every plugin tick produced a 1-frame
|
||||
// empty/partial render that the user sees as flicker — pronounced when the
|
||||
// player or camera is in motion (because the submitted contents change each
|
||||
// tick; when stationary the race window contains identical data so it's
|
||||
// invisible).
|
||||
//
|
||||
// Pattern:
|
||||
// pump: BeginFrame() → AddX(...) × N → CommitFrame()
|
||||
// render: reads from the "ready" buffer only; never touches "pending"
|
||||
// CommitFrame atomically swaps the index reads see.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System.Threading;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static class Nav3DRenderer
|
||||
{
|
||||
private const int MaxRings = 256;
|
||||
private const int MaxLines = 512;
|
||||
// Triangle: three vertices + color. Sized for a ~3×3-landblock slope
|
||||
// overlay around the player: 24-cell radius ≈ 49×49 cells × 2 triangles
|
||||
// = 4802 triangles worst case, with headroom for water and other uses.
|
||||
private const int MaxTriangles = 8192;
|
||||
|
||||
// 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;
|
||||
private const float DefaultRingHeight = 0.5f; // back-compat default for AddRing
|
||||
|
||||
// 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()
|
||||
private sealed class NavBuffer
|
||||
{
|
||||
_ringCount = 0;
|
||||
_lineCount = 0;
|
||||
public readonly float[] RingX = new float[MaxRings];
|
||||
public readonly float[] RingY = new float[MaxRings];
|
||||
public readonly float[] RingZ = new float[MaxRings];
|
||||
public readonly float[] RingRadius = new float[MaxRings];
|
||||
public readonly float[] RingThick = new float[MaxRings];
|
||||
public readonly float[] RingHeight = new float[MaxRings];
|
||||
public readonly uint[] RingColor = new uint[MaxRings];
|
||||
public int RingCount;
|
||||
|
||||
public readonly float[] LineX1 = new float[MaxLines];
|
||||
public readonly float[] LineY1 = new float[MaxLines];
|
||||
public readonly float[] LineZ1 = new float[MaxLines];
|
||||
public readonly float[] LineX2 = new float[MaxLines];
|
||||
public readonly float[] LineY2 = new float[MaxLines];
|
||||
public readonly float[] LineZ2 = new float[MaxLines];
|
||||
public readonly float[] LineThick = new float[MaxLines];
|
||||
public readonly uint[] LineColor = new uint[MaxLines];
|
||||
public int LineCount;
|
||||
|
||||
public readonly float[] TriX1 = new float[MaxTriangles];
|
||||
public readonly float[] TriY1 = new float[MaxTriangles];
|
||||
public readonly float[] TriZ1 = new float[MaxTriangles];
|
||||
public readonly float[] TriX2 = new float[MaxTriangles];
|
||||
public readonly float[] TriY2 = new float[MaxTriangles];
|
||||
public readonly float[] TriZ2 = new float[MaxTriangles];
|
||||
public readonly float[] TriX3 = new float[MaxTriangles];
|
||||
public readonly float[] TriY3 = new float[MaxTriangles];
|
||||
public readonly float[] TriZ3 = new float[MaxTriangles];
|
||||
public readonly uint[] TriColor = new uint[MaxTriangles];
|
||||
public int TriCount;
|
||||
|
||||
// The player's landblock at the moment ClearFrame was called for
|
||||
// this buffer. All AddX submissions in this tick are in PLAYER-
|
||||
// landblock-local coordinates (per RynthAi + RynthVision contract),
|
||||
// so the render side needs THIS landblock — not the current
|
||||
// player landblock — when it computes the view-matrix shift, or the
|
||||
// tick's geometry will jump 192m when the player crosses a boundary
|
||||
// between this tick and the next render frame.
|
||||
// Zero = "no player pose available; fall back to current".
|
||||
public uint SubmissionPlayerLandblock;
|
||||
|
||||
public void Reset() { RingCount = 0; LineCount = 0; TriCount = 0; SubmissionPlayerLandblock = 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;
|
||||
}
|
||||
// Triple buffer:
|
||||
// _ready — what the render thread reads (volatile, swap published here)
|
||||
// _pending — what the pump writes into for the current tick
|
||||
// _spare — last tick's ready, "cooling off" one tick before the pump
|
||||
// recycles it. This guarantees the buffer the render thread
|
||||
// has captured isn't overwritten mid-iteration: when pump
|
||||
// commits, the buffer the reader was holding becomes _spare
|
||||
// (untouched for this tick) before becoming _pending the
|
||||
// tick after that. Cheap insurance against any timing where
|
||||
// render takes longer than one pump interval.
|
||||
private static readonly NavBuffer _a = new();
|
||||
private static readonly NavBuffer _b = new();
|
||||
private static readonly NavBuffer _c = new();
|
||||
private static volatile NavBuffer _ready = _a;
|
||||
private static NavBuffer _pending = _b;
|
||||
private static NavBuffer _spare = _c;
|
||||
|
||||
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;
|
||||
}
|
||||
// ── Render-side reads ────────────────────────────────────────────────────
|
||||
|
||||
public static int RingCount => _ready.RingCount;
|
||||
public static int LineCount => _ready.LineCount;
|
||||
public static int TriangleCount => _ready.TriCount;
|
||||
|
||||
public static void GetRing(int i, out float x, out float y, out float z,
|
||||
out float radius, out float thickness, out uint color)
|
||||
out float radius, out float thickness, out float height, out uint color)
|
||||
{
|
||||
x = _ringX[i]; y = _ringY[i]; z = _ringZ[i];
|
||||
radius = _ringRadius[i]; thickness = _ringThick[i]; color = _ringColor[i];
|
||||
var r = _ready;
|
||||
x = r.RingX[i]; y = r.RingY[i]; z = r.RingZ[i];
|
||||
radius = r.RingRadius[i]; thickness = r.RingThick[i];
|
||||
height = r.RingHeight[i]; color = r.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];
|
||||
var r = _ready;
|
||||
x1 = r.LineX1[i]; y1 = r.LineY1[i]; z1 = r.LineZ1[i];
|
||||
x2 = r.LineX2[i]; y2 = r.LineY2[i]; z2 = r.LineZ2[i];
|
||||
thickness = r.LineThick[i]; color = r.LineColor[i];
|
||||
}
|
||||
|
||||
// C ABI callbacks for plugin contract
|
||||
public static void GetTriangle(int i, out float x1, out float y1, out float z1,
|
||||
out float x2, out float y2, out float z2,
|
||||
out float x3, out float y3, out float z3, out uint color)
|
||||
{
|
||||
var r = _ready;
|
||||
x1 = r.TriX1[i]; y1 = r.TriY1[i]; z1 = r.TriZ1[i];
|
||||
x2 = r.TriX2[i]; y2 = r.TriY2[i]; z2 = r.TriZ2[i];
|
||||
x3 = r.TriX3[i]; y3 = r.TriY3[i]; z3 = r.TriZ3[i];
|
||||
color = r.TriColor[i];
|
||||
}
|
||||
|
||||
// The landblock the plugin tick that produced the ready buffer was using.
|
||||
// Render thread uses this for view-matrix shifting so geometry stays
|
||||
// anchored to that tick's reference frame even if the player crosses a
|
||||
// landblock boundary between this tick and the next render frame.
|
||||
// Returns 0 when no pose was sampled; caller should fall back to
|
||||
// current player landblock in that case.
|
||||
public static uint ReadyPlayerLandblock => _ready.SubmissionPlayerLandblock;
|
||||
|
||||
// ── Pump-side writes ─────────────────────────────────────────────────────
|
||||
|
||||
public static void ClearFrame()
|
||||
{
|
||||
_pending.Reset();
|
||||
// Capture the player's current landblock so the render side knows
|
||||
// which frame the tick's submissions are anchored in.
|
||||
if (PlayerPhysicsHooks.TryGetPlayerPose(out uint cellId, out _, out _, out _,
|
||||
out _, out _, out _, out _))
|
||||
_pending.SubmissionPlayerLandblock = cellId >> 16;
|
||||
}
|
||||
|
||||
public static void AddRing(float wx, float wy, float wz, float radius, float thickness, uint colorArgb)
|
||||
=> AddRingEx(wx, wy, wz, radius, thickness, DefaultRingHeight, colorArgb);
|
||||
|
||||
public static void AddRingEx(float wx, float wy, float wz, float radius, float thickness, float height, uint colorArgb)
|
||||
{
|
||||
var p = _pending;
|
||||
if (p.RingCount >= MaxRings) return;
|
||||
int i = p.RingCount++;
|
||||
p.RingX[i] = wx; p.RingY[i] = wy; p.RingZ[i] = wz;
|
||||
p.RingRadius[i] = radius;
|
||||
p.RingThick[i] = thickness;
|
||||
p.RingHeight[i] = height;
|
||||
p.RingColor[i] = colorArgb;
|
||||
}
|
||||
|
||||
public static void AddLine(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb)
|
||||
{
|
||||
var p = _pending;
|
||||
if (p.LineCount >= MaxLines) return;
|
||||
int i = p.LineCount++;
|
||||
p.LineX1[i] = x1; p.LineY1[i] = y1; p.LineZ1[i] = z1;
|
||||
p.LineX2[i] = x2; p.LineY2[i] = y2; p.LineZ2[i] = z2;
|
||||
p.LineThick[i] = thickness;
|
||||
p.LineColor[i] = colorArgb;
|
||||
}
|
||||
|
||||
public static void AddTriangle(float x1, float y1, float z1,
|
||||
float x2, float y2, float z2,
|
||||
float x3, float y3, float z3, uint colorArgb)
|
||||
{
|
||||
var p = _pending;
|
||||
if (p.TriCount >= MaxTriangles) return;
|
||||
int i = p.TriCount++;
|
||||
p.TriX1[i] = x1; p.TriY1[i] = y1; p.TriZ1[i] = z1;
|
||||
p.TriX2[i] = x2; p.TriY2[i] = y2; p.TriZ2[i] = z2;
|
||||
p.TriX3[i] = x3; p.TriY3[i] = y3; p.TriZ3[i] = z3;
|
||||
p.TriColor[i] = colorArgb;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cycle: _pending → _ready → _spare → _pending. The newly-filled buffer
|
||||
/// becomes ready; the old ready becomes spare (idle this tick); the old
|
||||
/// spare becomes the next pending. Render reads of the new ready buffer
|
||||
/// become visible across cores via the volatile field. Called by
|
||||
/// PluginManager.TickAll AFTER all plugins have submitted.
|
||||
/// </summary>
|
||||
public static void CommitFrame()
|
||||
{
|
||||
NavBuffer newReady = _pending;
|
||||
NavBuffer newSpare = _ready;
|
||||
NavBuffer newPending = _spare;
|
||||
_spare = newSpare;
|
||||
_pending = newPending;
|
||||
Volatile.Write(ref _ready, newReady);
|
||||
}
|
||||
|
||||
// ── 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 Nav3DAddRingExCallback(float wx, float wy, float wz, float radius, float thickness, float height, uint color)
|
||||
=> AddRingEx(wx, wy, wz, radius, thickness, height, 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);
|
||||
public static void Nav3DAddTriangleCallback(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint color)
|
||||
=> AddTriangle(x1, y1, z1, x2, y2, z2, x3, y3, z3, color);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,10 +30,19 @@ internal static unsafe class OverlayTextureRenderer
|
|||
private const uint D3DRS_SRCBLEND = 19;
|
||||
private const uint D3DRS_DESTBLEND = 20;
|
||||
private const uint D3DRS_ZENABLE = 7;
|
||||
private const uint D3DRS_ALPHATESTENABLE = 15;
|
||||
private const uint D3DRS_CULLMODE = 22;
|
||||
private const uint D3DRS_LIGHTING = 137;
|
||||
private const uint D3DRS_FOGENABLE = 28;
|
||||
private const uint D3DRS_STENCILENABLE = 52;
|
||||
private const uint D3DRS_COLORWRITEENABLE = 168;
|
||||
private const uint D3DRS_BLENDOP = 171;
|
||||
private const uint D3DRS_SCISSORTESTENABLE = 174;
|
||||
private const uint D3DRS_SRGBWRITEENABLE = 194;
|
||||
private const uint D3DRS_SEPARATEALPHABLENDENABLE = 206;
|
||||
private const uint D3DBLENDOP_ADD = 1;
|
||||
|
||||
private const uint D3DBLEND_ONE = 2;
|
||||
private const uint D3DBLEND_SRCALPHA = 5;
|
||||
private const uint D3DBLEND_INVSRCALPHA = 6;
|
||||
private const uint D3DCULL_NONE = 1;
|
||||
|
|
@ -45,6 +54,7 @@ internal static unsafe class OverlayTextureRenderer
|
|||
private const uint D3DTSS_ALPHAARG1 = 5;
|
||||
private const uint D3DTSS_ALPHAARG2 = 6;
|
||||
|
||||
private const uint D3DTOP_SELECTARG1 = 2;
|
||||
private const uint D3DTOP_MODULATE = 4;
|
||||
private const uint D3DTA_TEXTURE = 2;
|
||||
private const uint D3DTA_DIFFUSE = 0;
|
||||
|
|
@ -88,10 +98,18 @@ internal static unsafe class OverlayTextureRenderer
|
|||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureStageStateD(IntPtr dev, uint stage, uint type, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetTextureStageStateD(IntPtr dev, uint stage, uint type, out uint pValue);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetSamplerStateD(IntPtr dev, uint sampler, uint type, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetSamplerStateD(IntPtr dev, uint sampler, uint type, out uint pValue);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetTextureD(IntPtr dev, uint stage, out IntPtr ppTex);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetFVFD(IntPtr dev, uint fvf);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetFVFD(IntPtr dev, out uint pFvf);
|
||||
[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);
|
||||
|
|
@ -120,8 +138,12 @@ internal static unsafe class OverlayTextureRenderer
|
|||
private static CreateTextureD? _createTexture;
|
||||
private static SetTextureD? _setTexture;
|
||||
private static SetTextureStageStateD? _setTexStageState;
|
||||
private static GetTextureStageStateD? _getTexStageState;
|
||||
private static SetSamplerStateD? _setSamplerState;
|
||||
private static GetSamplerStateD? _getSamplerState;
|
||||
private static GetTextureD? _getTexture;
|
||||
private static SetFVFD? _setFVF;
|
||||
private static GetFVFD? _getFVF;
|
||||
private static SetRenderStateD? _setRenderState;
|
||||
private static GetRenderStateD? _getRenderState;
|
||||
private static SetVertexShaderD? _setVertexShader;
|
||||
|
|
@ -158,6 +180,26 @@ internal static unsafe class OverlayTextureRenderer
|
|||
_delegatesCached = true;
|
||||
}
|
||||
|
||||
// Publish viewport size BEFORE consuming a frame so Avalonia has a non-zero
|
||||
// game-surface size on the very first tick. Without this, the producer waits
|
||||
// for size > 1 (set previously only inside DrawQuad), but DrawQuad doesn't
|
||||
// run until a frame is uploaded — chicken-and-egg when ImGui's Win32Backend
|
||||
// (which also publishes ClientPixelWidth/Height) is disabled.
|
||||
D3DVIEWPORT9 earlyVp;
|
||||
if (_getViewport!(pDevice, &earlyVp) >= 0)
|
||||
{
|
||||
int vw = (int)earlyVp.Width;
|
||||
int vh = (int)earlyVp.Height;
|
||||
if (vw > 1 && vh > 1)
|
||||
{
|
||||
bool changed = AvaloniaOverlay.ViewportWidth != vw || AvaloniaOverlay.ViewportHeight != vh;
|
||||
AvaloniaOverlay.ViewportWidth = vw;
|
||||
AvaloniaOverlay.ViewportHeight = vh;
|
||||
if (changed)
|
||||
AvaloniaOverlay.NotifyGameSurfaceMetricsChanged();
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
|
|
@ -239,23 +281,31 @@ internal static unsafe class OverlayTextureRenderer
|
|||
}
|
||||
|
||||
// Lock → copy → unlock
|
||||
var lockRect = GetTexMethod<TexLockRectD>(_texture, TextureVTableIndex.LockRect);
|
||||
var unlockRect = GetTexMethod<TexUnlockRectD>(_texture, TextureVTableIndex.UnlockRect);
|
||||
// Use raw function pointers (no GC delegate alloc) — Marshal.GetDelegateForFunctionPointer
|
||||
// creates a small heap object per call, which at 60+ FPS hammers the LFH and was bisected
|
||||
// as the cause of a heap-corruption AV in ntdll (write fault at addr ending in FFC).
|
||||
IntPtr texVtbl = Marshal.ReadIntPtr(_texture);
|
||||
var lockRectFn = (delegate* unmanaged[Stdcall]<IntPtr, uint, D3DLOCKED_RECT*, IntPtr, uint, int>)
|
||||
Marshal.ReadIntPtr(texVtbl, TextureVTableIndex.LockRect * IntPtr.Size);
|
||||
var unlockRectFn = (delegate* unmanaged[Stdcall]<IntPtr, uint, int>)
|
||||
Marshal.ReadIntPtr(texVtbl, TextureVTableIndex.UnlockRect * IntPtr.Size);
|
||||
|
||||
D3DLOCKED_RECT locked;
|
||||
if (lockRect(_texture, 0, &locked, IntPtr.Zero, 0) < 0)
|
||||
if (lockRectFn(_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++)
|
||||
fixed (byte* srcBase = pixels)
|
||||
{
|
||||
IntPtr dst = locked.pBits + row * locked.Pitch;
|
||||
fixed (byte* src = pixels)
|
||||
Buffer.MemoryCopy(src + row * srcStride, (void*)dst, srcStride, srcStride);
|
||||
for (int row = 0; row < h; row++)
|
||||
{
|
||||
IntPtr dst = locked.pBits + row * locked.Pitch;
|
||||
Buffer.MemoryCopy(srcBase + row * srcStride, (void*)dst, srcStride, srcStride);
|
||||
}
|
||||
}
|
||||
|
||||
unlockRect(_texture, 0);
|
||||
unlockRectFn(_texture, 0);
|
||||
}
|
||||
|
||||
private static bool TryUseSharedTexture(IntPtr pDevice, string label, OverlaySharedTextureDescriptor descriptor)
|
||||
|
|
@ -367,21 +417,51 @@ internal static unsafe class OverlayTextureRenderer
|
|||
_getRenderState!(pDevice, D3DRS_SRCBLEND, out uint savedSrcBlend);
|
||||
_getRenderState!(pDevice, D3DRS_DESTBLEND, out uint savedDstBlend);
|
||||
_getRenderState!(pDevice, D3DRS_ZENABLE, out uint savedZ);
|
||||
_getRenderState!(pDevice, D3DRS_ALPHATESTENABLE, out uint savedAlphaTest);
|
||||
_getRenderState!(pDevice, D3DRS_CULLMODE, out uint savedCull);
|
||||
_getRenderState!(pDevice, D3DRS_LIGHTING, out uint savedLighting);
|
||||
_getRenderState!(pDevice, D3DRS_FOGENABLE, out uint savedFog);
|
||||
_getRenderState!(pDevice, D3DRS_STENCILENABLE, out uint savedStencil);
|
||||
_getRenderState!(pDevice, D3DRS_COLORWRITEENABLE, out uint savedColorWrite);
|
||||
_getRenderState!(pDevice, D3DRS_BLENDOP, out uint savedBlendOp);
|
||||
_getRenderState!(pDevice, D3DRS_SCISSORTESTENABLE, out uint savedScissor);
|
||||
_getRenderState!(pDevice, D3DRS_SRGBWRITEENABLE, out uint savedSrgb);
|
||||
_getRenderState!(pDevice, D3DRS_SEPARATEALPHABLENDENABLE, out uint savedSeparateAlpha);
|
||||
_getVertexShader!(pDevice, out IntPtr savedVS);
|
||||
_getPixelShader!(pDevice, out IntPtr savedPS);
|
||||
_getFVF!(pDevice, out uint savedFVF);
|
||||
_getTexture!(pDevice, 0, out IntPtr savedTex0);
|
||||
_getTexStageState!(pDevice, 0, D3DTSS_COLOROP, out uint savedTSS_ColorOp);
|
||||
_getTexStageState!(pDevice, 0, D3DTSS_COLORARG1, out uint savedTSS_ColorArg1);
|
||||
_getTexStageState!(pDevice, 0, D3DTSS_COLORARG2, out uint savedTSS_ColorArg2);
|
||||
_getTexStageState!(pDevice, 0, D3DTSS_ALPHAOP, out uint savedTSS_AlphaOp);
|
||||
_getTexStageState!(pDevice, 0, D3DTSS_ALPHAARG1, out uint savedTSS_AlphaArg1);
|
||||
_getTexStageState!(pDevice, 0, D3DTSS_ALPHAARG2, out uint savedTSS_AlphaArg2);
|
||||
_getSamplerState!(pDevice, 0, D3DSAMP_MINFILTER, out uint savedSamp_Min);
|
||||
_getSamplerState!(pDevice, 0, D3DSAMP_MAGFILTER, out uint savedSamp_Mag);
|
||||
|
||||
try
|
||||
{
|
||||
// Set up fixed-function alpha-blended state
|
||||
// Avalonia produces premultiplied BGRA, so the right blend is
|
||||
// ONE / INVSRCALPHA. SRCALPHA would square the alpha and dim the
|
||||
// overlay; ONE matches the premul invariant exactly.
|
||||
_setRenderState!(pDevice, D3DRS_ALPHABLENDENABLE, 1);
|
||||
_setRenderState!(pDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
|
||||
_setRenderState!(pDevice, D3DRS_SRCBLEND, D3DBLEND_ONE);
|
||||
_setRenderState!(pDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
|
||||
_setRenderState!(pDevice, D3DRS_BLENDOP, D3DBLENDOP_ADD);
|
||||
_setRenderState!(pDevice, D3DRS_ZENABLE, 0);
|
||||
_setRenderState!(pDevice, D3DRS_ALPHATESTENABLE, 0);
|
||||
_setRenderState!(pDevice, D3DRS_CULLMODE, D3DCULL_NONE);
|
||||
_setRenderState!(pDevice, D3DRS_LIGHTING, 0);
|
||||
// AC enables fog (often white) for portal-space and dungeon
|
||||
// particle effects; without disabling it our quad gets
|
||||
// fog-blended toward white. Same for scissor (AC clips), stencil
|
||||
// (UI passes), and separate-alpha-blend (would override our blend).
|
||||
_setRenderState!(pDevice, D3DRS_FOGENABLE, 0);
|
||||
_setRenderState!(pDevice, D3DRS_STENCILENABLE, 0);
|
||||
_setRenderState!(pDevice, D3DRS_SCISSORTESTENABLE, 0);
|
||||
_setRenderState!(pDevice, D3DRS_SRGBWRITEENABLE, 0);
|
||||
_setRenderState!(pDevice, D3DRS_SEPARATEALPHABLENDENABLE, 0);
|
||||
_setRenderState!(pDevice, D3DRS_COLORWRITEENABLE, 0xF);
|
||||
|
||||
_setVertexShader!(pDevice, IntPtr.Zero);
|
||||
|
|
@ -390,40 +470,68 @@ internal static unsafe class OverlayTextureRenderer
|
|||
_setFVF!(pDevice, FVF);
|
||||
_setTexture!(pDevice, 0, _texture);
|
||||
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_COLOROP, D3DTOP_MODULATE);
|
||||
// Use SELECTARG1 (texture only) instead of MODULATE so a stale
|
||||
// per-vertex DIFFUSE left over from ImGui's previous DrawPrimitiveUP
|
||||
// call can't tint the overlay — our FVF doesn't include DIFFUSE,
|
||||
// making its value undefined under MODULATE.
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
|
||||
_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_ALPHAOP, D3DTOP_SELECTARG1);
|
||||
_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);
|
||||
// POINT filter is crisper than LINEAR when the texture and the
|
||||
// target backbuffer have the same dimensions — each output pixel
|
||||
// maps to exactly one texel, so we don't want any blending.
|
||||
_setSamplerState!(pDevice, 0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
|
||||
_setSamplerState!(pDevice, 0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
|
||||
|
||||
// D3D9 half-texel offset: pixel centers are at integer + 0.5, but
|
||||
// texel coords are at integer indexes. Without -0.5 vertex offset,
|
||||
// each output pixel samples *between* two texels, blending them
|
||||
// (visible blur even with POINT filter due to rasterization rules).
|
||||
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 };
|
||||
verts[0] = new QuadVertex { X = -0.5f, Y = -0.5f, Z = 0, RHW = 1, U = 0, V = 0 };
|
||||
verts[1] = new QuadVertex { X = W - 0.5f, Y = -0.5f, Z = 0, RHW = 1, U = 1, V = 0 };
|
||||
verts[2] = new QuadVertex { X = -0.5f, Y = H - 0.5f, Z = 0, RHW = 1, U = 0, V = 1 };
|
||||
verts[3] = new QuadVertex { X = W - 0.5f, Y = H - 0.5f, Z = 0, RHW = 1, U = 1, V = 1 };
|
||||
|
||||
_drawPrimitiveUP!(pDevice, D3DPT_TRIANGLESTRIP, 2,
|
||||
new IntPtr(verts), (uint)sizeof(QuadVertex));
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Restore changed state
|
||||
// Restore changed state. Anything we touched must be put back —
|
||||
// AC re-enters EndScene mid-frame for additional passes (post-fx,
|
||||
// particles, fog) and inherits whatever device state we left.
|
||||
_setRenderState!(pDevice, D3DRS_ALPHABLENDENABLE, savedAlpha);
|
||||
_setRenderState!(pDevice, D3DRS_SRCBLEND, savedSrcBlend);
|
||||
_setRenderState!(pDevice, D3DRS_DESTBLEND, savedDstBlend);
|
||||
_setRenderState!(pDevice, D3DRS_BLENDOP, savedBlendOp);
|
||||
_setRenderState!(pDevice, D3DRS_ZENABLE, savedZ);
|
||||
_setRenderState!(pDevice, D3DRS_ALPHATESTENABLE, savedAlphaTest);
|
||||
_setRenderState!(pDevice, D3DRS_CULLMODE, savedCull);
|
||||
_setRenderState!(pDevice, D3DRS_LIGHTING, savedLighting);
|
||||
_setRenderState!(pDevice, D3DRS_FOGENABLE, savedFog);
|
||||
_setRenderState!(pDevice, D3DRS_STENCILENABLE, savedStencil);
|
||||
_setRenderState!(pDevice, D3DRS_SCISSORTESTENABLE, savedScissor);
|
||||
_setRenderState!(pDevice, D3DRS_SRGBWRITEENABLE, savedSrgb);
|
||||
_setRenderState!(pDevice, D3DRS_SEPARATEALPHABLENDENABLE, savedSeparateAlpha);
|
||||
_setRenderState!(pDevice, D3DRS_COLORWRITEENABLE, savedColorWrite);
|
||||
_setVertexShader!(pDevice, savedVS);
|
||||
_setPixelShader!(pDevice, savedPS);
|
||||
_setTexture!(pDevice, 0, IntPtr.Zero);
|
||||
_setFVF!(pDevice, savedFVF);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_COLOROP, savedTSS_ColorOp);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_COLORARG1, savedTSS_ColorArg1);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_COLORARG2, savedTSS_ColorArg2);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAOP, savedTSS_AlphaOp);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAARG1, savedTSS_AlphaArg1);
|
||||
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAARG2, savedTSS_AlphaArg2);
|
||||
_setSamplerState!(pDevice, 0, D3DSAMP_MINFILTER, savedSamp_Min);
|
||||
_setSamplerState!(pDevice, 0, D3DSAMP_MAGFILTER, savedSamp_Mag);
|
||||
_setTexture!(pDevice, 0, savedTex0);
|
||||
|
||||
if (savedVS != IntPtr.Zero) ReleaseComObject(savedVS);
|
||||
if (savedPS != IntPtr.Zero) ReleaseComObject(savedPS);
|
||||
if (savedTex0 != IntPtr.Zero) ReleaseComObject(savedTex0);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -434,7 +542,9 @@ internal static unsafe class OverlayTextureRenderer
|
|||
if (_texture == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
var release = GetTexMethod<ReleaseD>(_texture, TextureVTableIndex.Release);
|
||||
IntPtr texVtbl = Marshal.ReadIntPtr(_texture);
|
||||
var release = (delegate* unmanaged[Stdcall]<IntPtr, uint>)
|
||||
Marshal.ReadIntPtr(texVtbl, TextureVTableIndex.Release * IntPtr.Size);
|
||||
release(_texture);
|
||||
_texture = IntPtr.Zero;
|
||||
_sharedTextureHandle = IntPtr.Zero;
|
||||
|
|
@ -446,8 +556,9 @@ internal static unsafe class OverlayTextureRenderer
|
|||
{
|
||||
if (pObj == IntPtr.Zero) return;
|
||||
IntPtr vtbl = Marshal.ReadIntPtr(pObj);
|
||||
var rel = Marshal.GetDelegateForFunctionPointer<ReleaseD>(
|
||||
Marshal.ReadIntPtr(vtbl, 2 * IntPtr.Size));
|
||||
// Raw function pointer — avoids GC delegate alloc on every per-frame Release.
|
||||
var rel = (delegate* unmanaged[Stdcall]<IntPtr, uint>)
|
||||
Marshal.ReadIntPtr(vtbl, 2 * IntPtr.Size);
|
||||
rel(pObj);
|
||||
}
|
||||
|
||||
|
|
@ -456,9 +567,13 @@ internal static unsafe class OverlayTextureRenderer
|
|||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
_createTexture = Get<CreateTextureD>(vtable, DeviceVTableIndex.CreateTexture);
|
||||
_setTexture = Get<SetTextureD>(vtable, DeviceVTableIndex.SetTexture);
|
||||
_getTexture = Get<GetTextureD>(vtable, DeviceVTableIndex.GetTexture);
|
||||
_setTexStageState = Get<SetTextureStageStateD>(vtable, DeviceVTableIndex.SetTextureStageState);
|
||||
_getTexStageState = Get<GetTextureStageStateD>(vtable, DeviceVTableIndex.GetTextureStageState);
|
||||
_setSamplerState = Get<SetSamplerStateD>(vtable, DeviceVTableIndex.SetSamplerState);
|
||||
_getSamplerState = Get<GetSamplerStateD>(vtable, DeviceVTableIndex.GetSamplerState);
|
||||
_setFVF = Get<SetFVFD>(vtable, DeviceVTableIndex.SetFVF);
|
||||
_getFVF = Get<GetFVFD>(vtable, DeviceVTableIndex.GetFVF);
|
||||
_setRenderState = Get<SetRenderStateD>(vtable, DeviceVTableIndex.SetRenderState);
|
||||
_getRenderState = Get<GetRenderStateD>(vtable, DeviceVTableIndex.GetRenderState);
|
||||
_setVertexShader = Get<SetVertexShaderD>(vtable, DeviceVTableIndex.SetVertexShader);
|
||||
|
|
|
|||
706
src/RynthCore.Engine/D3D9/VitalHud.cs
Normal file
706
src/RynthCore.Engine/D3D9/VitalHud.cs
Normal file
|
|
@ -0,0 +1,706 @@
|
|||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// RynthCore.Engine — D3D9/VitalHud.cs
|
||||
//
|
||||
// "Hot HUD" — draws player Health / Stamina / Mana bars directly in the D3D9
|
||||
// EndScene path, on AC's render thread, every frame. Ported from RynthCore2's
|
||||
// overlay/hud_overlay.cpp; the D3D9 plumbing mirrors TestRenderer.cs (cached
|
||||
// vtable delegates + full render-state save/restore).
|
||||
//
|
||||
// Visuals: a translucent panel with a drop shadow, three gradient-filled bars
|
||||
// (track + fill + gloss + border) with an HP/STAM/MANA label and a right-
|
||||
// aligned "cur/max" number drawn from the dependency-free BitmapFont.
|
||||
// Everything is colored 2D quads (D3DFVF_XYZRHW | D3DFVF_DIFFUSE, no texture)
|
||||
// accumulated into one static vertex batch flushed with a single
|
||||
// DrawPrimitiveUP — no per-frame heap allocation (avoids the LFH per-frame-
|
||||
// alloc AV class).
|
||||
//
|
||||
// Interactive: drag the panel to move it, drag the bottom-right grip to resize.
|
||||
// Win32Backend routes mouse messages to TryHandleMouse, which consumes the ones
|
||||
// that land on the HUD so they never reach AC (no stray camera spin). Position +
|
||||
// scale persist to %APPDATA%\RynthCore\vitalhud.cfg.
|
||||
//
|
||||
// Data source: Compatibility.PlayerVitalsHooks.TryGetSnapshot — the same
|
||||
// buffed-effective values AC's own bars render, maintained on AC's main thread.
|
||||
// Draw and TryHandleMouse both run on that thread (EndScene / WndProc), so the
|
||||
// shared geometry state needs no cross-thread synchronization.
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
using RynthCore.Engine.Plugins;
|
||||
|
||||
namespace RynthCore.Engine.D3D9;
|
||||
|
||||
internal static unsafe class VitalHud
|
||||
{
|
||||
// ─── D3D9 constants ───────────────────────────────────────────────
|
||||
private const uint D3DFVF_XYZRHW = 0x0004;
|
||||
private const uint D3DFVF_DIFFUSE = 0x0040;
|
||||
private const uint HudFvf = D3DFVF_XYZRHW | D3DFVF_DIFFUSE;
|
||||
|
||||
private const uint D3DPT_TRIANGLELIST = 4;
|
||||
|
||||
// D3DRENDERSTATETYPE
|
||||
private const uint D3DRS_ZENABLE = 7;
|
||||
private const uint D3DRS_ZWRITEENABLE = 14;
|
||||
private const uint D3DRS_ALPHATESTENABLE = 15;
|
||||
private const uint D3DRS_SRCBLEND = 19;
|
||||
private const uint D3DRS_DESTBLEND = 20;
|
||||
private const uint D3DRS_CULLMODE = 22;
|
||||
private const uint D3DRS_ALPHABLENDENABLE = 27;
|
||||
private const uint D3DRS_FOGENABLE = 28;
|
||||
private const uint D3DRS_STENCILENABLE = 52;
|
||||
private const uint D3DRS_LIGHTING = 137;
|
||||
private const uint D3DRS_COLORWRITEENABLE = 168;
|
||||
private const uint D3DRS_BLENDOP = 171;
|
||||
private const uint D3DRS_SCISSORTESTENABLE = 174;
|
||||
|
||||
// D3DTEXTURESTAGESTATETYPE
|
||||
private const uint D3DTSS_COLOROP = 1;
|
||||
private const uint D3DTSS_COLORARG1 = 2;
|
||||
private const uint D3DTSS_ALPHAOP = 4;
|
||||
private const uint D3DTSS_ALPHAARG1 = 6;
|
||||
|
||||
// values
|
||||
private const uint D3DBLEND_SRCALPHA = 5;
|
||||
private const uint D3DBLEND_INVSRCALPHA = 6;
|
||||
private const uint D3DBLENDOP_ADD = 1;
|
||||
private const uint D3DCULL_NONE = 1;
|
||||
private const uint D3DTOP_DISABLE = 1;
|
||||
private const uint D3DTOP_SELECTARG1 = 2;
|
||||
private const uint D3DTA_DIFFUSE = 0;
|
||||
|
||||
// ─── Win32 messages + capture P/Invoke ────────────────────────────
|
||||
private const uint WM_LBUTTONDOWN = 0x0201;
|
||||
private const uint WM_LBUTTONUP = 0x0202;
|
||||
private const uint WM_MOUSEMOVE = 0x0200;
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr SetCapture(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool ReleaseCapture();
|
||||
|
||||
// ─── Vertex ───────────────────────────────────────────────────────
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct Vertex
|
||||
{
|
||||
public float X, Y, Z, Rhw;
|
||||
public uint Color; // ARGB
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct D3DVIEWPORT9
|
||||
{
|
||||
public uint X, Y, Width, Height;
|
||||
public float MinZ, MaxZ;
|
||||
}
|
||||
|
||||
// ─── Device method delegates (COM/stdcall) ────────────────────────
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetRenderStateDelegate(IntPtr dev, uint state, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetRenderStateDelegate(IntPtr dev, uint state, out uint pValue);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureStageStateDelegate(IntPtr dev, uint stage, uint type, uint value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetTextureStageStateDelegate(IntPtr dev, uint stage, uint type, out uint pValue);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetTextureDelegate(IntPtr dev, uint stage, IntPtr pTexture);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetTextureDelegate(IntPtr dev, uint stage, out IntPtr ppTexture);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetFVFDelegate(IntPtr dev, uint fvf);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetFVFDelegate(IntPtr dev, out uint fvf);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetVertexShaderDelegate(IntPtr dev, IntPtr pShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetVertexShaderDelegate(IntPtr dev, out IntPtr ppShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int SetPixelShaderDelegate(IntPtr dev, IntPtr pShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetPixelShaderDelegate(IntPtr dev, out IntPtr ppShader);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int DrawPrimitiveUPDelegate(IntPtr dev, uint primitiveType, uint primitiveCount, IntPtr pData, uint stride);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate int GetViewportDelegate(IntPtr dev, out D3DVIEWPORT9 vp);
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
private delegate uint ReleaseComDelegate(IntPtr pUnk);
|
||||
|
||||
private static SetRenderStateDelegate? _setRenderState;
|
||||
private static GetRenderStateDelegate? _getRenderState;
|
||||
private static SetTextureStageStateDelegate? _setTextureStageState;
|
||||
private static GetTextureStageStateDelegate? _getTextureStageState;
|
||||
private static SetTextureDelegate? _setTexture;
|
||||
private static GetTextureDelegate? _getTexture;
|
||||
private static SetFVFDelegate? _setFVF;
|
||||
private static GetFVFDelegate? _getFVF;
|
||||
private static SetVertexShaderDelegate? _setVertexShader;
|
||||
private static GetVertexShaderDelegate? _getVertexShader;
|
||||
private static SetPixelShaderDelegate? _setPixelShader;
|
||||
private static GetPixelShaderDelegate? _getPixelShader;
|
||||
private static DrawPrimitiveUPDelegate? _drawPrimitiveUP;
|
||||
private static GetViewportDelegate? _getViewport;
|
||||
private static bool _delegatesCached;
|
||||
|
||||
// ─── Geometry / interaction state (AC main thread only) ───────────
|
||||
private const float MinScale = 0.6f;
|
||||
private const float MaxScale = 2.5f;
|
||||
|
||||
private static float _hudX = 16f, _hudY = 16f, _scale = 1f;
|
||||
private static float _vpW, _vpH; // last viewport, for input clamp
|
||||
private static bool _geomInit;
|
||||
private static bool _firstDrawLogged;
|
||||
|
||||
private static int _dragMode; // 0 none, 1 move, 2 resize
|
||||
private static float _grabDX, _grabDY;
|
||||
private static float _resizeStartScale = 1f, _resizeStartDist = 1f;
|
||||
|
||||
/// <summary>True while the user is dragging or resizing the HUD. Win32Backend
|
||||
/// keeps routing mouse messages to <see cref="TryHandleMouse"/> while set.</summary>
|
||||
public static bool IsDragging => _dragMode != 0;
|
||||
|
||||
// ─── Vertex batch (single static buffer; no per-frame heap alloc) ──
|
||||
// Text is the big consumer — the outline pass below draws each number 9×.
|
||||
private const int MaxVerts = 48000;
|
||||
private static readonly Vertex[] _batch = new Vertex[MaxVerts];
|
||||
private static int _batchCount;
|
||||
|
||||
// Cached text sink + color so BitmapFont.Emit allocates nothing per call.
|
||||
private static readonly BitmapFont.CellSink _cellSink = TextCell;
|
||||
private static uint _textColor;
|
||||
|
||||
// ─── Layout derived from the uniform scale ────────────────────────
|
||||
private struct Metrics
|
||||
{
|
||||
public float Scale, Pad, BarW, BarH, Gap, PanelW, PanelH, Grip;
|
||||
}
|
||||
|
||||
private static Metrics Metric(float s)
|
||||
{
|
||||
if (s < MinScale) s = MinScale;
|
||||
if (s > MaxScale) s = MaxScale;
|
||||
Metrics m;
|
||||
m.Scale = s;
|
||||
m.Pad = 8f * s;
|
||||
m.BarW = 228f * s; // wide enough for a big "cur/max" number
|
||||
m.BarH = 26f * s; // taller bars → bigger, retail-legible numbers
|
||||
m.Gap = 6f * s;
|
||||
m.PanelW = m.Pad * 2f + m.BarW;
|
||||
m.PanelH = m.Pad * 2f + m.BarH * 3f + m.Gap * 2f;
|
||||
m.Grip = 16f * s;
|
||||
return m;
|
||||
}
|
||||
|
||||
// ─── Color helpers ────────────────────────────────────────────────
|
||||
private static uint Argb(int a, int r, int g, int b)
|
||||
=> ((uint)a << 24) | ((uint)r << 16) | ((uint)g << 8) | (uint)b;
|
||||
|
||||
private static uint Lighten(uint c, int add)
|
||||
{
|
||||
static int Cl(int v) => v < 0 ? 0 : (v > 255 ? 255 : v);
|
||||
int a = (int)((c >> 24) & 0xFF);
|
||||
int r = (int)((c >> 16) & 0xFF);
|
||||
int g = (int)((c >> 8) & 0xFF);
|
||||
int b = (int)(c & 0xFF);
|
||||
return Argb(a, Cl(r + add), Cl(g + add), Cl(b + add));
|
||||
}
|
||||
|
||||
// ─── Batch builders ───────────────────────────────────────────────
|
||||
private static void BatchReset() => _batchCount = 0;
|
||||
|
||||
private static void PushQuad(float x0, float y0, float x1, float y1,
|
||||
uint cTL, uint cTR, uint cBR, uint cBL)
|
||||
{
|
||||
if (_batchCount + 6 > MaxVerts) return;
|
||||
Set(ref _batch[_batchCount + 0], x0, y0, cTL);
|
||||
Set(ref _batch[_batchCount + 1], x1, y0, cTR);
|
||||
Set(ref _batch[_batchCount + 2], x1, y1, cBR);
|
||||
Set(ref _batch[_batchCount + 3], x0, y0, cTL);
|
||||
Set(ref _batch[_batchCount + 4], x1, y1, cBR);
|
||||
Set(ref _batch[_batchCount + 5], x0, y1, cBL);
|
||||
_batchCount += 6;
|
||||
|
||||
static void Set(ref Vertex v, float x, float y, uint c)
|
||||
{
|
||||
v.X = x; v.Y = y; v.Z = 0f; v.Rhw = 1f; v.Color = c;
|
||||
}
|
||||
}
|
||||
|
||||
private static void PushRect(float x0, float y0, float x1, float y1, uint c)
|
||||
=> PushQuad(x0, y0, x1, y1, c, c, c, c);
|
||||
|
||||
private static void PushVGrad(float x0, float y0, float x1, float y1, uint top, uint bot)
|
||||
=> PushQuad(x0, y0, x1, y1, top, top, bot, bot);
|
||||
|
||||
// ─── Text → batched quads via the bitmap font ─────────────────────
|
||||
private static void TextCell(int x0, int y0, int x1, int y1)
|
||||
=> PushRect(x0, y0, x1, y1, _textColor);
|
||||
|
||||
// Draws text with a full dark outline (all 8 neighbour offsets) then the
|
||||
// foreground on top, so it stays legible over any bar fill color — the
|
||||
// single drop-shadow was washed out on the light (yellow) bar.
|
||||
private static void DrawText(ReadOnlySpan<char> s, int x, int y, int cellPx, uint color)
|
||||
{
|
||||
int o = cellPx >= 4 ? 2 : 1; // outline thickness in px
|
||||
_textColor = Argb(235, 0, 0, 0);
|
||||
BitmapFont.Emit(s, x - o, y - o, cellPx, _cellSink);
|
||||
BitmapFont.Emit(s, x, y - o, cellPx, _cellSink);
|
||||
BitmapFont.Emit(s, x + o, y - o, cellPx, _cellSink);
|
||||
BitmapFont.Emit(s, x - o, y, cellPx, _cellSink);
|
||||
BitmapFont.Emit(s, x + o, y, cellPx, _cellSink);
|
||||
BitmapFont.Emit(s, x - o, y + o, cellPx, _cellSink);
|
||||
BitmapFont.Emit(s, x, y + o, cellPx, _cellSink);
|
||||
BitmapFont.Emit(s, x + o, y + o, cellPx, _cellSink);
|
||||
_textColor = color;
|
||||
BitmapFont.Emit(s, x, y, cellPx, _cellSink);
|
||||
}
|
||||
|
||||
// "cur/max" formatted into the caller's buffer without allocating; returns
|
||||
// the number of chars written (≤ buf.Length).
|
||||
private static int FormatVital(uint cur, uint mx, Span<char> buf)
|
||||
{
|
||||
int len = 0;
|
||||
if (cur.TryFormat(buf, out int w1)) len += w1;
|
||||
if (len < buf.Length) buf[len++] = '/';
|
||||
if (mx.TryFormat(buf.Slice(len), out int w2)) len += w2;
|
||||
return len;
|
||||
}
|
||||
|
||||
private static void EmitBar(float x, float y, in Metrics m,
|
||||
uint cur, uint mx, uint baseColor)
|
||||
{
|
||||
float w = m.BarW, h = m.BarH;
|
||||
|
||||
PushRect(x, y, x + w, y + h, Argb(205, 18, 20, 26)); // track
|
||||
|
||||
if (mx > 0)
|
||||
{
|
||||
float ratio = (float)cur / mx;
|
||||
if (ratio < 0f) ratio = 0f;
|
||||
if (ratio > 1f) ratio = 1f;
|
||||
float fw = w * ratio;
|
||||
PushVGrad(x, y, x + fw, y + h, Lighten(baseColor, 55), baseColor); // fill
|
||||
PushRect(x, y, x + fw, y + h * 0.32f, Argb(60, 255, 255, 255)); // gloss
|
||||
}
|
||||
|
||||
float bw = m.Scale >= 1.5f ? 2f : 1f; // border
|
||||
uint bc = Argb(180, 90, 100, 120);
|
||||
PushRect(x, y, x + w, y + bw, bc);
|
||||
PushRect(x, y + h - bw, x + w, y + h, bc);
|
||||
PushRect(x, y, x + bw, y + h, bc);
|
||||
PushRect(x + w - bw, y, x + w, y + h, bc);
|
||||
|
||||
// Number only (no label — the red/yellow/blue color identifies the bar).
|
||||
// Sized as large as fits the bar, centered, with a dark outline so it
|
||||
// reads clearly over any fill color (especially white-on-yellow).
|
||||
Span<char> numBuf = stackalloc char[24];
|
||||
ReadOnlySpan<char> num = numBuf[..FormatVital(cur, mx, numBuf)];
|
||||
|
||||
int innerPad = (int)(m.Pad * 0.4f);
|
||||
if (innerPad < 2) innerPad = 2;
|
||||
int availW = (int)w - 2 * innerPad;
|
||||
|
||||
int cellPx = (int)(h * 0.82f / BitmapFont.GlyphH); // tallest that fits the bar
|
||||
if (cellPx < 1) cellPx = 1;
|
||||
while (cellPx > 1 && BitmapFont.MeasureWidth(num, cellPx) > availW) cellPx--;
|
||||
|
||||
int tw = BitmapFont.MeasureWidth(num, cellPx);
|
||||
int th = BitmapFont.Height(cellPx);
|
||||
int tx = (int)(x + (w - tw) * 0.5f); // center horizontally
|
||||
int ty = (int)(y + (h - th) * 0.5f); // center vertically
|
||||
DrawText(num, tx, ty, cellPx, Argb(255, 245, 250, 255));
|
||||
}
|
||||
|
||||
// ─── Public API ───────────────────────────────────────────────────
|
||||
public static void Draw(IntPtr pDevice)
|
||||
{
|
||||
if (pDevice == IntPtr.Zero) return;
|
||||
if (!PlayerVitalsHooks.TryGetSnapshot(out PlayerVitalsSnapshot snap)) return;
|
||||
|
||||
if (!_delegatesCached)
|
||||
CacheDelegates(pDevice);
|
||||
if (_drawPrimitiveUP == null) return; // delegate cache failed
|
||||
|
||||
if (_getViewport!(pDevice, out D3DVIEWPORT9 vp) < 0) return;
|
||||
float wF = vp.Width;
|
||||
float hF = vp.Height;
|
||||
if (wF < 1f || hF < 1f) return;
|
||||
|
||||
if (!_firstDrawLogged)
|
||||
{
|
||||
_firstDrawLogged = true;
|
||||
RynthLog.D3D9("VitalHud: first draw.");
|
||||
}
|
||||
|
||||
// First-draw placement: prefer the saved config, else default top-right.
|
||||
if (!_geomInit)
|
||||
{
|
||||
_geomInit = true;
|
||||
if (LoadCfg(out float lx, out float ly, out float ls))
|
||||
{
|
||||
_scale = ls; _hudX = lx; _hudY = ly;
|
||||
}
|
||||
else
|
||||
{
|
||||
_scale = 1f;
|
||||
Metrics dm = Metric(1f);
|
||||
_hudX = wF - dm.PanelW - 16f;
|
||||
_hudY = 16f;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Save the device state we are about to clobber ──────────────
|
||||
_getRenderState!(pDevice, D3DRS_ZENABLE, out uint svZE);
|
||||
_getRenderState(pDevice, D3DRS_ZWRITEENABLE, out uint svZWE);
|
||||
_getRenderState(pDevice, D3DRS_ALPHATESTENABLE, out uint svATE);
|
||||
_getRenderState(pDevice, D3DRS_ALPHABLENDENABLE, out uint svABE);
|
||||
_getRenderState(pDevice, D3DRS_SRCBLEND, out uint svSB);
|
||||
_getRenderState(pDevice, D3DRS_DESTBLEND, out uint svDB);
|
||||
_getRenderState(pDevice, D3DRS_BLENDOP, out uint svBO);
|
||||
_getRenderState(pDevice, D3DRS_CULLMODE, out uint svCull);
|
||||
_getRenderState(pDevice, D3DRS_LIGHTING, out uint svLit);
|
||||
_getRenderState(pDevice, D3DRS_FOGENABLE, out uint svFog);
|
||||
_getRenderState(pDevice, D3DRS_STENCILENABLE, out uint svSte);
|
||||
_getRenderState(pDevice, D3DRS_SCISSORTESTENABLE, out uint svSci);
|
||||
_getRenderState(pDevice, D3DRS_COLORWRITEENABLE, out uint svCW);
|
||||
_getFVF!(pDevice, out uint svFvf);
|
||||
|
||||
_getTextureStageState!(pDevice, 0, D3DTSS_COLOROP, out uint svT0CO);
|
||||
_getTextureStageState(pDevice, 0, D3DTSS_COLORARG1, out uint svT0CA1);
|
||||
_getTextureStageState(pDevice, 0, D3DTSS_ALPHAOP, out uint svT0AO);
|
||||
_getTextureStageState(pDevice, 0, D3DTSS_ALPHAARG1, out uint svT0AA1);
|
||||
_getTextureStageState(pDevice, 1, D3DTSS_COLOROP, out uint svT1CO);
|
||||
|
||||
_getVertexShader!(pDevice, out IntPtr svVS);
|
||||
_getPixelShader!(pDevice, out IntPtr svPS);
|
||||
_getTexture!(pDevice, 0, out IntPtr svTex0);
|
||||
|
||||
try
|
||||
{
|
||||
// ── Set HUD state: 2D, alpha-blended, colored verts, no tex/shaders ──
|
||||
_setRenderState!(pDevice, D3DRS_ZENABLE, 0);
|
||||
_setRenderState(pDevice, D3DRS_ZWRITEENABLE, 0);
|
||||
_setRenderState(pDevice, D3DRS_ALPHATESTENABLE, 0);
|
||||
_setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, 1);
|
||||
_setRenderState(pDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
|
||||
_setRenderState(pDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
|
||||
_setRenderState(pDevice, D3DRS_BLENDOP, D3DBLENDOP_ADD);
|
||||
_setRenderState(pDevice, D3DRS_CULLMODE, D3DCULL_NONE);
|
||||
_setRenderState(pDevice, D3DRS_LIGHTING, 0);
|
||||
_setRenderState(pDevice, D3DRS_FOGENABLE, 0);
|
||||
_setRenderState(pDevice, D3DRS_STENCILENABLE, 0);
|
||||
_setRenderState(pDevice, D3DRS_SCISSORTESTENABLE, 0);
|
||||
_setRenderState(pDevice, D3DRS_COLORWRITEENABLE, 0xF);
|
||||
|
||||
_setTextureStageState!(pDevice, 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
|
||||
_setTextureStageState(pDevice, 0, D3DTSS_COLORARG1, D3DTA_DIFFUSE);
|
||||
_setTextureStageState(pDevice, 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
|
||||
_setTextureStageState(pDevice, 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE);
|
||||
_setTextureStageState(pDevice, 1, D3DTSS_COLOROP, D3DTOP_DISABLE);
|
||||
|
||||
_setTexture!(pDevice, 0, IntPtr.Zero);
|
||||
_setVertexShader!(pDevice, IntPtr.Zero);
|
||||
_setPixelShader!(pDevice, IntPtr.Zero);
|
||||
_setFVF!(pDevice, HudFvf);
|
||||
|
||||
BuildBatch(in snap, wF, hF);
|
||||
|
||||
if (_batchCount >= 3)
|
||||
{
|
||||
fixed (Vertex* p = _batch)
|
||||
{
|
||||
_drawPrimitiveUP(pDevice, D3DPT_TRIANGLELIST,
|
||||
(uint)(_batchCount / 3), (IntPtr)p, (uint)sizeof(Vertex));
|
||||
}
|
||||
}
|
||||
|
||||
_vpW = wF; // for input hit-test clamping
|
||||
_vpH = hF;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// ── Restore the saved state ────────────────────────────────
|
||||
_setRenderState!(pDevice, D3DRS_ZENABLE, svZE);
|
||||
_setRenderState(pDevice, D3DRS_ZWRITEENABLE, svZWE);
|
||||
_setRenderState(pDevice, D3DRS_ALPHATESTENABLE, svATE);
|
||||
_setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, svABE);
|
||||
_setRenderState(pDevice, D3DRS_SRCBLEND, svSB);
|
||||
_setRenderState(pDevice, D3DRS_DESTBLEND, svDB);
|
||||
_setRenderState(pDevice, D3DRS_BLENDOP, svBO);
|
||||
_setRenderState(pDevice, D3DRS_CULLMODE, svCull);
|
||||
_setRenderState(pDevice, D3DRS_LIGHTING, svLit);
|
||||
_setRenderState(pDevice, D3DRS_FOGENABLE, svFog);
|
||||
_setRenderState(pDevice, D3DRS_STENCILENABLE, svSte);
|
||||
_setRenderState(pDevice, D3DRS_SCISSORTESTENABLE, svSci);
|
||||
_setRenderState(pDevice, D3DRS_COLORWRITEENABLE, svCW);
|
||||
|
||||
_setTextureStageState!(pDevice, 0, D3DTSS_COLOROP, svT0CO);
|
||||
_setTextureStageState(pDevice, 0, D3DTSS_COLORARG1, svT0CA1);
|
||||
_setTextureStageState(pDevice, 0, D3DTSS_ALPHAOP, svT0AO);
|
||||
_setTextureStageState(pDevice, 0, D3DTSS_ALPHAARG1, svT0AA1);
|
||||
_setTextureStageState(pDevice, 1, D3DTSS_COLOROP, svT1CO);
|
||||
|
||||
_setFVF!(pDevice, svFvf);
|
||||
_setVertexShader!(pDevice, svVS);
|
||||
_setPixelShader!(pDevice, svPS);
|
||||
_setTexture!(pDevice, 0, svTex0);
|
||||
|
||||
// GetVertexShader / GetPixelShader / GetTexture each AddRef — release.
|
||||
ReleaseCom(svVS);
|
||||
ReleaseCom(svPS);
|
||||
ReleaseCom(svTex0);
|
||||
}
|
||||
}
|
||||
|
||||
private static void BuildBatch(in PlayerVitalsSnapshot snap, float wF, float hF)
|
||||
{
|
||||
Metrics m = Metric(_scale);
|
||||
float px = _hudX;
|
||||
float py = _hudY;
|
||||
if (px > wF - m.PanelW) px = wF - m.PanelW; // keep on-screen (draw-only)
|
||||
if (py > hF - m.PanelH) py = hF - m.PanelH;
|
||||
if (px < 0f) px = 0f;
|
||||
if (py < 0f) py = 0f;
|
||||
|
||||
BatchReset();
|
||||
|
||||
float so = 5f * m.Scale; // shadow
|
||||
PushRect(px + so, py + so, px + m.PanelW + so, py + m.PanelH + so, Argb(110, 0, 0, 0));
|
||||
PushVGrad(px, py, px + m.PanelW, py + m.PanelH, // backing
|
||||
Argb(205, 28, 30, 38), Argb(205, 16, 17, 22));
|
||||
PushRect(px, py, px + m.PanelW, py + m.Pad * 0.6f, Argb(45, 255, 255, 255)); // header hint
|
||||
|
||||
float pbw = m.Scale >= 1.5f ? 2f : 1f; // panel border
|
||||
uint pbc = Argb(200, 120, 130, 150);
|
||||
PushRect(px, py, px + m.PanelW, py + pbw, pbc);
|
||||
PushRect(px, py + m.PanelH - pbw, px + m.PanelW, py + m.PanelH, pbc);
|
||||
PushRect(px, py, px + pbw, py + m.PanelH, pbc);
|
||||
PushRect(px + m.PanelW - pbw, py, px + m.PanelW, py + m.PanelH, pbc);
|
||||
|
||||
float bx = px + m.Pad;
|
||||
float by = py + m.Pad;
|
||||
EmitBar(bx, by, in m, snap.Health, snap.MaxHealth, Argb(235, 200, 45, 45));
|
||||
by += m.BarH + m.Gap;
|
||||
EmitBar(bx, by, in m, snap.Stamina, snap.MaxStamina, Argb(235, 205, 170, 45));
|
||||
by += m.BarH + m.Gap;
|
||||
EmitBar(bx, by, in m, snap.Mana, snap.MaxMana, Argb(235, 55, 115, 235));
|
||||
|
||||
// resize grip (three dots) bottom-right
|
||||
float d = 3f * m.Scale;
|
||||
if (d < 2f) d = 2f;
|
||||
float gx = px + m.PanelW - m.Pad * 0.5f;
|
||||
float gy = py + m.PanelH - m.Pad * 0.5f;
|
||||
uint gc = Argb(200, 200, 205, 215);
|
||||
for (int i = 1; i <= 3; i++)
|
||||
{
|
||||
float ox = gx - i * (d + 1f);
|
||||
float oy = gy - i * (d + 1f);
|
||||
PushRect(ox, oy, ox + d, oy + d, gc);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Input ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Handles left-button drag (anywhere on the panel) + grip resize. Returns
|
||||
/// true when the message landed on the HUD and should be swallowed so it
|
||||
/// never reaches AC. Called from Win32Backend.WndProcHook on AC's main
|
||||
/// thread, before the Avalonia forward. No-op (returns false) when the HUD
|
||||
/// is not being drawn.
|
||||
/// </summary>
|
||||
public static bool TryHandleMouse(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
|
||||
{
|
||||
if (!_geomInit || !EngineSettings.DrawCustomVitalBars)
|
||||
return false;
|
||||
|
||||
switch (msg)
|
||||
{
|
||||
case WM_LBUTTONDOWN:
|
||||
{
|
||||
float mxf = (short)((long)lParam & 0xFFFF);
|
||||
float myf = (short)(((long)lParam >> 16) & 0xFFFF);
|
||||
Metrics m = Metric(_scale);
|
||||
|
||||
// Clamp the same way Draw does so the hit-test matches the pixels.
|
||||
float px = _hudX, py = _hudY;
|
||||
if (_vpW > 0f && px > _vpW - m.PanelW) px = _vpW - m.PanelW;
|
||||
if (_vpH > 0f && py > _vpH - m.PanelH) py = _vpH - m.PanelH;
|
||||
if (px < 0f) px = 0f;
|
||||
if (py < 0f) py = 0f;
|
||||
|
||||
bool inPanel = mxf >= px && mxf <= px + m.PanelW &&
|
||||
myf >= py && myf <= py + m.PanelH;
|
||||
if (!inPanel) return false;
|
||||
|
||||
// Pin the (clamped) top-left so move/resize anchor to the pixels.
|
||||
_hudX = px; _hudY = py;
|
||||
|
||||
bool inGrip = mxf >= px + m.PanelW - m.Grip && myf >= py + m.PanelH - m.Grip;
|
||||
if (inGrip)
|
||||
{
|
||||
float dx = mxf - px, dy = myf - py;
|
||||
float dist = MathF.Sqrt(dx * dx + dy * dy);
|
||||
if (dist < 8f) dist = 8f;
|
||||
_resizeStartDist = dist;
|
||||
_resizeStartScale = m.Scale;
|
||||
_dragMode = 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
_grabDX = mxf - px;
|
||||
_grabDY = myf - py;
|
||||
_dragMode = 1;
|
||||
}
|
||||
SetCapture(hWnd);
|
||||
return true;
|
||||
}
|
||||
|
||||
case WM_MOUSEMOVE:
|
||||
{
|
||||
if (_dragMode == 0) return false;
|
||||
// Left button no longer held (we missed the UP — e.g. capture
|
||||
// stolen by alt-tab): end the drag and let the move through so the
|
||||
// HUD can't get stuck following the cursor.
|
||||
if (((long)wParam & 0x0001 /* MK_LBUTTON */) == 0)
|
||||
{
|
||||
_dragMode = 0;
|
||||
ReleaseCapture();
|
||||
SaveCfg();
|
||||
return false;
|
||||
}
|
||||
float mxf = (short)((long)lParam & 0xFFFF);
|
||||
float myf = (short)(((long)lParam >> 16) & 0xFFFF);
|
||||
|
||||
if (_dragMode == 1) // move
|
||||
{
|
||||
float nx = mxf - _grabDX;
|
||||
float ny = myf - _grabDY;
|
||||
Metrics m = Metric(_scale);
|
||||
if (_vpW > 0f && nx > _vpW - m.PanelW) nx = _vpW - m.PanelW;
|
||||
if (_vpH > 0f && ny > _vpH - m.PanelH) ny = _vpH - m.PanelH;
|
||||
if (nx < 0f) nx = 0f;
|
||||
if (ny < 0f) ny = 0f;
|
||||
_hudX = nx; _hudY = ny;
|
||||
}
|
||||
else // resize
|
||||
{
|
||||
float dx = mxf - _hudX, dy = myf - _hudY;
|
||||
float dist = MathF.Sqrt(dx * dx + dy * dy);
|
||||
float s = _resizeStartScale * dist / _resizeStartDist;
|
||||
if (s < MinScale) s = MinScale;
|
||||
if (s > MaxScale) s = MaxScale;
|
||||
_scale = s;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
case WM_LBUTTONUP:
|
||||
{
|
||||
if (_dragMode == 0) return false;
|
||||
_dragMode = 0;
|
||||
ReleaseCapture();
|
||||
SaveCfg();
|
||||
return true;
|
||||
}
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Persistence: %APPDATA%\RynthCore\vitalhud.cfg ("x y scale") ──
|
||||
private static string? CfgPath()
|
||||
{
|
||||
string? appData = Environment.GetEnvironmentVariable("APPDATA");
|
||||
if (string.IsNullOrEmpty(appData)) return null;
|
||||
return Path.Combine(appData, "RynthCore", "vitalhud.cfg");
|
||||
}
|
||||
|
||||
private static bool LoadCfg(out float x, out float y, out float s)
|
||||
{
|
||||
x = 0f; y = 0f; s = 1f;
|
||||
try
|
||||
{
|
||||
string? path = CfgPath();
|
||||
if (path == null || !File.Exists(path)) return false;
|
||||
string[] parts = File.ReadAllText(path)
|
||||
.Split([' ', '\t', '\r', '\n'], StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 3) return false;
|
||||
if (!float.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out float fx) ||
|
||||
!float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out float fy) ||
|
||||
!float.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out float fs))
|
||||
return false;
|
||||
if (fs < MinScale) fs = MinScale;
|
||||
if (fs > MaxScale) fs = MaxScale;
|
||||
if (fx < 0f) fx = 0f;
|
||||
if (fy < 0f) fy = 0f;
|
||||
x = fx; y = fy; s = fs;
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"VitalHud: LoadCfg failed - {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void SaveCfg()
|
||||
{
|
||||
try
|
||||
{
|
||||
string? path = CfgPath();
|
||||
if (path == null) return;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
string body = string.Format(CultureInfo.InvariantCulture, "{0:F1} {1:F1} {2:F4}", _hudX, _hudY, _scale);
|
||||
File.WriteAllText(path, body);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.D3D9($"VitalHud: SaveCfg failed - {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Internals ────────────────────────────────────────────────────
|
||||
private static void CacheDelegates(IntPtr pDevice)
|
||||
{
|
||||
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
|
||||
|
||||
_setRenderState = Get<SetRenderStateDelegate>(vtable, DeviceVTableIndex.SetRenderState);
|
||||
_getRenderState = Get<GetRenderStateDelegate>(vtable, DeviceVTableIndex.GetRenderState);
|
||||
_setTextureStageState = Get<SetTextureStageStateDelegate>(vtable, DeviceVTableIndex.SetTextureStageState);
|
||||
_getTextureStageState = Get<GetTextureStageStateDelegate>(vtable, DeviceVTableIndex.GetTextureStageState);
|
||||
_setTexture = Get<SetTextureDelegate>(vtable, DeviceVTableIndex.SetTexture);
|
||||
_getTexture = Get<GetTextureDelegate>(vtable, DeviceVTableIndex.GetTexture);
|
||||
_setFVF = Get<SetFVFDelegate>(vtable, DeviceVTableIndex.SetFVF);
|
||||
_getFVF = Get<GetFVFDelegate>(vtable, DeviceVTableIndex.GetFVF);
|
||||
_setVertexShader = Get<SetVertexShaderDelegate>(vtable, DeviceVTableIndex.SetVertexShader);
|
||||
_getVertexShader = Get<GetVertexShaderDelegate>(vtable, DeviceVTableIndex.GetVertexShader);
|
||||
_setPixelShader = Get<SetPixelShaderDelegate>(vtable, DeviceVTableIndex.SetPixelShader);
|
||||
_getPixelShader = Get<GetPixelShaderDelegate>(vtable, DeviceVTableIndex.GetPixelShader);
|
||||
_drawPrimitiveUP = Get<DrawPrimitiveUPDelegate>(vtable, DeviceVTableIndex.DrawPrimitiveUP);
|
||||
_getViewport = Get<GetViewportDelegate>(vtable, DeviceVTableIndex.GetViewport);
|
||||
|
||||
_delegatesCached = true;
|
||||
RynthLog.D3D9("VitalHud: D3D9 delegates cached.");
|
||||
}
|
||||
|
||||
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 void ReleaseCom(IntPtr pUnk)
|
||||
{
|
||||
if (pUnk == IntPtr.Zero) return;
|
||||
IntPtr vtbl = Marshal.ReadIntPtr(pUnk);
|
||||
IntPtr releaseAddr = Marshal.ReadIntPtr(vtbl, 2 * IntPtr.Size); // IUnknown::Release
|
||||
var release = Marshal.GetDelegateForFunctionPointer<ReleaseComDelegate>(releaseAddr);
|
||||
release(pUnk);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue