Rise
The Vieneo Province
Loading...
Searching...
No Matches
CloudRenderer11.cpp
Go to the documentation of this file.
1#include "CloudRenderer11.h"
4#include "FrameProfiler11.h"
5#include <DirectXPackedVector.h>
6#include <cstdlib>
8
9using Microsoft::WRL::ComPtr;
10using namespace DirectX;
11namespace Rendering
12{
14 {status=std::string("native clouds: ")+step+"; HRESULT="+std::to_string(hr);return hr;}
15
16 HRESULT CloudRenderer11::Initialize(ID3D11Device* native,const std::filesystem::path& directory)
17 {
18 if(!native) return E_INVALIDARG;
19 if(device.Get()==native && (ready || !enabled))return enabled ? S_OK : S_FALSE;
20 Reset();device=native;shaderDirectory=directory;
21 char setting[32]{};
22 enabled=!(GetEnvironmentVariableA("RISE_VOLUMETRIC_CLOUDS",setting,sizeof(setting))==1 && setting[0]=='0');
23 if(!enabled){status="Volumetric clouds disabled by RISE_VOLUMETRIC_CLOUDS=0";return S_FALSE;}
25 {
26 const DWORD n=GetEnvironmentVariableA("RISE_LIGHTNING_SEED",setting,sizeof(setting));
27 lightning.Seed(n && n<sizeof(setting) ? uint32_t(std::strtoul(setting,nullptr,0)) : GetTickCount()^GetCurrentProcessId());
28 lightningSeeded=true;
29 }
30 const DWORD n=GetEnvironmentVariableA("RISE_CLOUD_SEED",setting,sizeof(setting));
31 if(n && n<sizeof(setting)) seed=uint32_t(std::strtoul(setting,nullptr,0));
32 HRESULT hr=pass.Initialize(device.Get(),directory);
33 if(FAILED(hr))return Fail(pass.Status().c_str(),hr);
34 std::vector<float> values(64*64*64*4);
35 std::vector<uint16_t> clearanceValues(64*64*64);
36 const auto& billows=CloudBillows::Values();
37 const auto& perlin=CloudPerlin::Values();
38 for(int z=0;z<64;++z)for(int y=0;y<64;++y)for(int x=0;x<64;++x)
39 {
40 const auto index=(z*64+y)*64+x;
41 values[index*4]=CloudVolume::Voxel(x,y,z,seed)/255.f;
42 values[index*4+1]=billows[index];
43 values[index*4+2]=perlin[index];
44 clearanceValues[index]=PackedVector::XMConvertFloatToHalf(values[index*4]);
45 }
46 std::array<std::vector<uint16_t>,7> levels;
47 std::array<D3D11_SUBRESOURCE_DATA,7> data{};
48 for(unsigned level=0;level<7;++level)
49 {
50 const unsigned size=64u>>level;
51 levels[level].resize(values.size());
52 for(size_t i=0;i<values.size();++i)levels[level][i]=PackedVector::XMConvertFloatToHalf(values[i]);
53 data[level]={levels[level].data(),size*8,size*size*8};
54 const unsigned nextSize=size/2;
55 std::vector<float> next(nextSize*nextSize*nextSize*4);
56 for(unsigned z=0;z<nextSize;++z)for(unsigned y=0;y<nextSize;++y)for(unsigned x=0;x<nextSize;++x)
57 for(unsigned channel=0;channel<4;++channel)
58 {
59 float sum=0;
60 for(unsigned dz=0;dz<2;++dz)for(unsigned dy=0;dy<2;++dy)for(unsigned dx=0;dx<2;++dx)
61 sum+=values[(((z*2+dz)*size+y*2+dy)*size+x*2+dx)*4+channel];
62 next[((z*nextSize+y)*nextSize+x)*4+channel]=sum*.125f;
63 }
64 values=std::move(next);
65 }
66 D3D11_TEXTURE3D_DESC vd{};vd.Width=vd.Height=vd.Depth=64;vd.MipLevels=7;
67 vd.Format=DXGI_FORMAT_R16G16B16A16_FLOAT;vd.Usage=D3D11_USAGE_IMMUTABLE;vd.BindFlags=D3D11_BIND_SHADER_RESOURCE;
68 ComPtr<ID3D11Texture3D> volume;
69 if(FAILED(hr=device->CreateTexture3D(&vd,data.data(),&volume)) || FAILED(hr=device->CreateShaderResourceView(volume.Get(),nullptr,&noise)))
70 return Fail("create filtered noise volume",hr);
71 parameters.Texture("noiseVolume",noise.Get());
72 clearance.SetNoise(std::move(clearanceValues));
73 D3D11_TEXTURE2D_DESC td{};td.Width=td.Height=td.MipLevels=td.ArraySize=1;td.SampleDesc.Count=1;
74 td.Format=DXGI_FORMAT_R8_UNORM;td.Usage=D3D11_USAGE_IMMUTABLE;td.BindFlags=D3D11_BIND_SHADER_RESOURCE;
75 const uint8_t black=0;D3D11_SUBRESOURCE_DATA initial{&black,1,0};ComPtr<ID3D11Texture2D> zero;
76 if(FAILED(hr=device->CreateTexture2D(&td,&initial,&zero)) || FAILED(hr=device->CreateShaderResourceView(zero.Get(),nullptr,&blackWeather)))
77 return Fail("create empty weather map",hr);
78 // RGB retains the authored light map; alpha carries light-weighted
79 // source height in km MSL, including terrain below sea level.
80 td.Width=td.Height=64;td.Format=DXGI_FORMAT_R32G32B32A32_FLOAT;td.Usage=D3D11_USAGE_DEFAULT;
81 if(FAILED(hr=device->CreateTexture2D(&td,nullptr,&groundTexture)) || FAILED(hr=device->CreateShaderResourceView(groundTexture.Get(),nullptr,&ground)))
82 return Fail("create ground illumination",hr);
83 parameters.Texture("groundImage",ground.Get());groundDirty=true;
84 if(FAILED(hr=device->CreateTexture2D(&td,nullptr,&rainTexture)) || FAILED(hr=device->CreateShaderResourceView(rainTexture.Get(),nullptr,&rainView)))
85 return Fail("create plot rain volume",hr);
86 parameters.Texture("rainImage",rainView.Get());
87 if(FAILED(hr=device->CreateTexture2D(&td,nullptr,&localBaseTexture)) || FAILED(hr=device->CreateShaderResourceView(localBaseTexture.Get(),nullptr,&localBaseView)))
88 return Fail("create local cloud-base controls",hr);
89 parameters.Texture("localBaseImage",localBaseView.Get());
90 // Use the reduced-resolution scattering path by default, retaining an
91 // explicit startup override for the legacy cone fallback.
92 fogBeamsEnabled=!(GetEnvironmentVariableA("RISE_FOG_BEAMS",setting,sizeof(setting))==1 && setting[0]=='0');
93 const bool fogReady=SUCCEEDED(fogBeams.Initialize(device.Get(),directory));
94 ready=true;status="Volumetric clouds ready: native D3D11, shader-readable scene depth";
95 status+=!fogReady ? "; fog scattering unavailable, using cone fallback" : fogBeamsEnabled ? "; fog scattering enabled" : "; fog scattering disabled by RISE_FOG_BEAMS=0, using cone fallback";
96 return S_OK;
97 }
99 {
100 // Samplers also retain the device. Clearing only textures leaves the
101 // failed driver's allocation alive throughout device recreation.
102 ready=false;pass.Reset();fogBeams.Reset();parameters=Parameters11{};noise.Reset();blackWeather.Reset();ground.Reset();groundTexture.Reset();device.Reset();
104 organicOrbit=false;organicDistantOrbit=false;organicGlobeOrbit=false;organicUpperFlight=false;historyResetPending.store(false,std::memory_order_relaxed);
105 rainTexture.Reset();rainView.Reset();rainActive=rainDirty=false;
106 localBaseTexture.Reset();localBaseView.Reset();uploadedLocalBase.reset();
107 std::lock_guard<std::mutex> lock(weatherMutex);
109 status="native cloud renderer not initialized";
110 }
112 {
113 // No reset callback for managed resources is needed. Only the pass's
114 // viewport-sized image/depth-distance surfaces need replacement.
117 }
119 {std::lock_guard<std::mutex> lock(groundMutex);groundLighting=lighting;groundDirty=true;}
121 {
122 rainActive=grid!=nullptr;
123 if(grid)
124 {
125 rainGrid=*grid;rainDirty=true;
126 for(auto& cell:rainGrid.cells)
127 if(!std::isfinite(cell.x) || !std::isfinite(cell.y) || cell.y<cell.x ||
128 !std::isfinite(cell.z) || cell.z<=0 || !std::isfinite(cell.w))
129 cell={0,0,42.16f,2};
130 }
131 }
133 {
134 std::lock_guard<std::mutex> lock(weatherMutex);desiredWeather=map;
136 if(std::isfinite(elapsed) && elapsed>0)weatherBlendSeconds=(std::min)(60.,weatherBlendSeconds+elapsed);
139 }
141 {std::lock_guard<std::mutex> lock(weatherMutex);return weatherFrame;}
143 {
144 std::lock_guard<std::mutex> lock(weatherMutex);
145 if(lightningEnabled==value)return;lightningEnabled=value;
147 }
149 {
150 std::lock_guard<std::mutex> lock(weatherMutex);
152 if(!value)return true;
153 if(!Ready() || !lightningEnabled || (!weatherFrame.current && !weatherFrame.previous))return false;
154 lightningDiagnostic.Start();return true;
155 }
156 void CloudRenderer11::UpdateLightning(const CloudVolume::Parameters& params,double elapsed,const CloudVolume::Point& observer)
157 {
158 std::lock_guard<std::mutex> lock(weatherMutex);
160 {
161 lightning.Update(params,elapsed,seed);
162 lightningDiagnostic.Update(params,elapsed,seed,observer);
163 }
164 }
165 void CloudRenderer11::SetLocalLightning(const Vector& position,const Color& color,float radiusKm)
166 {SetLocalLightning(position,color,radiusKm,position);}
167 void CloudRenderer11::SetLocalLightning(const Vector& position,const Color& color,float radiusKm,const Vector& groundPosition)
168 {
169 std::lock_guard<std::mutex> lock(weatherMutex);
170 localPosition={position.x,position.y,position.z,1/(std::max)(.01f,radiusKm*radiusKm)};localColor=color;
171 localGround=groundPosition;
172 }
173 void CloudRenderer11::SetHeadlights(const std::vector<Headlight>& lights)
174 {
175 headlights.clear();
176 for(auto light:lights)
177 {
178 if(headlights.size()==MaxHeadlights)break;
179 const float length=CloudVolume::Length({light.direction.x,light.direction.y,light.direction.z});
180 if(!std::isfinite(length) || length<.0001f || !std::isfinite(light.rangeKm) || light.rangeKm<=0
181 || !std::isfinite(light.position.x) || !std::isfinite(light.position.y) || !std::isfinite(light.position.z)
182 || !std::isfinite(light.color.x) || !std::isfinite(light.color.y) || !std::isfinite(light.color.z))continue;
183 light.direction={light.direction.x/length,light.direction.y/length,light.direction.z/length};
184 light.rangeKm=(std::min)(2.f,light.rangeKm);
185 light.color.x=(std::max)(0.f,light.color.x);light.color.y=(std::max)(0.f,light.color.y);light.color.z=(std::max)(0.f,light.color.z);
186 light.up=LandingLights::OrthonormalUp(light.up,light.direction);
187 headlights.push_back(light);
188 }
189 }
190
191 HRESULT CloudRenderer11::PrepareWeather(ID3D11DeviceContext* context)
192 {
193 std::lock_guard<std::mutex> lock(weatherMutex);
194 weatherTextures.erase(std::remove_if(weatherTextures.begin(),weatherTextures.end(),[&](const WeatherTexture& t){
195 return t.map!=weatherFrame.current && t.map!=weatherFrame.previous && t.map!=desiredWeather;
196 }),weatherTextures.end());
198 {
199 auto it=std::find_if(weatherTextures.begin(),weatherTextures.end(),[&](const WeatherTexture& t){return t.map==desiredWeather;});
200 if(it==weatherTextures.end())
201 {
202 if(desiredWeather->mips.empty())return E_INVALIDARG;
203 WeatherTexture texture;texture.map=desiredWeather;const auto& mip=desiredWeather->mips.front();
204 D3D11_TEXTURE2D_DESC desc{};desc.Width=mip.width;desc.Height=mip.height;
205 desc.MipLevels=UINT(desiredWeather->mips.size());desc.ArraySize=1;desc.SampleDesc.Count=1;
206 desc.Format=DXGI_FORMAT_R8_UNORM;desc.BindFlags=D3D11_BIND_SHADER_RESOURCE;
207 HRESULT hr=device->CreateTexture2D(&desc,nullptr,&texture.texture);
208 if(SUCCEEDED(hr))hr=device->CreateShaderResourceView(texture.texture.Get(),nullptr,&texture.srv);
209 if(FAILED(hr))return Fail("create weather texture",hr);
210 weatherTextures.push_back(std::move(texture));it=weatherTextures.end()-1;
211 }
212 auto& texture=*it;unsigned budget=65536;
213 while(texture.level<texture.map->mips.size() && budget)
214 {
215 const auto& mip=texture.map->mips[texture.level];
216 if(!mip.width || mip.pixels.size()!=size_t(mip.width)*mip.height)return E_INVALIDARG;
217 const unsigned rows=(std::min)(mip.height-texture.row,budget/mip.width);if(!rows)break;
218 const D3D11_BOX box{0,texture.row,0,mip.width,texture.row+rows,1};
219 context->UpdateSubresource(texture.texture.Get(),texture.level,&box,mip.pixels.data()+size_t(texture.row)*mip.width,mip.width,0);
220 FrameProfiler11::Get().TextureUpload(UINT64(rows)*mip.width);
221 texture.row+=rows;budget-=rows*mip.width;
222 if(texture.row==mip.height){++texture.level;texture.row=0;}
223 }
224 if(texture.level==texture.map->mips.size())
226 }
227 const auto texture=[&](const CloudWeather::MapPtr& map){
228 for(const auto& t:weatherTextures)if(t.map==map && t.complete)return t.srv.Get();return blackWeather.Get();
229 };
230 parameters.Texture("weatherPrevious",texture(weatherFrame.previous));parameters.Texture("weatherCurrent",texture(weatherFrame.current));
231 const auto width=[](const CloudWeather::MapPtr& map){return map ? float(map->mips.front().width) : 1.f;};
233 boundWeather=weatherFrame;return S_OK;
234 }
235
236 HRESULT CloudRenderer11::Render(ID3D11DeviceContext* context,ID3D11RenderTargetView* scene,const SceneDepth11& depth,
237 const D3D11_VIEWPORT& viewport,const Matrix& view,const Matrix& projection,const Vector& planetEye,
238 const CloudVolume::Parameters& params,const Vector& sunlight,const Color& light,const Color& ambient,
239 const Color& airglow,const Color& horizonHaze,const Color& atmosphereHaze,const Color& nightVisionGain)
240 {
241 if(!Ready())return S_FALSE;
242 // A history reset also clears orbital hysteresis. Keep the previous
243 // mode long enough to restore full flight resolution on disable.
244 const bool wasOrganicOrbit=organicOrbit;
245 const bool wasOrganicTop=pass.SelectedOrganicPath()==CloudPass11::OrganicPath::Top;
246 const bool wasOrganicUpperFlight=organicUpperFlight;
247 if(historyResetPending.exchange(false,std::memory_order_relaxed))
249 if(!context || !scene || !std::isfinite(viewport.Width) || !std::isfinite(viewport.Height)
250 || viewport.Width<1 || viewport.Height<1 || !std::isfinite(projection._11) || !std::isfinite(projection._22)
251 || std::abs(projection._11)<1e-20f || std::abs(projection._22)<1e-20f)return E_INVALIDARG;
252 HRESULT hr=PrepareWeather(context);if(FAILED(hr))return hr;
253 Matrix inverse;XMVECTOR determinant;
254 XMStoreFloat4x4(&inverse,XMMatrixInverse(&determinant,XMLoadFloat4x4(&view)));
255 const float det=XMVectorGetX(determinant);if(!std::isfinite(det) || std::abs(det)<1e-20f)return E_INVALIDARG;
256 const Color eye(planetEye.x+inverse._41,planetEye.y+inverse._42,planetEye.z+inverse._43,0);
257 const float cameraAltitude=CloudVolume::Length({eye.x,eye.y,eye.z})-params.radius;
258 const bool organicField=params.organic && CloudOrganicShape::Weight(params)>0;
259 // The top-only integrator is an exterior view of the whole cloud
260 // envelope. The nominal 10 km deck is not the top of convective cells;
261 // retain the flight integrator through those cells on ascent/re-entry.
262 const bool aboveOrganicEnvelope=!CloudBaseWeather::Active(params.localBase)
263 && cameraAltitude>params.top+CloudVolume::MaxTopRiseKm+.65f;
264 if(FAILED(hr=pass.ConfigureOrganic(organicField,aboveOrganicEnvelope)))return Fail(pass.Status().c_str(),hr);
265 organicOrbit=params.organic && pass.OrganicOrbitAvailable() && params.base<=params.top-2.5f && !CloudBaseWeather::Active(params.localBase)
266 && cameraAltitude>params.top+CloudVolume::MaxTopRiseKm+(organicOrbit ? 10.f : 15.f);
270 // Spend near/upper-flight work on finding thin silhouettes rather than on
271 // redundant rays. Keep the half-grid density filtering, and the Top/
272 // Orbit integrators, unchanged. Start where the organic deck emerges;
273 // thin foreground lobes are already visible here, well below 18 km.
274 // A 250 m hysteresis prevents target churn while hovering near 9.5 km.
275 organicUpperFlight=organicField && !selectedTop && !organicOrbit
276 && !CloudBaseWeather::Active(params.localBase) && params.base<=params.top-2.5f
277 && cameraAltitude>params.top-(organicUpperFlight ? .75f : .5f);
278 parameters.Set("riseCloudRefinedSearch",organicUpperFlight ? 1u : 0u);
279 if(params.organic || wasOrganicOrbit || wasOrganicTop || wasOrganicUpperFlight)
280 {
281 // Preserve detail at smaller viewports while bounding the orbital
282 // ray count for the 18 ms budget on VICTUS.
283 const float requested=organicOrbit ? CloudOrbitResolution11(viewport.Width,viewport.Height,organicDistantOrbit,organicGlobeOrbit)
284 : selectedTop ? .25f : organicUpperFlight ? CloudRefinedFlightResolution11(viewport.Width,viewport.Height) : .5f;
285 // Invalidate only the pass history; retain the orbital entry/exit hysteresis.
286 if(pass.ResolutionScale()!=requested)pass.ResetCloudHistory();
287 pass.SetResolutionScale(requested);
288 }
289 parameters.Set("riseOrganicClouds",params.organic ? 1u : 0u);
290 {
291 std::lock_guard<std::mutex> lock(groundMutex);
292 if(groundDirty)
293 {
294 std::array<CloudVolume::GroundLightTexel,64*64> texels;
295 for(size_t i=0;i<texels.size();++i)texels[i]=CloudVolume::GroundLightAt(groundLighting,i);
296 context->UpdateSubresource(groundTexture.Get(),0,nullptr,texels.data(),64*sizeof(texels[0]),0);
297 FrameProfiler11::Get().TextureUpload(sizeof(texels));
298 groundDirty=false;
299 }
301 parameters.Set("groundU",Color(mapping.east.x,mapping.east.y,mapping.east.z,mapping.u));
302 parameters.Set("groundV",Color(mapping.down.x,mapping.down.y,mapping.down.z,mapping.v));
303 parameters.Set("groundNormal",Color(mapping.normal.x,mapping.normal.y,mapping.normal.z,0));
304 }
305 const float scale=(std::min)(pass.ResolutionScale(),(std::min)(CloudVolume::MaxWidth/viewport.Width,CloudVolume::MaxHeight/viewport.Height));
306 const Color screen(1/projection._11,1/projection._22,float((std::max)(1u,UINT(viewport.Width*scale))),float((std::max)(1u,UINT(viewport.Height*scale))));
307 // Keep field filtering on the capped half-resolution grid while changing
308 // the number of traced rays. Use integer target sizes, including odd viewports.
309 float footprintScale=1.f;
310 if(organicOrbit || selectedTop || organicUpperFlight)
311 {
312 const float referenceScale=(std::min)(.5f,(std::min)(CloudVolume::MaxWidth/viewport.Width,CloudVolume::MaxHeight/viewport.Height));
313 const UINT referenceWidth=(std::max)(1u,UINT(viewport.Width*referenceScale));
314 const UINT referenceHeight=(std::max)(1u,UINT(viewport.Height*referenceScale));
315 const float rawAngular=(std::max)(std::abs(screen.x)/screen.z,std::abs(screen.y)/screen.w);
316 const float referenceAngular=(std::max)(std::abs(screen.x)/referenceWidth,std::abs(screen.y)/referenceHeight);
317 footprintScale=referenceAngular/rawAngular;
318 }
319 parameters.Set("riseCloudFootprintScale",footprintScale);
320 parameters.Set("screen",screen);
322 2*(std::max)(std::abs(double(screen.x))/screen.z,std::abs(double(screen.y))/screen.w)) : 0;
323 parameters.Set("riseClearAirRadius",clearAirRadius);
325 parameters.Set("view",view);parameters.Set("projection",projection);parameters.Set("inverseView",inverse);
326 parameters.Set("eye",eye);parameters.Set("layer",Color(params.radius,params.base,params.top,params.activity));
327 parameters.Set("maxTopRise",CloudVolume::MaxTopRiseKm);parameters.Set("lightDirection",Color(sunlight.x,sunlight.y,sunlight.z,0));
328 parameters.Set("lightColor",light);parameters.Set("ambientColor",ambient);parameters.Set("airglowColor",airglow);
329 // Spatial eclipse evaluation: an orbital observer's shadow must not
330 // darken unrelated parts of the visible cloud hemisphere.
331 parameters.Set("eclipseOccluder",Color(params.eclipse.center.x,params.eclipse.center.y,
332 params.eclipse.center.z,params.eclipse.radius));
333 parameters.Set("eclipseSunRadius",params.eclipse.sunAngularRadius);
334 parameters.Set("eclipseUniformVisibility",CelestialEclipse::UniformVisibility(params.eclipse,
335 params.radius+params.top+CloudVolume::MaxTopRiseKm,{-sunlight.x,-sunlight.y,-sunlight.z}));
336 parameters.Set("nightVisionGain",nightVisionGain);
337 parameters.Set("horizonHaze",horizonHaze);parameters.Set("atmosphereHaze",atmosphereHaze);
338 parameters.Set("localBaseInfo",Color(CloudBaseWeather::Active(params.localBase) ? params.localBase.weight : 0,
339 CloudVolume::MinimumBase(params),0,0));
341 {
342 const auto& grid=*params.localBase.grid;
344 {
345 auto pixels=std::make_unique<std::array<Color,4096>>();
346 for(size_t i=0;i<pixels->size();++i)
347 {
348 const auto& cell=grid.cells[i];
349 (*pixels)[i]={cell.base*cell.coverage,cell.turbulence*cell.coverage,cell.coverage,0};
350 }
351 context->UpdateSubresource(localBaseTexture.Get(),0,nullptr,pixels->data(),64*sizeof(Color),0);
353 }
354 const auto mapping=CloudVolume::ProjectGround(grid.cube,grid.u,grid.v);
355 parameters.Set("localBaseU",Color(mapping.east.x,mapping.east.y,mapping.east.z,mapping.u));
356 parameters.Set("localBaseV",Color(mapping.down.x,mapping.down.y,mapping.down.z,mapping.v));
357 parameters.Set("localBaseNormal",Color(mapping.normal.x,mapping.normal.y,mapping.normal.z,0));
358 }
359 else uploadedLocalBase.reset();
360 parameters.Set("rainInfo",Color(rainActive ? 1.f : 0.f,42.16f,params.radius,0));
361 if(rainActive)
362 {
363 if(rainDirty)
364 {
365 context->UpdateSubresource(rainTexture.Get(),0,nullptr,rainGrid.cells.data(),64*sizeof(Color),0);
367 }
369 parameters.Set("rainU",Color(mapping.east.x,mapping.east.y,mapping.east.z,mapping.u));
370 parameters.Set("rainV",Color(mapping.down.x,mapping.down.y,mapping.down.z,mapping.v));
371 parameters.Set("rainNormal",Color(mapping.normal.x,mapping.normal.y,mapping.normal.z,0));
372 }
373 // Resolve once per view, rather than per MSAA ray. Above the layer the
374 // atmospheric backdrop retreats continuously out of the cloud march.
375 const float fogBlend=1-CloudVolume::BackgroundZenithWeight(CloudVolume::Length({eye.x,eye.y,eye.z})-params.radius,params);
376 const float fogEnd=!rainActive && horizonHaze.w>0 && fogBlend>0 ?
377 (std::min)(1e8f,horizonHaze.w/(std::max)(1e-8f,fogBlend)) : 1e8f;
378 // Reuse depends on whether fog hides this surface, not on a global
379 // 1-2 km visibility switch. A global blend still required the full
380 // partial march until its weight reached exactly one.
381 parameters.Set("riseFogEndKm",fogEnd);
382 parameters.Set("baseLightingWeight",CloudVolume::BaseLightingWeight({eye.x,eye.y,eye.z},params,seed));
383 parameters.Set("noiseOffset",Color(params.noiseOffset.x,params.noiseOffset.y,params.noiseOffset.z,0));
384 std::array<Color,MaxHeadlights> positions{},directions{},colors{},ups{},angles{},profiles{};unsigned headlightCount=0;
385 std::vector<FogBeams11::Light> fogLights;
386 fogLights.reserve(headlights.size());
387 for(const auto& spot:headlights)
388 {
389 const float visibility=spot.extinctionPerKm>0 ? 3.912f/spot.extinctionPerKm : 1e8f;
390 const float fogGain=fogDensity*fogBlend*(std::clamp)(1-visibility/5,0.f,1.f);
391 const Vector relative(spot.position.x-eye.x,spot.position.y-eye.y,spot.position.z-eye.z);
392 FogBeams11::Light fog{relative,spot.direction,spot.up,{spot.color.x,spot.color.y,spot.color.z,fogGain},spot.profile,spot.extinctionPerKm,-1};
393 const float altitude=CloudVolume::Length({spot.position.x,spot.position.y,spot.position.z})-params.radius;
394 if(altitude+spot.rangeKm<CloudVolume::MinimumBase(params)-.4f || altitude-spot.rangeKm>params.top+CloudVolume::MaxTopRiseKm)
395 {if(fogGain>0)fogLights.push_back(fog);continue;}
396 const auto i=headlightCount++;
397 fog.cloudIndex=int(i);if(fogGain>0)fogLights.push_back(fog);
398 positions[i]={spot.position.x-eye.x,spot.position.y-eye.y,spot.position.z-eye.z,spot.rangeKm};
399 directions[i]={spot.direction.x,spot.direction.y,spot.direction.z,0};colors[i]=spot.color;
400 ups[i]={spot.up.x,spot.up.y,spot.up.z,0};
401 angles[i]=spot.profile.Angles<Color>();profiles[i]=spot.profile.Parameters<Color>(spot.extinctionPerKm);
402 }
403 parameters.Set("headlightUp",ups);parameters.Set("headlightAngles",angles);parameters.Set("headlightParameters",profiles);
404 parameters.Set("headlightPosition",positions);parameters.Set("headlightDirection",directions);parameters.Set("headlightColor",colors);
405 struct Candidate{Color position,light,shape;float score;};
406 std::array<Candidate,CloudLightning::MaxEvents+CloudLightning::Diagnostic::MaxEvents+1> candidates{};unsigned candidateCount=0;
407 const float zScale=CloudVolume::Length({view._13,view._23,view._33});
408 const float xMargin=std::abs(projection._11)*CloudVolume::Length({view._11,view._21,view._31})+zScale;
409 const float yMargin=std::abs(projection._22)*CloudVolume::Length({view._12,view._22,view._32})+zScale;
410 {
411 std::lock_guard<std::mutex> lock(weatherMutex);
412 if(lightningEnabled && (localColor.x>0 || localColor.y>0 || localColor.z>0))
413 candidates[candidateCount++]={localPosition,{localColor.x*LocalLightning::PeakRadiance,
416 {eye.x,eye.y,eye.z},{0,0,0},{localColor.x,localColor.y,localColor.z,1},1,horizonHaze.w,
418 parameters.Set("StrikeGround",strike.ground);parameters.Set("StrikeTop",strike.top);
419 parameters.Set("StrikeColor",strike.color);parameters.Set("StrikeEye",strike.eye);parameters.Set("StrikeUp",strike.up);
420 const auto addFlash=[&](const CloudLightning::Flash& flash)
421 {
422 const float brightness=flash.Brightness();if(brightness<.001f)return;
423 const Vector delta(flash.position.x-eye.x,flash.position.y-eye.y,flash.position.z-eye.z);
424 const float range=CloudVolume::Length({delta.x,delta.y,delta.z}),support=flash.radius*2;
425 if(range>support)
426 {
427 const float b=(eye.x*delta.x+eye.y*delta.y+eye.z*delta.z)/range;
428 const float radius=CloudVolume::Length({eye.x,eye.y,eye.z}),occluder=params.radius-support;
429 const float discriminant=b*b-(radius-occluder)*(radius+occluder);
430 if(b<0 && discriminant>0 && -b-std::sqrt(discriminant)<range-support)return;
431 }
432 Vector camera;XMStoreFloat3(&camera,XMVector3TransformNormal(XMLoadFloat3(&delta),XMLoadFloat4x4(&view)));
433 if(camera.z>support*zScale || std::abs(camera.x*projection._11)>-camera.z+support*xMargin
434 || std::abs(camera.y*projection._22)>-camera.z+support*yMargin)return;
435 candidates[candidateCount++]={{flash.position.x,flash.position.y,flash.position.z,1/(flash.radius*flash.radius)},
436 {brightness*.8f,brightness*.88f,brightness,.18f},
437 {flash.axis.x,flash.axis.y,flash.axis.z,flash.width},brightness*flash.radius*flash.radius/(1+range*range)};
438 };
440 {
441 for(const auto& flash:lightning.Events())addFlash(flash);
442 for(const auto& flash:lightningDiagnostic.Events())addFlash(flash);
443 }
444 }
445 std::sort(candidates.begin(),candidates.begin()+candidateCount,[](const Candidate& a,const Candidate& b){return a.score>b.score;});
446 const int count=int((std::min)(candidateCount,CloudLightning::MaxLights));
447 std::array<Color,CloudLightning::MaxLights> flashPositions{},flashColors{},flashShapes{};
448 for(int i=0;i<count;++i){flashPositions[i]=candidates[i].position;flashColors[i]=candidates[i].light;flashShapes[i]=candidates[i].shape;}
449 parameters.Set("lightningCount",count);parameters.Set("lightningPosition",flashPositions);parameters.Set("lightningColor",flashColors);
450 parameters.Set("lightningShape",flashShapes);
452 history.view=view;history.projection=projection;history.inverseView=inverse;
453 history.eye={eye.x,eye.y,eye.z};history.sun=sunlight;
454 history.eclipse={params.eclipse.center.x,params.eclipse.center.y,params.eclipse.center.z,params.eclipse.radius};
456 history.noiseOffset={params.noiseOffset.x,params.noiseOffset.y,params.noiseOffset.z};
457 history.layer={params.radius,params.base,params.top,params.activity};history.light=light;history.ambient=ambient;
458 history.nightVision=nightVisionGain;history.airglow=airglow;history.horizon=horizonHaze;history.atmosphere=atmosphereHaze;
459 history.previousWeather=boundWeather.previous.get();history.currentWeather=boundWeather.current.get();history.weatherBlend=boundWeather.blend;
460 history.milliseconds=GetTickCount64();history.transientLight=count>0 || headlightCount>0;
462 hr=pass.Render(context,parameters,scene,depth,viewport,headlightCount,fogEnd<1e8f,rainActive,cameraAltitude<params.base);
463 if(SUCCEEDED(hr) && FogBeamsEnabled() && !fogLights.empty())
464 {
465 if(FAILED(hr=fogBeams.ConfigureOrganic(organicField)))return Fail("matching organic fog shaders unavailable",hr);
466 parameters.Texture("headlightDepth",pass.HeadlightDepth());
467 hr=fogBeams.Render(context,scene,depth,viewport,view,projection,fogLights,&parameters);
468 parameters.Texture("headlightDepth",nullptr);
469 }
470 return FAILED(hr) ? Fail(pass.Status().c_str(),hr) : hr;
471 }
472}
SCRIPT_CONTROL SCRIPT_STATE const void int
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
SCRIPT_CONTROL SCRIPT_STATE const void DWORD
const std::array< Flash, MaxEvents > & Events() const
void Update(const CloudVolume::Parameters &params, double, uint32_t cloudSeed, const Point &observer, double now=MonotonicSeconds())
void Update(const CloudVolume::Parameters &params, double elapsed, uint32_t cloudSeed)
void Seed(uint32_t seed)
const std::array< Flash, MaxEvents > & Events() const
float Radius(CloudVolume::Point eye, const CloudVolume::Parameters &p, const CloudWeather::Frame &weather, double angularPixel) const
void SetNoise(std::vector< uint16_t > values)
HRESULT Initialize(ID3D11Device *device, const std::filesystem::path &shaderDirectory={})
void ConfigureTemporal(const CloudTemporal11::Frame &frame, bool enabled)
Definition CloudPass11.h:65
const std::string & Status() const
Definition CloudPass11.h:86
bool OrganicOrbitAvailable() const
Definition CloudPass11.h:59
HRESULT ConfigureOrganic(bool enabled, bool aboveDeck)
OrganicPath SelectedOrganicPath() const
Definition CloudPass11.h:63
void SetResolutionScale(float value)
Definition CloudPass11.h:81
ID3D11ShaderResourceView * HeadlightDepth() const
Definition CloudPass11.h:85
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)
float ResolutionScale() const
Definition CloudPass11.h:82
HRESULT Render(ID3D11DeviceContext *context, ID3D11RenderTargetView *scene, const SceneDepth11 &depth, const D3D11_VIEWPORT &viewport, const Matrix &view, const Matrix &projection, const Vector &planetEye, const CloudVolume::Parameters &params, const Vector &sunlight, const Color &light, const Color &ambient, const Color &airglow=Color(.125f,.375f,.25f, 1), const Color &horizonHaze=Color(0, 0, 0, 0), const Color &atmosphereHaze=Color(0, 0, 0, 0), const Color &nightVisionGain=Color(1, 1, 1, 0))
HRESULT Fail(const char *step, HRESULT hr)
void SetHeadlights(const std::vector< Headlight > &lights)
Microsoft::WRL::ComPtr< ID3D11Device > device
CloudWeather::Frame WeatherFrame()
Microsoft::WRL::ComPtr< ID3D11ShaderResourceView > localBaseView
CloudLightning::Diagnostic lightningDiagnostic
void SetLocalLightning(const Vector &position, const Color &color, float radiusKm)
void SetGroundLighting(const CloudVolume::GroundLighting &lighting)
HRESULT PrepareWeather(ID3D11DeviceContext *context)
CloudLightning::System lightning
bool SetLightningDiagnostic(bool enabled)
std::vector< Headlight > headlights
CloudWeather::Frame weatherFrame
void UpdateLightning(const CloudVolume::Parameters &parameters, double elapsed, const CloudVolume::Point &observer={})
Microsoft::WRL::ComPtr< ID3D11Texture2D > groundTexture
CloudWeather::MapPtr desiredWeather
CloudVolume::GroundLighting groundLighting
Microsoft::WRL::ComPtr< ID3D11ShaderResourceView > rainView
void SetLightningEnabled(bool value)
std::vector< WeatherTexture > weatherTextures
void UpdateWeather(const CloudWeather::MapPtr &map, double elapsed)
CloudWeather::Frame boundWeather
DirectX::XMFLOAT4X4 Matrix
Microsoft::WRL::ComPtr< ID3D11ShaderResourceView > noise
static constexpr unsigned MaxHeadlights
void SetRainGrid(const RainGrid *grid)
CloudBaseWeather::GridPtr uploadedLocalBase
HRESULT Initialize(ID3D11Device *device, const std::filesystem::path &shaderDirectory={})
std::atomic< bool > historyResetPending
std::filesystem::path shaderDirectory
Microsoft::WRL::ComPtr< ID3D11Texture2D > localBaseTexture
Microsoft::WRL::ComPtr< ID3D11Texture2D > rainTexture
Microsoft::WRL::ComPtr< ID3D11ShaderResourceView > ground
Microsoft::WRL::ComPtr< ID3D11ShaderResourceView > blackWeather
HRESULT Initialize(ID3D11Device *device, const std::filesystem::path &directory={})
HRESULT Render(ID3D11DeviceContext *context, ID3D11RenderTargetView *scene, const SceneDepth11 &depth, const D3D11_VIEWPORT &viewport, const Matrix &view, const Matrix &projection, const std::vector< Light > &lights, const Parameters11 *clouds=nullptr)
HRESULT ConfigureOrganic(bool enabled)
Definition FogBeams11.h:30
void TextureUpload(UINT64 bytes)
void CloudClearance(float radiusKm)
static FrameProfiler11 & Get()
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
Definition grid.h:14
char cube
Definition grid.h:45
float UniformVisibility(const Sphere &body, float bound, Point towardSun)
bool Active(const Frame &frame)
const std::vector< float > & Values()
constexpr unsigned MaxLights
float Weight(const Parameters &params)
const std::vector< float > & Values()
float Smooth(float x)
Definition CloudVolume.h:51
uint8_t Voxel(int x, int y, int z, uint32_t seed)
GroundProjection ProjectGround(int cube, int u, int v)
constexpr float MaxTopRiseKm
Definition CloudVolume.h:23
float BackgroundZenithWeight(float altitude, const Parameters &params)
Definition CloudVolume.h:52
constexpr unsigned MaxHeight
Definition CloudVolume.h:24
GroundLightTexel GroundLightAt(const GroundLighting &lighting, size_t index)
float MinimumBase(const Parameters &params)
constexpr unsigned MaxWidth
Definition CloudVolume.h:24
float Length(Point p)
Definition CloudVolume.h:94
float BaseLightingWeight(Point eye, const Parameters &params, uint32_t seed=DefaultSeed)
std::shared_ptr< const Map > MapPtr
Definition DDS.h:24
Vector OrthonormalUp(Vector up, const Vector &direction)
Definition BeamProfile.h:43
Frame Build(const RiseMath::Vector3 &ground, const RiseMath::Vector3 &top, const RiseMath::Vector3 &origin, const RiseMath::Vector3 &camera, const RiseMath::Color &color, float brightness, float visibilityKm, bool enabled, bool separateFog=false)
constexpr float PeakRadiance
float CloudOrbitResolution11(float width, float height, bool distant=false, bool globe=false)
bool CloudGlobeOrbit11(float altitudeKm, bool wasGlobe)
bool CloudDistantOrbit11(float altitudeKm, bool wasDistant)
float CloudRefinedFlightResolution11(float width, float height)
CelestialEclipse::Sphere eclipse
Definition CloudVolume.h:37
CloudBaseWeather::Frame localBase
Definition CloudVolume.h:36
std::array< Color, 4096 > cells
Microsoft::WRL::ComPtr< ID3D11ShaderResourceView > srv
Microsoft::WRL::ComPtr< ID3D11Texture2D > texture