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

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

1#include "../Rendering/CloudPass11.h"
2#include "../Rendering/CloudRenderer11.h"
3#include "../Rendering/Texture11.h"
4#include "../ThirdParty/DirectXTK/ScreenGrab.h"
5#include <d3d11sdklayers.h>
6#include <wincodec.h>
7#include <fstream>
8#include <iostream>
9#include <stdexcept>
10#include <cstring>
11#include <cmath>
12#include "CloudTestDiagnostics.h"
13using namespace Rendering;
14using Microsoft::WRL::ComPtr;
15namespace fs=std::filesystem;
16static void HR(HRESULT hr,const char* what) {if(FAILED(hr))throw std::runtime_error(std::string(what)+": "+std::to_string(hr));}
17static void Check(bool value,const char* what) {if(!value)throw std::runtime_error(what);}
18static uint32_t Integer(std::ifstream& file) {uint32_t value=0;file.read(reinterpret_cast<char*>(&value),4);Check(file.good(),"truncated replay");return value;}
19static std::vector<uint8_t> Field(std::ifstream& file)
20{
21 const auto length=Integer(file);Check(length<=65536,"replay field limit");std::vector<uint8_t> data(length);
22 file.read(reinterpret_cast<char*>(data.data()),length);Check(file.good(),"truncated replay field");return data;
23}
24static std::vector<uint8_t> Pixels(Device11& gpu,ID3D11Resource* resource)
25{
26 ComPtr<ID3D11Texture2D> texture;HR(resource->QueryInterface(IID_PPV_ARGS(&texture)),"image 2D");
27 D3D11_TEXTURE2D_DESC desc{};texture->GetDesc(&desc);
28 Check(desc.Format==DXGI_FORMAT_B8G8R8A8_UNORM || desc.Format==DXGI_FORMAT_R8G8B8A8_UNORM,"image readback format");
29 const auto samples=desc.SampleDesc;
30 desc.MipLevels=desc.ArraySize=1;desc.SampleDesc={1,0};desc.BindFlags=0;desc.MiscFlags=0;
31 ComPtr<ID3D11Texture2D> resolved;
32 if(samples.Count>1)
33 {
34 HR(gpu.Device()->CreateTexture2D(&desc,nullptr,&resolved),"resolve target");
35 gpu.Context()->ResolveSubresource(resolved.Get(),0,texture.Get(),0,desc.Format);texture=resolved;
36 }
37 desc.Usage=D3D11_USAGE_STAGING;desc.CPUAccessFlags=D3D11_CPU_ACCESS_READ;
38 ComPtr<ID3D11Texture2D> staging;HR(gpu.Device()->CreateTexture2D(&desc,nullptr,&staging),"readback target");
39 gpu.Context()->CopySubresourceRegion(staging.Get(),0,0,0,0,texture.Get(),0,nullptr);
40 D3D11_MAPPED_SUBRESOURCE mapped{};HR(gpu.Context()->Map(staging.Get(),0,D3D11_MAP_READ,0,&mapped),"read pixels");
41 std::vector<uint8_t> pixels(size_t(desc.Width)*desc.Height*4);
42 for(UINT y=0;y<desc.Height;++y)memcpy(pixels.data()+size_t(y)*desc.Width*4,static_cast<char*>(mapped.pData)+y*mapped.RowPitch,desc.Width*4);
43 gpu.Context()->Unmap(staging.Get(),0);
44 if(desc.Format==DXGI_FORMAT_B8G8R8A8_UNORM)for(size_t i=0;i<pixels.size();i+=4)std::swap(pixels[i],pixels[i+2]);
45 return pixels;
46}
47static void DebugMessages(Device11& gpu)
48{
49 ComPtr<ID3D11InfoQueue> queue;
50 if(FAILED(gpu.Device()->QueryInterface(IID_PPV_ARGS(&queue))))return;
51 for(UINT64 i=0;i<queue->GetNumStoredMessages();++i)
52 {
53 SIZE_T n=0;queue->GetMessage(i,nullptr,&n);std::vector<uint8_t> data(n);auto* message=reinterpret_cast<D3D11_MESSAGE*>(data.data());
54 HR(queue->GetMessage(i,message,&n),"debug queue");
55 if(message->Severity<=D3D11_MESSAGE_SEVERITY_WARNING)throw std::runtime_error(message->pDescription);
56 }
57 queue->ClearStoredMessages();
58}
59#include "CloudQuality11.h"
60#include "CloudCityLighting11Tests.h"
61#include "CloudWeatherTests.h"
62#include "CloudVolumeCpuTests.h"
63#include "CloudLightningTests.h"
64#include "CloudTemporalPrototype11.h"
65#include "CloudTopPrototype11.h"
66#include "CloudOrganicAudit11.h"
67#include "CloudTemporal11Tests.h"
68#include "CloudLightningGpu11.h"
69
70int main(int argc,char** argv)
71{
72 InitializeCloudTestDiagnostics();
73 try
74 {
75 HR(CoInitializeEx(nullptr,COINIT_MULTITHREADED),"COM initialization");
76 bool warp=false,runtime=false,debug=true,cloudCpuOnly=false,temporalAudit=false;fs::path organicOutput,qualityOutput,topOutput,topReference,topWeather,cityOutput,cityReference,cityCapture,lightningOutput,lightningReference,shaders="outputs/direct3d11/shaders";
77 for(int i=1;i<argc;++i) {if(!strcmp(argv[i],"--warp"))warp=true;else if(!strcmp(argv[i],"--runtime"))runtime=true;
78 else if(!strcmp(argv[i],"--no-debug-layer"))debug=false;
79 else if(!strcmp(argv[i],"--cloud-cpu-only"))cloudCpuOnly=true;
80 else if(!strcmp(argv[i],"--temporal-audit"))temporalAudit=true;
81 else if(!strcmp(argv[i],"--organic-audit") && i+1<argc)organicOutput=argv[++i];
82 else if(!strcmp(argv[i],"--quality-output") && i+1<argc)qualityOutput=argv[++i];
83 else if(!strcmp(argv[i],"--top-output") && i+1<argc)topOutput=argv[++i];
84 else if(!strcmp(argv[i],"--top-reference") && i+1<argc)topReference=argv[++i];
85 else if(!strcmp(argv[i],"--top-weather") && i+1<argc)topWeather=argv[++i];
86 else if(!strcmp(argv[i],"--city-output") && i+1<argc)cityOutput=argv[++i];
87 else if(!strcmp(argv[i],"--city-capture") && i+1<argc)cityCapture=argv[++i];
88 else if(!strcmp(argv[i],"--city-reference") && i+1<argc)cityReference=argv[++i];
89 else if(!strcmp(argv[i],"--lightning-output") && i+1<argc)lightningOutput=argv[++i];
90 else if(!strcmp(argv[i],"--lightning-reference") && i+1<argc)lightningReference=argv[++i];
91 else if(!strcmp(argv[i],"--shaders") && i+1<argc)shaders=argv[++i];else throw std::runtime_error("unknown argument");}
92 if(cloudCpuOnly)
93 {
94 if(topOutput.empty())topOutput="outputs/cloud-cpu-tests";
95 fs::create_directories(topOutput);
96 CloudWeatherTests();CpuTests();CloudLightningTests();CloudTopHeightAudit(topOutput,false);
97 std::cout<<"PASS: cloud CPU weather, flight and top-shape contracts\n";CoUninitialize();return 0;
98 }
99 Device11 gpu;HR(gpu.Create({warp ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE,debug}),"native device");
100 std::cout<<gpu.Status()<<std::endl;
101 if(!lightningOutput.empty()){CloudLightningGpu(gpu,shaders,lightningReference,lightningOutput);CoUninitialize();return 0;}
102 if(temporalAudit){CloudTemporalAudit(gpu,shaders);CoUninitialize();return 0;}
103 if(!organicOutput.empty()){CloudOrganicAudit(gpu,shaders,organicOutput);CoUninitialize();return 0;}
104 if(!topOutput.empty())
105 {
106 CloudWeatherTests();CpuTests();
107 CloudTopPrototype(gpu,shaders,topOutput,topReference,topWeather);CoUninitialize();return 0;
108 }
109 if(!cityOutput.empty())
110 {
111 Check(!cityReference.empty(),"--city-reference requires pre-change cloud shader bytecode");
112 CloudCityLighting(gpu,shaders,cityReference,cityOutput,cityCapture);CoUninitialize();return 0;
113 }
114 if(!qualityOutput.empty()){CloudQuality(gpu,shaders,qualityOutput);CoUninitialize();return 0;}
115 CloudPass11 clouds;HR(clouds.Initialize(gpu.Device(),shaders),clouds.Status().c_str());
117 SetEnvironmentVariableA("RISE_CLOUD_SEED","0x52495345");SetEnvironmentVariableA("RISE_LIGHTNING_SEED","123456");
118 if(runtime)
119 {
120 SetEnvironmentVariableA("RISE_VOLUMETRIC_CLOUDS","1");
121 HR(renderer.Initialize(gpu.Device(),shaders),renderer.InitializationStatus().c_str());Check(renderer.Ready(),"native runtime enabled");
122 }
123 const fs::path folder="outputs/direct3d11/baseline/geographic";
124 const fs::path output=std::string("outputs/direct3d11/cloud-")+(runtime ? "runtime-" : "")+(warp ? "warp" : "hardware");
125 fs::create_directories(output);std::ofstream csv(output/"metrics.csv");csv<<"fixture,mean_rgb,max_rgb,pixels_over_3,mean_alpha\n";
126 unsigned count=0,failures=0;
127 for(const auto& entry:fs::directory_iterator(folder))
128 {
129 if(entry.path().extension()!=L".r11")continue;
130 std::ifstream file(entry.path(),std::ios::binary);char magic[4]{};file.read(magic,4);Check(!memcmp(magic,"R11C",4),"replay magic");
131 const UINT width=Integer(file),height=Integer(file),samples=Integer(file),fields=Integer(file);
132 Check(width>0 && height>0 && width<=4096 && height<=4096 && fields<1024,"replay dimensions");
133 Parameters11 parameters;std::vector<Texture11> textures;
134 std::map<std::string,std::vector<uint8_t>> constants;
135 for(UINT i=0;i<fields;++i)
136 {
137 const auto nameData=Field(file);const std::string name(nameData.begin(),nameData.end());
138 const auto kind=Integer(file);const auto value=Field(file);
139 if(kind==0) {parameters.Set(name,value.data(),value.size());constants[name]=value;}
140 else
141 {
142 const std::string relative(value.begin(),value.end());
143 Check(relative.rfind("inputs/",0)==0 && relative.find("..") == relative.npos,"replay texture path");
144 Texture11 texture;HR(texture.Load(gpu.Device(),gpu.Context(),(folder/relative).c_str()),texture.Status().c_str());
145 parameters.Texture(name,texture.View());textures.push_back(std::move(texture));
146 }
147 }
148 D3D11_TEXTURE2D_DESC desc{};desc.Width=width;desc.Height=height;desc.MipLevels=desc.ArraySize=1;
149 desc.SampleDesc={samples,0};desc.Format=DXGI_FORMAT_B8G8R8A8_UNORM;desc.BindFlags=D3D11_BIND_RENDER_TARGET;
150 ComPtr<ID3D11Texture2D> image;ComPtr<ID3D11RenderTargetView> target;
151 HR(gpu.Device()->CreateTexture2D(&desc,nullptr,&image),"scene texture");HR(gpu.Device()->CreateRenderTargetView(image.Get(),nullptr,&target),"scene target");
152 SceneDepth11 depth;HR(depth.Create(gpu.Device(),width,height,desc.SampleDesc),"scene depth");
153 const float black[]={0,0,0,1};gpu.Context()->ClearRenderTargetView(target.Get(),black);
154 gpu.Context()->ClearDepthStencilView(depth.WriteView(),D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL,1,0);
155 const D3D11_VIEWPORT viewport{0,0,float(width),float(height),0,1};
156 // Seed unrelated caller state and verify the pass restores it.
157 const D3D11_VIEWPORT callerViewport{3,7,27,39,.2f,.8f};gpu.Context()->RSSetViewports(1,&callerViewport);
158 gpu.Context()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP);
159 if(runtime)
160 {
161 const auto constant=[&](const char* name,auto& output) {
162 const auto& bytes=constants.at(name);Check(bytes.size()==sizeof(output),"captured constant size");memcpy(&output,bytes.data(),bytes.size());
163 };
164 CloudRenderer11::Matrix view,projection;CloudRenderer11::Color eye,layer,sun,light,ambient,glow,haze,atmosphere;
165 constant("view",view);constant("projection",projection);constant("eye",eye);constant("layer",layer);
166 constant("lightDirection",sun);constant("lightColor",light);constant("ambientColor",ambient);
167 constant("airglowColor",glow);constant("horizonHaze",haze);constant("atmosphereHaze",atmosphere);
168 const auto stem=entry.path().stem().string();const auto last=stem.rfind('-'),before=stem.rfind('-',last-1);
169 const auto convection=uint8_t(std::stoi(stem.substr(before+1,last-before-1)));
170 auto map=std::make_shared<CloudWeather::Map>();map->mips.push_back({2048,1024,std::vector<uint8_t>(2048*1024,convection)});CloudWeather::BuildMips(*map);
171 renderer.UpdateWeather(map,60);
172 for(unsigned i=0;i<100 && renderer.WeatherFrame().current!=map;++i)HR(renderer.PrepareResources(gpu.Context()),"incremental native weather upload");
173 Check(renderer.WeatherFrame().current==map,"complete native weather before publication");renderer.UpdateWeather(map,60);
174 CloudVolume::Parameters params;params.radius=layer.x;params.base=layer.y;params.top=layer.z;params.activity=layer.w;params.weather=renderer.WeatherFrame();
175 HR(renderer.Render(gpu.Context(),target.Get(),depth,viewport,view,projection,{eye.x,eye.y,eye.z},params,{sun.x,sun.y,sun.z},light,ambient,glow,haze,atmosphere),renderer.InitializationStatus().c_str());
176 }
177 else HR(clouds.Render(gpu.Context(),parameters,target.Get(),depth,viewport),clouds.Status().c_str());
178 D3D11_VIEWPORT restored{};UINT viewports=1;gpu.Context()->RSGetViewports(&viewports,&restored);
179 Check(!memcmp(&restored,&callerViewport,sizeof(restored)),"caller viewport restored");
180 D3D11_PRIMITIVE_TOPOLOGY topology{};gpu.Context()->IAGetPrimitiveTopology(&topology);
181 Check(topology==D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP,"caller topology restored");
182 Texture11 reference;HR(reference.Load(gpu.Device(),gpu.Context(),(folder/(entry.path().stem().wstring()+L".png")).c_str()),"reference image");
183 const auto expected=Pixels(gpu,reference.Resource()),actual=Pixels(gpu,image.Get());Check(expected.size()==actual.size(),"reference size");
184 double sum=0,alpha=0;unsigned maximum=0,over=0;
185 for(size_t i=0;i<actual.size();i+=4)
186 {
187 unsigned pixelMax=0;
188 for(unsigned c=0;c<3;++c){const auto delta=unsigned(std::abs(int(actual[i+c])-int(expected[i+c])));sum+=delta;pixelMax=(std::max)(pixelMax,delta);}
189 maximum=(std::max)(maximum,pixelMax);if(pixelMax>3)++over;
190 alpha+=std::abs(int(actual[i+3])-int(expected[i+3]));
191 }
192 const double mean=sum/(width*height*3.),meanAlpha=alpha/(width*height),fraction=double(over)/(width*height);
193 const bool passed=mean<=1 && fraction<=.01 && meanAlpha<=1;
194 std::cout<<(passed ? "PASS: " : "FAIL: ")<<entry.path().stem().string()<<" mean="<<mean<<" max="<<maximum<<" over3="<<fraction<<" alpha="<<meanAlpha<<std::endl;
195 csv<<entry.path().stem().string()<<','<<mean<<','<<maximum<<','<<fraction<<','<<meanAlpha<<'\n';
196 HR(DirectX::SaveWICTextureToFile(gpu.Context(),image.Get(),GUID_ContainerFormatPng,(output/(entry.path().stem().wstring()+L".png")).c_str()),"save native image");
197 DebugMessages(gpu);++count;if(!passed)++failures;
198 }
199 Check(count==9,"all nine geographical baselines replayed");
200 std::cout<<count<<" native cloud replays; "<<failures<<" failures\n";clouds.Reset();gpu.Reset();CoUninitialize();return failures ? 1 : 0;
201 }
202 catch(const std::exception& error){std::cerr<<"FAIL: "<<error.what()<<std::endl;return 1;}
203}
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
HRESULT Initialize(ID3D11Device *device, const std::filesystem::path &shaderDirectory={})
const std::string & Status() const
Definition CloudPass11.h:86
HRESULT Render(ID3D11DeviceContext *context, Parameters11 &parameters, ID3D11RenderTargetView *scene, const SceneDepth11 &depth, const D3D11_VIEWPORT &viewport, unsigned activeHeadlights=0, bool atmosphericFog=false, bool spatialRain=false, bool belowNominalCloudBase=false)
DirectX::XMFLOAT4X4 Matrix
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
HRESULT Create(ID3D11Device *device, UINT width, UINT height, DXGI_SAMPLE_DESC samples)
Definition Device11.cpp:20
ID3D11DepthStencilView * WriteView() const
Definition Device11.h:18
ID3D11ShaderResourceView * View() const
Definition Texture11.h:20
ID3D11Resource * Resource() const
Definition Texture11.h:19
const std::string & Status() const
Definition Texture11.h:21
HRESULT Load(ID3D11Device *device, ID3D11DeviceContext *context, const wchar_t *path)
Definition Texture11.cpp:70
void BuildMips(Map &map)
DIRECTX_TOOLKIT_API HRESULT __cdecl SaveWICTextureToFile(_In_ ID3D11DeviceContext *pContext, _In_ ID3D11Resource *pSource, _In_ REFGUID guidContainerFormat, _In_z_ const wchar_t *fileName, _In_opt_ const GUID *targetFormat=nullptr, _In_ std::function< void __cdecl(IPropertyBag2 *)> setCustomProps=nullptr, _In_ bool forceSRGB=false)
constexpr uint8_t Pixels[262144]
std::vector< Texel > Field(const std::vector< Segment > &cuts, float width, float height, int condition)
CloudWeather::Frame weather
Definition CloudVolume.h:35