Rise
The Vieneo Province
Loading...
Searching...
No Matches
CloudPass11.cpp
Go to the documentation of this file.
1#include "CloudPass11.h"
2#include "FrameProfiler11.h"
3#include "ShaderBytecode11.h"
6#include <cmath>
7#include <climits>
8#include <thread>
9#include <mutex>
10#include <condition_variable>
11#include <atomic>
12#ifdef RISE_CLOUD_TEST_TEMPORAL_DIAGNOSTICS
13#include <d3d11sdklayers.h>
14#endif
15
16using Microsoft::WRL::ComPtr;
17namespace Rendering
18{
19 namespace
20 {
21 void Unbind(ID3D11DeviceContext* context)
22 {
23 ID3D11ShaderResourceView* empty[D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT]{};
24 context->PSSetShaderResources(0,UINT(std::size(empty)),empty);
25 context->VSSetShaderResources(0,UINT(std::size(empty)),empty);
26 context->OMSetRenderTargets(0,nullptr,nullptr);
27 }
28 struct Restore
29 {
30 ComPtr<ID3D11DeviceContext1> context;
31 ComPtr<ID3DDeviceContextState> previous;
32 ~Restore() { if(previous) {Unbind(context.Get());context->SwapDeviceContextState(previous.Get(),nullptr);} }
33 };
34 }
35 HRESULT CloudPass11::Fail(const char* stage,HRESULT hr)
36 {
37 status=std::string("native clouds: ")+stage+"; HRESULT="+std::to_string(hr);return hr;
38 }
40 {
43 loadingStep={};
45#ifdef RISE_CLOUD_TEST_TEMPORAL_DIAGNOSTICS
46 testTopLoadingFallbacks=0;
47#endif
50 for(auto* list:{&adPixel,&adEdge,&adFogPixel,&adFogEdge})for(auto& program:*list)program.Reset();
51 for(auto& program:compositePixel) program.Reset();
52 for(auto& program:compositeEdge) program.Reset();
53 for(auto& program:compositeFogPixel) program.Reset();
54 for(auto& program:compositeFogEdge) program.Reset();
55 for(auto& program:rainPixel) program.Reset();
56 for(auto& program:rainEdge) program.Reset();
57 for(auto& program:rainClassify) program.Reset();
59 hiddenWrite.Reset();hiddenRead.Reset();reduceHidden.Reset();for(auto& program:classifyHidden)program.Reset();hiddenAvailable={};
60 for(auto* programs:{&cachedComposite,&visibleComposite})for(auto& program:*programs)program.Reset();cachedCompositeAvailable={};
61 for(auto* list:{&firstHitClassify,&seededEdge,&seededFogEdge})for(auto& program:*list)program.Reset();sharedSearchAvailable={};
62 for(auto& program:completeComposite)program.Reset();compositeWorkAvailable={};
63 compositeArgumentsView.Reset();compositeArguments.Reset();for(auto& scan:compositeWorkScan)scan.Reset();
66 for(auto& direct:topDirect)direct.Reset();
67 activeOrganic=nullptr;organicReady=false;
68 samplers.clear();blend.Reset();straightBlend.Reset();compositeDepth.Reset();disabledDepth.Reset();raster.Reset();device.Reset();
69 status="native cloud pass not initialized";
70 }
71 HRESULT CloudPass11::Initialize(ID3D11Device* native,const std::filesystem::path& directory)
72 {
73 Reset();if(!native) return E_INVALIDARG;device=native;shaderDirectory=directory;
74 ComPtr<ID3D11Device1> device1;
75 HRESULT hr=device.As(&device1);
76 if(FAILED(hr)) return Fail("D3D11.1 runtime context-state support required",hr);
77 const D3D_FEATURE_LEVEL level=device->GetFeatureLevel();
78 hr=device1->CreateDeviceContextState(0,&level,1,D3D11_SDK_VERSION,__uuidof(ID3D11Device),nullptr,&passState);
79 if(FAILED(hr)) return Fail("create isolated graphics context state",hr);
80 // Validate the complete package without asking the driver to allocate/JIT
81 // every inactive MSAA, fog and cloud-mode variant in this 32-bit process.
82 // First use creates the exact precompiled program; subsequent draws reuse it.
83 for(const char* name:{"CloudVolume-Fullscreen11-1.cso","CloudVolume-march-1.cso","CloudVolume-headlightDepthPixel-1.cso"})
84 if(!HasShaderBytecode11(directory/name))return Fail(name,HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND));
85 for(const char* entry:{"compositeRainPixel","compositeRainEdge","compositeRainClassify",
86 "compositePixel","compositeEdge","compositeFogPixel","compositeFogEdge"})
87 for(unsigned i=0;i<4;++i)
88 {
89 const auto name=std::string("CloudVolume-")+entry+"-"+std::to_string(1u<<i)+".cso";
90 if(!HasShaderBytecode11(directory/name))return Fail(name.c_str(),HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND));
91 }
92 // Optional for historical offscreen packages. Availability is separate
93 // from residency, so ground startup need not create the orbital program.
94 orbitalReady=HasShaderBytecode11(directory/"CloudOrganicOrbit-march-1.cso");
95 orbitalCoverageAvailable=orbitalReady && HasShaderBytecode11(directory/"CloudOrganicCoverage-resolveCoverage-1.cso");
96 if(orbitalReady && !HasShaderBytecode11(directory/"CloudTemporal-resolve-1.cso"))
97 return Fail("cloud history program",HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND));
98 const D3D11_INPUT_ELEMENT_DESC ringLayout[]={
99 {"POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA,0},
100 {"COLOR",0,DXGI_FORMAT_R8G8B8A8_UNORM,0,12,D3D11_INPUT_PER_VERTEX_DATA,0},
101 {"TEXCOORD",0,DXGI_FORMAT_R32G32_FLOAT,0,16,D3D11_INPUT_PER_VERTEX_DATA,0}};
102 const D3D11_INPUT_ELEMENT_DESC particleLayout[]={
103 {"POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA,0},
104 {"TEXCOORD",0,DXGI_FORMAT_R32G32B32A32_FLOAT,0,12,D3D11_INPUT_PER_VERTEX_DATA,0}};
105 const auto geometryProgram=[&](Program11& out,const char* source,const char* vertexEntry,const char* pixelEntry,
106 const D3D11_INPUT_ELEMENT_DESC* layout,UINT count,UINT packed) {
107 const auto vertexCode=ReadShaderBytecode11(directory/(std::string(source)+"-"+vertexEntry+"-1.cso"));
108 const auto pixelCode=ReadShaderBytecode11(directory/(std::string(source)+"-"+pixelEntry+"-1.cso"));
109 return out.Create(device.Get(),vertexCode.data(),vertexCode.size(),pixelCode.data(),pixelCode.size(),layout,count,packed);
110 };
111 if(FAILED(hr=geometryProgram(skyRing,"CloudVolume","ringVertex","ringPixel",ringLayout,3,1))) return Fail(skyRing.Status().c_str(),hr);
112 if(FAILED(hr=geometryProgram(rainLines,"CloudVolume","rainVertex","rainPixel",ringLayout,2,1))) return Fail(rainLines.Status().c_str(),hr);
113 if(FAILED(hr=geometryProgram(rainParticles,"CloudVolume","rainParticleVertex","rainParticlePixel",particleLayout,2,0))) return Fail(rainParticles.Status().c_str(),hr);
114 if(FAILED(hr=geometryProgram(clearRainParticles,"ExteriorRain","rainParticleVertex","rainParticlePixel",particleLayout,2,0))) return Fail(clearRainParticles.Status().c_str(),hr);
115 for(const auto& definition:CloudVolumeSamplers)
116 {
117 ComPtr<ID3D11SamplerState> sampler;
118 if(FAILED(hr=device->CreateSamplerState(&definition.description,&sampler))) return Fail("create cloud sampler",hr);
119 samplers.push_back(std::move(sampler));
120 }
121 D3D11_RASTERIZER_DESC rs{};
122 rs.FillMode=D3D11_FILL_SOLID;rs.CullMode=D3D11_CULL_NONE;rs.DepthClipEnable=TRUE;rs.MultisampleEnable=TRUE;
123 if(FAILED(hr=device->CreateRasterizerState(&rs,&raster))) return Fail("create cloud rasterizer",hr);
124 D3D11_DEPTH_STENCIL_DESC ds{};ds.DepthFunc=D3D11_COMPARISON_ALWAYS;
125 if(FAILED(hr=device->CreateDepthStencilState(&ds,&disabledDepth))) return Fail("create march depth state",hr);
126 ds.DepthEnable=TRUE;ds.DepthWriteMask=D3D11_DEPTH_WRITE_MASK_ZERO;ds.DepthFunc=D3D11_COMPARISON_LESS_EQUAL;
127 ds.StencilEnable=TRUE;ds.StencilReadMask=255;ds.StencilWriteMask=0;
128 ds.FrontFace={D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_KEEP,D3D11_COMPARISON_GREATER};
129 ds.BackFace=ds.FrontFace;
130 if(FAILED(hr=device->CreateDepthStencilState(&ds,&compositeDepth))) return Fail("create read-only composite depth/stencil state",hr);
131 D3D11_BLEND_DESC bs{};
132 bs.RenderTarget[0]={TRUE,D3D11_BLEND_ONE,D3D11_BLEND_INV_SRC_ALPHA,D3D11_BLEND_OP_ADD,
133 D3D11_BLEND_ONE,D3D11_BLEND_INV_SRC_ALPHA,D3D11_BLEND_OP_ADD,D3D11_COLOR_WRITE_ENABLE_ALL};
134 if(FAILED(hr=device->CreateBlendState(&bs,&blend))) return Fail("create premultiplied cloud blend",hr);
135 bs.RenderTarget[0].SrcBlend=bs.RenderTarget[0].SrcBlendAlpha=D3D11_BLEND_SRC_ALPHA;
136 if(FAILED(hr=device->CreateBlendState(&bs,&straightBlend))) return Fail("create atmosphere/rain blend",hr);
137 if(HasShaderBytecode11(directory/"CloudOrganicFlight-march-1.cso"))
138 if(FAILED(hr=InitializeOrganic()))return Fail("organic flight/top programs",hr);
139 for(unsigned variant:{1u,2u})
140 {
141 const auto suffix=std::to_string(1u<<variant)+".cso";
142 cachedCompositeAvailable[variant]=HasShaderBytecode11(directory/("CloudVisibility-compositeCached-"+suffix))
143 && HasShaderBytecode11(directory/("CloudVisibility-compositeVisible-"+suffix));
144 hiddenAvailable[variant]=HasShaderBytecode11(directory/"CloudVisibility-reduceHiddenCloud-1.cso")
145 && HasShaderBytecode11(directory/("CloudVisibility-classifyHiddenCloud-"+suffix));
146 }
147 for(unsigned variant:{1u,2u})
148 {
149 const auto suffix=std::to_string(1u<<variant)+".cso";
150 sharedSearchAvailable[variant]=HasShaderBytecode11(directory/("CloudEdgeShared-classifyFirstHit-"+suffix))
151 && HasShaderBytecode11(directory/("CloudEdgeShared-compositeSeededEdge-"+suffix))
152 && HasShaderBytecode11(directory/("CloudEdgeShared-compositeSeededFogEdge-"+suffix));
154 && HasShaderBytecode11(directory/("CloudWork-scan-"+suffix))
155 && HasShaderBytecode11(directory/("CloudComplete-compositeCachedSamples-"+suffix));
156 }
157 UINT maskSupport=0;
158 const UINT requiredMaskSupport=D3D11_FORMAT_SUPPORT_TEXTURE2D|D3D11_FORMAT_SUPPORT_RENDER_TARGET|D3D11_FORMAT_SUPPORT_SHADER_LOAD;
159 const bool maskSupported=SUCCEEDED(device->CheckFormatSupport(DXGI_FORMAT_R16_UINT,&maskSupport))
160 && (maskSupport&requiredMaskSupport)==requiredMaskSupport;
161 for(unsigned variant:{1u,2u})
162 {
163 const auto suffix=std::to_string(1u<<variant)+".cso";
164 topDirect[variant].available=maskSupported
165 && HasShaderBytecode11(directory/("CloudTopDirect-integrate-"+suffix))
166 && HasShaderBytecode11(directory/("CloudTopDirect-selectPartialWork-"+suffix))
167 && HasShaderBytecode11(directory/("CloudTopDirect-resolvePartial-"+suffix))
168 && HasShaderBytecode11(directory/"CloudTopWork-scanPartialWork-1.cso");
169 }
170 status="native cloud pass ready: original scene depth samples";return S_OK;
171 }
173 {
174 // Keep unused MSAA/fog variants out of the driver's 32-bit allocation
175 // budget. The exact precompiled program is created on its first use.
176 for(unsigned mode=0;mode<2;++mode)
177 {
178 const std::string prefix=mode ? "CloudOrganicTop-" : "CloudOrganicFlight-";
179 if(!HasShaderBytecode11(shaderDirectory/(prefix+"march-1.cso")))return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
180 for(const char* entry:{"compositePixel-","compositeEdge-","compositeFogPixel-","compositeFogEdge-"})
181 for(unsigned i=0;i<4;++i)
182 if(!HasShaderBytecode11(shaderDirectory/(prefix+entry+std::to_string(1u<<i)+".cso")))return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
183 }
184 for(const char* name:{"CloudOrganicFlight-headlightDepthPixel-1.cso","CloudOrganicFlight-rainParticlePixel-1.cso"})
185 if(!HasShaderBytecode11(shaderDirectory/name))return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
186 organicReady=true;return S_OK;
187 }
188 HRESULT CloudPass11::LoadFullscreenProgram(Program11& program,const std::string& name)
189 {
190 if(program.Ready())return S_OK;
191 const auto vs=ReadShaderBytecode11(shaderDirectory/"CloudVolume-Fullscreen11-1.cso");
192 const auto ps=ReadShaderBytecode11(shaderDirectory/(name+".cso"));
193 return program.Create(device.Get(),vs.data(),vs.size(),ps.data(),ps.size());
194 }
196 {
197 HRESULT hr;
198 if(!compositeWorkScan[variant])
199 {
200 const auto code=ReadShaderBytecode11(shaderDirectory/("CloudWork-scan-"+std::to_string(1u<<variant)+".cso"));
201 if(FAILED(hr=device->CreateComputeShader(code.data(),code.size(),nullptr,&compositeWorkScan[variant])))return hr;
202 }
204 D3D11_BUFFER_DESC desc{};desc.ByteWidth=8*sizeof(UINT);
205 desc.BindFlags=D3D11_BIND_UNORDERED_ACCESS;desc.MiscFlags=D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS;
206 if(FAILED(hr=device->CreateBuffer(&desc,nullptr,&compositeArguments)))return hr;
207 D3D11_UNORDERED_ACCESS_VIEW_DESC view{};view.Format=DXGI_FORMAT_R32_UINT;
208 view.ViewDimension=D3D11_UAV_DIMENSION_BUFFER;view.Buffer.NumElements=8;
209 return device->CreateUnorderedAccessView(compositeArguments.Get(),&view,&compositeArgumentsView);
210 }
212 {
213 auto& direct=topDirect[variant];if(!direct.available || direct.failed)return E_NOTIMPL;
214 const auto suffix=std::to_string(1u<<variant);HRESULT hr;
215 if(FAILED(hr=LoadFullscreenProgram(direct.integrate,"CloudTopDirect-integrate-"+suffix))
216 || FAILED(hr=LoadFullscreenProgram(direct.classify,"CloudTopDirect-selectPartialWork-"+suffix))
217 || FAILED(hr=LoadFullscreenProgram(direct.composite,"CloudTopDirect-resolvePartial-"+suffix)))return hr;
218 return PrepareTopDirectWork(variant);
219 }
221 {
222 auto& direct=topDirect[variant];HRESULT hr;
223 if(!direct.scan)
224 {
225 const auto code=ReadShaderBytecode11(shaderDirectory/"CloudTopWork-scanPartialWork-1.cso");
226 if(FAILED(hr=device->CreateComputeShader(code.data(),code.size(),nullptr,&direct.scan)))return hr;
227 }
228 if(!direct.arguments || !direct.argumentView)
229 {
230 ComPtr<ID3D11Buffer> buffer;ComPtr<ID3D11UnorderedAccessView> target;
231 D3D11_BUFFER_DESC desc{};desc.ByteWidth=16*sizeof(UINT);desc.BindFlags=D3D11_BIND_UNORDERED_ACCESS;
232 desc.MiscFlags=D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS;
233 if(FAILED(hr=device->CreateBuffer(&desc,nullptr,&buffer)))return hr;
234 D3D11_UNORDERED_ACCESS_VIEW_DESC view{};view.Format=DXGI_FORMAT_R32_UINT;
235 view.ViewDimension=D3D11_UAV_DIMENSION_BUFFER;view.Buffer.NumElements=16;
236 if(FAILED(hr=device->CreateUnorderedAccessView(buffer.Get(),&view,&target)))return hr;
237 direct.arguments=std::move(buffer);direct.argumentView=std::move(target);
238 }
239 return S_OK;
240 }
241 HRESULT CloudPass11::PrepareTopDirectTargets(unsigned variant,const D3D11_TEXTURE2D_DESC& scene)
242 {
243 auto& direct=topDirect[variant];D3D11_TEXTURE2D_DESC current{};
244 if(direct.mask.texture)direct.mask.texture->GetDesc(&current);
245 if(direct.mask.texture && current.Width==scene.Width && current.Height==scene.Height)return S_OK;
246 // The state mask is single-sample integer data, independent of the
247 // scene's MSAA quality. Commit replacements only after all views exist.
248 Target next;D3D11_TEXTURE2D_DESC desc{};desc.Width=scene.Width;desc.Height=scene.Height;
249 desc.MipLevels=desc.ArraySize=1;desc.SampleDesc={1,0};desc.Format=DXGI_FORMAT_R16_UINT;
250 desc.BindFlags=D3D11_BIND_RENDER_TARGET|D3D11_BIND_SHADER_RESOURCE;
251 HRESULT hr=device->CreateTexture2D(&desc,nullptr,&next.texture);
252 if(SUCCEEDED(hr))hr=device->CreateRenderTargetView(next.texture.Get(),nullptr,&next.rtv);
253 if(SUCCEEDED(hr))hr=device->CreateShaderResourceView(next.texture.Get(),nullptr,&next.srv);
254 if(FAILED(hr))return hr;
255 direct.mask=std::move(next);
256 for(unsigned other=0;other<4;++other)if(other!=variant)topDirect[other].ReleaseTargets();
257 return S_OK;
258 }
259 std::vector<CloudPass11::LoadingJob> CloudPass11::LoadingJobs(UINT samples,bool organic,size_t& topBegin)
260 {
261 unsigned variant=0;while(variant<4 && (1u<<variant)!=samples)++variant;
262 std::vector<LoadingJob> jobs;const auto suffix=std::to_string(samples);
263 topBegin=0;
264 const auto add=[&](Program11& program,const std::string& name,bool composite=false,DXGI_FORMAT format=DXGI_FORMAT_UNKNOWN)
265 {
266 if(format==DXGI_FORMAT_UNKNOWN)format=composite ? DXGI_FORMAT_R8G8B8A8_UNORM : DXGI_FORMAT_B8G8R8A8_UNORM;
267 jobs.push_back({&program,name,composite,format,
268 (name.size()>=7 && name.compare(name.size()-7,7,"march-1")==0) || name=="CloudTemporal-resolve-1" || name=="CloudOrganicCoverage-resolveCoverage-1"});
269 };
270 const auto mode=[&](OrganicPrograms* programs,const std::string& prefix)
271 {
272 add(programs ? programs->march : march,prefix+"march-1");
273 add(programs ? programs->pixel[variant] : compositePixel[variant],prefix+"compositePixel-"+suffix,true);
274 add(programs ? programs->fogPixel[variant] : compositeFogPixel[variant],prefix+"compositeFogPixel-"+suffix,true);
275 if(variant)
276 {
277 add(programs ? programs->edge[variant] : compositeEdge[variant],prefix+"compositeEdge-"+suffix,true);
278 add(programs ? programs->fogEdge[variant] : compositeFogEdge[variant],prefix+"compositeFogEdge-"+suffix,true);
279 }
280 };
281 const bool flightSharing=organic && (samples==2 || samples==4);
282 const bool topSharing=flightSharing && topDirect[variant].available && !topDirect[variant].failed;
283 if(organic)
284 {
285 if(flightSharing)
286 {
287 // Warm only the programs used by the selected production path.
288 // The cached/shared variants replace the original composites;
289 // priming both would pay for unused driver specialization.
290 add(organicFlight.march,"CloudOrganicFlight-march-1");
291 if(cachedCompositeAvailable[variant])
292 {
293 add(cachedComposite[variant],"CloudVisibility-compositeCached-"+suffix,true);
294 add(visibleComposite[variant],"CloudVisibility-compositeVisible-"+suffix,true);
295 }
296 else add(organicFlight.pixel[variant],"CloudOrganicFlight-compositePixel-"+suffix,true);
297 add(organicFlight.fogPixel[variant],"CloudOrganicFlight-compositeFogPixel-"+suffix,true);
298 if(sharedSearchAvailable[variant])
299 {
300 add(firstHitClassify[variant],"CloudEdgeShared-classifyFirstHit-"+suffix,false,DXGI_FORMAT_R32G32B32A32_FLOAT);
301 add(seededEdge[variant],"CloudEdgeShared-compositeSeededEdge-"+suffix,true);
302 add(seededFogEdge[variant],"CloudEdgeShared-compositeSeededFogEdge-"+suffix,true);
303 if(samples==4)
304 {
305 // Upper-flight 4x retains its original composites; the
306 // expanded cache costs more than it saves in that mode.
307 add(organicFlight.edge[variant],"CloudOrganicFlight-compositeEdge-"+suffix,true);
308 add(organicFlight.fogEdge[variant],"CloudOrganicFlight-compositeFogEdge-"+suffix,true);
309 }
310 }
311 else
312 {
313 add(organicFlight.edge[variant],"CloudOrganicFlight-compositeEdge-"+suffix,true);
314 add(organicFlight.fogEdge[variant],"CloudOrganicFlight-compositeFogEdge-"+suffix,true);
315 }
316 if(compositeWorkAvailable[variant])
317 {
318 jobs.push_back({nullptr,"CloudWork-scan-"+suffix,false,DXGI_FORMAT_UNKNOWN,false});
319 add(completeComposite[variant],"CloudComplete-compositeCachedSamples-"+suffix,true);
320 }
321 }
322 else mode(&organicFlight,"CloudOrganicFlight-");
323 topBegin=jobs.size();
324 if(topSharing)
325 {
326 add(organicTop.march,"CloudOrganicTop-march-1");
327 auto& direct=topDirect[variant];
328 add(direct.integrate,"CloudTopDirect-integrate-"+suffix,true);
329 add(direct.classify,"CloudTopDirect-selectPartialWork-"+suffix,false,DXGI_FORMAT_R16_UINT);
330 jobs.push_back({nullptr,"CloudTopWork-scanPartialWork-1",false,DXGI_FORMAT_UNKNOWN,false});
331 add(direct.composite,"CloudTopDirect-resolvePartial-"+suffix,true);
332 }
333 else mode(&organicTop,"CloudOrganicTop-");
334 }
335 else mode(nullptr,"CloudVolume-");
336 add(organic ? organicLightDepth : lightDepth,organic ? "CloudOrganicFlight-headlightDepthPixel-1" : "CloudVolume-headlightDepthPixel-1",false,DXGI_FORMAT_R16G16B16A16_FLOAT);
337 add(rainPixel[variant],"CloudVolume-compositeRainPixel-"+suffix,true);
338 if(variant)
339 {
340 add(rainEdge[variant],"CloudVolume-compositeRainEdge-"+suffix,true);
341 add(rainClassify[variant],"CloudVolume-compositeRainClassify-"+suffix,false,DXGI_FORMAT_R8_UNORM);
342 }
343 if(flightSharing)
344 {
345 if(hiddenAvailable[variant])
346 {add(reduceHidden,"CloudVisibility-reduceHiddenCloud-1",false,DXGI_FORMAT_R8_UNORM);add(classifyHidden[variant],"CloudVisibility-classifyHiddenCloud-"+suffix,false,DXGI_FORMAT_R8_UNORM);}
347 }
348 if(organic && orbitalReady)
349 {
350 add(orbitalMarch,"CloudOrganicOrbit-march-1");
351 if(orbitalCoverageAvailable)add(orbitalCoverage,"CloudOrganicCoverage-resolveCoverage-1");
352 add(temporal.resolve,"CloudTemporal-resolve-1",false,DXGI_FORMAT_R16G16B16A16_FLOAT);
353 }
354 return jobs;
355 }
357 {
358 HRESULT hr=S_OK;
359 if(job.name=="CloudTopWork-scanPartialWork-1")return PrepareTopDirectWork(variant);
360 if(job.name=="CloudWork-scan-"+std::to_string(1u<<variant))return PrepareCompositeWork(variant);
361 if(job.name=="CloudTemporal-resolve-1" && !temporalProgramsReady)
362 {
363 if(FAILED(hr=temporal.Initialize(device.Get(),shaderDirectory)))return hr;
365 }
366 return job.program ? LoadFullscreenProgram(*job.program,job.name) : E_INVALIDARG;
367 }
368 HRESULT CloudPass11::PrepareLoadingStepNow(ID3D11DeviceContext* context,UINT samples,bool organic)
369 {
370 if(!device || !context || context->GetType()!=D3D11_DEVICE_CONTEXT_IMMEDIATE)return E_INVALIDARG;
371 unsigned variant=0;while(variant<4 && (1u<<variant)!=samples)++variant;
372 if(variant==4 || (organic && !organicReady))return E_INVALIDARG;
373 size_t topBegin=0;auto jobs=LoadingJobs(samples,organic,topBegin);
374 const auto suffix=std::to_string(samples);
375 const unsigned plan=variant+(organic ? 4 : 0);
376 if(loadingVariant!=plan)
377 {
380 }
381 // Even the last priming draw must present before loading completes.
384 auto& step=loadingStep[plan];
385 if(step>=jobs.size())
386 {
387 loadingProgress={jobs.back().name,unsigned(jobs.size()),unsigned(jobs.size()),true};return S_OK;
388 }
389 const auto& job=jobs[step];
390 if(loadingProgress.current!=step+1 || loadingProgress.shader!=job.name)
391 {
392 loadingProgress={job.name,step+1,unsigned(jobs.size()),false};
393 loadingPresented=false;
394 return S_FALSE;
395 }
396 if(!loadingPresented)return S_FALSE;
398 const bool optionalTopJob=job.name.compare(0,15,"CloudTopDirect-")==0 || job.name=="CloudTopWork-scanPartialWork-1";
399 const auto warmupFailure=[&](HRESULT failure)
400 {
401 // Optional warmup allocation/binding must not turn a usable
402 // original renderer into a failed startup. Restart the Top block
403 // under its original job plan on the next loading frame. Device
404 // removal and common pipeline failures remain real errors.
405 if(!optionalTopJob || FAILED(device->GetDeviceRemovedReason()))return failure;
406 topDirect[variant].failed=true;topDirect[variant].ReleaseTargets();
407#ifdef RISE_CLOUD_TEST_TEMPORAL_DIAGNOSTICS
408 ++testTopLoadingFallbacks;
409#endif
410 step=unsigned(topBegin);
411 status="native cloud pass ready: original Top warmup selected";
412 return HRESULT(S_FALSE);
413 };
414 ProfileScope11 preparation("Loading cloud shader preparation",false);
415 ProfileScope11 selectedProgram(job.name.c_str(),false);
416 HRESULT hr=S_OK;
417 // Object creation can trigger driver work too; defer it until the job
418 // name has appeared on screen, including the optional fallback path.
419 if(FAILED(hr=PrepareLoadingObjects(job,variant)))return warmupFailure(hr);
420
421 // A shader object alone can defer driver specialization until Draw.
422 // Exercise the same RT formats/MSAA while an empty scissor excludes all
423 // pixels. No weather, camera, lighting or history state is advanced.
424 Restore restore;
425 if(FAILED(hr=context->QueryInterface(IID_PPV_ARGS(&restore.context))))return hr;
426 restore.context->SwapDeviceContextState(passState.Get(),&restore.previous);
427#ifdef RISE_CLOUD_TEST_TEMPORAL_DIAGNOSTICS
428 char forcedJob[128]{};
429 if(optionalTopJob && !testTopLoadingFallbacks
430 && GetEnvironmentVariableA("RISE_LOADING_FAIL_TOP_JOB",forcedJob,sizeof(forcedJob))
431 && job.name==forcedJob)return warmupFailure(E_OUTOFMEMORY);
432#endif
433 if(!job.program)
434 {
435 if(job.name=="CloudTopWork-scanPartialWork-1")
436 {
437 auto& direct=topDirect[variant];Target mask;
438 if(FAILED(hr=TargetCreate(mask,4,4,DXGI_FORMAT_R16_UINT)))return warmupFailure(hr);
439 context->OMSetRenderTargets(0,nullptr,nullptr);
440 const float clear[4]{};context->ClearRenderTargetView(mask.rtv.Get(),clear);
441 const UINT initial[]={0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0};
442 context->UpdateSubresource(direct.arguments.Get(),0,nullptr,initial,0,0);
443 auto* source=mask.srv.Get();auto* arguments=direct.argumentView.Get();
444 context->CSSetShader(direct.scan.Get(),nullptr,0);context->CSSetShaderResources(0,1,&source);
445 context->CSSetUnorderedAccessViews(0,1,&arguments,nullptr);context->Dispatch(1,1,1);
446 source=nullptr;arguments=nullptr;context->CSSetShaderResources(0,1,&source);
447 context->CSSetUnorderedAccessViews(0,1,&arguments,nullptr);context->CSSetShader(nullptr,nullptr,0);
448 ++step;return S_FALSE;
449 }
450 // CreateComputeShader can defer specialization until Dispatch too.
451 // Prime the selected MSAA scan with initialized, private resources.
452 SceneDepth11 depth;
453 if(FAILED(hr=depth.Create(device.Get(),4,4,{samples,0})))return hr;
454 context->OMSetRenderTargets(0,nullptr,nullptr);
455 context->ClearDepthStencilView(depth.WriteView(),D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL,1,0);
456 const UINT initial[]={3,1,0,0,0,1,0,0};
457 context->UpdateSubresource(compositeArguments.Get(),0,nullptr,initial,0,0);
458 ID3D11ShaderResourceView* source[]={depth.ShaderView(),depth.StencilView()};
459 auto* arguments=compositeArgumentsView.Get();
460 context->CSSetShader(compositeWorkScan[variant].Get(),nullptr,0);
461 context->CSSetShaderResources(0,2,source);
462 context->CSSetUnorderedAccessViews(0,1,&arguments,nullptr);
463 context->Dispatch(1,1,1);
464 source[0]=source[1]=nullptr;arguments=nullptr;
465 context->CSSetShaderResources(0,2,source);
466 context->CSSetUnorderedAccessViews(0,1,&arguments,nullptr);
467 context->CSSetShader(nullptr,nullptr,0);
468 ++step;return S_FALSE;
469 }
470 D3D11_TEXTURE2D_DESC desc{};desc.Width=desc.Height=4;desc.MipLevels=desc.ArraySize=1;
471 desc.SampleDesc.Count=job.composite ? samples : 1;desc.Format=job.format;desc.BindFlags=D3D11_BIND_RENDER_TARGET;
472 ComPtr<ID3D11Texture2D> color,distanceTarget;ComPtr<ID3D11RenderTargetView> colorView,distanceView;
473 if(FAILED(hr=device->CreateTexture2D(&desc,nullptr,&color)) || FAILED(hr=device->CreateRenderTargetView(color.Get(),nullptr,&colorView)))return warmupFailure(hr);
474 desc.Format=DXGI_FORMAT_R32G32_FLOAT;
475 if(job.distance && (FAILED(hr=device->CreateTexture2D(&desc,nullptr,&distanceTarget)) || FAILED(hr=device->CreateRenderTargetView(distanceTarget.Get(),nullptr,&distanceView))))return hr;
476 ID3D11RenderTargetView* targets[]={colorView.Get(),distanceView.Get()};
477 SceneDepth11 depth;
478 if(job.composite && FAILED(hr=depth.Create(device.Get(),4,4,{samples,0})))return warmupFailure(hr);
479 context->OMSetRenderTargets(job.distance ? 2 : 1,targets,depth.ReadView());
480 context->OMSetDepthStencilState(job.composite ? compositeDepth.Get() : disabledDepth.Get(),3);
481 context->OMSetBlendState(job.composite ? blend.Get() : nullptr,nullptr,0xffffffff);
482 D3D11_RASTERIZER_DESC rs{};raster->GetDesc(&rs);rs.ScissorEnable=TRUE;
483 ComPtr<ID3D11RasterizerState> clipped;if(FAILED(hr=device->CreateRasterizerState(&rs,&clipped)))return hr;
484 context->RSSetState(clipped.Get());const RECT empty{};context->RSSetScissorRects(1,&empty);
485 const D3D11_VIEWPORT viewport{0,0,4,4,0,1};context->RSSetViewports(1,&viewport);
486 context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
487 context->GSSetShader(nullptr,nullptr,0);context->HSSetShader(nullptr,nullptr,0);context->DSSetShader(nullptr,nullptr,0);
488 Parameters11 defaults;for(size_t i=0;i<samplers.size();++i)defaults.Sampler(CloudVolumeSamplers[i].name,samplers[i].Get());
489 if(job.name=="CloudTemporal-resolve-1")
490 {defaults.Sampler("linearSampler",temporal.linear.Get());defaults.Sampler("pointSampler",temporal.point.Get());}
491 defaults.Texture("riseSceneDepth",depth.ShaderView());defaults.Texture("riseSceneStencil",depth.StencilView());
492 defaults.Set("risePartialFog",0u);defaults.Set("risePartialSample",0u);
493 if(FAILED(hr=Draw(context,*job.program,defaults)))return warmupFailure(hr);
494 // No flush, query wait or Present here. The loading frame submits the
495 // priming draw normally; subsequent frames prepare the remaining jobs.
496 // Let the final loading frame present before allowing STATUS_GAME.
497 ++step;return S_FALSE;
498 }
499 HRESULT CloudPass11::PreparePrograms(unsigned variant,bool fog,bool headlights,bool spatialRain,bool rainMaskEnabled,bool cached,bool sharedSearch,bool directComposite)
500 {
501 const std::string prefix=activeOrganic==&organicTop ? "CloudOrganicTop-" : activeOrganic ? "CloudOrganicFlight-" : "CloudVolume-";
502 const auto suffix=std::to_string(1u<<variant);HRESULT hr;
504 {
505 if(FAILED(hr=LoadFullscreenProgram(orbitalMarch,"CloudOrganicOrbit-march-1")))return hr;
506 if(orbitalCoverageAvailable && FAILED(hr=LoadFullscreenProgram(orbitalCoverage,"CloudOrganicCoverage-resolveCoverage-1")))return hr;
508 {
509 if(FAILED(hr=temporal.Initialize(device.Get(),shaderDirectory)))return hr;
511 }
512 }
513 else if(FAILED(hr=LoadFullscreenProgram(activeOrganic ? activeOrganic->march : march,prefix+"march-1")))return hr;
514 if(!directComposite)
515 {
518 // Create only the active pixel program. Loading both heavy composites
519 // would add an unused driver allocation and JIT pause at ground startup.
520 if(cached)
521 {
522 if(FAILED(hr=LoadFullscreenProgram(cachedComposite[variant],"CloudVisibility-compositeCached-"+suffix)))return hr;
523 if(FAILED(hr=LoadFullscreenProgram(visibleComposite[variant],"CloudVisibility-compositeVisible-"+suffix)))return hr;
524 }
525 else if(FAILED(hr=LoadFullscreenProgram(pixels[variant],prefix+(fog ? "compositeFogPixel-" : "compositePixel-")+suffix)))return hr;
526 if(sharedSearch)
527 {
528 if(FAILED(hr=LoadFullscreenProgram(firstHitClassify[variant],"CloudEdgeShared-classifyFirstHit-"+suffix)))return hr;
529 if(FAILED(hr=LoadFullscreenProgram(fog ? seededFogEdge[variant] : seededEdge[variant],
530 std::string("CloudEdgeShared-")+(fog ? "compositeSeededFogEdge-" : "compositeSeededEdge-")+suffix)))return hr;
531 if(compositeWorkAvailable[variant])
532 {
533 if(FAILED(hr=PrepareCompositeWork(variant)))return hr;
534 if(FAILED(hr=LoadFullscreenProgram(completeComposite[variant],"CloudComplete-compositeCachedSamples-"+suffix)))return hr;
535 }
536 }
537 else if(variant && FAILED(hr=LoadFullscreenProgram(edges[variant],prefix+(fog ? "compositeFogEdge-" : "compositeEdge-")+suffix)))return hr;
538 }
540 activeOrganic ? "CloudOrganicFlight-headlightDepthPixel-1" : "CloudVolume-headlightDepthPixel-1")))return hr;
541 if(spatialRain)
542 {
543 if(FAILED(hr=LoadFullscreenProgram(rainPixel[variant],"CloudVolume-compositeRainPixel-"+suffix)))return hr;
544 if(variant && FAILED(hr=LoadFullscreenProgram(rainEdge[variant],"CloudVolume-compositeRainEdge-"+suffix)))return hr;
545 if(rainMaskEnabled && FAILED(hr=LoadFullscreenProgram(rainClassify[variant],"CloudVolume-compositeRainClassify-"+suffix)))return hr;
546 }
547 return S_OK;
548 }
550 {
551 if(organicRainParticles.Ready())return S_OK;
552 const auto vertex=ReadShaderBytecode11(shaderDirectory/"CloudVolume-rainParticleVertex-1.cso");
553 const auto pixel=ReadShaderBytecode11(shaderDirectory/"CloudOrganicFlight-rainParticlePixel-1.cso");
554 const D3D11_INPUT_ELEMENT_DESC layout[]={
555 {"POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA,0},
556 {"TEXCOORD",0,DXGI_FORMAT_R32G32B32A32_FLOAT,0,12,D3D11_INPUT_PER_VERTEX_DATA,0}};
557 return organicRainParticles.Create(device.Get(),vertex.data(),vertex.size(),pixel.data(),pixel.size(),layout,2,0);
558 }
559 HRESULT CloudPass11::ConfigureOrganic(bool enabled,bool aboveDeck)
560 {
561 if(enabled && !organicReady)return Fail("matching organic shader programs are unavailable",E_NOTIMPL);
562 auto* next=enabled ? (aboveDeck ? &organicTop : &organicFlight) : nullptr;
564 if(next!=&organicTop)for(auto& direct:topDirect)direct.ReleaseTargets();
565 activeOrganic=next;return S_OK;
566 }
568 {
570 if(ready)return S_OK;
571 const auto vs=ReadShaderBytecode11(shaderDirectory/"CloudVolume-Fullscreen11-1.cso");
572 const char* names[]={"AdCloudPixel","AdCloudEdge","AdCloudFogPixel","AdCloudFogEdge"};
573 const std::string prefix=activeOrganic==&organicTop ? "CloudOrganicTopAd-" : activeOrganic ? "CloudOrganicFlightAd-" : "AdCloudOpacity-";
574 unsigned entry=0;
577 {
578 for(unsigned i=0;i<4;++i)
579 {
580 const auto ps=ReadShaderBytecode11(shaderDirectory/(prefix+names[entry]+"-"+std::to_string(1u<<i)+".cso"));
581 const HRESULT hr=(*list)[i].Create(device.Get(),vs.data(),vs.size(),ps.data(),ps.size());
582 if(FAILED(hr))return hr;
583 }
584 ++entry;
585 }
586 D3D11_BLEND_DESC bs{};blend->GetDesc(&bs);bs.IndependentBlendEnable=TRUE;
587 bs.RenderTarget[1].RenderTargetWriteMask=D3D11_COLOR_WRITE_ENABLE_ALL;
588 const HRESULT hr=device->CreateBlendState(&bs,&adBlend);
589 if(SUCCEEDED(hr))ready=true;
590 return hr;
591 }
592 HRESULT CloudPass11::TargetCreate(Target& target,UINT w,UINT h,DXGI_FORMAT format)
593 {
594 Target next;
595 D3D11_TEXTURE2D_DESC desc{};
596 desc.Width=w;desc.Height=h;desc.MipLevels=desc.ArraySize=1;desc.Format=format;desc.SampleDesc.Count=1;
597 desc.BindFlags=D3D11_BIND_SHADER_RESOURCE|D3D11_BIND_RENDER_TARGET;
598 HRESULT hr=device->CreateTexture2D(&desc,nullptr,&next.texture);
599 if(SUCCEEDED(hr)) hr=device->CreateRenderTargetView(next.texture.Get(),nullptr,&next.rtv);
600 if(SUCCEEDED(hr)) hr=device->CreateShaderResourceView(next.texture.Get(),nullptr,&next.srv);
601 if(FAILED(hr)) return Fail("create cloud render target",hr);
602 target=std::move(next);return S_OK;
603 }
604 HRESULT CloudPass11::Draw(ID3D11DeviceContext* context,Program11& program,Parameters11& parameters)
605 {
606 const HRESULT hr=program.Bind(context,parameters);
607 if(FAILED(hr)) return Fail(program.Status().c_str(),hr);
608 context->Draw(3,0);return S_OK;
609 }
610 HRESULT CloudPass11::Render(ID3D11DeviceContext* context,Parameters11& parameters,
611 ID3D11RenderTargetView* scene,const SceneDepth11& depth,const D3D11_VIEWPORT& viewport,unsigned activeHeadlights,bool atmosphericFog,bool spatialRain,bool belowNominalCloudBase)
612 {
613 adOpacityWritten=false;
614#ifdef RISE_CLOUD_TEST_TEMPORAL_DIAGNOSTICS
615 static const bool captureTemporal=[](){char value[2]{};return GetEnvironmentVariableA("RISE_FLIGHT_REQUIRE_HISTORY",value,2)!=0;}();
616 if(captureTemporal){parameters.Set("_testTemporalActive",temporalEnabled ? 1u : 0u);parameters.Set("_testTemporalHistory",0u);}
617#endif
618 // Visual-test alpha: both organic and fallback opacity MRT draws have
619 // triggered AMD device removal (0x887A0020). Preserve rendering and report this
620 // optional measurement unavailable; ad diagnostics already reject
621 // unmeasured weather instead of treating it as transparent.
622 // Its unused native variants are also omitted by PortShaders11.py.
623 // Restore those entries before re-enabling this measurement path.
624 const bool measureOpacity=false;
625 HRESULT hr=ValidateScene(context,scene,depth,viewport);
626 if(FAILED(hr)) return hr;
627 if(activeHeadlights>8) return E_INVALIDARG;
628 const UINT sampleCount=depth.Description().SampleDesc.Count;
629 unsigned variant=0;while(variant<4 && (1u<<variant)!=sampleCount) ++variant;
630 if(variant==4) return E_INVALIDARG;
631 const float scale=(std::min)(resolutionScale,(std::min)(CloudVolume::MaxWidth/viewport.Width,CloudVolume::MaxHeight/viewport.Height));
632 const UINT w=(std::max)(1u,UINT(viewport.Width*scale)),h=(std::max)(1u,UINT(viewport.Height*scale));
633 bool refineCoverage=temporalEnabled && orbitalCoverageAvailable;
634 if(refineCoverage)
635 {
636 // Cull the whole pass when even the nearest possible silhouette
637 // is beyond its 2.5-km footprint limit. Use the same capped reference
638 // grid as CloudRenderer11 and retain footprintAt's distance filter.
639 // Orbital rays have no grazing multiplier; this lower bound is
640 // independent of view direction.
641 const float referenceScale=(std::min)(.5f,(std::min)(CloudVolume::MaxWidth/viewport.Width,CloudVolume::MaxHeight/viewport.Height));
642 const UINT rw=(std::max)(1u,UINT(viewport.Width*referenceScale)),rh=(std::max)(1u,UINT(viewport.Height*referenceScale));
643 const auto& e=temporalFrame.eye;
644 const double radius=std::sqrt(double(e.x)*e.x+double(e.y)*e.y+double(e.z)*e.z);
645 const double tangent=double(temporalFrame.layer.x)+temporalFrame.layer.z+CloudVolume::MaxTopRiseKm+1;
646 const double nearest=std::sqrt((std::max)(0.,(radius-tangent)*(radius+tangent)));
647 const float angular=2*(std::max)(std::abs(1/temporalFrame.projection._11)/rw,std::abs(1/temporalFrame.projection._22)/rh);
648 const double distanceBlend=(std::max)(0.,(std::min)(1.,(nearest-20)/60));
649 const double distanceFilter=1+.4*distanceBlend*distanceBlend*(3-2*distanceBlend);
650 refineCoverage=angular*nearest*distanceFilter<2.5;
651 }
652#ifdef RISE_CLOUD_TEST_TEMPORAL_DIAGNOSTICS
653 parameters.Set("_testCoverageActive",refineCoverage ? 1u : 0u);
654#endif
655 if(!image.texture || width!=w || height!=h)
656 {
657 Target nextImage,nextDistance;
658 if(FAILED(hr=TargetCreate(nextImage,w,h,DXGI_FORMAT_B8G8R8A8_UNORM))) return hr;
659 if(FAILED(hr=TargetCreate(nextDistance,w,h,DXGI_FORMAT_R32G32_FLOAT))) return hr;
661 image=std::move(nextImage);distance=std::move(nextDistance);width=w;height=h;
663 // The raw grid can change while the half-resolution history size stays
664 // unchanged (for example, an odd viewport resize at one-third scale).
666 }
667 if(refineCoverage && !coverageImage.texture)
668 {
669 Target color,depthTarget;
670 if(FAILED(hr=TargetCreate(color,w,h,DXGI_FORMAT_B8G8R8A8_UNORM)))return hr;
671 if(FAILED(hr=TargetCreate(depthTarget,w,h,DXGI_FORMAT_R32G32_FLOAT)))return hr;
672 coverageImage=std::move(color);coverageDistance=std::move(depthTarget);
673 }
674 if(activeHeadlights && !headlight.texture && FAILED(hr=TargetCreate(headlight,64,512,DXGI_FORMAT_R16G16B16A16_FLOAT))) return hr;
675 D3D11_RENDER_TARGET_VIEW_DESC sceneFormat{};scene->GetDesc(&sceneFormat);
676 // The sharing error includes transmission of a destination in [0,1].
677 // Keep the exact path for HDR/sRGB targets with different error units.
678 const bool unormScene=sceneFormat.Format==DXGI_FORMAT_R8G8B8A8_UNORM || sceneFormat.Format==DXGI_FORMAT_B8G8R8A8_UNORM;
679 const UINT useRainMask=spatialRain && sampleCount>1 && rainMsaaSharingEnabled && unormScene ? 1u : 0u;
680 const bool useCachedComposite=visibilityOptimizationEnabled && cachedCompositeAvailable[variant]
681 && activeOrganic==&organicFlight && !atmosphericFog && !temporalEnabled && (sampleCount==2 || sampleCount==4) && !measureOpacity;
682 // Original MSAA rays share their pixel-center UV, first search and
683 // underside lighting. Their depth endpoints and all integration steps
684 // remain per sample, including the atmospheric-fog blend.
685 const bool useSharedSearch=visibilityOptimizationEnabled && sharedSearchAvailable[variant]
686 && (sampleCount==2 || parameters.ZeroOrUnset("riseCloudRefinedSearch"))
687 && activeOrganic==&organicFlight && !temporalEnabled && !measureOpacity && (sampleCount==2 || sampleCount==4);
688 const bool useCompositeWork=useSharedSearch && compositeWorkAvailable[variant];
689 bool useTopDirect=visibilityOptimizationEnabled && activeOrganic==&organicTop && !measureOpacity
690 && (sampleCount==2 || sampleCount==4) && topDirect[variant].available && !topDirect[variant].failed
691 && std::floor(viewport.TopLeftX)==viewport.TopLeftX && std::floor(viewport.TopLeftY)==viewport.TopLeftY
692 && std::floor(viewport.Width)==viewport.Width && std::floor(viewport.Height)==viewport.Height
693 && parameters.ZeroOrUnset("_risePixelCenterOffset");
694 // Complete all optional allocations before rendering to the scene. If
695 // unavailable, use the original path; never replay over a partial blend.
696 if(useTopDirect)
697 {
698 hr=PrepareTopDirectPrograms(variant);
699 if(SUCCEEDED(hr))hr=PrepareTopDirectTargets(variant,depth.Description());
700 if(FAILED(hr))
701 {
702 if(FAILED(device->GetDeviceRemovedReason()))return hr;
703 topDirect[variant].failed=true;topDirect[variant].ReleaseTargets();useTopDirect=false;
704 }
705 }
706 struct ClearDirectMask
707 {
708 Parameters11& parameters;
709 ~ClearDirectMask(){parameters.Texture("risePartialMask",nullptr);}
710 } clearDirectMask{parameters};
711 (void)belowNominalCloudBase;
712 if(FAILED(hr=PreparePrograms(variant,atmosphericFog,activeHeadlights!=0,spatialRain,useRainMask!=0,useCachedComposite,useSharedSearch,useTopDirect)))
713 return Fail("prepare active cloud programs",hr);
714 if(useSharedSearch)
715 {
716 D3D11_TEXTURE2D_DESC desc{};if(firstHit.texture)firstHit.texture->GetDesc(&desc);
717 if(!firstHit.texture || desc.Width!=depth.Description().Width || desc.Height!=depth.Description().Height)
718 if(FAILED(hr=TargetCreate(firstHit,depth.Description().Width,depth.Description().Height,DXGI_FORMAT_R32G32B32A32_FLOAT)))return hr;
719 }
720 // Spatial fog selects the normal composite. Its sharing decision uses
721 // the unchanged cloud image and scene depth, so retain it in the same
722 // R8 mask as the fog decision. Reset eligibility on every view.
723 parameters.Set("riseCloudSharedMaskEnabled",useRainMask && !atmosphericFog ? 1u : 0u);
724 if(useRainMask && (!rainMask.texture || maskWidth!=depth.Description().Width || maskHeight!=depth.Description().Height))
725 {
726 if(FAILED(hr=TargetCreate(rainMask,depth.Description().Width,depth.Description().Height,DXGI_FORMAT_R8_UNORM)))return hr;
727 maskWidth=depth.Description().Width;maskHeight=depth.Description().Height;
728 }
729 // The mask is a proof over the full bilinear footprint and all original
730 // MSAA samples, not a reduced-depth approximation. Other views retain
731 // the unchanged marcher and composite paths.
733 && activeOrganic==&organicFlight && !temporalEnabled && !measureOpacity && (sampleCount==2 || sampleCount==4)
734 && viewport.MinDepth==0 && viewport.MaxDepth==1 && viewport.TopLeftX==0 && viewport.TopLeftY==0
735 && viewport.Width==float(depth.Description().Width) && viewport.Height==float(depth.Description().Height);
736 if(useHidden)
737 {
738 if(!hiddenMask.texture && FAILED(hr=TargetCreate(hiddenMask,w,h,DXGI_FORMAT_R8_UNORM)))return hr;
739 D3D11_TEXTURE2D_DESC fullDesc{};if(fullHiddenMask.texture)fullHiddenMask.texture->GetDesc(&fullDesc);
740 if((!fullHiddenMask.texture || fullDesc.Width!=UINT(viewport.Width) || fullDesc.Height!=UINT(viewport.Height))
741 && FAILED(hr=TargetCreate(fullHiddenMask,UINT(viewport.Width),UINT(viewport.Height),DXGI_FORMAT_R8_UNORM)))return hr;
742 if(FAILED(hr=LoadFullscreenProgram(reduceHidden,"CloudVisibility-reduceHiddenCloud-1")))return hr;
743 if(FAILED(hr=LoadFullscreenProgram(classifyHidden[variant],"CloudVisibility-classifyHiddenCloud-"+std::to_string(sampleCount))))return hr;
744 if(!hiddenDepth)
745 {
746 D3D11_TEXTURE2D_DESC desc{};desc.Width=w;desc.Height=h;desc.MipLevels=desc.ArraySize=1;
747 desc.Format=DXGI_FORMAT_D24_UNORM_S8_UINT;desc.SampleDesc.Count=1;desc.Usage=D3D11_USAGE_DEFAULT;desc.BindFlags=D3D11_BIND_DEPTH_STENCIL;
748 if(FAILED(hr=device->CreateTexture2D(&desc,nullptr,&hiddenDepthTexture)))return hr;
749 if(FAILED(hr=device->CreateDepthStencilView(hiddenDepthTexture.Get(),nullptr,&hiddenDepth)))return hr;
750 }
751 if(!hiddenWrite || !hiddenRead)
752 {
753 D3D11_DEPTH_STENCIL_DESC ds{};ds.StencilEnable=TRUE;ds.StencilReadMask=ds.StencilWriteMask=1;
754 ds.FrontFace={D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_REPLACE,D3D11_COMPARISON_ALWAYS};ds.BackFace=ds.FrontFace;
755 if(FAILED(hr=device->CreateDepthStencilState(&ds,&hiddenWrite)))return hr;
756 ds.StencilWriteMask=0;ds.FrontFace.StencilPassOp=D3D11_STENCIL_OP_KEEP;ds.FrontFace.StencilFunc=D3D11_COMPARISON_EQUAL;ds.BackFace=ds.FrontFace;
757 if(FAILED(hr=device->CreateDepthStencilState(&ds,&hiddenRead)))return hr;
758 }
759 }
760 Restore restore;
761 if(FAILED(hr=context->QueryInterface(IID_PPV_ARGS(&restore.context)))) return Fail("immediate context state interface",hr);
762 restore.context->SwapDeviceContextState(passState.Get(),&restore.previous);
763 context->RSSetState(raster.Get());
764 context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
765 context->GSSetShader(nullptr,nullptr,0);context->HSSetShader(nullptr,nullptr,0);context->DSSetShader(nullptr,nullptr,0);
766 context->OMSetDepthStencilState(disabledDepth.Get(),0);
767 context->OMSetBlendState(nullptr,nullptr,0xffffffff);
768 for(size_t i=0;i<samplers.size();++i) parameters.Sampler(CloudVolumeSamplers[i].name,samplers[i].Get());
769 const int lightCount=int(activeHeadlights);parameters.Set("headlightCount",lightCount);
770 parameters.Texture("headlightDepth",nullptr);
771 if(activeHeadlights)
772 {
773 ProfileScope11 timing("Cloud headlight depth");
774 Unbind(context);auto* target=headlight.rtv.Get();context->OMSetRenderTargets(1,&target,nullptr);
775 const D3D11_VIEWPORT vp{0,0,float(activeHeadlights*8),512,0,1};context->RSSetViewports(1,&vp);
776 if(FAILED(hr=Draw(context,activeOrganic ? organicLightDepth : lightDepth,parameters))) return hr;
777 Unbind(context);parameters.Texture("headlightDepth",headlight.srv.Get());
778 }
779 Unbind(context);
781 {
782 if(FAILED(hr=temporal.BeginFrame(temporalFrame,UINT(viewport.Width),UINT(viewport.Height),w,h)))return Fail("cloud history frame",hr);
783 parameters.Set("riseCloudJitterUV",temporal.Jitter());
784#ifdef RISE_CLOUD_TEST_TEMPORAL_DIAGNOSTICS
785 if(captureTemporal)
786 {
787 parameters.Set("_testTemporalHistory",temporal.HasHistory() ? 1u : 0u);
788 const auto jitter=temporal.Jitter();const unsigned phase=(jitter.x>0 ? 1u : 0u)|(jitter.y>0 ? 2u : 0u);
789 for(unsigned i=0;i<4;++i)parameters.Set("_testTemporalPhase"+std::to_string(i),i==phase ? 1u : 0u);
790 }
791#endif
792 }
793 if(useHidden)
794 {
795 ProfileScope11 timing("Cloud hidden ray classification");
796 parameters.Texture("riseSceneDepth",depth.ShaderView());parameters.Texture("riseSceneStencil",depth.StencilView());
797 parameters.Set("riseSceneStencilAvailable",depth.StencilView() ? 1u : 0u);
798 parameters.Set("riseHiddenSceneSize",DirectX::XMFLOAT4(viewport.Width,viewport.Height,0,0));
799 auto* target=fullHiddenMask.rtv.Get();context->OMSetRenderTargets(1,&target,nullptr);
800 context->RSSetViewports(1,&viewport);
801 if(FAILED(hr=Draw(context,classifyHidden[variant],parameters)))return hr;
802 Unbind(context);parameters.Texture("riseCloudFullHiddenMask",fullHiddenMask.srv.Get());
803 const float clearMask[4]{};context->ClearRenderTargetView(hiddenMask.rtv.Get(),clearMask);
804 context->ClearDepthStencilView(hiddenDepth.Get(),D3D11_CLEAR_STENCIL,1,0);
805 context->OMSetDepthStencilState(hiddenWrite.Get(),1);
806 target=hiddenMask.rtv.Get();context->OMSetRenderTargets(1,&target,hiddenDepth.Get());
807 const D3D11_VIEWPORT vp{0,0,float(w),float(h),0,1};context->RSSetViewports(1,&vp);
808 if(FAILED(hr=Draw(context,reduceHidden,parameters)))return hr;
809 Unbind(context);parameters.Texture("riseCloudFullHiddenMask",nullptr);
810 // Skipped texels cannot contribute to any visible original sample.
811 // Empty image plus unknown opacity depth is conservative for every
812 // later cached-image/occlusion lookup.
813 const float clearImage[4]{};const float clearDistance[4]={0,1e8f,0,0};
814 context->ClearRenderTargetView(image.rtv.Get(),clearImage);context->ClearRenderTargetView(distance.rtv.Get(),clearDistance);
815 context->OMSetDepthStencilState(hiddenRead.Get(),0);
816 }
817 ID3D11RenderTargetView* targets[]={image.rtv.Get(),distance.rtv.Get()};context->OMSetRenderTargets(2,targets,useHidden ? hiddenDepth.Get() : nullptr);
818 const D3D11_VIEWPORT cloudViewport{0,0,float(w),float(h),0,1};context->RSSetViewports(1,&cloudViewport);
819 {
820 ProfileScope11 timing("Cloud ray march");
821 auto& program=temporalEnabled ? orbitalMarch : activeOrganic ? activeOrganic->march : march;
822 hr=Draw(context,program,parameters);
823 if(FAILED(hr))return hr;
824 }
825 context->OMSetDepthStencilState(disabledDepth.Get(),0);
826 Unbind(context);
827 ID3D11ShaderResourceView* temporalImage=image.srv.Get();
828 ID3D11ShaderResourceView* temporalDistance=distance.srv.Get();
829 if(refineCoverage)
830 {
831 ProfileScope11 timing("Cloud silhouette coverage");
832 struct ClearCoverageSources
833 {
834 Parameters11& parameters;
835 ~ClearCoverageSources(){parameters.Texture("riseCoverageImage",nullptr);parameters.Texture("riseCoverageDistance",nullptr);}
836 } clearCoverage{parameters};
837 parameters.Texture("riseCoverageImage",image.srv.Get());
838 parameters.Texture("riseCoverageDistance",distance.srv.Get());
839 ID3D11RenderTargetView* filtered[]={coverageImage.rtv.Get(),coverageDistance.rtv.Get()};
840 context->OMSetRenderTargets(2,filtered,nullptr);
841 if(FAILED(hr=Draw(context,orbitalCoverage,parameters)))return hr;
842 Unbind(context);
843 temporalImage=coverageImage.srv.Get();temporalDistance=coverageDistance.srv.Get();
844 }
845#ifdef RISE_CLOUD_TEST_TEMPORAL_DIAGNOSTICS
846 if(captureTemporal){parameters.Texture("_testRawCloudImage",temporalImage);parameters.Texture("_testRawCloudDistance",temporalDistance);}
847#endif
849 {
850 ProfileScope11 timing("Cloud history reconstruction");
851 if(FAILED(hr=temporal.Resolve(context,temporalImage,temporalDistance)))return Fail("cloud history resolve",hr);
852 parameters.Set("riseCloudJitterUV",DirectX::XMFLOAT4{});
853 }
854 // Clouds determine which background sky samples are fully hidden.
855 // Composite order remains background fog, then the fogged cloud image.
856 parameters.Texture("cloudImage",Image());
857 parameters.Texture("cloudDistance",Distance());
858 if(spatialRain)
859 {
860 ProfileScope11 timing("Spatial rain fog");
861 parameters.Texture("riseSceneDepth",depth.ShaderView());
862 parameters.Texture("riseSceneStencil",depth.StencilView());
863 const UINT hasStencil=depth.StencilView() ? 1u : 0u;
864 parameters.Set("riseSceneStencilAvailable",hasStencil);
865 parameters.Set("riseRainSharedMaskEnabled",useRainMask);
866 parameters.Set("riseRainCloudOcclusionEnabled",rainCloudOcclusionEnabled ? 1u : 0u);
867 parameters.Texture("riseRainSharedMask",nullptr);
868 context->RSSetViewports(1,&viewport);
869 if(useRainMask)
870 {
871 ProfileScope11 classifyTiming("Fog and cloud MSAA classification");
872 auto* target=rainMask.rtv.Get();context->OMSetRenderTargets(1,&target,nullptr);
873 if(FAILED(hr=Draw(context,rainClassify[variant],parameters)))return hr;
874 Unbind(context);parameters.Texture("riseRainSharedMask",rainMask.srv.Get());
875 }
876 context->OMSetRenderTargets(1,&scene,depth.ReadView());
877 context->OMSetDepthStencilState(compositeDepth.Get(),3);
878 context->OMSetBlendState(blend.Get(),nullptr,UINT_MAX);
879 {ProfileScope11 pixelTiming("Fog shared pixels");if(FAILED(hr=Draw(context,rainPixel[variant],parameters)))return hr;}
880 if(sampleCount>1)
881 {ProfileScope11 edgeTiming("Fog individual samples");if(FAILED(hr=Draw(context,rainEdge[variant],parameters)))return hr;}
882 Unbind(context);
883 // The cloud composite reads the other flag from this same mask.
884 context->OMSetDepthStencilState(disabledDepth.Get(),0);
885 context->OMSetBlendState(nullptr,nullptr,UINT_MAX);
886 }
887 if(useCompositeWork)
888 {
889 ProfileScope11 timing("Cloud composite work selection");
890 const UINT initial[]={3,1,0,0,0,1,0,0};
891 context->UpdateSubresource(compositeArguments.Get(),0,nullptr,initial,0,0);
892 ID3D11ShaderResourceView* source[]={depth.ShaderView(),depth.StencilView()};auto* arguments=compositeArgumentsView.Get();
893 context->CSSetShader(compositeWorkScan[variant].Get(),nullptr,0);context->CSSetShaderResources(0,2,source);
894 context->CSSetUnorderedAccessViews(0,1,&arguments,nullptr);
895 context->Dispatch((depth.Description().Width+15)/16,(depth.Description().Height+15)/16,1);
896 source[0]=source[1]=nullptr;arguments=nullptr;context->CSSetShaderResources(0,2,source);
897 context->CSSetUnorderedAccessViews(0,1,&arguments,nullptr);context->CSSetShader(nullptr,nullptr,0);
898 }
899 if(useSharedSearch)
900 {
901 ProfileScope11 timing("Cloud shared initial search");
902 parameters.Texture("riseSceneDepth",depth.ShaderView());
903 parameters.Texture("riseSceneStencil",depth.StencilView());
904 parameters.Set("riseSceneStencilAvailable",depth.StencilView() ? 1u : 0u);
905 // Integer viewport edges give classifier/composite matching pixel
906 // coverage. Fractional edges may cover an MSAA sample without its
907 // center; clear those views so the original per-sample search can
908 // safely handle any unclassified edge pixel via the -2 sentinel.
909 const bool aligned=std::floor(viewport.TopLeftX)==viewport.TopLeftX
910 && std::floor(viewport.TopLeftY)==viewport.TopLeftY
911 && std::floor(viewport.Width)==viewport.Width && std::floor(viewport.Height)==viewport.Height
912 && parameters.ZeroOrUnset("_risePixelCenterOffset");
913 if(!aligned)
914 {
915 const float unneeded[4]={-2,0,0,0};context->ClearRenderTargetView(firstHit.rtv.Get(),unneeded);
916 }
917
918 auto* target=firstHit.rtv.Get();context->OMSetRenderTargets(1,&target,nullptr);
919 context->RSSetViewports(1,&viewport);
920 parameters.Set("riseSharedCloudFog",atmosphericFog ? 1u : 0u);
921 if(useCompositeWork)
922 {
923 if(FAILED(hr=firstHitClassify[variant].Bind(context,parameters)))return hr;
924 context->DrawInstancedIndirect(compositeArguments.Get(),16);
925 }
926 else if(FAILED(hr=Draw(context,firstHitClassify[variant],parameters)))return hr;
927 Unbind(context);parameters.Texture("riseCloudFirstHit",firstHit.srv.Get());
928 }
929 {
930 ProfileScope11 timing("Cloud MSAA composite");
931 if(useTopDirect)
932 {
933 auto& direct=topDirect[variant];
934 parameters.Texture("riseSceneDepth",depth.ShaderView());
935 parameters.Texture("riseSceneStencil",depth.StencilView());
936 parameters.Set("riseSceneStencilAvailable",depth.StencilView() ? 1u : 0u);
937 parameters.Set("risePartialFog",atmosphericFog ? 1u : 0u);
938 {
939 ProfileScope11 part("Cloud Top sample classification");
940 const float clear[4]{};context->ClearRenderTargetView(direct.mask.rtv.Get(),clear);
941 auto* target=direct.mask.rtv.Get();context->OMSetRenderTargets(1,&target,nullptr);
942 context->OMSetDepthStencilState(disabledDepth.Get(),0);context->OMSetBlendState(nullptr,nullptr,UINT_MAX);
943 context->RSSetViewports(1,&viewport);
944 if(FAILED(hr=Draw(context,direct.classify,parameters)))return hr;
945 Unbind(context);parameters.Texture("risePartialMask",direct.mask.srv.Get());
946 const UINT initial[]={0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0};
947 context->UpdateSubresource(direct.arguments.Get(),0,nullptr,initial,0,0);
948 auto* source=direct.mask.srv.Get();auto* arguments=direct.argumentView.Get();
949 context->CSSetShader(direct.scan.Get(),nullptr,0);context->CSSetShaderResources(0,1,&source);
950 context->CSSetUnorderedAccessViews(0,1,&arguments,nullptr);
951 context->Dispatch((depth.Description().Width+15)/16,(depth.Description().Height+15)/16,1);
952 source=nullptr;arguments=nullptr;context->CSSetShaderResources(0,1,&source);
953 context->CSSetUnorderedAccessViews(0,1,&arguments,nullptr);context->CSSetShader(nullptr,nullptr,0);
954 }
955 context->OMSetRenderTargets(1,&scene,depth.ReadView());
956 context->OMSetDepthStencilState(compositeDepth.Get(),3);context->OMSetBlendState(blend.Get(),nullptr,UINT_MAX);
957 {
958 ProfileScope11 part("Cloud Top partial integration");
959 for(UINT sample=0;sample<sampleCount;++sample)
960 {
961 parameters.Set("risePartialSample",sample);
962 if(FAILED(hr=direct.integrate.Bind(context,parameters)))return hr;
963 context->DrawInstancedIndirect(direct.arguments.Get(),16*sample);
964 }
965 }
966 Unbind(context);
967 }
968 ID3D11RenderTargetView* compositeTargets[]={scene,adOpacityTarget.Get()};
969 context->OMSetRenderTargets(measureOpacity ? 2 : 1,compositeTargets,depth.ReadView());context->RSSetViewports(1,&viewport);
970 context->OMSetDepthStencilState(compositeDepth.Get(),3);context->OMSetBlendState(measureOpacity ? adBlend.Get() : blend.Get(),nullptr,0xffffffff);
971 parameters.Texture("riseSceneDepth",depth.ShaderView());
972 parameters.Texture("riseSceneStencil",depth.StencilView());
973 const UINT stencilAvailable=depth.StencilView() ? 1u : 0u;
974 parameters.Set("riseSceneStencilAvailable",stencilAvailable);
975 {
976 if(useTopDirect)
977 {
978 ProfileScope11 part("Cloud Top cached samples");
979 hr=Draw(context,topDirect[variant].composite,parameters);
980 }
981 else
982 {
983 const auto compositeDraw=[&](Program11& program,UINT offset=16) {
984 if(!useCompositeWork)return Draw(context,program,parameters);
985 const HRESULT result=program.Bind(context,parameters);
986 if(FAILED(result))return result;
987 context->DrawInstancedIndirect(compositeArguments.Get(),offset);return S_OK;
988 };
989 if(useCompositeWork)
990 {
991 parameters.Set("riseCompositeFog",atmosphericFog ? 1u : 0u);
992 if(FAILED(hr=compositeDraw(completeComposite[variant],0)))return hr;
993 }
994 if(useCachedComposite) { ProfileScope11 part("Composite cached"); if(FAILED(hr=compositeDraw(cachedComposite[variant])))return hr; }
995 auto& pixel=measureOpacity ? (atmosphericFog ? adFogPixel : adPixel) : (atmosphericFog ? compositeFogPixel : compositePixel);
996 auto& edge=measureOpacity ? (atmosphericFog ? adFogEdge : adEdge) : (atmosphericFog ? compositeFogEdge : compositeEdge);
997 auto& selectedPixel=activeOrganic ? (measureOpacity ? (atmosphericFog ? activeOrganic->adFogPixel : activeOrganic->adPixel)
998 : (atmosphericFog ? activeOrganic->fogPixel : activeOrganic->pixel)) : pixel;
999 auto& selectedEdge=activeOrganic ? (measureOpacity ? (atmosphericFog ? activeOrganic->adFogEdge : activeOrganic->adEdge)
1000 : (atmosphericFog ? activeOrganic->fogEdge : activeOrganic->edge)) : edge;
1001 if(sampleCount==1) hr=Draw(context,selectedPixel[0],parameters);
1002 else
1003 {
1004 { ProfileScope11 part("Composite finite shared"); hr=compositeDraw(useCachedComposite ? visibleComposite[variant] : selectedPixel[variant]); }
1005 if(SUCCEEDED(hr)) { ProfileScope11 part("Composite individual samples"); hr=compositeDraw(useSharedSearch ? (atmosphericFog ? seededFogEdge[variant] : seededEdge[variant]) : selectedEdge[variant]); }
1006 }
1007 }
1008 }
1009 }
1010 parameters.Texture("riseCloudFirstHit",nullptr);
1011 adOpacityWritten=measureOpacity && SUCCEEDED(hr);
1012 parameters.Texture("cloudImage",nullptr);parameters.Texture("cloudDistance",nullptr);
1013 parameters.Texture("riseRainSharedMask",nullptr);
1014 parameters.Texture("headlightDepth",nullptr);parameters.Texture("riseSceneDepth",nullptr);
1015 parameters.Texture("riseSceneStencil",nullptr);
1016 return hr;
1017 }
1018 HRESULT CloudPass11::ValidateScene(ID3D11DeviceContext* context,ID3D11RenderTargetView* scene,
1019 const SceneDepth11& depth,const D3D11_VIEWPORT& viewport)
1020 {
1021 if(!device || !passState || !context || !scene || !depth.ReadView()) return E_UNEXPECTED;
1022 if(context->GetType()!=D3D11_DEVICE_CONTEXT_IMMEDIATE) return E_INVALIDARG;
1023 if(!std::isfinite(viewport.Width) || !std::isfinite(viewport.Height) || !std::isfinite(viewport.TopLeftX) || !std::isfinite(viewport.TopLeftY)
1024 || !std::isfinite(viewport.MinDepth) || !std::isfinite(viewport.MaxDepth) || viewport.MinDepth<0 || viewport.MaxDepth>1 || viewport.MinDepth>viewport.MaxDepth
1025 || viewport.Width<1 || viewport.Height<1
1026 || viewport.TopLeftX<0 || viewport.TopLeftY<0 || viewport.TopLeftX+viewport.Width>depth.Description().Width
1027 || viewport.TopLeftY+viewport.Height>depth.Description().Height) return E_INVALIDARG;
1028 ComPtr<ID3D11Resource> resource;scene->GetResource(&resource);
1029 ComPtr<ID3D11Texture2D> texture;
1030 if(FAILED(resource.As(&texture))) return E_INVALIDARG;
1031 D3D11_TEXTURE2D_DESC desc{};texture->GetDesc(&desc);
1032 D3D11_RENDER_TARGET_VIEW_DESC view{};scene->GetDesc(&view);
1033 if(desc.ArraySize!=1 || (view.ViewDimension!=D3D11_RTV_DIMENSION_TEXTURE2D && view.ViewDimension!=D3D11_RTV_DIMENSION_TEXTURE2DMS)
1034 || (view.ViewDimension==D3D11_RTV_DIMENSION_TEXTURE2D && view.Texture2D.MipSlice!=0)) return E_INVALIDARG;
1035 const auto& expected=depth.Description();
1036 if(desc.Width!=expected.Width || desc.Height!=expected.Height || desc.SampleDesc.Count!=expected.SampleDesc.Count
1037 || desc.SampleDesc.Quality!=expected.SampleDesc.Quality) return E_INVALIDARG;
1038 return S_OK;
1039 }
1040 HRESULT CloudPass11::Geometry(ID3D11DeviceContext* context,Program11& program,Parameters11& parameters,
1041 ID3D11RenderTargetView* scene,const SceneDepth11& depth,const D3D11_VIEWPORT& viewport,
1042 ID3D11Buffer* vertices,UINT stride,UINT count,D3D11_PRIMITIVE_TOPOLOGY topology,
1043 ID3D11Buffer* indices,UINT indexCount,bool premultiplied)
1044 {
1045 HRESULT hr=ValidateScene(context,scene,depth,viewport);
1046 if(FAILED(hr)) return hr;
1047 if(!vertices) return E_INVALIDARG;
1048 D3D11_BUFFER_DESC desc{};vertices->GetDesc(&desc);
1049 if(!(desc.BindFlags&D3D11_BIND_VERTEX_BUFFER) || uint64_t(stride)*count>desc.ByteWidth) return E_INVALIDARG;
1050 if(indices)
1051 {
1052 indices->GetDesc(&desc);
1053 if(!(desc.BindFlags&D3D11_BIND_INDEX_BUFFER) || uint64_t(indexCount)*2>desc.ByteWidth) return E_INVALIDARG;
1054 }
1055 Restore restore;
1056 if(FAILED(hr=context->QueryInterface(IID_PPV_ARGS(&restore.context)))) return Fail("immediate context state interface",hr);
1057 restore.context->SwapDeviceContextState(passState.Get(),&restore.previous);
1058 Unbind(context);
1059 context->RSSetState(raster.Get());
1060 context->RSSetViewports(1,&viewport);
1061 context->IASetPrimitiveTopology(topology);
1062 context->GSSetShader(nullptr,nullptr,0);context->HSSetShader(nullptr,nullptr,0);context->DSSetShader(nullptr,nullptr,0);
1063 context->OMSetRenderTargets(1,&scene,depth.ReadView());
1064 context->OMSetDepthStencilState(compositeDepth.Get(),3);
1065 context->OMSetBlendState(premultiplied ? blend.Get() : straightBlend.Get(),nullptr,0xffffffff);
1066 const UINT offset=0;context->IASetVertexBuffers(0,1,&vertices,&stride,&offset);
1067 context->IASetIndexBuffer(indices,DXGI_FORMAT_R16_UINT,0);
1068 for(size_t i=0;i<samplers.size();++i) parameters.Sampler(CloudVolumeSamplers[i].name,samplers[i].Get());
1069 if(FAILED(hr=program.Bind(context,parameters))) return Fail(program.Status().c_str(),hr);
1070 if(indices) context->DrawIndexed(indexCount,0,0);else context->Draw(count,0);
1071 return S_OK;
1072 }
1073 HRESULT CloudPass11::RenderSkyRing(ID3D11DeviceContext* context,Parameters11& parameters,
1074 ID3D11RenderTargetView* scene,const SceneDepth11& depth,const D3D11_VIEWPORT& viewport,
1075 ID3D11ShaderResourceView* atmosphere,ID3D11Buffer* vertices,const DirectX::XMFLOAT4X4& world,UINT segments,float physicalScale)
1076 {
1077 if(!image.srv || !atmosphere || !segments || segments>UINT_MAX/2-1 || !std::isfinite(physicalScale) || physicalScale<=0) return E_INVALIDARG;
1078 const HRESULT valid=ValidateScene(context,scene,depth,viewport);
1079 if(FAILED(valid)) return valid;
1080 parameters.Texture("cloudImage",Image());parameters.Texture("cloudDistance",Distance());
1081 parameters.Texture("atmosphereImage",atmosphere);parameters.Set("ringWorld",world);parameters.Set("ringScale",physicalScale);
1082 const DirectX::XMFLOAT4 screen(viewport.TopLeftX,viewport.TopLeftY,1.f/viewport.Width,1.f/viewport.Height);parameters.Set("ringViewport",screen);
1083 const HRESULT hr=Geometry(context,skyRing,parameters,scene,depth,viewport,vertices,24,segments*2+2,D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
1084 parameters.Texture("cloudImage",nullptr);parameters.Texture("cloudDistance",nullptr);parameters.Texture("atmosphereImage",nullptr);
1085 return hr;
1086 }
1087 HRESULT CloudPass11::RenderRainLines(ID3D11DeviceContext* context,Parameters11& parameters,
1088 ID3D11RenderTargetView* scene,const SceneDepth11& depth,const D3D11_VIEWPORT& viewport,
1089 ID3D11Buffer* vertices,const DirectX::XMFLOAT4X4& world,UINT drops)
1090 {
1091 if(drops>UINT_MAX/2) return E_INVALIDARG;
1092 parameters.Set("rainWorld",world);
1093 return Geometry(context,rainLines,parameters,scene,depth,viewport,vertices,16,drops*2,D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
1094 }
1095 HRESULT CloudPass11::RenderRainParticles(ID3D11DeviceContext* context,Parameters11& parameters,
1096 ID3D11RenderTargetView* scene,const SceneDepth11& depth,const D3D11_VIEWPORT& viewport,
1097 ID3D11Buffer* vertices,ID3D11Buffer* indices,UINT drops,bool cloudAttenuation)
1098 {
1099 if(!indices || drops>16384) return E_INVALIDARG; // 16-bit indices, four vertices per drop.
1100 if(cloudAttenuation && activeOrganic){const auto hr=PrepareOrganicRain();if(FAILED(hr))return Fail("prepare organic rain",hr);}
1101 return Geometry(context,cloudAttenuation ? (activeOrganic ? organicRainParticles : rainParticles) : clearRainParticles,parameters,scene,depth,viewport,
1102 vertices,28,drops*4,D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST,indices,drops*6,true);
1103 }
1104}
1105
1106#include "CloudLoading11.inl"
SCRIPT_CONTROL SCRIPT_STATE const void int
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
std::array< Program11, 4 > seededEdge
HRESULT LoadFullscreenProgram(Program11 &program, const std::string &name)
HRESULT RenderRainParticles(ID3D11DeviceContext *context, Parameters11 &parameters, ID3D11RenderTargetView *scene, const SceneDepth11 &depth, const D3D11_VIEWPORT &viewport, ID3D11Buffer *vertices, ID3D11Buffer *indices, UINT drops, bool cloudAttenuation=true)
std::array< bool, 4 > hiddenAvailable
std::filesystem::path shaderDirectory
LoadingProgress loadingDisplayProgress
std::array< bool, 4 > cachedCompositeAvailable
std::array< Program11, 4 > adPixel
Microsoft::WRL::ComPtr< ID3D11UnorderedAccessView > compositeArgumentsView
std::array< Program11, 4 > visibleComposite
HRESULT Initialize(ID3D11Device *device, const std::filesystem::path &shaderDirectory={})
ID3D11ShaderResourceView * Image() const
Definition CloudPass11.h:83
HRESULT PrepareLoadingStepNow(ID3D11DeviceContext *context, UINT samples, bool organic)
std::array< Program11, 4 > compositeFogPixel
std::array< bool, 4 > sharedSearchAvailable
std::array< bool, 4 > compositeWorkAvailable
std::array< Program11, 4 > adFogPixel
std::array< Microsoft::WRL::ComPtr< ID3D11ComputeShader >, 4 > compositeWorkScan
OrganicPrograms organicTop
Microsoft::WRL::ComPtr< ID3D11BlendState > adBlend
Microsoft::WRL::ComPtr< ID3D11Buffer > compositeArguments
HRESULT PrepareLoadingObjects(const LoadingJob &job, unsigned variant)
Microsoft::WRL::ComPtr< ID3D11RenderTargetView > adOpacityTarget
CloudTemporal11::Frame temporalFrame
ID3D11ShaderResourceView * Distance() const
Definition CloudPass11.h:84
std::array< Program11, 4 > adFogEdge
std::array< Program11, 4 > completeComposite
HRESULT RenderRainLines(ID3D11DeviceContext *context, Parameters11 &parameters, ID3D11RenderTargetView *scene, const SceneDepth11 &depth, const D3D11_VIEWPORT &viewport, ID3D11Buffer *vertices, const DirectX::XMFLOAT4X4 &world, UINT drops)
OrganicPrograms * activeOrganic
std::array< Program11, 4 > classifyHidden
LoadingProgress loadingProgress
HRESULT ConfigureOrganic(bool enabled, bool aboveDeck)
HRESULT PrepareCompositeWork(unsigned variant)
CloudTemporal11 temporal
std::array< Program11, 4 > firstHitClassify
std::array< Program11, 4 > cachedComposite
Microsoft::WRL::ComPtr< ID3D11BlendState > straightBlend
std::array< Program11, 4 > compositeEdge
std::vector< Microsoft::WRL::ComPtr< ID3D11SamplerState > > samplers
std::array< TopDirectState, 4 > topDirect
HRESULT ValidateScene(ID3D11DeviceContext *context, ID3D11RenderTargetView *scene, const SceneDepth11 &depth, const D3D11_VIEWPORT &viewport)
HRESULT RenderSkyRing(ID3D11DeviceContext *context, Parameters11 &parameters, ID3D11RenderTargetView *scene, const SceneDepth11 &depth, const D3D11_VIEWPORT &viewport, ID3D11ShaderResourceView *atmosphere, ID3D11Buffer *vertices, const DirectX::XMFLOAT4X4 &world, UINT segments, float physicalScale)
Microsoft::WRL::ComPtr< ID3D11DepthStencilState > disabledDepth
HRESULT PreparePrograms(unsigned variant, bool fog, bool headlights, bool spatialRain, bool rainMaskEnabled, bool cached, bool sharedSearch, bool directComposite)
Program11 organicRainParticles
HRESULT PrepareTopDirectTargets(unsigned variant, const D3D11_TEXTURE2D_DESC &scene)
std::array< Program11, 4 > compositePixel
std::array< Program11, 4 > rainEdge
Microsoft::WRL::ComPtr< ID3D11RasterizerState > raster
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)
OrganicPrograms organicFlight
Microsoft::WRL::ComPtr< ID3D11DepthStencilState > compositeDepth
Microsoft::WRL::ComPtr< ID3D11BlendState > blend
std::array< unsigned, 8 > loadingStep
Microsoft::WRL::ComPtr< ID3D11Device > device
HRESULT TargetCreate(Target &target, UINT w, UINT h, DXGI_FORMAT format)
std::array< Program11, 4 > rainPixel
std::array< Program11, 4 > compositeFogEdge
HRESULT Draw(ID3D11DeviceContext *context, Program11 &program, Parameters11 &parameters)
Microsoft::WRL::ComPtr< ID3D11Texture2D > hiddenDepthTexture
HRESULT Geometry(ID3D11DeviceContext *context, Program11 &program, Parameters11 &parameters, ID3D11RenderTargetView *scene, const SceneDepth11 &depth, const D3D11_VIEWPORT &viewport, ID3D11Buffer *vertices, UINT stride, UINT count, D3D11_PRIMITIVE_TOPOLOGY topology, ID3D11Buffer *indices=nullptr, UINT indexCount=0, bool premultiplied=false)
Microsoft::WRL::ComPtr< ID3D11DepthStencilState > hiddenRead
std::array< Program11, 4 > adEdge
Microsoft::WRL::ComPtr< ID3D11DepthStencilState > hiddenWrite
Microsoft::WRL::ComPtr< ID3DDeviceContextState > passState
Microsoft::WRL::ComPtr< ID3D11DepthStencilView > hiddenDepth
HRESULT Fail(const char *stage, HRESULT hr)
HRESULT PrepareTopDirectPrograms(unsigned variant)
HRESULT PrepareTopDirectWork(unsigned variant)
std::array< Program11, 4 > rainClassify
std::vector< LoadingJob > LoadingJobs(UINT samples, bool organic, size_t &topBegin)
std::array< Program11, 4 > seededFogEdge
HRESULT Initialize(ID3D11Device *native, const std::filesystem::path &shaders)
Microsoft::WRL::ComPtr< ID3D11SamplerState > linear
Microsoft::WRL::ComPtr< ID3D11SamplerState > point
HRESULT BeginFrame(const Frame &frame, unsigned fullWidth, unsigned fullHeight, unsigned sampleWidth, unsigned sampleHeight)
DirectX::XMFLOAT4 Jitter() const
HRESULT Resolve(ID3D11DeviceContext *context, ID3D11ShaderResourceView *current, ID3D11ShaderResourceView *currentDistance)
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
bool ZeroOrUnset(const std::string &name) const
Definition Program11.h:26
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)
bool Ready() const
Definition Program11.h:66
const std::string & Status() const
Definition Program11.h:67
HRESULT Bind(ID3D11DeviceContext *context, const Parameters11 &parameters)
ID3D11ShaderResourceView * StencilView() const
Definition Device11.h:21
ID3D11ShaderResourceView * ShaderView() const
Definition Device11.h:20
const D3D11_TEXTURE2D_DESC & Description() const
Definition Device11.h:22
HRESULT Create(ID3D11Device *device, UINT width, UINT height, DXGI_SAMPLE_DESC samples)
Definition Device11.cpp:20
ID3D11DepthStencilView * ReadView() const
Definition Device11.h:19
ID3D11DepthStencilView * WriteView() const
Definition Device11.h:18
constexpr float MaxTopRiseKm
Definition CloudVolume.h:23
constexpr unsigned MaxHeight
Definition CloudVolume.h:24
constexpr unsigned MaxWidth
Definition CloudVolume.h:24
bool HasShaderBytecode11(const std::filesystem::path &path)
const ShaderSampler11 CloudVolumeSamplers[]
std::vector< char > ReadShaderBytecode11(const std::filesystem::path &path, HMODULE resourceModule=nullptr)
Model.
typedef void(S_CALLTYPE *SteamAPIWarningMessageHook_t)(int
std::array< Program11, 4 > edge
std::array< Program11, 4 > adPixel
std::array< Program11, 4 > adFogEdge
std::array< Program11, 4 > pixel
std::array< Program11, 4 > adFogPixel
std::array< Program11, 4 > fogEdge
std::array< Program11, 4 > fogPixel
std::array< Program11, 4 > adEdge
Microsoft::WRL::ComPtr< ID3D11Texture2D > texture
Definition CloudPass11.h:90
Microsoft::WRL::ComPtr< ID3D11ShaderResourceView > srv
Definition CloudPass11.h:92
Microsoft::WRL::ComPtr< ID3D11RenderTargetView > rtv
Definition CloudPass11.h:91