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:
tombohar 2026-04-10 18:38:07 -04:00
commit 80b71d295d
179 changed files with 52858 additions and 0 deletions

View file

@ -0,0 +1,128 @@
using System;
using System.Threading;
namespace RynthCore.Engine.UI;
internal sealed class AngleOverlaySurfaceBridge : IOverlaySurfaceBridge
{
private readonly object _sync = new();
private readonly SoftwareOverlaySurfaceBridge _softwareFallback = new();
private OverlaySurfaceFrame? _pendingSharedFrame;
private IntPtr _activeSharedHandle;
private IntPtr _lastProbedSharedHandle;
private bool _sharedInteropUnavailable;
private int _loggedSoftwareFallback;
private int _loggedSharedTexture;
private int _loggedSharedUnavailable;
public string Name => "angle-preferred-hybrid";
public bool SupportsGpuInterop => true;
public bool ShouldAttemptSharedTextures => !_sharedInteropUnavailable;
public void SubmitSoftwareFrame(IntPtr pixelData, int byteCount, int width, int height)
{
if (Interlocked.Exchange(ref _loggedSoftwareFallback, 1) == 0)
{
RynthLog.UI("AngleOverlaySurfaceBridge: Using software frames as a fallback until native shared textures are available.");
}
_softwareFallback.SubmitSoftwareFrame(pixelData, byteCount, width, height);
}
public void SubmitSharedTexture(OverlaySurfaceKind kind, OverlaySharedTextureDescriptor descriptor)
{
if (_sharedInteropUnavailable)
return;
if (Interlocked.Exchange(ref _loggedSharedTexture, 1) == 0)
{
RynthLog.UI($"AngleOverlaySurfaceBridge: Received first {kind} shared texture submission.");
}
lock (_sync)
{
if (descriptor.SharedHandle != IntPtr.Zero &&
_activeSharedHandle != IntPtr.Zero &&
descriptor.SharedHandle != _activeSharedHandle)
{
// A new shared handle usually means the producer recreated its texture.
// Pause shared consumption until the renderer confirms it opened the new one.
_activeSharedHandle = IntPtr.Zero;
}
_pendingSharedFrame = new OverlaySurfaceFrame(kind, descriptor);
}
}
public void NotifySharedTextureOpened(IntPtr sharedHandle)
{
if (sharedHandle == IntPtr.Zero)
return;
lock (_sync)
{
_activeSharedHandle = sharedHandle;
_lastProbedSharedHandle = sharedHandle;
}
}
public void NotifySharedTextureUnavailable()
{
lock (_sync)
{
_sharedInteropUnavailable = true;
_pendingSharedFrame = null;
_activeSharedHandle = IntPtr.Zero;
_lastProbedSharedHandle = IntPtr.Zero;
}
if (Interlocked.Exchange(ref _loggedSharedUnavailable, 1) == 0)
{
RynthLog.UI("AngleOverlaySurfaceBridge: Shared-texture consumption is unavailable on this client; staying on software frames.");
}
}
public bool TryConsume(out OverlaySurfaceFrame? frame)
{
if (_sharedInteropUnavailable)
return _softwareFallback.TryConsume(out frame);
OverlaySurfaceFrame? sharedProbeFrame = null;
bool sharedIsActive;
lock (_sync)
{
sharedIsActive = _activeSharedHandle != IntPtr.Zero;
if (_pendingSharedFrame?.SharedTexture is OverlaySharedTextureDescriptor descriptor &&
descriptor.SharedHandle != IntPtr.Zero)
{
if (_activeSharedHandle != IntPtr.Zero && descriptor.SharedHandle == _activeSharedHandle)
{
_pendingSharedFrame = null;
sharedIsActive = true;
}
else if (descriptor.SharedHandle != _lastProbedSharedHandle)
{
_lastProbedSharedHandle = descriptor.SharedHandle;
sharedProbeFrame = _pendingSharedFrame;
_pendingSharedFrame = null;
}
}
}
if (sharedProbeFrame != null)
{
frame = sharedProbeFrame;
return true;
}
if (sharedIsActive)
{
frame = null;
return false;
}
return _softwareFallback.TryConsume(out frame);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,15 @@
using System;
namespace RynthCore.Engine.UI;
internal interface IOverlaySurfaceBridge
{
string Name { get; }
bool SupportsGpuInterop { get; }
bool ShouldAttemptSharedTextures { get; }
void SubmitSoftwareFrame(IntPtr pixelData, int byteCount, int width, int height);
void SubmitSharedTexture(OverlaySurfaceKind kind, OverlaySharedTextureDescriptor descriptor);
void NotifySharedTextureOpened(IntPtr sharedHandle);
void NotifySharedTextureUnavailable();
bool TryConsume(out OverlaySurfaceFrame? frame);
}

View file

@ -0,0 +1,354 @@
using System;
using System.Runtime.InteropServices;
using RynthCore.Engine.D3D9;
namespace RynthCore.Engine.UI;
internal sealed unsafe class OverlayD3D9SharedTexturePublisher : IDisposable
{
private const uint D3D_SDK_VERSION = 32;
private const uint D3DDEVTYPE_HAL = 1;
private const uint D3DCREATE_FPU_PRESERVE = 0x00000002;
private const uint D3DCREATE_MULTITHREADED = 0x00000004;
private const uint D3DCREATE_SOFTWARE_VERTEXPROCESSING = 0x00000020;
private const uint D3DFMT_UNKNOWN = 0;
private const uint D3DFMT_A8R8G8B8 = 21;
private const uint D3DSWAPEFFECT_DISCARD = 1;
private const uint D3DPOOL_DEFAULT = 0;
private const uint D3DUSAGE_DYNAMIC = 0x00000200;
[StructLayout(LayoutKind.Sequential)]
private struct D3DPRESENT_PARAMETERS
{
public uint BackBufferWidth;
public uint BackBufferHeight;
public uint BackBufferFormat;
public uint BackBufferCount;
public uint MultiSampleType;
public uint MultiSampleQuality;
public uint SwapEffect;
public IntPtr hDeviceWindow;
public int Windowed;
public int EnableAutoDepthStencil;
public uint AutoDepthStencilFormat;
public uint Flags;
public uint FullScreen_RefreshRateInHz;
public uint PresentationInterval;
}
[StructLayout(LayoutKind.Sequential)]
private struct D3DLOCKED_RECT
{
public int Pitch;
public IntPtr pBits;
}
[StructLayout(LayoutKind.Sequential)]
private struct Luid
{
public uint LowPart;
public int HighPart;
}
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int CreateDeviceExD(
IntPtr pD3D9Ex,
uint adapter,
uint deviceType,
IntPtr hFocusWindow,
uint behaviorFlags,
IntPtr pPresentationParameters,
IntPtr pFullscreenDisplayMode,
out IntPtr ppReturnedDeviceInterface);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetAdapterLuidD(IntPtr pD3D9Ex, uint adapter, out Luid luid);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int CreateTextureD(
IntPtr device,
uint width,
uint height,
uint levels,
uint usage,
uint format,
uint pool,
out IntPtr texture,
IntPtr sharedHandle);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int LockRectD(IntPtr texture, uint level, D3DLOCKED_RECT* lockedRect, IntPtr rect, uint flags);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int UnlockRectD(IntPtr texture, uint level);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseD(IntPtr pObj);
[DllImport("d3d9.dll")]
private static extern int Direct3DCreate9Ex(uint sdkVersion, out IntPtr direct3D9Ex);
[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);
private IntPtr _windowHandle;
private IntPtr _d3d9Ex;
private IntPtr _deviceEx;
private IntPtr _texture;
private IntPtr _sharedHandle;
private int _width;
private int _height;
private long _adapterLuid;
private bool _loggedAvailability;
public bool TryUpload(
IntPtr pixelData,
int byteCount,
int width,
int height,
int rowPitch,
out OverlaySharedTextureDescriptor descriptor)
{
descriptor = default;
if (pixelData == IntPtr.Zero || byteCount <= 0 || width <= 0 || height <= 0 || rowPitch <= 0)
return false;
if (!EnsureDevice())
return false;
if (!EnsureTexture(width, height))
return false;
var lockRect = GetTextureMethod<LockRectD>(_texture, TextureVTableIndex.LockRect);
var unlockRect = GetTextureMethod<UnlockRectD>(_texture, TextureVTableIndex.UnlockRect);
D3DLOCKED_RECT locked;
int hr = lockRect(_texture, 0, &locked, IntPtr.Zero, 0);
if (hr < 0 || locked.pBits == IntPtr.Zero)
{
RynthLog.UI($"OverlayD3D9SharedTexturePublisher: LockRect failed, HRESULT=0x{hr:X8}.");
return false;
}
try
{
int bytesPerRow = Math.Min(rowPitch, locked.Pitch);
for (int row = 0; row < height; row++)
{
IntPtr sourceRow = pixelData + (row * rowPitch);
IntPtr targetRow = locked.pBits + (row * locked.Pitch);
Buffer.MemoryCopy((void*)sourceRow, (void*)targetRow, bytesPerRow, bytesPerRow);
}
}
finally
{
unlockRect(_texture, 0);
}
descriptor = new OverlaySharedTextureDescriptor(
_sharedHandle,
_adapterLuid,
width,
height,
(int)D3DFMT_A8R8G8B8,
rowPitch,
(int)D3DUSAGE_DYNAMIC);
return true;
}
public void Dispose()
{
ReleaseTexture();
ReleaseComObject(ref _deviceEx);
ReleaseComObject(ref _d3d9Ex);
if (_windowHandle != IntPtr.Zero)
{
DestroyWindow(_windowHandle);
_windowHandle = IntPtr.Zero;
}
}
private bool EnsureDevice()
{
if (_deviceEx != IntPtr.Zero)
return true;
_windowHandle = CreateWindowExA(
0,
"STATIC",
"RynthCore_D3D9_SharedTexture",
0,
0,
0,
1,
1,
IntPtr.Zero,
IntPtr.Zero,
GetModuleHandleA(null),
IntPtr.Zero);
if (_windowHandle == IntPtr.Zero)
{
RynthLog.UI("OverlayD3D9SharedTexturePublisher: Failed to create helper window.");
return false;
}
int hr = Direct3DCreate9Ex(D3D_SDK_VERSION, out _d3d9Ex);
if (hr < 0 || _d3d9Ex == IntPtr.Zero)
{
RynthLog.UI($"OverlayD3D9SharedTexturePublisher: Direct3DCreate9Ex failed, HRESULT=0x{hr:X8}.");
Dispose();
return false;
}
IntPtr d3d9ExVTable = Marshal.ReadIntPtr(_d3d9Ex);
var createDeviceEx = Marshal.GetDelegateForFunctionPointer<CreateDeviceExD>(
Marshal.ReadIntPtr(d3d9ExVTable, 20 * IntPtr.Size));
var getAdapterLuid = Marshal.GetDelegateForFunctionPointer<GetAdapterLuidD>(
Marshal.ReadIntPtr(d3d9ExVTable, 21 * IntPtr.Size));
var presentParameters = new D3DPRESENT_PARAMETERS
{
BackBufferWidth = 1,
BackBufferHeight = 1,
BackBufferFormat = D3DFMT_UNKNOWN,
BackBufferCount = 1,
SwapEffect = D3DSWAPEFFECT_DISCARD,
hDeviceWindow = _windowHandle,
Windowed = 1
};
IntPtr parametersPtr = Marshal.AllocHGlobal(Marshal.SizeOf<D3DPRESENT_PARAMETERS>());
try
{
Marshal.StructureToPtr(presentParameters, parametersPtr, false);
hr = createDeviceEx(
_d3d9Ex,
0,
D3DDEVTYPE_HAL,
_windowHandle,
D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED | D3DCREATE_FPU_PRESERVE,
parametersPtr,
IntPtr.Zero,
out _deviceEx);
}
finally
{
Marshal.FreeHGlobal(parametersPtr);
}
if (hr < 0 || _deviceEx == IntPtr.Zero)
{
RynthLog.UI($"OverlayD3D9SharedTexturePublisher: CreateDeviceEx failed, HRESULT=0x{hr:X8}.");
Dispose();
return false;
}
if (getAdapterLuid(_d3d9Ex, 0, out Luid luid) >= 0)
{
_adapterLuid = ((long)luid.HighPart << 32) | luid.LowPart;
}
if (!_loggedAvailability)
{
_loggedAvailability = true;
RynthLog.UI("OverlayD3D9SharedTexturePublisher: D3D9Ex shared-texture upload path is available.");
}
return true;
}
private bool EnsureTexture(int width, int height)
{
if (_texture != IntPtr.Zero && _width == width && _height == height && _sharedHandle != IntPtr.Zero)
return true;
ReleaseTexture();
var createTexture = GetDeviceMethod<CreateTextureD>(_deviceEx, DeviceVTableIndex.CreateTexture);
IntPtr sharedHandle = IntPtr.Zero;
int hr = createTexture(
_deviceEx,
(uint)width,
(uint)height,
1,
D3DUSAGE_DYNAMIC,
D3DFMT_A8R8G8B8,
D3DPOOL_DEFAULT,
out _texture,
new IntPtr(&sharedHandle));
if (hr < 0 || _texture == IntPtr.Zero || sharedHandle == IntPtr.Zero)
{
RynthLog.UI(
$"OverlayD3D9SharedTexturePublisher: CreateTexture failed for {width}x{height}, HRESULT=0x{hr:X8}, handle=0x{sharedHandle:X8}.");
ReleaseTexture();
return false;
}
_sharedHandle = sharedHandle;
_width = width;
_height = height;
RynthLog.UI(
$"OverlayD3D9SharedTexturePublisher: Created shared upload texture {width}x{height}, handle=0x{_sharedHandle:X8}.");
return true;
}
private void ReleaseTexture()
{
if (_texture == IntPtr.Zero)
return;
ReleaseComObject(ref _texture);
_sharedHandle = IntPtr.Zero;
_width = 0;
_height = 0;
}
private static void ReleaseComObject(ref IntPtr obj)
{
if (obj == IntPtr.Zero)
return;
IntPtr vtable = Marshal.ReadIntPtr(obj);
var release = Marshal.GetDelegateForFunctionPointer<ReleaseD>(
Marshal.ReadIntPtr(vtable, 2 * IntPtr.Size));
release(obj);
obj = IntPtr.Zero;
}
private static T GetDeviceMethod<T>(IntPtr device, int index) where T : Delegate
{
IntPtr vtable = Marshal.ReadIntPtr(device);
IntPtr address = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
return Marshal.GetDelegateForFunctionPointer<T>(address);
}
private static T GetTextureMethod<T>(IntPtr texture, int index) where T : Delegate
{
IntPtr vtable = Marshal.ReadIntPtr(texture);
IntPtr address = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
return Marshal.GetDelegateForFunctionPointer<T>(address);
}
}

View file

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

View file

@ -0,0 +1,26 @@
// ============================================================================
// RynthCore.Engine - UI/OverlayHost.cs
// Static registry for overlay panels. Engine code registers panels before
// AvaloniaOverlay.Start() is called; the window reads them at creation time.
// ============================================================================
using System;
using System.Collections.Generic;
using Avalonia.Controls;
namespace RynthCore.Engine.UI;
internal static class OverlayHost
{
private static readonly List<(string Title, Func<Control> Factory)> _panels = new();
/// <summary>
/// Register a panel tab. Call before AvaloniaOverlay.Start().
/// Factory is invoked on the Avalonia UI thread when the window is created.
/// </summary>
internal static void RegisterPanel(string title, Func<Control> factory)
=> _panels.Add((title, factory));
internal static IReadOnlyList<(string Title, Func<Control> Factory)> GetPanels()
=> _panels;
}

View file

@ -0,0 +1,262 @@
using System;
using System.Collections.Generic;
using System.Threading;
using Avalonia;
using Avalonia.Platform;
using Avalonia.Skia;
using SkiaSharp;
namespace RynthCore.Engine.UI;
internal sealed class OverlaySkiaPlatformGraphics : IPlatformGraphicsWithFeatures
{
private readonly OverlaySkiaGpuContext _sharedContext = new();
public bool UsesSharedContext => true;
public IPlatformGraphicsContext CreateContext() => _sharedContext;
public IPlatformGraphicsContext GetSharedContext() => _sharedContext;
public object? TryGetFeature(Type featureType) => _sharedContext.TryGetFeature(featureType);
}
internal sealed class OverlaySkiaGpuContext : ISkiaGpu
{
private static readonly IDisposable NoopLease = new NoopDisposable();
private readonly object _sync = new();
private OverlaySkiaRenderTarget? _renderTarget;
public bool IsLost => false;
public IDisposable EnsureCurrent() => NoopLease;
public object? TryGetFeature(Type featureType) => null;
public ISkiaGpuRenderTarget? TryCreateRenderTarget(IEnumerable<object> surfaces)
{
lock (_sync)
{
_renderTarget ??= new OverlaySkiaRenderTarget();
return _renderTarget;
}
}
public ISkiaSurface? TryCreateSurface(PixelSize size, ISkiaGpuRenderSession? session)
{
if (size.Width <= 0 || size.Height <= 0)
return null;
return new OverlaySkiaSurface(size.Width, size.Height);
}
public void Dispose()
{
lock (_sync)
{
_renderTarget?.Dispose();
_renderTarget = null;
}
}
private sealed class NoopDisposable : IDisposable
{
public void Dispose()
{
}
}
}
internal sealed class OverlaySkiaRenderTarget : ISkiaGpuRenderTarget
{
private readonly object _sync = new();
private OverlayD3D9SharedTexturePublisher? _sharedTexturePublisher;
private SKSurface? _surface;
private byte[]? _softwareBuffer;
private int _width;
private int _height;
private int _loggedSharedTextureDisabled;
public bool IsCorrupted => false;
public ISkiaGpuRenderSession BeginRenderingSession()
{
lock (_sync)
{
EnsureSurface();
if (_surface == null)
throw new InvalidOperationException("Overlay Skia render surface could not be created.");
_surface.Canvas.Clear(SKColors.Transparent);
return new OverlaySkiaRenderSession(this, _surface, _width, _height);
}
}
public void Dispose()
{
lock (_sync)
{
_surface?.Dispose();
_surface = null;
_softwareBuffer = null;
_sharedTexturePublisher?.Dispose();
_width = 0;
_height = 0;
}
}
public byte[] RentSoftwareBuffer(int byteCount)
{
lock (_sync)
{
if (_softwareBuffer == null || _softwareBuffer.Length != byteCount)
_softwareBuffer = new byte[byteCount];
return _softwareBuffer;
}
}
public bool TrySubmitSharedTexture(
IntPtr pixelData,
int byteCount,
int width,
int height,
int rowPitch,
out OverlaySharedTextureDescriptor descriptor)
{
lock (_sync)
{
if (!AvaloniaOverlay.UseAnglePreferredBridge || !OverlaySurfaceBridge.ShouldAttemptSharedTextures)
{
if (_sharedTexturePublisher != null)
{
_sharedTexturePublisher.Dispose();
_sharedTexturePublisher = null;
}
if (Interlocked.Exchange(ref _loggedSharedTextureDisabled, 1) == 0)
{
RynthLog.UI("OverlaySkiaRenderTarget: Shared-texture uploads disabled for this session; continuing with software submissions.");
}
descriptor = default;
return false;
}
_sharedTexturePublisher ??= new OverlayD3D9SharedTexturePublisher();
return _sharedTexturePublisher.TryUpload(pixelData, byteCount, width, height, rowPitch, out descriptor);
}
}
private void EnsureSurface()
{
int width = AvaloniaOverlay.ClientPixelWidth > 1 ? AvaloniaOverlay.ClientPixelWidth : AvaloniaOverlay.ViewportWidth;
int height = AvaloniaOverlay.ClientPixelHeight > 1 ? AvaloniaOverlay.ClientPixelHeight : AvaloniaOverlay.ViewportHeight;
if (width <= 1 || height <= 1)
{
width = _width > 1 ? _width : 1;
height = _height > 1 ? _height : 1;
}
if (_surface != null && width == _width && height == _height)
return;
_surface?.Dispose();
_width = width;
_height = height;
var info = new SKImageInfo(width, height, SKColorType.Bgra8888, SKAlphaType.Premul);
_surface = SKSurface.Create(info);
RynthLog.UI($"OverlaySkiaRenderTarget: Created raster render surface {_width}x{_height}.");
}
}
internal sealed class OverlaySkiaRenderSession : ISkiaGpuRenderSession
{
private static int _loggedTinyBootstrapFrame;
private readonly OverlaySkiaRenderTarget _owner;
private readonly SKSurface _surface;
private readonly int _width;
private readonly int _height;
private bool _disposed;
public OverlaySkiaRenderSession(OverlaySkiaRenderTarget owner, SKSurface surface, int width, int height)
{
_owner = owner;
_surface = surface;
_width = width;
_height = height;
}
public GRContext GrContext => null!;
public double ScaleFactor => 1.0d;
public SKSurface SkSurface => _surface;
public GRSurfaceOrigin SurfaceOrigin => GRSurfaceOrigin.TopLeft;
public unsafe void Dispose()
{
if (_disposed)
return;
_disposed = true;
if (_width <= 1 || _height <= 1)
{
if (Interlocked.Exchange(ref _loggedTinyBootstrapFrame, 1) == 0)
{
RynthLog.UI("OverlaySkiaRenderSession: Skipping tiny bootstrap frame until the game surface reports a real size.");
}
return;
}
if (!AvaloniaOverlay.ShouldUseCustomSkiaProducer)
return;
var info = new SKImageInfo(_width, _height, SKColorType.Bgra8888, SKAlphaType.Premul);
byte[] pixels = _owner.RentSoftwareBuffer(info.BytesSize);
fixed (byte* pixelPtr = pixels)
{
if (!_surface.ReadPixels(info, (IntPtr)pixelPtr, info.RowBytes, 0, 0))
{
RynthLog.UI("OverlaySkiaRenderSession: Failed to read pixels from custom render target.");
return;
}
AvaloniaOverlay.SurfacePixelWidth = _width;
AvaloniaOverlay.SurfacePixelHeight = _height;
if (_owner.TrySubmitSharedTexture((IntPtr)pixelPtr, pixels.Length, _width, _height, info.RowBytes, out OverlaySharedTextureDescriptor sharedDescriptor))
{
OverlaySurfaceBridge.SubmitSharedTexture(OverlaySurfaceKind.D3D9SharedTexture, sharedDescriptor);
}
OverlaySurfaceBridge.SubmitSoftwareFrame((IntPtr)pixelPtr, pixels.Length, _width, _height);
AvaloniaOverlay.NotifyCustomFrameSubmitted(_width, _height);
}
}
}
internal sealed class OverlaySkiaSurface : ISkiaSurface
{
public OverlaySkiaSurface(int width, int height)
{
var info = new SKImageInfo(width, height, SKColorType.Bgra8888, SKAlphaType.Premul);
Surface = SKSurface.Create(info) ?? throw new InvalidOperationException("Unable to create Skia surface.");
}
public bool CanBlit => true;
public SKSurface Surface { get; }
public void Blit(SKCanvas canvas)
{
using var snapshot = Surface.Snapshot();
canvas.DrawImage(snapshot, 0, 0);
}
public void Dispose()
{
Surface.Dispose();
}
}

View file

@ -0,0 +1,64 @@
using System;
namespace RynthCore.Engine.UI;
internal static class OverlaySurfaceBridge
{
private static readonly IOverlaySurfaceBridge SoftwareBridge = new SoftwareOverlaySurfaceBridge();
private static readonly IOverlaySurfaceBridge AngleBridge = new AngleOverlaySurfaceBridge();
private static IOverlaySurfaceBridge _activeBridge = SoftwareBridge;
private static bool _loggedSelection;
public static string ActiveName => _activeBridge.Name;
public static bool ActiveSupportsGpuInterop => _activeBridge.SupportsGpuInterop;
public static bool ShouldAttemptSharedTextures => _activeBridge.ShouldAttemptSharedTextures;
public static void UseSoftwareFallback()
{
_activeBridge = SoftwareBridge;
_loggedSelection = false;
}
public static void UseAngleStub()
{
_activeBridge = AngleBridge;
_loggedSelection = false;
}
public static void SubmitSoftwareFrame(IntPtr pixelData, int byteCount, int width, int height)
{
LogSelectionOnce();
_activeBridge.SubmitSoftwareFrame(pixelData, byteCount, width, height);
}
public static void SubmitSharedTexture(OverlaySurfaceKind kind, OverlaySharedTextureDescriptor descriptor)
{
LogSelectionOnce();
_activeBridge.SubmitSharedTexture(kind, descriptor);
}
public static void NotifySharedTextureOpened(IntPtr sharedHandle)
{
_activeBridge.NotifySharedTextureOpened(sharedHandle);
}
public static void NotifySharedTextureUnavailable()
{
_activeBridge.NotifySharedTextureUnavailable();
}
public static bool TryConsume(out OverlaySurfaceFrame? frame)
{
LogSelectionOnce();
return _activeBridge.TryConsume(out frame);
}
private static void LogSelectionOnce()
{
if (_loggedSelection)
return;
_loggedSelection = true;
RynthLog.UI($"OverlaySurfaceBridge: Active path = {ActiveName} (gpuInterop={ActiveSupportsGpuInterop}).");
}
}

View file

@ -0,0 +1,45 @@
using System;
namespace RynthCore.Engine.UI;
internal enum OverlaySurfaceKind
{
SoftwareBgra32 = 0,
AngleSharedTexture = 1,
DxgiSharedTexture = 2,
D3D9SharedTexture = 3
}
internal readonly record struct OverlaySharedTextureDescriptor(
IntPtr SharedHandle,
long AdapterLuid,
int Width,
int Height,
int PixelFormat,
int RowPitch,
int Usage);
internal sealed class OverlaySurfaceFrame
{
public OverlaySurfaceFrame(byte[] pixels, int width, int height)
{
Kind = OverlaySurfaceKind.SoftwareBgra32;
SoftwarePixels = pixels;
Width = width;
Height = height;
}
public OverlaySurfaceFrame(OverlaySurfaceKind kind, OverlaySharedTextureDescriptor sharedTexture)
{
Kind = kind;
SharedTexture = sharedTexture;
Width = sharedTexture.Width;
Height = sharedTexture.Height;
}
public OverlaySurfaceKind Kind { get; }
public byte[]? SoftwarePixels { get; }
public OverlaySharedTextureDescriptor? SharedTexture { get; }
public int Width { get; }
public int Height { get; }
}

View file

@ -0,0 +1,102 @@
// ============================================================================
// RynthCore.Engine - UI/Panels/HelloBoxPanel.cs
// Shows live status from the HelloBox plugin. Resolves the plugin's
// RynthPluginGetStatusText export via GetProcAddress on the module handle —
// no changes to the plugin contract needed.
// ============================================================================
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI.Panels;
internal static class HelloBoxPanel
{
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr GetStatusTextFn();
private static GetStatusTextFn? _getStatusText;
internal static Control Create()
{
TryBindDelegate();
var textBlock = new TextBlock
{
FontFamily = new FontFamily("Consolas,Courier New,monospace"),
FontSize = 10,
Foreground = new SolidColorBrush(Color.FromArgb(200, 210, 210, 210)),
TextWrapping = TextWrapping.Wrap,
Margin = new Avalonia.Thickness(8, 6)
};
var scroll = new ScrollViewer
{
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
Content = textBlock
};
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) };
timer.Tick += (_, _) =>
{
if (_getStatusText == null)
TryBindDelegate();
string text;
if (_getStatusText != null)
{
try
{
IntPtr ptr = _getStatusText();
text = Marshal.PtrToStringAnsi(ptr) ?? "(empty)";
}
catch (Exception ex)
{
text = $"Error reading status: {ex.Message}";
}
}
else
{
var plugin = PluginManager.Plugins.FirstOrDefault(p => p.DisplayName.Contains("Hello"));
text = plugin == null
? "Hello Box plugin not loaded."
: $"Hello Box loaded ({plugin.DisplayName}) but RynthPluginGetStatusText not found.";
}
if (textBlock.Text != text)
textBlock.Text = text;
};
scroll.DetachedFromVisualTree += (_, _) => timer.Stop();
timer.Start();
return scroll;
}
private static void TryBindDelegate()
{
var plugin = PluginManager.Plugins.FirstOrDefault(p => p.DisplayName.Contains("Hello"));
if (plugin == null)
return;
IntPtr fn = GetProcAddress(plugin.ModuleHandle, "RynthPluginGetStatusText");
if (fn == IntPtr.Zero)
return;
if (_getStatusText != null)
return;
_getStatusText = Marshal.GetDelegateForFunctionPointer<GetStatusTextFn>(fn);
RynthLog.UI($"HelloBoxPanel: bound RynthPluginGetStatusText for '{plugin.DisplayName}'.");
}
}

