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

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

1// Compare the production fog function against a frozen generated shader.
2// Float targets catch differences that an 8-bit screenshot could conceal.
3#include "../Rendering/Device11.h"
4#include "../Rendering/Program11.h"
5#include "../Viewscreen/CloudVolume.h"
6#include <d3dcompiler.h>
7#include <d3d11sdklayers.h>
8#include <DirectXMath.h>
9#include <algorithm>
10#include <array>
11#include <cmath>
12#include <filesystem>
13#include <fstream>
14#include <iostream>
15#include <numeric>
16#include <stdexcept>
17using namespace Rendering;
18using namespace DirectX;
19using Microsoft::WRL::ComPtr;
20namespace
21{
22 void Check(bool ok,const char* reason){if(!ok)throw std::runtime_error(reason);}
23 void HR(HRESULT hr,const char* reason){if(FAILED(hr))throw std::runtime_error(std::string(reason)+": "+std::to_string(hr));}
24 std::string Read(const std::filesystem::path& path)
25 {std::ifstream input(path,std::ios::binary);Check(bool(input),"open fog source");return {std::istreambuf_iterator<char>(input),{}};}
26 std::string Shader(const std::filesystem::path& path)
27 {
28 const auto source=Read(path);const auto first=source.find("struct RainColumn");
29 const auto last=source.find("float4 localBaseInfo;",first);
30 Check(first!=std::string::npos && last!=std::string::npos,"locate production fog functions");
31 return R"(
32float4 eye,horizonHaze,rainInfo,rainU,rainV,rainNormal;
33float4 StrikeColor,StrikeGround,StrikeTop;
34float4 forward,right,up,limits;
35Texture2D rainImage;SamplerState rainSampler;
36)"+source.substr(first,last-first)+R"(
37struct Vertex {float4 position:SV_Position;float2 uv:TEXCOORD0;};
38Vertex VS(uint id:SV_VertexID) {
39 Vertex v;v.uv=float2(id==2?2:0,id==1?2:0);
40 v.position=float4(v.uv.x*2-1,1-v.uv.y*2,0,1);return v;
41}
42float4 PS(Vertex v):SV_Target {
43 float3 direction=normalize(forward.xyz+right.xyz*(v.uv.x*2-1)+up.xyz*(1-v.uv.y*2));
44 float distance=limits.x;
45 if(limits.y>0) {
46 const float depths[8]={0,.7499,.7501,47.999,48.001,127.999,128,256};
47 distance=depths[min(7,uint(v.uv.y*8))];
48 }
49 return RainAlongRay(direction,distance);
50})";
51 }
52 ComPtr<ID3DBlob> Compile(const std::string& source,const char* entry,const char* profile)
53 {
54 ComPtr<ID3DBlob> code,errors;
55 const auto result=D3DCompile(source.data(),source.size(),"ProductionFog",nullptr,nullptr,entry,profile,
56 D3DCOMPILE_ENABLE_STRICTNESS|D3DCOMPILE_PACK_MATRIX_ROW_MAJOR|D3DCOMPILE_OPTIMIZATION_LEVEL3,0,&code,&errors);
57 if(errors)std::cerr<<static_cast<const char*>(errors->GetBufferPointer());HR(result,"compile fog fixture");return code;
58 }
59 struct Fixture
60 {
61 Device11 gpu;std::array<Program11,2> programs;Parameters11 values;
62 ComPtr<ID3D11Texture2D> image,target,staging;
63 ComPtr<ID3D11ShaderResourceView> texture;
64 ComPtr<ID3D11RenderTargetView> rtv;
65 ComPtr<ID3D11DepthStencilState> depth;
66 ComPtr<ID3D11RasterizerState> raster;
67 UINT width=0,height=0;
68 Fixture(bool warp,bool debug,const std::filesystem::path& before,const std::filesystem::path& after)
69 {
70 HR(gpu.Create({warp?D3D_DRIVER_TYPE_WARP:D3D_DRIVER_TYPE_HARDWARE,debug}),"create device");
71 std::cout<<gpu.Status()<<std::endl;
72 unsigned index=0;
73 for(const auto& path:{before,after})
74 {
75 const auto source=Shader(path);const auto vs=Compile(source,"VS","vs_5_0"),ps=Compile(source,"PS","ps_5_0");
76 HR(programs[index++].Create(gpu.Device(),vs->GetBufferPointer(),vs->GetBufferSize(),ps->GetBufferPointer(),ps->GetBufferSize()),"create fog program");
77 }
78 D3D11_TEXTURE2D_DESC td{};td.Width=td.Height=64;td.MipLevels=td.ArraySize=td.SampleDesc.Count=1;
79 td.Format=DXGI_FORMAT_R32G32B32A32_FLOAT;td.BindFlags=D3D11_BIND_SHADER_RESOURCE;
80 HR(gpu.Device()->CreateTexture2D(&td,nullptr,&image),"create weather grid");
81 HR(gpu.Device()->CreateShaderResourceView(image.Get(),nullptr,&texture),"create grid view");values.Texture("rainImage",texture.Get());
82 D3D11_SAMPLER_DESC sd{};sd.Filter=D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT;
83 sd.AddressU=sd.AddressV=sd.AddressW=D3D11_TEXTURE_ADDRESS_CLAMP;
84 ComPtr<ID3D11SamplerState> sampler;HR(gpu.Device()->CreateSamplerState(&sd,&sampler),"create sampler");values.Sampler("rainSampler",sampler.Get());
85 D3D11_DEPTH_STENCIL_DESC dd{};HR(gpu.Device()->CreateDepthStencilState(&dd,&depth),"depth off");
86 D3D11_RASTERIZER_DESC rd{};rd.FillMode=D3D11_FILL_SOLID;rd.CullMode=D3D11_CULL_NONE;rd.DepthClipEnable=TRUE;
87 HR(gpu.Device()->CreateRasterizerState(&rd,&raster),"raster state");
88 Resize(160,96);
89 }
90 void Resize(UINT w,UINT h)
91 {
92 gpu.Context()->ClearState();target.Reset();staging.Reset();rtv.Reset();width=w;height=h;
93 D3D11_TEXTURE2D_DESC d{};d.Width=w;d.Height=h;d.MipLevels=d.ArraySize=d.SampleDesc.Count=1;
94 d.Format=DXGI_FORMAT_R32G32B32A32_FLOAT;d.BindFlags=D3D11_BIND_RENDER_TARGET;
95 HR(gpu.Device()->CreateTexture2D(&d,nullptr,&target),"float target");
96 HR(gpu.Device()->CreateRenderTargetView(target.Get(),nullptr,&rtv),"float target view");
97 d.BindFlags=0;d.Usage=D3D11_USAGE_STAGING;d.CPUAccessFlags=D3D11_CPU_ACCESS_READ;
98 HR(gpu.Device()->CreateTexture2D(&d,nullptr,&staging),"float readback");
99 }
100 void Configure(float altitude,float pitch,unsigned weather,bool flash,bool variedDepth=true)
101 {
102 std::array<XMFLOAT4,64*64> cells;
103 for(unsigned y=0;y<64;++y)for(unsigned x=0;x<64;++x)
104 {
105 const bool boundary=x>=28 && x<40 && y>=20 && y<50;
106 const float surface=boundary ? 2.f : 0.f;
107 float precipitation=weather==1 ? 16.f : weather==2 ? (boundary ? 16.f : 2.f) :
108 weather==5 ? (boundary ? 2.00001f : 1.99999f) : 2.f;
109 const float ceiling=weather==3 ? surface : surface+(weather==4 ? .01f : 2.8f);
110 const float visibility=weather==4 ? (boundary ? .01f : .75f) : boundary ? 3.f : 27.72f;
111 cells[y*64+x]={surface,ceiling,visibility,precipitation};
112 }
113 gpu.Context()->UpdateSubresource(image.Get(),0,nullptr,cells.data(),64*sizeof(XMFLOAT4),0);
114 const auto mapping=CloudVolume::ProjectGround(0,1019,1019);const float radius=CloudVolume::Parameters{}.radius;
115 values.Set("rainInfo",XMFLOAT4(1,42.16f,radius,0));
116 values.Set("rainU",XMFLOAT4(mapping.east.x,mapping.east.y,mapping.east.z,mapping.u));
117 values.Set("rainV",XMFLOAT4(mapping.down.x,mapping.down.y,mapping.down.z,mapping.v));
118 values.Set("rainNormal",XMFLOAT4(mapping.normal.x,mapping.normal.y,mapping.normal.z,0));
119 values.Set("eye",XMFLOAT4(0,radius+altitude,0,0));values.Set("horizonHaze",XMFLOAT4(.3f,.4f,.5f,42.16f));
120 values.Set("StrikeColor",XMFLOAT4(.4f,.6f,1.f,flash ? 12.f : 0.f));
121 values.Set("StrikeGround",XMFLOAT4(.3f,-altitude,-1,0));values.Set("StrikeTop",XMFLOAT4(.3f,3-altitude,-1,0));
122 const float angle=XMConvertToRadians(pitch);
123 values.Set("forward",XMFLOAT4(0,std::sin(angle),-std::cos(angle),0));
124 values.Set("right",XMFLOAT4(.8f,0,0,0));values.Set("up",XMFLOAT4(0,.5f*std::cos(angle),.5f*std::sin(angle),0));
125 values.Set("limits",XMFLOAT4(128,variedDepth ? 1.f : 0.f,0,0));
126 }
127 void Draw(unsigned version)
128 {
129 auto* context=gpu.Context();auto* output=rtv.Get();context->OMSetRenderTargets(1,&output,nullptr);
130 context->OMSetDepthStencilState(depth.Get(),0);context->OMSetBlendState(nullptr,nullptr,UINT_MAX);context->RSSetState(raster.Get());
131 const D3D11_VIEWPORT viewport{0,0,float(width),float(height),0,1};context->RSSetViewports(1,&viewport);
132 context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
133 HR(programs[version].Bind(context,values),"bind fog program");context->Draw(3,0);
134 }
135 std::vector<XMFLOAT4> Pixels()
136 {
137 auto* context=gpu.Context();context->CopyResource(staging.Get(),target.Get());D3D11_MAPPED_SUBRESOURCE mapped{};
138 HR(context->Map(staging.Get(),0,D3D11_MAP_READ,0,&mapped),"read float pixels");std::vector<XMFLOAT4> out(size_t(width)*height);
139 for(UINT y=0;y<height;++y)memcpy(out.data()+size_t(y)*width,static_cast<const char*>(mapped.pData)+size_t(y)*mapped.RowPitch,size_t(width)*sizeof(XMFLOAT4));
140 context->Unmap(staging.Get(),0);return out;
141 }
142 void Clean()
143 {
144 ComPtr<ID3D11InfoQueue> queue;if(FAILED(gpu.Device()->QueryInterface(IID_PPV_ARGS(&queue))))return;
145 for(UINT64 i=0;i<queue->GetNumStoredMessages();++i)
146 {
147 SIZE_T length=0;queue->GetMessage(i,nullptr,&length);std::vector<char> bytes(length);
148 auto* message=reinterpret_cast<D3D11_MESSAGE*>(bytes.data());HR(queue->GetMessage(i,message,&length),"debug message");
149 if(message->Severity<=D3D11_MESSAGE_SEVERITY_WARNING)throw std::runtime_error(message->pDescription);
150 }
151 queue->ClearStoredMessages();
152 }
153 double Time(unsigned version)
154 {
155 auto* context=gpu.Context();ComPtr<ID3D11Query> frequency,begin,end;
156 D3D11_QUERY_DESC d{D3D11_QUERY_TIMESTAMP_DISJOINT,0};HR(gpu.Device()->CreateQuery(&d,&frequency),"timestamp frequency");
157 d.Query=D3D11_QUERY_TIMESTAMP;HR(gpu.Device()->CreateQuery(&d,&begin),"timestamp begin");HR(gpu.Device()->CreateQuery(&d,&end),"timestamp end");
158 Draw(version);Draw(version);context->Begin(frequency.Get());context->End(begin.Get());
159 constexpr unsigned batch=4;for(unsigned i=0;i<batch;++i)Draw(version);
160 context->End(end.Get());context->End(frequency.Get());context->Flush();
161 const auto read=[&](ID3D11Query* query,void* data,UINT bytes){HRESULT hr;const auto deadline=GetTickCount64()+30000;
162 while((hr=context->GetData(query,data,bytes,0))==S_FALSE){Check(GetTickCount64()<deadline,"GPU query timeout");Sleep(1);}HR(hr,"GPU timestamp");};
163 D3D11_QUERY_DATA_TIMESTAMP_DISJOINT f{};UINT64 a=0,b=0;read(frequency.Get(),&f,sizeof(f));read(begin.Get(),&a,sizeof(a));read(end.Get(),&b,sizeof(b));
164 Check(!f.Disjoint && f.Frequency,"valid timestamp batch");return double(b-a)*1000/f.Frequency/batch;
165 }
166 };
167 void Save(const std::filesystem::path& path,const std::vector<XMFLOAT4>& pixels,UINT w,UINT h)
168 {
169 BITMAPFILEHEADER file{};BITMAPINFOHEADER info{};file.bfType=0x4d42;file.bfOffBits=sizeof(file)+sizeof(info);file.bfSize=file.bfOffBits+w*h*4;
170 info.biSize=sizeof(info);info.biWidth=LONG(w);info.biHeight=-LONG(h);info.biPlanes=1;info.biBitCount=32;info.biCompression=BI_RGB;
171 std::ofstream output(path,std::ios::binary);output.write(reinterpret_cast<char*>(&file),sizeof(file));output.write(reinterpret_cast<char*>(&info),sizeof(info));
172 for(size_t i=0;i<pixels.size();++i)
173 {
174 const auto& p=pixels[i];const float background=((i/w/8+i%w/8)%2) ? .1f : .7f;
175 const auto channel=[&](float value){return uint32_t(std::clamp(value+background*(1-p.w),0.f,1.f)*255+.5f);};
176 const uint32_t color=0xff000000|(channel(p.x)<<16)|(channel(p.y)<<8)|channel(p.z);
177 output.write(reinterpret_cast<const char*>(&color),4);
178 }
179 Check(bool(output),"save comparison image");
180 }
181}
182int main(int argc,char** argv)
183{
184 try
185 {
186 bool warp=false,debug=true,benchmark=false;std::filesystem::path before,after="Rendering/Shaders/CloudVolume.hlsl",output;
187 for(int i=1;i<argc;++i)
188 {
189 const std::string arg=argv[i];
190 if(arg=="--warp")warp=true;else if(arg=="--no-debug-layer")debug=false;else if(arg=="--benchmark")benchmark=true;
191 else if(arg=="--reference" && i+1<argc)before=argv[++i];else if(arg=="--candidate" && i+1<argc)after=argv[++i];
192 else if(arg=="--output" && i+1<argc)output=argv[++i];else throw std::runtime_error("unknown argument");
193 }
194 Check(!before.empty(),"--reference requires frozen pre-change generated CloudVolume.hlsl");
195 if(!output.empty())std::filesystem::create_directories(output);
196 Fixture fixture(warp,debug,before,after);size_t compared=0;unsigned cases=0;double worst=0;
197 for(float altitude:{-2.f,.3f,2.074463f,8.499f,9.999f,10.001f,15.f,117.f})
198 for(float pitch:{-85.f,-30.f,0.f,45.f,85.f})for(unsigned weather=0;weather<6;++weather)for(bool flash:{false,true})
199 {
200 fixture.Configure(altitude,pitch,weather,flash);fixture.Draw(0);const auto reference=fixture.Pixels();
201 fixture.Draw(1);const auto candidate=fixture.Pixels();
202 for(size_t i=0;i<reference.size();++i)
203 {
204 const float* a=&reference[i].x;const float* b=&candidate[i].x;
205 for(unsigned c=0;c<4;++c){Check(std::isfinite(a[c]) && std::isfinite(b[c]),"finite fog output");worst=std::max(worst,double(std::abs(a[c]-b[c])));}
206 }
207 compared+=reference.size();++cases;
208 if(!output.empty() && altitude==2.074463f && pitch==0 && (weather==0 || weather==2))
209 {
210 const auto name="weather"+std::to_string(weather)+(flash ? "-flash" : "-steady");
211 Save(output/(name+"-before.bmp"),reference,fixture.width,fixture.height);Save(output/(name+"-after.bmp"),candidate,fixture.width,fixture.height);
212 }
213 }
214 fixture.Clean();std::cout<<cases<<" scenes; "<<compared<<" float RGBA pixels; maximum absolute difference="<<worst<<std::endl;
215 Check(worst==0,"fog integration must retain exact float color and opacity");
216 if(benchmark)
217 {
218 Check(!warp && !debug,"benchmark requires hardware and --no-debug-layer");fixture.Resize(3440,1351);
219 for(unsigned weather:{0u,1u,2u})for(float pitch:{0.f,45.f})
220 {
221 fixture.Configure(2.074463f,pitch,weather,false,false);std::array<std::vector<double>,2> times;
222 for(unsigned trial=0;trial<8;++trial)for(unsigned index=0;index<2;++index)
223 {const unsigned version=(trial+index)%2;const auto elapsed=fixture.Time(version);if(trial)times[version].push_back(elapsed);}
224 for(auto& values:times)std::sort(values.begin(),values.end());
225 std::cout<<"weather="<<weather<<" pitch="<<pitch<<" before_ms="<<times[0][3]<<" after_ms="<<times[1][3]<<" ratio="<<times[1][3]/times[0][3]<<std::endl;
226 }
227 }
228 fixture.Clean();std::cout<<"PASS: fog integration parity"<<std::endl;return 0;
229 }
230 catch(const std::exception& error){std::cerr<<"FAIL: "<<error.what()<<std::endl;return 1;}
231}
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
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
Sphere Configure(bool simulator, Point center, float radius, float solarRadius)
GroundProjection ProjectGround(int cube, int u, int v)
Definition DDS.h:24
Sources Create(int count, Kind kind, float sideArmKm, float forwardKm)
Definition EngineAudio.h:55
constexpr uint8_t Pixels[262144]
void Bind(Rendering::RenderDevice &device, Rendering::RenderTexture *texture)
HRESULT Draw(Rendering::RenderDevice *device, Rendering::RenderTexture *texture, Rendering::RenderBuffer *vertices, const RiseMath::Matrix &world, UINT segments, Rendering::RenderMaterial *volumeEffect=nullptr, float physicalScale=1)
info
Definition erin.py:153