using System.Numerics;
using System.Runtime.InteropServices;
using System.Text.Json;
using Vortice.D3DCompiler;
using Vortice.Direct3D;
using Vortice.Direct3D11;
using Vortice.DXGI;
using Vortice.Mathematics;
using XFEEDToolBox.Core.Rendering;
using XFEEDToolBox.Core.Galaxy;
using static Vortice.Direct3D11.D3D11;
const int width=512,height=512;
var output=Path.GetFullPath("artifacts/galaxy-territory-shader-validation");Directory.CreateDirectory(output);
D3D11CreateDevice(IntPtr.Zero,DriverType.Warp,DeviceCreationFlags.BgraSupport,[FeatureLevel.Level_11_0],out var device,out _,out var context).CheckError();
using var d=device;using var c=context;
using var targetTexture=device.CreateTexture2D(Format.R32G32B32A32_Float,width,height,mipLevels:1,bindFlags:BindFlags.RenderTarget);
using var target=device.CreateRenderTargetView(targetTexture);
using var staging=device.CreateTexture2D(new Texture2DDescription{Width=width,Height=height,Format=Format.R32G32B32A32_Float,ArraySize=1,MipLevels=1,
SampleDescription=new(1,0),Usage=ResourceUsage.Staging,CPUAccessFlags=CpuAccessFlags.Read});
using var blend=device.CreateBlendState(new BlendDescription(Blend.One,Blend.InverseSourceAlpha));
using var rasterizer=device.CreateRasterizerState(new RasterizerDescription(CullMode.None,FillMode.Solid));
using var noDepth=device.CreateDepthStencilState(new DepthStencilDescription(false,DepthWriteMask.Zero,ComparisonFunction.Always));
using var sampler=device.CreateSamplerState(new SamplerDescription(Filter.MinMagMipLinear,TextureAddressMode.Clamp,TextureAddressMode.Clamp,TextureAddressMode.Clamp));
var source=GalaxyOriginalTerritoryGlow.Reference;MemoryMarshal.TryGetArray(source.Payload,out ArraySegment<byte> payload);
var pin=GCHandle.Alloc(payload.Array!,GCHandleType.Pinned);ID3D11Texture2D glowTexture;
try
{
var mips=source.Mips.Select(m=>new SubresourceData(pin.AddrOfPinnedObject()+payload.Offset+m.Offset,(uint)m.RowPitch,(uint)m.DepthPitch)).ToArray();
glowTexture=device.CreateTexture2D(new Texture2DDescription{Width=512,Height=512,Format=Format.BC4_UNorm,ArraySize=1,MipLevels=10,
SampleDescription=new(1,0),Usage=ResourceUsage.Immutable,BindFlags=BindFlags.ShaderResource},mips);
}
finally{pin.Free();}
using var gt=glowTexture;using var glow=device.CreateShaderResourceView(glowTexture);
var shader=Path.GetFullPath("XFEEDToolBox/Assets/GalaxyMap.hlsl");var vertexCode=Compiler.CompileFromFile(shader,"VSPowerContour","vs_5_0");
using var vertex=device.CreateVertexShader(vertexCode.Span);using var pixel=device.CreatePixelShader(Compiler.CompileFromFile(shader,"PSPowerContour","ps_5_0").Span);
using var layout=device.CreateInputLayout([
new InputElementDescription("POSITION",0,Format.R32G32B32A32_Float,0,0,InputClassification.PerInstanceData,1),
new InputElementDescription("COLOR",0,Format.R32G32B32A32_Float,16,0,InputClassification.PerInstanceData,1)],vertexCode.Span);
using var cameraBuffer=device.CreateBuffer(80,BindFlags.ConstantBuffer);
using var instanceBuffer=device.CreateBuffer(32,BindFlags.VertexBuffer,ResourceUsage.Dynamic,CpuAccessFlags.Write);
float[] Draw(float radius,Vector4 colour,int repeats=1)
{
var lens=GalaxyCamera.Create(new(0,0,0),width,height,0,.6,8);
var instance=new Instance(new(0,0,0,radius),colour);
var camera=new Camera(new(width,height,0,.6f),new(0,0,(float)lens.FocalLength,(float)lens.Distance),new(0,0,0,8),default,
new(0,0,(float)lens.Near,(float)lens.ProjectionFar));
context.UpdateSubresource(in camera,cameraBuffer);
unsafe{var mapped=context.Map(instanceBuffer,0,MapMode.WriteDiscard);MemoryMarshal.Write(new Span<byte>((void*)mapped.DataPointer,32),in instance);context.Unmap(instanceBuffer,0);}
context.OMSetRenderTargets(target);context.ClearRenderTargetView(target,new Color4(0,0,0,0));context.RSSetViewport(new Viewport(width,height));
context.RSSetState(rasterizer);context.OMSetDepthStencilState(noDepth);context.OMSetBlendState(blend);
context.IASetInputLayout(layout);context.IASetPrimitiveTopology(PrimitiveTopology.TriangleList);context.IASetVertexBuffer(0,instanceBuffer,32);
context.VSSetShader(vertex);context.PSSetShader(pixel);context.VSSetConstantBuffer(0,cameraBuffer);context.PSSetShaderResource(8,glow);context.PSSetSampler(0,sampler);
for(var i=0;i<repeats;i++)context.DrawInstanced(6,1,0,0);
context.OMSetRenderTargets(Array.Empty<ID3D11RenderTargetView>());context.CopyResource(staging,targetTexture);
var read=context.Map(staging,0,MapMode.Read);var result=new float[width*height*4];
for(var y=0;y<height;y++)Marshal.Copy(read.DataPointer+(int)(y*read.RowPitch),result,y*width*4,width*4);context.Unmap(staging,0);return result;
}
void Require(bool condition,string message){if(!condition)throw new InvalidOperationException(message);}
var ordinary=Draw(10.5875f,new(2,1,.5f,.15f));
var doubled=Draw(10.5875f,new(2,1,.5f,.15f),2);var invisible=Draw(10.5875f,new(2,1,.5f,0));
var insideRadius=Draw(100,new(2,1,.5f,.15f));
var centre=(height/2*width+width/2)*4;var light=ordinary[centre];
Require(light>0&&ordinary.All(float.IsFinite),"Original BC4 glow did not reach the production shader.");
Require(Math.Abs(light-2*ordinary[centre+1])<1e-6&&Math.Abs(light-4*ordinary[centre+2])<1e-6,"Original linear RGB ratios changed.");
Require(ordinary.Where((_,i)=>i%4==3).All(v=>v==0),"Original additive output alpha must remain zero.");
Require(invisible.All(v=>v==0),"Zero source alpha produced a visible glow.");
Require(ordinary.Zip(doubled,(a,b)=>Math.Abs(b-2*a)).Max()<1e-6,"Glow must add without obscuring the previous layer.");
Require(insideRadius[centre]>0,"Territory billboard was incorrectly culled by an outer-sphere inside-radius rule.");
var bytes=new byte[width*height*4];
for(var i=0;i<width*height;i++){bytes[i*4]=(byte)Math.Clamp(MathF.Round(ordinary[i*4+2]*255),0,255);bytes[i*4+1]=(byte)Math.Clamp(MathF.Round(ordinary[i*4+1]*255),0,255);bytes[i*4+2]=(byte)Math.Clamp(MathF.Round(ordinary[i*4]*255),0,255);bytes[i*4+3]=255;}
File.WriteAllBytes(Path.Combine(output,"original-territory-glow.bgra"),bytes);
var report=new{passed=true,shaderSourceSha256=Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(shader))),
source=GalaxyOriginalTerritoryGlow.PayloadSha256,format="BC4_UNorm",mips=10,width,height,centre=new[]{ordinary[centre],ordinary[centre+1],ordinary[centre+2],ordinary[centre+3]},
zeroAlphaInvisible=true,additiveRgb=true,cameraInsideRadiusVisible=true,originalPreparedFrameFadeRestored=false,originalSharedRgbMultiplierRestored=false,gameAccess=false};
File.WriteAllText(Path.Combine(output,"report.json"),JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true}));Console.WriteLine(JsonSerializer.Serialize(report));
[StructLayout(LayoutKind.Sequential)] readonly record struct Camera(Vector4 Viewport,Vector4 Options,Vector4 CentreScale,Vector4 PanOrigin,Vector4 DensityExtent);
[StructLayout(LayoutKind.Sequential)] readonly record struct Instance(Vector4 CentreRadius,Vector4 Colour);
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text.Json;
using Vortice.D3DCompiler;
using Vortice.Direct3D;
using Vortice.Direct3D11;
using Vortice.DXGI;
using Vortice.Mathematics;
using XFEEDToolBox.Core.Rendering;
using XFEEDToolBox.Core.Galaxy;
using static Vortice.Direct3D11.D3D11;
const int width=512,height=512;
var output=Path.GetFullPath("artifacts/galaxy-territory-shader-validation");Directory.CreateDirectory(output);
D3D11CreateDevice(IntPtr.Zero,DriverType.Warp,DeviceCreationFlags.BgraSupport,[FeatureLevel.Level_11_0],out var device,out _,out var context).CheckError();
using var d=device;using var c=context;
using var targetTexture=device.CreateTexture2D(Format.R32G32B32A32_Float,width,height,mipLevels:1,bindFlags:BindFlags.RenderTarget);
using var target=device.CreateRenderTargetView(targetTexture);
using var staging=device.CreateTexture2D(new Texture2DDescription{Width=width,Height=height,Format=Format.R32G32B32A32_Float,ArraySize=1,MipLevels=1,
SampleDescription=new(1,0),Usage=ResourceUsage.Staging,CPUAccessFlags=CpuAccessFlags.Read});
using var blend=device.CreateBlendState(new BlendDescription(Blend.One,Blend.InverseSourceAlpha));
using var rasterizer=device.CreateRasterizerState(new RasterizerDescription(CullMode.None,FillMode.Solid));
using var noDepth=device.CreateDepthStencilState(new DepthStencilDescription(false,DepthWriteMask.Zero,ComparisonFunction.Always));
using var sampler=device.CreateSamplerState(new SamplerDescription(Filter.MinMagMipLinear,TextureAddressMode.Clamp,TextureAddressMode.Clamp,TextureAddressMode.Clamp));
var source=GalaxyOriginalTerritoryGlow.Reference;MemoryMarshal.TryGetArray(source.Payload,out ArraySegment<byte> payload);
var pin=GCHandle.Alloc(payload.Array!,GCHandleType.Pinned);ID3D11Texture2D glowTexture;
try
{
var mips=source.Mips.Select(m=>new SubresourceData(pin.AddrOfPinnedObject()+payload.Offset+m.Offset,(uint)m.RowPitch,(uint)m.DepthPitch)).ToArray();
glowTexture=device.CreateTexture2D(new Texture2DDescription{Width=512,Height=512,Format=Format.BC4_UNorm,ArraySize=1,MipLevels=10,
SampleDescription=new(1,0),Usage=ResourceUsage.Immutable,BindFlags=BindFlags.ShaderResource},mips);
}
finally{pin.Free();}
using var gt=glowTexture;using var glow=device.CreateShaderResourceView(glowTexture);
var shader=Path.GetFullPath("XFEEDToolBox/Assets/GalaxyMap.hlsl");var vertexCode=Compiler.CompileFromFile(shader,"VSPowerContour","vs_5_0");
using var vertex=device.CreateVertexShader(vertexCode.Span);using var pixel=device.CreatePixelShader(Compiler.CompileFromFile(shader,"PSPowerContour","ps_5_0").Span);
using var layout=device.CreateInputLayout([
new InputElementDescription("POSITION",0,Format.R32G32B32A32_Float,0,0,InputClassification.PerInstanceData,1),
new InputElementDescription("COLOR",0,Format.R32G32B32A32_Float,16,0,InputClassification.PerInstanceData,1)],vertexCode.Span);
using var cameraBuffer=device.CreateBuffer(80,BindFlags.ConstantBuffer);
using var instanceBuffer=device.CreateBuffer(32,BindFlags.VertexBuffer,ResourceUsage.Dynamic,CpuAccessFlags.Write);
float[] Draw(float radius,Vector4 colour,int repeats=1)
{
var lens=GalaxyCamera.Create(new(0,0,0),width,height,0,.6,8);
var instance=new Instance(new(0,0,0,radius),colour);
var camera=new Camera(new(width,height,0,.6f),new(0,0,(float)lens.FocalLength,(float)lens.Distance),new(0,0,0,8),default,
new(0,0,(float)lens.Near,(float)lens.ProjectionFar));
context.UpdateSubresource(in camera,cameraBuffer);
unsafe{var mapped=context.Map(instanceBuffer,0,MapMode.WriteDiscard);MemoryMarshal.Write(new Span<byte>((void*)mapped.DataPointer,32),in instance);context.Unmap(instanceBuffer,0);}
context.OMSetRenderTargets(target);context.ClearRenderTargetView(target,new Color4(0,0,0,0));context.RSSetViewport(new Viewport(width,height));
context.RSSetState(rasterizer);context.OMSetDepthStencilState(noDepth);context.OMSetBlendState(blend);
context.IASetInputLayout(layout);context.IASetPrimitiveTopology(PrimitiveTopology.TriangleList);context.IASetVertexBuffer(0,instanceBuffer,32);
context.VSSetShader(vertex);context.PSSetShader(pixel);context.VSSetConstantBuffer(0,cameraBuffer);context.PSSetShaderResource(8,glow);context.PSSetSampler(0,sampler);
for(var i=0;i<repeats;i++)context.DrawInstanced(6,1,0,0);
context.OMSetRenderTargets(Array.Empty<ID3D11RenderTargetView>());context.CopyResource(staging,targetTexture);
var read=context.Map(staging,0,MapMode.Read);var result=new float[width*height*4];
for(var y=0;y<height;y++)Marshal.Copy(read.DataPointer+(int)(y*read.RowPitch),result,y*width*4,width*4);context.Unmap(staging,0);return result;
}
void Require(bool condition,string message){if(!condition)throw new InvalidOperationException(message);}
var ordinary=Draw(10.5875f,new(2,1,.5f,.15f));
var doubled=Draw(10.5875f,new(2,1,.5f,.15f),2);var invisible=Draw(10.5875f,new(2,1,.5f,0));
var insideRadius=Draw(100,new(2,1,.5f,.15f));
var centre=(height/2*width+width/2)*4;var light=ordinary[centre];
Require(light>0&&ordinary.All(float.IsFinite),"Original BC4 glow did not reach the production shader.");
Require(Math.Abs(light-2*ordinary[centre+1])<1e-6&&Math.Abs(light-4*ordinary[centre+2])<1e-6,"Original linear RGB ratios changed.");
Require(ordinary.Where((_,i)=>i%4==3).All(v=>v==0),"Original additive output alpha must remain zero.");
Require(invisible.All(v=>v==0),"Zero source alpha produced a visible glow.");
Require(ordinary.Zip(doubled,(a,b)=>Math.Abs(b-2*a)).Max()<1e-6,"Glow must add without obscuring the previous layer.");
Require(insideRadius[centre]>0,"Territory billboard was incorrectly culled by an outer-sphere inside-radius rule.");
var bytes=new byte[width*height*4];
for(var i=0;i<width*height;i++){bytes[i*4]=(byte)Math.Clamp(MathF.Round(ordinary[i*4+2]*255),0,255);bytes[i*4+1]=(byte)Math.Clamp(MathF.Round(ordinary[i*4+1]*255),0,255);bytes[i*4+2]=(byte)Math.Clamp(MathF.Round(ordinary[i*4]*255),0,255);bytes[i*4+3]=255;}
File.WriteAllBytes(Path.Combine(output,"original-territory-glow.bgra"),bytes);
var report=new{passed=true,shaderSourceSha256=Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(shader))),
source=GalaxyOriginalTerritoryGlow.PayloadSha256,format="BC4_UNorm",mips=10,width,height,centre=new[]{ordinary[centre],ordinary[centre+1],ordinary[centre+2],ordinary[centre+3]},
zeroAlphaInvisible=true,additiveRgb=true,cameraInsideRadiusVisible=true,originalPreparedFrameFadeRestored=false,originalSharedRgbMultiplierRestored=false,gameAccess=false};
File.WriteAllText(Path.Combine(output,"report.json"),JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true}));Console.WriteLine(JsonSerializer.Serialize(report));
[StructLayout(LayoutKind.Sequential)] readonly record struct Camera(Vector4 Viewport,Vector4 Options,Vector4 CentreScale,Vector4 PanOrigin,Vector4 DensityExtent);
[StructLayout(LayoutKind.Sequential)] readonly record struct Instance(Vector4 CentreRadius,Vector4 Colour);