View file

@ -0,0 +1,91 @@
// ============================================================================
// RynthCore.Engine - UI/Panels/LogPanel.cs
// Scrollable log viewer. Polls EntryPoint.GetRecentLogLines() every second.
// Auto-scroll follows the tail; checkbox to pin scroll position.
// ============================================================================
using System;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
namespace RynthCore.Engine.UI.Panels;
internal static class LogPanel
{
internal static Control Create()
{
var listBox = new ListBox
{
FontSize = 10,
FontFamily = new FontFamily("Consolas,Courier New,monospace"),
Background = Brushes.Transparent,
BorderThickness = new Avalonia.Thickness(0)
};
ScrollViewer.SetHorizontalScrollBarVisibility(listBox, ScrollBarVisibility.Disabled);
var autoScrollCheck = new CheckBox
{
Content = "Auto-scroll",
IsChecked = true,
Margin = new Avalonia.Thickness(4, 0, 0, 0)
};
var clearButton = new Button
{
Content = "Clear",
Margin = new Avalonia.Thickness(4, 0, 0, 0)
};
string[]? _clearedSnapshot = null;
clearButton.Click += (_, _) =>
{
_clearedSnapshot = EntryPoint.GetRecentLogLines();
listBox.ItemsSource = Array.Empty<string>();
};
var toolbar = new StackPanel
{
Orientation = Orientation.Horizontal,
Children = { autoScrollCheck, clearButton }
};
var scroll = new ScrollViewer
{
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
Content = listBox
};
var root = new DockPanel();
DockPanel.SetDock(toolbar, Dock.Bottom);
root.Children.Add(toolbar);
root.Children.Add(scroll);
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
timer.Tick += (_, _) =>
{
string[] lines = EntryPoint.GetRecentLogLines();
// If cleared, only show lines that arrived after the clear snapshot
if (_clearedSnapshot != null)
{
int clearCount = _clearedSnapshot.Length;
if (lines.Length > clearCount)
lines = lines[clearCount..];
else
lines = Array.Empty<string>();
}
listBox.ItemsSource = lines;
if (autoScrollCheck.IsChecked == true && lines.Length > 0)
scroll.ScrollToEnd();
};
timer.Start();
return root;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,101 @@
// ============================================================================
// RynthCore.Engine - UI/Panels/StatusPanel.cs
// Shows engine build info, game HWND, and the loaded plugin list.
// Refreshes on demand (Refresh button) — not polled continuously.
// ============================================================================
using System;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI.Panels;
internal static class StatusPanel
{
internal static Control Create()
{
var content = new StackPanel { Spacing = 4 };
var refreshButton = new Button { Content = "Refresh", HorizontalAlignment = HorizontalAlignment.Left };
refreshButton.Click += (_, _) => Populate(content);
var root = new DockPanel { Margin = new Avalonia.Thickness(8) };
DockPanel.SetDock(refreshButton, Dock.Bottom);
root.Children.Add(refreshButton);
var scroll = new ScrollViewer
{
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
Content = content
};
root.Children.Add(scroll);
Populate(content);
return root;
}
private static void Populate(StackPanel panel)
{
panel.Children.Clear();
AddHeader(panel, "Engine");
AddRow(panel, "Build", EntryPoint.BuildStamp);
AddRow(panel, "Game HWND", $"0x{EntryPoint.GameHwnd:X8}");
AddRow(panel, "Plugin dir", PluginManager.PluginDirectory);
panel.Children.Add(new Border
{
Height = 1,
Background = new SolidColorBrush(Color.FromArgb(60, 255, 255, 255)),
Margin = new Avalonia.Thickness(0, 6, 0, 6)
});
var plugins = PluginManager.Plugins;
AddHeader(panel, $"Plugins ({plugins.Count})");
if (plugins.Count == 0)
{
AddRow(panel, "", "None loaded");
}
else
{
foreach (var p in plugins)
{
string state = p.Failed ? "FAILED" : p.Initialized ? "OK" : "pending";
string version = p.VersionString.Length > 0 ? $" v{p.VersionString}" : "";
AddRow(panel, p.DisplayName + version, state, p.Failed);
}
}
}
private static void AddHeader(StackPanel panel, string text)
{
panel.Children.Add(new TextBlock
{
Text = text,
FontSize = 11,
FontWeight = FontWeight.Bold,
Foreground = new SolidColorBrush(Color.FromArgb(200, 140, 200, 255)),
Margin = new Avalonia.Thickness(0, 4, 0, 2)
});
}
private static void AddRow(StackPanel panel, string label, string value, bool error = false)
{
var color = error
? Color.FromArgb(220, 255, 100, 100)
: Color.FromArgb(200, 210, 210, 210);
string display = label.Length > 0 ? $"{label}: {value}" : value;
panel.Children.Add(new TextBlock
{
Text = display,
FontSize = 11,
Foreground = new SolidColorBrush(color),
TextWrapping = TextWrapping.Wrap
});
}
}

View file

@ -0,0 +1,57 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.UI;
internal sealed class SoftwareOverlaySurfaceBridge : IOverlaySurfaceBridge
{
private sealed class PendingFrame
{
public PendingFrame(byte[] pixels, int width, int height)
{
Frame = new OverlaySurfaceFrame(pixels, width, height);
}
public OverlaySurfaceFrame Frame { get; }
}
private PendingFrame? _pending;
public string Name => "software-bgra32";
public bool SupportsGpuInterop => false;
public bool ShouldAttemptSharedTextures => false;
public void SubmitSoftwareFrame(IntPtr pixelData, int byteCount, int width, int height)
{
var buffer = new byte[byteCount];
Marshal.Copy(pixelData, buffer, 0, byteCount);
Interlocked.Exchange(ref _pending, new PendingFrame(buffer, width, height));
}
public void SubmitSharedTexture(OverlaySurfaceKind kind, OverlaySharedTextureDescriptor descriptor)
{
RynthLog.UI($"SoftwareOverlaySurfaceBridge: Ignoring {kind} shared texture submission while software bridge is active.");
}
public void NotifySharedTextureOpened(IntPtr sharedHandle)
{
}
public void NotifySharedTextureUnavailable()
{
}
public bool TryConsume(out OverlaySurfaceFrame? frame)
{
PendingFrame? pending = Interlocked.Exchange(ref _pending, null);
if (pending == null)
{
frame = null;
return false;
}
frame = pending.Frame;
return true;
}
}