XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWarframe

【WinUI】基于Warframe游戏本体的公开服务器以及安装器

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Runtime.InteropServices;
using XFEWarframe.Client;

namespace XFEWarframe.Bridge;

/// <summary>Reads the game's Direct3D back buffer on its render thread. Never captures the desktop or sends window input.</summary>
internal static partial class GraphicsFrameCapture
{
    internal sealed record Frame(int Width, int Height, byte[] Rgba);
    private static TaskCompletionSource<Frame>? pending;
    private static int reading;
    internal static bool Available { get; private set; }
    internal static unsafe void Prepare(List<NativeHook> hooks)
    {
        nint window = 0, chain = 0, device = 0, context = 0;
        try
        {
            // A hidden, temporary surface obtains the COM implementation; it is never shown or used for game input.
            window = CreateWindowExW(0, "STATIC", "XFE render binding", 0x80000000, 0, 0, 64, 64, 0, 0, 0, 0);
            if (window == 0) throw new IOException("Cannot create the graphics binding surface.");
            var desc = new SwapDescription { Width = 64, Height = 64, Format = 28, SampleCount = 1, Usage = 32, Buffers = 1, Window = window, Windowed = 1 };
            var hr = D3D11CreateDeviceAndSwapChain(0, 1, 0, 0, 0, 0, 7, &desc, &chain, &device, 0, &context);
            if (hr < 0 || chain == 0) Marshal.ThrowExceptionForHR(hr);
            hooks.Add(NativeHook.Observe(V(chain, 8), (nint)(delegate* unmanaged<nint, uint, uint, void>)&ObservePresent));
            Available = true;
        }
        finally { Release(context); Release(device); Release(chain); if (window != 0) DestroyWindow(window); }
    }
    internal static async Task<Frame> ReadAsync(CancellationToken cancellation)
    {
        if (!Available) throw new InvalidOperationException("This launch has no Direct3D 11 card capture binding.");
        var request = Volatile.Read(ref pending);
        if (request is null)
        {
            var candidate = new TaskCompletionSource<Frame>(TaskCreationOptions.RunContinuationsAsynchronously);
            request = Interlocked.CompareExchange(ref pending, candidate, null) ?? candidate;
            if (ReferenceEquals(request, candidate)) _ = ExpireAsync(candidate);
        }
        // Cards drawn in the same UI frame share one GPU read, rather than racing each other.
        return await request.Task.WaitAsync(TimeSpan.FromSeconds(3), cancellation).ConfigureAwait(false);
    }
    private static async Task ExpireAsync(TaskCompletionSource<Frame> request)
    {
        await Task.Delay(3000).ConfigureAwait(false);
        if (ReferenceEquals(Interlocked.CompareExchange(ref pending, null, request), request)) request.TrySetException(new TimeoutException("The game did not present a capture frame."));
    }
    [UnmanagedCallersOnly] private static unsafe void ObservePresent(nint chain, uint sync, uint flags)
    {
        var request = Volatile.Read(ref pending); if (request is null || Interlocked.CompareExchange(ref reading, 1, 0) != 0) return;
        nint texture = 0, device = 0, context = 0, staging = 0;
        try
        {
            var textureId = new Guid("6f15aaf2-d208-4e89-9ab4-489535d34f9c");
            Check(((delegate* unmanaged<nint, uint, Guid*, nint*, int>)V(chain, 9))(chain, 0, &textureId, &texture));
            var deviceId = new Guid("db6f6ddb-ac77-4e88-8253-819df9bbf140");
            Check(((delegate* unmanaged<nint, Guid*, nint*, int>)V(chain, 7))(chain, &deviceId, &device));
            ((delegate* unmanaged<nint, nint*, void>)V(device, 40))(device, &context);
            TextureDescription desc = default;
            ((delegate* unmanaged<nint, TextureDescription*, void>)V(texture, 10))(texture, &desc);
            if (desc.Width is < 1 or > 8192 || desc.Height is < 1 or > 8192 || desc.Format is not (28 or 29 or 87 or 91) || desc.SampleCount != 1)
                throw new InvalidDataException("Unsupported render surface dimensions or format.");
            desc.Usage = 3; desc.Bind = 0; desc.Cpu = 0x20000; desc.Misc = 0;
            Check(((delegate* unmanaged<nint, TextureDescription*, nint, nint*, int>)V(device, 5))(device, &desc, 0, &staging));
            ((delegate* unmanaged<nint, nint, nint, void>)V(context, 47))(context, staging, texture);
            Mapped mapped = default;
            Check(((delegate* unmanaged<nint, nint, uint, uint, uint, Mapped*, int>)V(context, 14))(context, staging, 0, 1, 0, &mapped));
            byte[] rgba;
            try
            {
                rgba = new byte[checked((int)(desc.Width * desc.Height * 4))];
                for (var y = 0; y < desc.Height; y++) new ReadOnlySpan<byte>((void*)(mapped.Data + y * mapped.RowPitch), (int)desc.Width * 4).CopyTo(rgba.AsSpan(y * (int)desc.Width * 4));
                for (var i = 0; i < rgba.Length; i += 4) { if (desc.Format is 87 or 91) (rgba[i], rgba[i + 2]) = (rgba[i + 2], rgba[i]); rgba[i + 3] = 255; }
            }
            finally { ((delegate* unmanaged<nint, nint, uint, void>)V(context, 15))(context, staging, 0); }
            request.TrySetResult(new((int)desc.Width, (int)desc.Height, rgba));
        }
        catch (Exception ex) { request.TrySetException(ex); }
        finally { Release(staging); Release(context); Release(device); Release(texture); Interlocked.CompareExchange(ref pending, null, request); Volatile.Write(ref reading, 0); }
    }
    internal static byte[] Png(Frame frame, int left, int top, int width, int height)
        => PngImages.CropRgba(frame.Rgba, frame.Width, frame.Height, left, top, width, height);
    internal static byte[] CardPng(Frame dark, Frame light, int left, int top, int width, int height, float movieWidth, float movieHeight)
    {
        if (dark.Width != light.Width || dark.Height != light.Height) throw new InvalidDataException("Game resolution changed while rendering a card; retry the batch.");
        // The original movie uses proportional scaling and centered viewport margins.
        var scale = MathF.Min(dark.Width / movieWidth, dark.Height / movieHeight);
        var x = (int)MathF.Round((dark.Width - movieWidth * scale) / 2 + left * scale);
        var y = (int)MathF.Round((dark.Height - movieHeight * scale) / 2 + top * scale);
        var w = (int)MathF.Round(width * scale); var h = (int)MathF.Round(height * scale);
        return NativeCardPixels.Encode(dark.Rgba, light.Rgba, dark.Width, dark.Height, x, y, w, h, trimTransparentMargin: true);
    }
    private static unsafe nint V(nint value, int index) => (*(nint**)value)[index];
    private static unsafe void Release(nint value) { if (value != 0) ((delegate* unmanaged<nint, uint>)V(value, 2))(value); }
    private static void Check(int result) { if (result < 0) Marshal.ThrowExceptionForHR(result); }
    [StructLayout(LayoutKind.Sequential)] private struct SwapDescription { public uint Width, Height, RefreshN, RefreshD, Format, Scanline, Scaling, SampleCount, SampleQuality, Usage, Buffers; public nint Window; public uint Windowed, Effect, Flags; }
    [StructLayout(LayoutKind.Sequential)] private struct TextureDescription { public uint Width, Height, Levels, ArraySize, Format, SampleCount, SampleQuality, Usage, Bind, Cpu, Misc; }
    [StructLayout(LayoutKind.Sequential)] private struct Mapped { public nint Data; public uint RowPitch, DepthPitch; }
    [LibraryImport("d3d11")] private static unsafe partial int D3D11CreateDeviceAndSwapChain(nint adapter, uint driver, nint software, uint flags, nint levels, uint count, uint sdk, SwapDescription* description, nint* chain, nint* device, nint featureLevel, nint* context);
    [LibraryImport("user32", StringMarshalling = StringMarshalling.Utf16)] private static partial nint CreateWindowExW(uint extended, string className, string name, uint style, int x, int y, int width, int height, nint parent, nint menu, nint instance, nint parameter);
    [LibraryImport("user32")] [return: MarshalAs(UnmanagedType.Bool)] private static partial bool DestroyWindow(nint window);
}