using System.Numerics;
using System.Runtime.InteropServices;
using Microsoft.UI.Composition;
using Vortice.D3DCompiler;
using Vortice.Direct3D;
using Vortice.Direct3D11;
using Vortice.DXGI;
using Vortice.Mathematics;
using Vortice.WinUI.Composition;
using static Vortice.Direct3D11.D3D11;
namespace XFEEDToolBox.Rendering;
[StructLayout(LayoutKind.Sequential)]
internal readonly record struct LocalSystemBody(Vector4 Rect,Vector4 Colour,Vector4 Light,Vector4 Style);
[StructLayout(LayoutKind.Sequential)]
internal readonly record struct LocalSystemLine(Vector4 Position,Vector4 Colour);
/// Depth-ordered, sphere-shaded GPU symbols on a genuine composition drawing surface.
internal sealed class LocalSystemGraphics:IDisposable
{
private readonly ID3D11Device device;
private readonly ID3D11DeviceContext context;
private readonly CompositionGraphicsDevice compositionDevice;
private readonly ICompositionDrawingSurfaceInterop interop;
private readonly BeginDraw beginDraw;
private readonly ResizeDraw resizeDraw;
private readonly ID3D11VertexShader bodyVs,lineVs,backgroundVs;
private readonly ID3D11PixelShader bodyPs,linePs,backgroundPs;
private readonly ID3D11InputLayout bodyLayout,lineLayout;
private readonly ID3D11Buffer bodies,lines,constants;
private readonly ID3D11RasterizerState raster;
private readonly ID3D11BlendState blend;
private readonly ID3D11DepthStencilState noDepth;
private ID3D11Texture2D? pixels;
private ID3D11RenderTargetView? target;
private int width,height;
public CompositionDrawingSurface Surface{get;}
public long Frames{get;private set;}
public LocalSystemGraphics(Compositor compositor)
{
D3D11CreateDevice(IntPtr.Zero,DriverType.Hardware,DeviceCreationFlags.BgraSupport,
[FeatureLevel.Level_11_1,FeatureLevel.Level_11_0],out device,out _,out context).CheckError();
using(var unknown=new SharpGen.Runtime.ComObject(WinRT.MarshalInspectable.FromManaged(compositor)))
using(var api=unknown.QueryInterface())
{api.CreateGraphicsDevice(device,out var created).CheckError();compositionDevice=created!;}
Surface=compositionDevice.CreateDrawingSurface(new Windows.Foundation.Size(1,1),
Microsoft.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized,Microsoft.Graphics.DirectX.DirectXAlphaMode.Premultiplied);
using(var unknown=new SharpGen.Runtime.ComObject(WinRT.MarshalInspectable.FromManaged(Surface)))
interop=unknown.QueryInterface();
beginDraw=Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(Marshal.ReadIntPtr(interop.NativePointer),3*IntPtr.Size));
resizeDraw=Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(Marshal.ReadIntPtr(interop.NativePointer),5*IntPtr.Size));
bodies=device.CreateBuffer(2048*64,BindFlags.VertexBuffer,ResourceUsage.Dynamic,CpuAccessFlags.Write);
lines=device.CreateBuffer(4096*32,BindFlags.VertexBuffer,ResourceUsage.Dynamic,CpuAccessFlags.Write);
constants=device.CreateBuffer(16,BindFlags.ConstantBuffer);
var shader=Path.Combine(AppContext.BaseDirectory,"Assets","LocalSystemMap.hlsl");
var body=Compiler.CompileFromFile(shader,"VSBody","vs_5_0");bodyVs=device.CreateVertexShader(body.Span);
bodyPs=device.CreatePixelShader(Compiler.CompileFromFile(shader,"PSBody","ps_5_0").Span);
bodyLayout=device.CreateInputLayout([
new InputElementDescription("RECT",0,Format.R32G32B32A32_Float,0,0,InputClassification.PerInstanceData,1),
new InputElementDescription("COLOR",0,Format.R32G32B32A32_Float,16,0,InputClassification.PerInstanceData,1),
new InputElementDescription("LIGHT",0,Format.R32G32B32A32_Float,32,0,InputClassification.PerInstanceData,1),
new InputElementDescription("STYLE",0,Format.R32G32B32A32_Float,48,0,InputClassification.PerInstanceData,1)],body.Span);
var line=Compiler.CompileFromFile(shader,"VSLine","vs_5_0");lineVs=device.CreateVertexShader(line.Span);
linePs=device.CreatePixelShader(Compiler.CompileFromFile(shader,"PSLine","ps_5_0").Span);
lineLayout=device.CreateInputLayout([new InputElementDescription("POSITION",0,Format.R32G32B32A32_Float,0,0),new InputElementDescription("COLOR",0,Format.R32G32B32A32_Float,16,0)],line.Span);
backgroundVs=device.CreateVertexShader(Compiler.CompileFromFile(shader,"VSBackground","vs_5_0").Span);
backgroundPs=device.CreatePixelShader(Compiler.CompileFromFile(shader,"PSBackground","ps_5_0").Span);
raster=device.CreateRasterizerState(new RasterizerDescription(CullMode.None,FillMode.Solid));
blend=device.CreateBlendState(new BlendDescription(Blend.One,Blend.InverseSourceAlpha));
noDepth=device.CreateDepthStencilState(new DepthStencilDescription(false,DepthWriteMask.Zero,ComparisonFunction.Always));
}
private void Resize(int w,int h)
{
if(width==w&&height==h)return;
context.OMSetRenderTargets(Array.Empty());target?.Dispose();pixels?.Dispose();
Marshal.ThrowExceptionForHR(resizeDraw(interop.NativePointer,new(w,h)));width=w;height=h;
pixels=device.CreateTexture2D(Format.B8G8R8A8_UNorm,(uint)w,(uint)h,mipLevels:1,bindFlags:BindFlags.RenderTarget);
target=device.CreateRenderTargetView(pixels);
}
private unsafe void Upload(ID3D11Buffer buffer,ReadOnlySpan data)where T:unmanaged
{
if(data.IsEmpty)return;var mapped=context.Map(buffer,0,MapMode.WriteDiscard);
try{var bytes=MemoryMarshal.AsBytes(data);bytes.CopyTo(new Span((void*)mapped.DataPointer,bytes.Length));}
finally{context.Unmap(buffer,0);}
}
public void Draw(ReadOnlySpan bodyData,ReadOnlySpan lineData,double w,double h,double rasterScale)
{
if(bodyData.Length>2048||lineData.Length%2!=0)throw new InvalidOperationException("Local scene exceeds GPU symbol capacity or has an incomplete line.");
Resize(Math.Clamp((int)Math.Ceiling(w*rasterScale),1,7680),Math.Clamp((int)Math.Ceiling(h*rasterScale),1,4320));
var camera=new Vector4((float)w,(float)h,0,0);context.UpdateSubresource(in camera,constants);
context.VSSetConstantBuffer(0,constants);context.PSSetConstantBuffer(0,constants);
context.OMSetRenderTargets(target!);context.RSSetViewport(new Viewport(width,height));context.RSSetState(raster);context.OMSetDepthStencilState(noDepth);
context.OMSetBlendState(null);context.IASetInputLayout(null);context.IASetPrimitiveTopology(PrimitiveTopology.TriangleList);
context.VSSetShader(backgroundVs);context.PSSetShader(backgroundPs);context.Draw(3,0);context.OMSetBlendState(blend);
if(!lineData.IsEmpty)
{
context.IASetInputLayout(lineLayout);context.IASetPrimitiveTopology(PrimitiveTopology.LineList);
context.IASetVertexBuffer(0,lines,32);context.VSSetShader(lineVs);context.PSSetShader(linePs);
// Orbit polylines share this small dynamic buffer. Each even-sized
// batch keeps line pairs intact without dropping later bodies' paths.
for(var vertexOffset=0;vertexOffset());
var iid=typeof(ID3D11Texture2D).GUID;Marshal.ThrowExceptionForHR(beginDraw(interop.NativePointer,IntPtr.Zero,in iid,out var texture,out var offset));
using(var destination=new ID3D11Texture2D(texture))
{try{context.CopySubresourceRegion(destination,0,(uint)offset.X,(uint)offset.Y,0,pixels!,0,new Box(0,0,0,width,height,1));context.Flush();}finally{interop.EndDraw().CheckError();}}
Frames++;
}
internal (int Width,int Height,byte[] Pixels) ReadPixels()
{
if(pixels is null)throw new InvalidOperationException("3D场景尚未绘制。");
var description=pixels.Description;description.BindFlags=BindFlags.None;description.CPUAccessFlags=CpuAccessFlags.Read;
description.Usage=ResourceUsage.Staging;description.MiscFlags=ResourceOptionFlags.None;
using var staging=device.CreateTexture2D(description);context.CopyResource(staging,pixels);var mapped=context.Map(staging,0,MapMode.Read);
try{var result=new byte[width*height*4];for(var y=0;y