Rise
The Vieneo Province
Loading...
Searching...
No Matches
Tests/ShaderParity11Tests.cpp

Source at documentation-generation time. See Test catalog for fixture associations.

1#include "../Viewscreen/BeamProfile.h"
2// Compare the shipped SM3 material equations against their native SM5 port.
3// D3D9 is intentionally linked ONLY as the reference renderer in this fixture.
4#include "../Rendering/Device11.h"
5#include "../Rendering/Program11.h"
6#include "../Rendering/Shaders/Catalog11.generated.h"
7#include <d3dx9.h>
8#include <d3d11sdklayers.h>
9#include <array>
10#include <cmath>
11#include <cstring>
12#include <filesystem>
13#include <fstream>
14#include <iostream>
15#include <stdexcept>
16
17using Microsoft::WRL::ComPtr;
18using namespace Rendering;
19namespace
20{
21 constexpr UINT Width = 256, Height = 192;
22 void HR(HRESULT hr, const char* message)
23 {
24 if (FAILED(hr)) throw std::runtime_error(std::string(message) + ": HRESULT=" + std::to_string(hr));
25 }
26 void Check(bool ok, const char* message) { if (!ok) throw std::runtime_error(message); }
27 std::vector<char> Bytes(const std::string& name)
28 {
29 std::ifstream file(name, std::ios::binary);
30 Check(file.good(), ("open " + name).c_str());
31 return {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
32 }
33 struct Vertex
34 {
35 float position[4], normal[4], uv[2], uv2[2], color[4], emission[4];
36 };
37 constexpr Vertex vertices[] = {
38 {{-1,1,.1f,1},{0,0,-1,0},{0,0},{0,0},{.4f,.5f,.6f,1},{.05f,.07f,.1f,0}},
39 {{1,1,.1f,1},{0,0,-1,0},{1,0},{1,0},{.4f,.5f,.6f,1},{.05f,.07f,.1f,0}},
40 {{-1,-1,.1f,1},{0,0,-1,0},{0,1},{0,1},{.4f,.5f,.6f,1},{.05f,.07f,.1f,0}},
41 {{1,-1,.1f,1},{0,0,-1,0},{1,1},{1,1},{.4f,.5f,.6f,1},{.05f,.07f,.1f,0}}
42 };
43 constexpr D3D11_INPUT_ELEMENT_DESC elements[] = {
44 {"POSITION",0,DXGI_FORMAT_R32G32B32A32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA,0},
45 {"NORMAL",0,DXGI_FORMAT_R32G32B32A32_FLOAT,0,16,D3D11_INPUT_PER_VERTEX_DATA,0},
46 {"TEXCOORD",0,DXGI_FORMAT_R32G32_FLOAT,0,32,D3D11_INPUT_PER_VERTEX_DATA,0},
47 {"TEXCOORD",1,DXGI_FORMAT_R32G32_FLOAT,0,40,D3D11_INPUT_PER_VERTEX_DATA,0},
48 {"COLOR",0,DXGI_FORMAT_R32G32B32A32_FLOAT,0,48,D3D11_INPUT_PER_VERTEX_DATA,0},
49 {"COLOR",1,DXGI_FORMAT_R32G32B32A32_FLOAT,0,64,D3D11_INPUT_PER_VERTEX_DATA,0},
50 };
51
52 struct Fixture
53 {
54 bool packedColors = false;
55 UINT vertexStride = sizeof(Vertex);
56 std::vector<unsigned char> vertexBytes;
57 std::array<D3D11_INPUT_ELEMENT_DESC,ARRAYSIZE(elements)> inputElements{};
58 HWND window = nullptr;
59 Device11 gpu;
60 Parameters11 parameters;
61 ComPtr<IDirect3D9> d3d9;
62 ComPtr<IDirect3DDevice9> device9;
63 ComPtr<ID3DXEffect> effect;
64 ComPtr<IDirect3DSurface9> target9, staging9;
65 ComPtr<IDirect3DVertexDeclaration9> layout9;
66 ComPtr<ID3D11Texture2D> target11, staging11;
67 ComPtr<ID3D11RenderTargetView> rtv;
68 ComPtr<ID3D11Buffer> geometry;
69 std::vector<ComPtr<IDirect3DTexture9>> textures9;
70 std::vector<ComPtr<IDirect3DVolumeTexture9>> volumes9;
71 DWORD background=0xff102030;
72
73 explicit Fixture(bool warp, bool packed, bool debugLayer) : packedColors(packed)
74 {
75 std::copy(std::begin(elements),std::end(elements),inputElements.begin());
76 if(packed)
77 {
78 vertexStride=56;
79 inputElements[4].Format=inputElements[5].Format=DXGI_FORMAT_R8G8B8A8_UNORM;
80 inputElements[5].AlignedByteOffset=52;
81 }
82 vertexBytes.resize(vertexStride*ARRAYSIZE(vertices));
83 for(size_t i=0;i<ARRAYSIZE(vertices);++i)
84 {
85 auto* destination=vertexBytes.data()+i*vertexStride;
86 memcpy(destination,&vertices[i],packed ? 48 : sizeof(Vertex));
87 if(packed) for(unsigned channel=0;channel<2;++channel)
88 {
89 const float* color=channel ? vertices[i].emission : vertices[i].color;
90 const DWORD argb=D3DCOLOR_ARGB(unsigned(std::lround(color[3]*255)),unsigned(std::lround(color[0]*255)),
91 unsigned(std::lround(color[1]*255)),unsigned(std::lround(color[2]*255)));
92 memcpy(destination+48+channel*4,&argb,4);
93 }
94 }
95 window = CreateWindowW(L"STATIC", L"Shader parity", WS_POPUP, 0, 0, Width, Height,
96 nullptr, nullptr, GetModuleHandleW(nullptr), nullptr);
97 Check(window != nullptr, "create fixture window");
98 HR(gpu.Create({warp ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE, debugLayer}), "create D3D11");
99 std::cout << gpu.Status() << '\n';
100 d3d9.Attach(Direct3DCreate9(D3D_SDK_VERSION)); Check(bool(d3d9), "create D3D9 reference");
101 D3DPRESENT_PARAMETERS present{};
102 present.Windowed = TRUE; present.SwapEffect = D3DSWAPEFFECT_DISCARD;
103 present.BackBufferWidth = Width; present.BackBufferHeight = Height; present.hDeviceWindow = window;
104 HR(d3d9->CreateDevice(0, D3DDEVTYPE_HAL, window, D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE,
105 &present, &device9), "create reference device");
106 D3DADAPTER_IDENTIFIER9 adapter{}; HR(d3d9->GetAdapterIdentifier(0, 0, &adapter), "reference adapter");
107 std::cout << "D3D9 reference adapter=" << adapter.Description << '\n';
108 ComPtr<ID3DXBuffer> errors;
109 const auto hr = D3DXCreateEffectFromFileW(device9.Get(), L"CustomUI.fx", nullptr, nullptr,
110 D3DXSHADER_OPTIMIZATION_LEVEL3, nullptr, &effect, &errors);
111 if (errors) std::cout << static_cast<const char*>(errors->GetBufferPointer());
112 HR(hr, "compile reference effect");
113 HR(device9->CreateRenderTarget(Width, Height, D3DFMT_A8R8G8B8, D3DMULTISAMPLE_NONE, 0, FALSE, &target9, nullptr), "reference target");
114 HR(device9->CreateOffscreenPlainSurface(Width, Height, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &staging9, nullptr), "reference readback");
115 D3DVERTEXELEMENT9 declaration[] = {
116 {0,0,D3DDECLTYPE_FLOAT4,D3DDECLMETHOD_DEFAULT,D3DDECLUSAGE_POSITION,0},
117 {0,16,D3DDECLTYPE_FLOAT4,D3DDECLMETHOD_DEFAULT,D3DDECLUSAGE_NORMAL,0},
118 {0,32,D3DDECLTYPE_FLOAT2,D3DDECLMETHOD_DEFAULT,D3DDECLUSAGE_TEXCOORD,0},
119 {0,40,D3DDECLTYPE_FLOAT2,D3DDECLMETHOD_DEFAULT,D3DDECLUSAGE_TEXCOORD,1},
120 {0,48,D3DDECLTYPE_FLOAT4,D3DDECLMETHOD_DEFAULT,D3DDECLUSAGE_COLOR,0},
121 {0,64,D3DDECLTYPE_FLOAT4,D3DDECLMETHOD_DEFAULT,D3DDECLUSAGE_COLOR,1},D3DDECL_END()
122 };
123 if(packed)
124 {
125 declaration[4].Type=declaration[5].Type=D3DDECLTYPE_D3DCOLOR;
126 declaration[5].Offset=52;
127 }
128 HR(device9->CreateVertexDeclaration(declaration, &layout9), "reference input layout");
129 auto* device = gpu.Device();
130 D3D11_TEXTURE2D_DESC desc{};
131 desc.Width = Width; desc.Height = Height; desc.MipLevels = desc.ArraySize = 1;
132 desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; desc.SampleDesc.Count = 1;
133 desc.BindFlags = D3D11_BIND_RENDER_TARGET;
134 HR(device->CreateTexture2D(&desc, nullptr, &target11), "native target");
135 HR(device->CreateRenderTargetView(target11.Get(), nullptr, &rtv), "native RTV");
136 desc.Usage = D3D11_USAGE_STAGING; desc.BindFlags = 0; desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
137 HR(device->CreateTexture2D(&desc, nullptr, &staging11), "native readback");
138 D3D11_BUFFER_DESC vb{};
139 vb.ByteWidth = UINT(vertexBytes.size()); vb.Usage = D3D11_USAGE_IMMUTABLE; vb.BindFlags = D3D11_BIND_VERTEX_BUFFER;
140 D3D11_SUBRESOURCE_DATA initial{vertexBytes.data(),0,0};
141 HR(device->CreateBuffer(&vb, &initial, &geometry), "native vertex buffer");
142 for (const auto& sampler : CustomUISamplers)
143 {
144 ComPtr<ID3D11SamplerState> state;
145 HR(device->CreateSamplerState(&sampler.description, &state), "native sampler state");
146 parameters.Sampler(sampler.name, state.Get());
147 }
148 D3D11_RASTERIZER_DESC raster{};
149 raster.FillMode = D3D11_FILL_SOLID; raster.CullMode = D3D11_CULL_NONE; raster.DepthClipEnable = TRUE;
150 ComPtr<ID3D11RasterizerState> state;
151 HR(device->CreateRasterizerState(&raster, &state), "native raster state");
152 gpu.Context()->RSSetState(state.Get());
153 D3D11_DEPTH_STENCIL_DESC ds{};
154 ds.DepthFunc = D3D11_COMPARISON_ALWAYS;
155 ComPtr<ID3D11DepthStencilState> depth;
156 HR(device->CreateDepthStencilState(&ds, &depth), "native disabled depth");
157 gpu.Context()->OMSetDepthStencilState(depth.Get(),0);
158 const D3D11_VIEWPORT viewport{0,0,float(Width),float(Height),0,1};
159 gpu.Context()->RSSetViewports(1,&viewport);
160 for (const char* name : {"AlphaMap","AlphaMap2","ColorMap","ColorMap2","ColorMap3","ColorMap4",
161 "CityRoadNorth","CityRoadSouth","CloudMap","OverlayMap","RainScene","RainWater","RainVisibility","RainBeads","RainWakes"})
162 Texture(name);
163 Volume("ColorMap3");
164 }
165 ~Fixture()
166 {
167 gpu.Context()->ClearState(); parameters.ClearTextures(); gpu.Reset();
168 effect.Reset(); device9.Reset(); d3d9.Reset();
169 if (window) DestroyWindow(window);
170 }
171 void Texture(const char* name)
172 {
173 constexpr UINT Size = 16;
174 std::array<DWORD,Size*Size> pixels{};
175 for (UINT y=0;y<Size;++y) for (UINT x=0;x<Size;++x)
176 pixels[y*Size+x] = D3DCOLOR_ARGB(192,32+x*11,48+y*9,96+(x+y)*3);
177 if (strcmp(name,"RainVisibility")==0) pixels.fill(0xffffffff);
178 if (strcmp(name,"RainBeads")==0 || strcmp(name,"RainWakes")==0) pixels.fill(0);
179 ComPtr<IDirect3DTexture9> tex;
180 HR(device9->CreateTexture(Size,Size,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,&tex,nullptr),"create reference texture");
181 D3DLOCKED_RECT rect{}; HR(tex->LockRect(0,&rect,nullptr,0),"lock reference texture");
182 for(UINT y=0;y<Size;++y) memcpy(static_cast<char*>(rect.pBits)+rect.Pitch*y,pixels.data()+Size*y,Size*4);
183 tex->UnlockRect(0);
184 HR(effect->SetTexture(name,tex.Get()),"reference effect texture"); textures9.push_back(tex);
185 D3D11_TEXTURE2D_DESC desc{};
186 desc.Width=desc.Height=Size;desc.MipLevels=desc.ArraySize=1;desc.Format=DXGI_FORMAT_B8G8R8A8_UNORM;
187 desc.SampleDesc.Count=1;desc.Usage=D3D11_USAGE_IMMUTABLE;desc.BindFlags=D3D11_BIND_SHADER_RESOURCE;
188 D3D11_SUBRESOURCE_DATA data{pixels.data(),Size*4,0};
189 ComPtr<ID3D11Texture2D> texture; ComPtr<ID3D11ShaderResourceView> view;
190 HR(gpu.Device()->CreateTexture2D(&desc,&data,&texture),"create native texture");
191 HR(gpu.Device()->CreateShaderResourceView(texture.Get(),nullptr,&view),"native texture SRV");
192 parameters.Texture(name,view.Get());
193 }
194 void Volume(const char* name)
195 {
196 std::array<DWORD,64> pixels{};
197 for(UINT z=0;z<4;++z) for(UINT y=0;y<4;++y) for(UINT x=0;x<4;++x)
198 pixels[(z*4+y)*4+x]=D3DCOLOR_ARGB(192,32+x*45,48+y*40,64+z*40);
199 ComPtr<IDirect3DVolumeTexture9> tex;
200 HR(device9->CreateVolumeTexture(4,4,4,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,&tex,nullptr),"create reference volume");
201 D3DLOCKED_BOX box{}; HR(tex->LockBox(0,&box,nullptr,0),"lock reference volume");
202 for(UINT z=0;z<4;++z) for(UINT y=0;y<4;++y)
203 memcpy(static_cast<char*>(box.pBits)+box.SlicePitch*z+box.RowPitch*y,pixels.data()+z*16+y*4,16);
204 tex->UnlockBox(0); volumes9.push_back(tex);
205 D3D11_TEXTURE3D_DESC desc{};
206 desc.Width=desc.Height=desc.Depth=4;desc.MipLevels=1;desc.Format=DXGI_FORMAT_B8G8R8A8_UNORM;
207 desc.Usage=D3D11_USAGE_IMMUTABLE;desc.BindFlags=D3D11_BIND_SHADER_RESOURCE;
208 // B8G8R8A8 is not a required Texture3D format. Preserve channels in
209 // standard RGBA instead of assuming the 2D format family works.
210 desc.Format=DXGI_FORMAT_R8G8B8A8_UNORM;
211 for(auto& color:pixels) color=(color&0xff00ff00)|((color&255)<<16)|((color>>16)&255);
212 D3D11_SUBRESOURCE_DATA data{pixels.data(),16,64};
213 ComPtr<ID3D11Texture3D> texture;ComPtr<ID3D11ShaderResourceView> view;
214 HR(gpu.Device()->CreateTexture3D(&desc,&data,&texture),"create native volume");
215 HR(gpu.Device()->CreateShaderResourceView(texture.Get(),nullptr,&view),"native volume SRV");
216 parameters.Texture(std::string(name)+"Volume",view.Get());
217 }
218 void Vector(const char* name,float x,float y,float z,float w)
219 {
220 const D3DXVECTOR4 value(x,y,z,w);
221 parameters.Set(name,value); HR(effect->SetVector(name,&value),"reference vector");
222 }
223 void Configure(const ShaderPass11& pass, int scenario)
224 {
225 D3DXMATRIX identity; D3DXMatrixIdentity(&identity);
226 parameters.Set("matWorld",identity); HR(effect->SetMatrix("matWorld",&identity),"world matrix");
227 parameters.Set("matWorldViewProj",identity);
228 // Align reference pixel centers with the native rasterizer. This
229 // is fixture-only; the client port must handle screen quads itself.
230 identity._41=-1.f/Width;identity._42=1.f/Height;
231 HR(effect->SetMatrix("matWorldViewProj",&identity),"reference half-pixel correction");
232 Vector("ambient",.3f,.4f,.5f,50);
233 Vector("shiplight",.5f,.6f,.7f,1);
234 Vector("clouduv",0,.5f,.25f,.25f);
235 Vector("Sunlight",0,0,-1,1);
236 Vector("Radiosity",0,0,1,.2f);
237 const int lampCount=scenario==1 ? 2 : 0;
238 const D3DXVECTOR4 lampPositions[2]={{-.03f,0,0,.4f},{.03f,0,0,.4f}};
239 const D3DXVECTOR4 lampDirections[2]={{0,0,1,0},{0,0,1,0}};
240 const D3DXVECTOR4 lampColors[2]={{1,1,.75f,1},{1,1,.75f,1}};
241 parameters.Set("LandingLightCount",lampCount);HR(effect->SetInt("LandingLightCount",lampCount),"lamp count");
242 parameters.Set("LandingLightPosition",lampPositions);HR(effect->SetVectorArray("LandingLightPosition",lampPositions,2),"lamp positions");
243 parameters.Set("LandingLightDirection",lampDirections);HR(effect->SetVectorArray("LandingLightDirection",lampDirections,2),"lamp directions");
244 parameters.Set("LandingLightColor",lampColors);HR(effect->SetVectorArray("LandingLightColor",lampColors,2),"lamp colors");
245 const D3DXVECTOR4 lampUps[2]={{0,1,0,0},{0,1,0,0}};
246 const auto angle=LandingLights::AircraftLanding.Angles<D3DXVECTOR4>();
247 const auto profile=LandingLights::AircraftLanding.Parameters<D3DXVECTOR4>();
248 const D3DXVECTOR4 lampAngles[2]={angle,angle},lampProfiles[2]={profile,profile};
249 parameters.Set("LandingLightUp",lampUps);HR(effect->SetVectorArray("LandingLightUp",lampUps,2),"lamp up");
250 parameters.Set("LandingLightAngles",lampAngles);HR(effect->SetVectorArray("LandingLightAngles",lampAngles,2),"lamp angles");
251 parameters.Set("LandingLightParameters",lampProfiles);HR(effect->SetVectorArray("LandingLightParameters",lampProfiles,2),"lamp profiles");
252 Vector("WeapPos",.2f,.2f,.5f,float(scenario==1));
253 Vector("WeapCol",1,.6f,.2f,1);
254 Vector("Tangent",1,0,0,0);
255 Vector("Features",0,0,0,.5f);
256 Vector("volumeFog",.2f,.3f,.4f,.02f);
257 Vector("RainExtent",2,2,1.f/16,1.f/16);
258 Vector("RainU",.5f,0,0,.5f); Vector("RainV",0,-.5f,0,.5f);
259 Vector("RainSceneTexel",1.f/Width,1.f/Height,float(Width),float(Height));
260 const float opacity=.6f,cockpit=.3f;
261 parameters.Set("RainOpacity",opacity);effect->SetFloat("RainOpacity",opacity);
262 parameters.Set("RainCockpitLight",cockpit);effect->SetFloat("RainCockpitLight",cockpit);
263 const int flags[]={scenario==2,1,0,1,0};
264 parameters.Set("flags",flags);effect->SetIntArray("flags",flags,5);
265 const D3DXVECTOR4 road[]={{.03f,.04f,.05f,0},{.05f,.04f,.03f,0},{.02f,.03f,.04f,0},{.04f,.04f,.04f,0}};
266 parameters.Set("RtsRoadEmission",road);effect->SetVectorArray("RtsRoadEmission",road,4);
267 effect->SetTexture("ColorMap",textures9[2].Get());effect->SetTexture("ColorMap3",textures9[4].Get());
268 if(!strcmp(pass.technique,"TShader"))
269 {
270 if(pass.index==2 || pass.index==3)
271 if(scenario==2) {Vector("Features",141,.37f,0,0);effect->SetTexture("ColorMap3",volumes9[0].Get());}
272 if(pass.index==9)
273 {
274 Vector("clouduv",1,0,0,scenario==0 ? 0.f : scenario==1 ? 1.f : -1.f);
275 Vector("Features",.25f,.25f,.75f,.75f);
276 }
277 if(pass.index==14) Vector("ambient",.3f,.4f,.5f,.2f);
278 if(pass.index==8) Vector("Features",0,0,0,0); // Undamaged glass; damage has its own fixture.
279 if(pass.index==12) Vector("ambient",12.25f+scenario*7.5f,.4f,0,0); // Controlled animation times.
280 }
281 }
282 std::vector<DWORD> Reference(const ShaderPass11& pass)
283 {
284 HR(device9->SetRenderTarget(0,target9.Get()),"bind reference target");
285 device9->SetDepthStencilSurface(nullptr);
286 device9->SetRenderState(D3DRS_ZENABLE,FALSE);device9->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);
287 device9->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);device9->SetRenderState(D3DRS_ALPHATESTENABLE,FALSE);
288 device9->SetRenderState(D3DRS_FOGENABLE,FALSE);
289 HR(device9->Clear(0,nullptr,D3DCLEAR_TARGET,background,1,0),"clear reference");
290 HR(device9->BeginScene(),"begin reference");
291 HR(device9->SetVertexDeclaration(layout9.Get()),"bind reference layout");
292 HR(effect->SetTechnique(pass.technique),"reference technique");
293 HR(effect->Begin(nullptr,0),"begin reference effect"); HR(effect->BeginPass(pass.index),"reference pass");
294 HR(device9->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP,2,vertexBytes.data(),vertexStride),"reference draw");
295 effect->EndPass();effect->End();device9->EndScene();
296 HR(device9->GetRenderTargetData(target9.Get(),staging9.Get()),"reference readback");
297 D3DLOCKED_RECT rect{};HR(staging9->LockRect(&rect,nullptr,D3DLOCK_READONLY),"reference pixels");
298 std::vector<DWORD> result(Width*Height);
299 for(UINT y=0;y<Height;++y) memcpy(result.data()+y*Width,static_cast<char*>(rect.pBits)+y*rect.Pitch,Width*4);
300 staging9->UnlockRect();return result;
301 }
302 std::vector<DWORD> Native(Program11& program)
303 {
304 auto* context=gpu.Context(); auto* target=rtv.Get();
305 context->OMSetRenderTargets(1,&target,nullptr);
306 const float clear[]={float((background>>16)&255)/255,float((background>>8)&255)/255,float(background&255)/255,1};
307 context->ClearRenderTargetView(target,clear);
308 context->OMSetBlendState(nullptr,nullptr,UINT_MAX);
309 auto* buffer=geometry.Get();const UINT stride=vertexStride,offset=0;
310 context->IASetVertexBuffers(0,1,&buffer,&stride,&offset);
311 context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
312 const HRESULT result=program.Bind(context,parameters);
313 if(FAILED(result)) std::cerr<<program.Status()<<'\n';
314 HR(result,"bind native program");
315 context->Draw(4,0);
316 context->OMSetRenderTargets(0,nullptr,nullptr);
317 context->CopyResource(staging11.Get(),target11.Get());
318 D3D11_MAPPED_SUBRESOURCE mapped{};HR(context->Map(staging11.Get(),0,D3D11_MAP_READ,0,&mapped),"native readback");
319 std::vector<DWORD> output(Width*Height);
320 for(UINT y=0;y<Height;++y) memcpy(output.data()+y*Width,static_cast<char*>(mapped.pData)+y*mapped.RowPitch,Width*4);
321 context->Unmap(staging11.Get(),0);return output;
322 }
323 void Save(const std::vector<DWORD>& pixels,const std::filesystem::path& path)
324 {
325 D3DLOCKED_RECT rect{};HR(staging9->LockRect(&rect,nullptr,0),"lock image export");
326 for(UINT y=0;y<Height;++y) memcpy(static_cast<char*>(rect.pBits)+y*rect.Pitch,pixels.data()+y*Width,Width*4);
327 staging9->UnlockRect();HR(D3DXSaveSurfaceToFileW(path.c_str(),D3DXIFF_PNG,staging9.Get(),nullptr,nullptr),"save image");
328 }
329 void DebugCheck()
330 {
331 ComPtr<ID3D11InfoQueue> queue;
332 if(FAILED(gpu.Device()->QueryInterface(IID_PPV_ARGS(&queue)))) {std::cout<<"UNVERIFIED: debug layer unavailable\n";return;}
333 unsigned failures=0;
334 for(UINT64 i=0;i<queue->GetNumStoredMessages();++i)
335 {
336 SIZE_T size=0;queue->GetMessage(i,nullptr,&size);std::vector<char> bytes(size);
337 auto* msg=reinterpret_cast<D3D11_MESSAGE*>(bytes.data());queue->GetMessage(i,msg,&size);
338 if(msg->Severity<=D3D11_MESSAGE_SEVERITY_WARNING) {std::cerr<<msg->pDescription<<'\n';++failures;}
339 }
340 Check(!failures,"native shader debug-layer warnings/errors");
341 }
342 };
343}
344
345int main(int argc,char** argv)
346{
347 try
348 {
349 bool warp=false,packed=false,debugLayer=true;
350 std::string nativeReference;
351 std::filesystem::path shaderDirectory="outputs/direct3d11/shaders";
352 for(int i=1;i<argc;++i)
353 {
354 if(!strcmp(argv[i],"--warp"))warp=true;
355 else if(!strcmp(argv[i],"--packed"))packed=true;
356 else if(!strcmp(argv[i],"--no-debug-layer"))debugLayer=false;
357 else if(!strcmp(argv[i],"--shader-dir") && i+1<argc)shaderDirectory=argv[++i];
358 else if(!strcmp(argv[i],"--native-reference") && i+1<argc)nativeReference=argv[++i];
359 else throw std::runtime_error("unknown argument");
360 }
361 const std::filesystem::path output=std::string("outputs/direct3d11/")+(nativeReference.empty() ? "" : "native-")+"material-"+(packed ? "packed-" : "")+(warp ? "warp" : "hardware");
362 std::filesystem::create_directories(output);
363 Fixture test(warp,packed,debugLayer);
364 std::ofstream report(output/"metrics.csv");
365 report<<"technique,pass,scenario,mean_rgb_levels,max_rgb_levels,fraction_over_3,mean_alpha_levels,block16_error,relative_energy_error,relative_coverage_error,comparison\n";
366 unsigned failures=0,scenarios=0;
367 for(const auto& pass:CustomUIPasses)
368 {
369 const auto vs=Bytes((shaderDirectory/(std::string("CustomUI-")+pass.vertex+"-1.cso")).string());
370 const auto ps=Bytes((shaderDirectory/(std::string("CustomUI-")+pass.pixel+"-1.cso")).string());
371 Program11 program;
372 HR(program.Create(test.gpu.Device(),vs.data(),vs.size(),ps.data(),ps.size(),test.inputElements.data(),
373 UINT(test.inputElements.size()),packed ? 3 : 0),"create native program");
374 Program11 baseline;
375 if(!nativeReference.empty())
376 {
377 const auto oldVS=Bytes(nativeReference+"/CustomUI-"+pass.vertex+"-1.cso");
378 const auto oldPS=Bytes(nativeReference+"/CustomUI-"+pass.pixel+"-1.cso");
379 HR(baseline.Create(test.gpu.Device(),oldVS.data(),oldVS.size(),oldPS.data(),oldPS.size(),
380 test.inputElements.data(),UINT(test.inputElements.size()),packed ? 3 : 0),"create native baseline");
381 }
382 for(int scenario=0;scenario<3;++scenario)
383 {
384 test.Configure(pass,scenario);
385 const auto reference=nativeReference.empty() ? test.Reference(pass) : test.Native(baseline);
386 const auto native=test.Native(program);
387 if(!nativeReference.empty())Check(reference==native,"native baseline pixels must match exactly");
388 double sum=0,alpha=0;unsigned maximum=0,outliers=0;
389 std::vector<DWORD> diff(Width*Height);
390 for(size_t i=0;i<reference.size();++i)
391 {
392 unsigned pixelError=0;
393 for(int shift:{0,8,16})
394 {
395 const unsigned error=unsigned(std::abs(int((reference[i]>>shift)&255)-int((native[i]>>shift)&255)));
396 sum+=error;maximum=(std::max)(maximum,error);pixelError=(std::max)(pixelError,error);
397 }
398 alpha+=std::abs(int(reference[i]>>24)-int(native[i]>>24));
399 if(pixelError>3) ++outliers;
400 diff[i]=0xff000000|((std::min)(255u,pixelError*8)*0x10101);
401 }
402 const double mean=sum/(Width*Height*3),alphaMean=alpha/(Width*Height),fraction=double(outliers)/(Width*Height);
403 double energy9=0,energy11=0,blockError=0;unsigned coverage9=0,coverage11=0;
404 for(UINT by=0;by<Height;by+=16) for(UINT bx=0;bx<Width;bx+=16)
405 {
406 double a=0,b=0;
407 for(UINT y=by;y<by+16;++y) for(UINT x=bx;x<bx+16;++x)
408 {
409 const unsigned pa=reference[y*Width+x]&255,pb=native[y*Width+x]&255;
410 a+=pa;b+=pb;coverage9+=pa>3;coverage11+=pb>3;
411 }
412 energy9+=a;energy11+=b;blockError+=std::abs(a-b);
413 }
414 blockError/=Width*Height;
415 const double energyError=std::abs(energy11-energy9)/(std::max)(1.,energy9);
416 const double coverageError=std::abs(double(coverage11)-coverage9)/(std::max)(1u,coverage9);
417 const bool snow=!strcmp(pass.technique,"TShader") && pass.index==12;
418 report<<pass.technique<<','<<pass.index<<','<<scenario<<','<<mean<<','<<maximum<<','<<fraction<<','<<alphaMean
419 <<','<<blockError<<','<<energyError<<','<<coverageError<<','<<(!nativeReference.empty() ? "native-exact" : snow ? "procedural-snow" : "pixel")<<'\n';
420 std::cout<<pass.technique<<'/'<<pass.index<<'/'<<scenario<<": mean RGB="<<mean<<" max="<<maximum<<" >3="<<fraction<<" alpha="<<alphaMean<<'\n';
421 const auto name=std::string(pass.technique)+"-"+std::to_string(pass.index)+"-"+std::to_string(scenario);
422 test.Save(reference,output/(name+(nativeReference.empty() ? "-d3d9.png" : "-before.png")));
423 test.Save(native,output/(name+"-d3d11.png"));test.Save(diff,output/(name+"-diff8x.png"));
424 // The legacy holiday shader hashes fractional floating-point
425 // division. SM3/SM5 reciprocal rounding moves individual flakes.
426 // Gate its spatial distribution, energy and density explicitly;
427 // this exception never applies to scene materials or clouds.
428 const bool matches=snow ? mean<=2 && blockError<=.5 && energyError<=.05 && coverageError<=.05 && alphaMean<=1
429 : mean<=1 && fraction<=.01 && alphaMean<=1;
430 if(!matches) ++failures;
431 ++scenarios;
432 }
433 }
434 test.DebugCheck();
435 std::cout<<"Compared "<<scenarios<<" material fixtures; "<<failures<<" exceed RGB/alpha tolerances\n";
436 Check(!failures,"material image parity (see metrics and images)");
437 return 0;
438 }
439 catch(const std::exception& error) {std::cerr<<"FAIL: "<<error.what()<<'\n';return 1;}
440}
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
SCRIPT_CONTROL SCRIPT_STATE const void DWORD
Reference
Definition ServerTypes.h:40
ID3D11DeviceContext * Context() const
Definition Device11.h:66
ID3D11Device * Device() const
Definition Device11.h:65
const std::string & Status() const
Definition Device11.h:75
HRESULT Create(const DeviceOptions11 &options={})
Definition Device11.cpp:84
void Set(const std::string &name, const void *data, size_t bytes)
Definition Program11.cpp:45
void Texture(const std::string &name, ID3D11ShaderResourceView *value)
Definition Program11.cpp:55
void Sampler(const std::string &name, ID3D11SamplerState *value)
Definition Program11.cpp:66
HRESULT Create(ID3D11Device *device, const void *vertexCode, size_t vertexSize, const void *pixelCode, size_t pixelSize, const D3D11_INPUT_ELEMENT_DESC *elements=nullptr, UINT elementCount=0, UINT bgraColorMask=0)
const std::string & Status() const
Definition Program11.h:67
HRESULT Bind(ID3D11DeviceContext *context, const Parameters11 &parameters)
Sphere Configure(bool simulator, Point center, float radius, float solarRadius)
constexpr float Width
constexpr float Height
constexpr Profile AircraftLanding
Definition BeamProfile.h:38
DirectX::XMFLOAT3 Vector
Definition Math11.h:7
const ShaderPass11 CustomUIPasses[]
matches(path, entry)
path
Definition erin.py:153
PackedVector Parameters(float extinctionPerKm=0) const
Definition BeamProfile.h:24
PackedVector Angles() const
Definition BeamProfile.h:18