using System.Diagnostics; 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 XFEEDToolBox.Core.Rendering; using static Vortice.Direct3D11.D3D11; namespace XFEEDToolBox.Rendering; /// GPU hologram on a true XAML composition surface, with transparent empty pixels. internal sealed class ShipGraphics : IDisposable { private readonly ID3D11Device device; private readonly ID3D11DeviceContext context; private readonly ID3D11Buffer vertices, constants, pedestal, pedestalLines; private readonly ID3D11Buffer? featureLines; private readonly ID3D11VertexShader vertexShader, fullscreenShader, lineShader; private readonly ID3D11PixelShader normalsShader, outlineShader, linePixelShader, baseShader; private readonly ID3D11PixelShader horizontalBloomShader,verticalBloomShader,compositeShader; private readonly ID3D11SamplerState linearClamp; private readonly ID3D11InputLayout input; private readonly ID3D11RasterizerState rasterizer; private readonly ID3D11BlendState blend; private readonly ID3D11DepthStencilState depthWrite, depthRead, noDepth; private ID3D11Texture2D? backBuffer, depth, normals; private ID3D11RenderTargetView? target, normalsTarget; private ID3D11ShaderResourceView? normalsView; private ID3D11Texture2D? emission,bloomHorizontal,bloomVertical; private ID3D11RenderTargetView? emissionTarget,bloomHorizontalTarget,bloomVerticalTarget; private ID3D11ShaderResourceView? emissionView,bloomHorizontalView,bloomVerticalView; private ID3D11DepthStencilView? depthView; private readonly HologramScene scene; private readonly Vector4 hologramColor; private readonly bool fitToViewport; private readonly uint vertexCount, pedestalCount, pedestalLineCount, featureLineCount; private readonly CompositionGraphicsDevice compositionDevice; private readonly ICompositionDrawingSurfaceInterop surfaceInterop; private readonly BeginSurfaceDraw beginSurfaceDraw; private readonly ResizeSurface resizeSurface; public CompositionDrawingSurface Surface { get; } private int width, height; private long frames, firstFrame, lastFrame; public long Frames => Interlocked.Read(ref frames); public int Width => width; public int Height => height; public double MeasuredFps => lastFrame > firstFrame ? (Frames - 1) * (double)Stopwatch.Frequency / (lastFrame - firstFrame) : 0; public double AngleDegrees { get; private set; } public string Adapter { get; } public int FeatureEdges => (int)featureLineCount / 2; public string LastOperation { get; private set; } = "create"; public ShipGraphics(ShipMesh mesh, HologramScene scene, int width, int height, Compositor compositor,Vector4 hologramColor,bool fitToViewport=false) { this.scene = scene;this.hologramColor=hologramColor;this.fitToViewport=fitToViewport; D3D11CreateDevice(IntPtr.Zero, DriverType.Hardware, DeviceCreationFlags.BgraSupport, [FeatureLevel.Level_11_1, FeatureLevel.Level_11_0], out device, out _, out context).CheckError(); using (var protection = context.QueryInterface()) protection.SetMultithreadProtected(true); using (var dxgiDevice = device.QueryInterface()) using (var adapter = dxgiDevice.GetAdapter()) Adapter = adapter.Description.Description; using (var unknown = new SharpGen.Runtime.ComObject(WinRT.MarshalInspectable.FromManaged(compositor))) using (var interop = unknown.QueryInterface()) { interop.CreateGraphicsDevice(device, out var created).CheckError(); compositionDevice = created!; } Surface = compositionDevice.CreateDrawingSurface(new Windows.Foundation.Size(width, height), Microsoft.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized, Microsoft.Graphics.DirectX.DirectXAlphaMode.Premultiplied); using (var unknown = new SharpGen.Runtime.ComObject(WinRT.MarshalInspectable.FromManaged(Surface))) surfaceInterop = unknown.QueryInterface(); // RECT is a pointer in the native ABI; null requests the full surface even after a resize. beginSurfaceDraw = Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(Marshal.ReadIntPtr(surfaceInterop.NativePointer), 3 * IntPtr.Size)); resizeSurface = Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(Marshal.ReadIntPtr(surfaceInterop.NativePointer), 5 * IntPtr.Size)); vertexCount = (uint)mesh.Vertices.Length; vertices = device.CreateBuffer(mesh.Vertices, BindFlags.VertexBuffer); pedestalCount = (uint)scene.Pedestal.Length; pedestalLineCount = (uint)scene.PedestalLines.Length; featureLineCount = (uint)scene.FeatureLines.Length; pedestal = device.CreateBuffer(scene.Pedestal, BindFlags.VertexBuffer); pedestalLines = device.CreateBuffer(scene.PedestalLines, BindFlags.VertexBuffer); if (featureLineCount > 0) featureLines = device.CreateBuffer(scene.FeatureLines, BindFlags.VertexBuffer); constants = device.CreateBuffer((uint)Marshal.SizeOf(), BindFlags.ConstantBuffer); var shader = Path.Combine(AppContext.BaseDirectory, "Assets", "ShipModel.hlsl"); var vs = Compiler.CompileFromFile(shader, "VSMain", "vs_5_0"); vertexShader = device.CreateVertexShader(vs.Span); fullscreenShader = device.CreateVertexShader(Compiler.CompileFromFile(shader, "VSFullscreen", "vs_5_0").Span); lineShader = device.CreateVertexShader(Compiler.CompileFromFile(shader, "VSLine", "vs_5_0").Span); normalsShader = device.CreatePixelShader(Compiler.CompileFromFile(shader, "PSNormals", "ps_5_0").Span); outlineShader = device.CreatePixelShader(Compiler.CompileFromFile(shader, "PSOutline", "ps_5_0").Span); horizontalBloomShader=device.CreatePixelShader(Compiler.CompileFromFile(shader,"PSBlurHorizontal","ps_5_0").Span); verticalBloomShader=device.CreatePixelShader(Compiler.CompileFromFile(shader,"PSBlurVertical","ps_5_0").Span); compositeShader=device.CreatePixelShader(Compiler.CompileFromFile(shader,"PSComposite","ps_5_0").Span); linearClamp=device.CreateSamplerState(new SamplerDescription(Filter.MinMagMipLinear,TextureAddressMode.Clamp,0,1,ComparisonFunction.Never,0,float.MaxValue)); linePixelShader = device.CreatePixelShader(Compiler.CompileFromFile(shader, "PSLine", "ps_5_0").Span); baseShader = device.CreatePixelShader(Compiler.CompileFromFile(shader, "PSBase", "ps_5_0").Span); input = device.CreateInputLayout([ new InputElementDescription("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElementDescription("NORMAL", 0, Format.R32G32B32_Float, 12, 0)], vs.Span); rasterizer = device.CreateRasterizerState(new RasterizerDescription(CullMode.None, FillMode.Solid)); blend = device.CreateBlendState(new BlendDescription(Blend.One, Blend.InverseSourceAlpha)); depthWrite = device.CreateDepthStencilState(new DepthStencilDescription(true, DepthWriteMask.All, ComparisonFunction.LessEqual)); depthRead = device.CreateDepthStencilState(new DepthStencilDescription(true, DepthWriteMask.Zero, ComparisonFunction.LessEqual)); noDepth = device.CreateDepthStencilState(new DepthStencilDescription(false, DepthWriteMask.Zero, ComparisonFunction.Always)); CreateTargets(width, height); } private void CreateTargets(int w, int h) { width = w; height = h; backBuffer = device.CreateTexture2D(Format.B8G8R8A8_UNorm, (uint)w, (uint)h, mipLevels: 1, bindFlags: BindFlags.RenderTarget); target = device.CreateRenderTargetView(backBuffer); normals = device.CreateTexture2D(Format.R16G16B16A16_Float, (uint)w, (uint)h, mipLevels: 1, bindFlags: BindFlags.RenderTarget | BindFlags.ShaderResource); normalsTarget = device.CreateRenderTargetView(normals); normalsView = device.CreateShaderResourceView(normals); emission=device.CreateTexture2D(Format.R16G16B16A16_Float,(uint)w,(uint)h,mipLevels:1,bindFlags:BindFlags.RenderTarget|BindFlags.ShaderResource); emissionTarget=device.CreateRenderTargetView(emission);emissionView=device.CreateShaderResourceView(emission); var bw=(uint)Math.Max(1,(w+1)/2);var bh=(uint)Math.Max(1,(h+1)/2); bloomHorizontal=device.CreateTexture2D(Format.R16G16B16A16_Float,bw,bh,mipLevels:1,bindFlags:BindFlags.RenderTarget|BindFlags.ShaderResource); bloomHorizontalTarget=device.CreateRenderTargetView(bloomHorizontal);bloomHorizontalView=device.CreateShaderResourceView(bloomHorizontal); bloomVertical=device.CreateTexture2D(Format.R16G16B16A16_Float,bw,bh,mipLevels:1,bindFlags:BindFlags.RenderTarget|BindFlags.ShaderResource); bloomVerticalTarget=device.CreateRenderTargetView(bloomVertical);bloomVerticalView=device.CreateShaderResourceView(bloomVertical); depth = device.CreateTexture2D(Format.D32_Float, (uint)w, (uint)h, mipLevels: 1, bindFlags: BindFlags.DepthStencil); depthView = device.CreateDepthStencilView(depth); } public void Resize(int w, int h) { if (w == width && h == height) return; LastOperation = $"resize {width}x{height} -> {w}x{h}"; context.OMSetRenderTargets(Array.Empty()); context.PSSetShaderResource(0, null!); context.PSSetShaderResource(1, null!); target?.Dispose(); backBuffer?.Dispose(); depthView?.Dispose(); depth?.Dispose(); normalsTarget?.Dispose(); normalsView?.Dispose(); normals?.Dispose(); DisposeBloomTargets(); // Native interop takes Win32 SIZE (two integer LONGs), not a floating-point Size. Marshal.ThrowExceptionForHR(resizeSurface(surfaceInterop.NativePointer, new PixelSize(w, h))); CreateTargets(w, h); } public void Draw(double seconds, bool present = true) { AngleDegrees = seconds * 3; var world=HologramScene.HullWorld(seconds); var (viewProjection, eye) = fitToViewport?scene.FittedCamera((float)width/height,world):scene.Camera((float)width / height); void Camera(Matrix4x4 world,bool structural=true) { var original=LoadingHologramProfile.Default; var camera = new CameraConstants(world, viewProjection, new(eye, 1),hologramColor,new(width,height,structural ? 5 : 0,structural ? .4f : .7f), original.Sobel,original.TintHigh,original.TintLow,new(original.ScanlineUvScale,.25f,(float)seconds)); context.UpdateSubresource(in camera, constants); } Camera(world); context.ClearRenderTargetView(target!, new Color4(0, 0, 0, 0)); context.ClearRenderTargetView(normalsTarget!, new Color4(0, 0, 0, 0)); context.ClearDepthStencilView(depthView!, DepthStencilClearFlags.Depth, 1, 0); context.RSSetViewport(new Viewport(width, height)); context.RSSetState(rasterizer); context.OMSetBlendState(null); context.OMSetDepthStencilState(depthWrite); context.OMSetRenderTargets(normalsTarget!, depthView); context.IASetPrimitiveTopology(PrimitiveTopology.TriangleList); context.IASetInputLayout(input); context.IASetVertexBuffer(0, vertices, 24); context.VSSetShader(vertexShader); context.PSSetShader(normalsShader); context.VSSetConstantBuffer(0, constants);context.PSSetConstantBuffer(0,constants); context.Draw(vertexCount, 0); // The loading screen renders the original hull normals/depth first, // then applies its EdgeDetection material. Keep HDR tint values intact // until bloom and final display conversion, including in small previews. context.OMSetRenderTargets(emissionTarget!); context.OMSetDepthStencilState(noDepth); context.IASetInputLayout(null); context.VSSetShader(fullscreenShader); context.PSSetShader(outlineShader); context.PSSetSampler(0,linearClamp); context.PSSetShaderResource(0, normalsView!); context.Draw(3, 0); context.PSSetShaderResource(0, null!); context.RSSetViewport(new Viewport(Math.Max(1,(width+1)/2),Math.Max(1,(height+1)/2))); context.OMSetRenderTargets(bloomHorizontalTarget!);context.PSSetShader(horizontalBloomShader); context.PSSetShaderResource(0,emissionView!);context.Draw(3,0);context.PSSetShaderResource(0,null!); context.OMSetRenderTargets(bloomVerticalTarget!);context.PSSetShader(verticalBloomShader); context.PSSetShaderResource(0,bloomHorizontalView!);context.Draw(3,0);context.PSSetShaderResource(0,null!); context.RSSetViewport(new Viewport(width,height));context.OMSetRenderTargets(target!);context.PSSetShader(compositeShader); context.PSSetShaderResource(0,emissionView!);context.PSSetShaderResource(1,bloomVerticalView!);context.Draw(3,0); context.PSSetShaderResource(0,null!);context.PSSetShaderResource(1,null!); // Optional legacy display plinth is separate from the shared hull effect. context.OMSetRenderTargets(target!, depthView); context.OMSetBlendState(blend); context.OMSetDepthStencilState(depthRead); context.IASetInputLayout(input); context.IASetPrimitiveTopology(PrimitiveTopology.LineList); context.VSSetShader(lineShader); context.PSSetShader(linePixelShader); // A stationary low-profile plinth; only the hull floats and rotates above it. if(scene.ShowPedestal) { Camera(Matrix4x4.Identity,false); context.OMSetDepthStencilState(depthWrite); context.IASetPrimitiveTopology(PrimitiveTopology.TriangleList); context.IASetVertexBuffer(0, pedestal, 24); context.VSSetShader(vertexShader); context.PSSetShader(baseShader); context.Draw(pedestalCount, 0); context.OMSetDepthStencilState(depthRead); context.IASetPrimitiveTopology(PrimitiveTopology.LineList); context.IASetVertexBuffer(0, pedestalLines, 24); context.VSSetShader(lineShader); context.PSSetShader(linePixelShader); context.Draw(pedestalLineCount, 0); } if (present) Present(); var now = Stopwatch.GetTimestamp(); if (frames == 0) firstFrame = now; lastFrame = now; Interlocked.Increment(ref frames); } public void Present() { // BeginDraw returns an atlas texture and an offset. Copy exactly our own viewport into that region. LastOperation = $"begin draw {width}x{height}"; var iid = typeof(ID3D11Texture2D).GUID; Marshal.ThrowExceptionForHR(beginSurfaceDraw(surfaceInterop.NativePointer, 0, in iid, out var pointer, out var offset)); using var destination = new ID3D11Texture2D(pointer); try { context.OMSetRenderTargets(Array.Empty()); context.CopySubresourceRegion(destination, 0, (uint)offset.X, (uint)offset.Y, 0, backBuffer!, 0, new Box(0, 0, 0, width, height, 1)); context.Flush(); } finally { LastOperation = $"end draw {width}x{height}"; surfaceInterop.EndDraw().CheckError(); } } // Probe reads this renderer's own texture; it never captures the user's screen. public byte[] ReadPixels() { var description = backBuffer!.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, backBuffer); var mapped = context.Map(staging, 0, MapMode.Read); try { var result = new byte[width * height * 4]; for (var y = 0; y < height; y++) Marshal.Copy(mapped.DataPointer + (int)(y * mapped.RowPitch), result, y * width * 4, width * 4); return result; } finally { context.Unmap(staging, 0); } } public void Dispose() { context.ClearState(); context.Flush(); target?.Dispose(); depthView?.Dispose(); backBuffer?.Dispose(); depth?.Dispose(); normalsTarget?.Dispose(); normalsView?.Dispose(); normals?.Dispose(); DisposeBloomTargets(); surfaceInterop.Dispose(); Surface.Dispose(); compositionDevice.Dispose(); blend.Dispose(); depthWrite.Dispose(); depthRead.Dispose(); noDepth.Dispose(); rasterizer.Dispose(); input.Dispose(); vertexShader.Dispose(); fullscreenShader.Dispose(); lineShader.Dispose(); normalsShader.Dispose(); outlineShader.Dispose(); linePixelShader.Dispose(); baseShader.Dispose(); horizontalBloomShader.Dispose();verticalBloomShader.Dispose();compositeShader.Dispose();linearClamp.Dispose(); vertices.Dispose(); constants.Dispose(); pedestal.Dispose(); pedestalLines.Dispose(); featureLines?.Dispose(); context.Dispose(); device.Dispose(); } private void DisposeBloomTargets() { emissionTarget?.Dispose();emissionView?.Dispose();emission?.Dispose(); bloomHorizontalTarget?.Dispose();bloomHorizontalView?.Dispose();bloomHorizontal?.Dispose(); bloomVerticalTarget?.Dispose();bloomVerticalView?.Dispose();bloomVertical?.Dispose(); } [StructLayout(LayoutKind.Sequential)] private readonly record struct CameraConstants(Matrix4x4 World, Matrix4x4 ViewProjection, Vector4 Eye,Vector4 HologramColor,Vector4 Detail, Vector4 Sobel,Vector4 TintHigh,Vector4 TintLow,Vector4 Scan); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int BeginSurfaceDraw(nint surface, nint rectangle, in Guid iid, out nint texture, out Int2 offset); [StructLayout(LayoutKind.Sequential)] private readonly record struct PixelSize(int Width, int Height); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int ResizeSurface(nint surface, PixelSize size); }