1#include "Reference9/CloudVolumeRenderer.h"
2#include "../Viewscreen/CloudBaseGeometry.h"
3#include "Reference9/SkyRingRenderer.h"
4#include <iostream>
5#include <vector>
6#include <chrono>
7#include <cstring>
8#include <string>
9
10using Microsoft::WRL::ComPtr;
11static int Width=960, Height=540;
12static int checks=0;
13static void Check(bool condition,const char* message)
14{
15 ++checks;
16 if (!condition) { std::cerr<<"FAIL: "<<message<<'\n'; std::exit(1); }
17}
18static void HR(
HRESULT hr,
const char* message)
19{
20 if (FAILED(hr)) std::cerr<<"HRESULT "<<std::hex<<hr<<std::dec<<'\n';
21 Check(SUCCEEDED(hr),message);
22}
23#include "CloudWeatherTests.h"
24#include "CloudLightningTests.h"
25#include "SunPositionOverrideTests.h"
26#include "NvidiaDepthCopyTests.h"
27#include "RenderCapture9.h"
28
29#include "CloudVolumeCpuTests.h"
30
31int main(int argc, char** argv)
32{
33 bool orbitalPreview=false,headlightPreview=false,topPreview=false,captureInputs=false,migrationReference=false;
34 for(int i=1;i<argc;++i)
35 {
36 if (std::strcmp(argv[i],"--full-hd")==0) { Width=1920; Height=1080; }
37 if (std::strcmp(argv[i],
"--ultrawide")==0) {
Width=3440;
Height=1440; }
38 if (std::strcmp(argv[i],"--orbital-preview")==0) orbitalPreview=true;
39 if (std::strcmp(argv[i],"--headlight-preview")==0) headlightPreview=true;
40 if (std::strcmp(argv[i],"--top-preview")==0) topPreview=true;
41 if (std::strcmp(argv[i],"--capture-inputs")==0) captureInputs=true;
42 if (std::strcmp(argv[i],"--migration-reference")==0) migrationReference=captureInputs=true;
43 }
44 CloudWeatherTests();
45 CloudLightningTests();
46 SunPositionOverrideTests();
47 CpuTests();
48 HWND window=CreateWindowW(L"STATIC",L"Cloud test",WS_POPUP,0,0,Width,Height,nullptr,nullptr,nullptr,nullptr);
49 Check(window!=nullptr,"create hidden test window");
50 ComPtr<IDirect3D9> d3d; d3d.Attach(Direct3DCreate9(D3D_SDK_VERSION));
51 Check(bool(d3d),"create D3D9");
52 D3DADAPTER_IDENTIFIER9 adapter{}; HR(d3d->GetAdapterIdentifier(0,0,&adapter),"adapter name");
53 std::cout<<"Adapter: "<<adapter.Description<<'\n';
54 D3DPRESENT_PARAMETERS pp{}; pp.Windowed=TRUE; pp.SwapEffect=D3DSWAPEFFECT_DISCARD;
55 pp.hDeviceWindow=window; pp.BackBufferWidth=
Width; pp.BackBufferHeight=
Height;
56 pp.EnableAutoDepthStencil=TRUE; pp.AutoDepthStencilFormat=D3DFMT_D24S8;
57 ComPtr<IDirect3DDevice9> device;
58 HR(d3d->CreateDevice(0,D3DDEVTYPE_HAL,window,D3DCREATE_HARDWARE_VERTEXPROCESSING,&pp,&device),"create HAL device");
59 NvidiaDepthCopyTest::Run(device.Get());
61 SetEnvironmentVariableA("RISE_LIGHTNING_SEED","123456");
62 const auto initStart=std::chrono::steady_clock::now();
63 HR(
renderer.Initialize(device.Get()),
"initialize cloud resources"); Check(
renderer.Ready(),
"volume supported");
64 std::cout<<
renderer.InitializationStatus()<<std::endl;
65 SetEnvironmentVariableA("RISE_LIGHTNING_SEED",nullptr);
66 const double initMs=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-initStart).count();
67 std::cout << "Cloud initialization: " << initMs << " ms" << std::endl;
68 Check(initMs<2000,"precompiled cloud initialization avoids the long startup stall");
69 ComPtr<IDirect3DSurface9>
target,depth,readback;
70 HR(device->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,D3DMULTISAMPLE_NONE,0,FALSE,&target,nullptr),"create test target");
71 HR(device->GetDepthStencilSurface(&depth),"get depth");
72 HR(device->CreateOffscreenPlainSurface(Width,Height,D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&readback,nullptr),"create readback");
73 HR(device->SetRenderTarget(0,
target.Get()),
"bind test target");
74 const auto pixels=[&]() {
75 D3DSURFACE_DESC desc{}; HR(
target->GetDesc(&desc),
"target description");
76 ComPtr<IDirect3DSurface9> resolved;
77 if(desc.MultiSampleType!=D3DMULTISAMPLE_NONE)
78 {
79 HR(device->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,D3DMULTISAMPLE_NONE,0,FALSE,&resolved,nullptr),"create resolve");
80 HR(device->StretchRect(
target.Get(),
nullptr,resolved.Get(),
nullptr,D3DTEXF_NONE),
"resolve MSAA frame");
81 }
82 HR(device->GetRenderTargetData(resolved ? resolved.Get() :
target.Get(),readback.Get()),
"read frame");
83 D3DLOCKED_RECT lock{}; HR(readback->LockRect(&lock,nullptr,D3DLOCK_READONLY),"lock readback");
84 std::vector<DWORD> result(Width*Height);
85 for(
int y=0;y<
Height;++y) std::memcpy(result.data()+y*Width,
static_cast<char*
>(lock.pBits)+y*lock.Pitch,Width*4);
86 HR(readback->UnlockRect(),"unlock readback"); return result;
87 };
89 D3DXMATRIX view,proj;
90 D3DXMatrixPerspectiveFovRH(&proj,D3DX_PI/3,float(Width)/Height,.0001f,100000.f);
91 const D3DXVECTOR3 zero(0,0,0),up(0,1,0),daySun(-.5f,-.8f,.2f);
92 D3DXVECTOR3 sun=daySun;
93 D3DXCOLOR light(.9f,.86f,.8f,1),ambient(.4f,.46f,.55f,1),glow(.125f,.375f,.25f,1);
94 D3DXVECTOR4 haze(0,0,0,0);
95 D3DXVECTOR4 atmosphereHaze(0,0,0,0);
96 DWORD backgroundColor=0xff6080b0;
97 DWORD foregroundColor=0xff102030;
98 float foregroundDepth=0, cameraZoom=1, cameraRoll=0;
99 bool measureSunQuery=false;
100 DWORD sunSamplesBefore=0,sunSamplesAfter=0;
101 const auto sunQuery=[&](IDirect3DQuery9* query) {
102 ComPtr<IDirect3DStateBlock9> state;
103 HR(device->CreateStateBlock(D3DSBT_ALL,&state),"save sun query state");
104 struct SunVertex {
float x,y,z,rhw;
DWORD color; };
106 const SunVertex quad[]={{x-8,y-8,1,1,0xffffffff},{x+8,y-8,1,1,0xffffffff},
107 {x-8,y+8,1,1,0xffffffff},{x+8,y+8,1,1,0xffffffff}};
108 device->SetVertexShader(nullptr); device->SetPixelShader(nullptr);
109 device->SetFVF(D3DFVF_XYZRHW|D3DFVF_DIFFUSE);
110 device->SetRenderState(D3DRS_COLORWRITEENABLE,0);
111 device->SetRenderState(D3DRS_ZWRITEENABLE,FALSE);
112 device->SetRenderState(D3DRS_ZENABLE,TRUE);
113 device->SetRenderState(D3DRS_ZFUNC,D3DCMP_LESSEQUAL);
114 device->SetRenderState(D3DRS_STENCILENABLE,FALSE);
115 device->SetRenderState(D3DRS_ALPHATESTENABLE,FALSE);
116 device->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);
117 HR(query->Issue(D3DISSUE_BEGIN),"begin sun visibility query");
118 HR(device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP,2,quad,sizeof(SunVertex)),"query sun geometry");
119 HR(query->Issue(D3DISSUE_END),"end sun visibility query");
120 HR(state->Apply(),"restore sun query state");
121 };
122 bool geographicEyeEnabled=false;
123 D3DXVECTOR3 geographicEye{},capturedEye{};
124 const auto render=[&](
float altitude,D3DXVECTOR3 direction,
bool occlusion=
false,
bool read=
true,
float eyeOffset=0) {
125 D3DXVECTOR3 viewUp=(direction.x==0 && direction.z==0) ? D3DXVECTOR3(0,0,1) : up;
126 if(cameraRoll!=0)
127 {
128 D3DXVECTOR3 axis;
129 D3DXVec3Normalize(&axis,&direction);
130 D3DXMATRIX roll;
131 D3DXMatrixRotationAxis(&roll,&axis,cameraRoll);
132 D3DXVec3TransformNormal(&viewUp,&viewUp,&roll);
133 }
134 D3DXMatrixLookAtRH(&view,&zero,&direction,&viewUp);
135 D3DXMATRIX zoom;
136 D3DXMatrixScaling(&zoom,cameraZoom,cameraZoom,1);
137 view*=zoom;
138 HR(device->Clear(0,nullptr,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,backgroundColor,1,0),"clear frame");
139 if(occlusion)
140 {
142 HR(device->Clear(1,&foreground,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER,foregroundColor,foregroundDepth,0),"foreground depth");
143 HR(device->Clear(1,&
cockpit,D3DCLEAR_TARGET|D3DCLEAR_STENCIL,0xff203010,1,3),
"cockpit stencil");
144 }
145 device->SetRenderState(D3DRS_ZWRITEENABLE,TRUE);
146 HR(device->BeginScene(),"begin cloud frame");
147 ComPtr<IDirect3DQuery9> beforeCloud,afterCloud;
148 if(measureSunQuery)
149 {
150 HR(device->CreateQuery(D3DQUERYTYPE_OCCLUSION,&beforeCloud),"create opaque sun query");
151 HR(device->CreateQuery(D3DQUERYTYPE_OCCLUSION,&afterCloud),"create legacy sun query");
152 sunQuery(beforeCloud.Get());
153 }
154 capturedEye=geographicEyeEnabled ? geographicEye : D3DXVECTOR3(eyeOffset,params.
radius+altitude,0);
155 HR(
renderer.Render(device.Get(),view,proj,capturedEye,params,sun,light,ambient,glow,haze,atmosphereHaze),
"render volume");
156 if(measureSunQuery) sunQuery(afterCloud.Get());
157 HR(device->EndScene(),"end cloud frame");
158 if(measureSunQuery)
159 {
160 while(beforeCloud->GetData(&sunSamplesBefore,
sizeof(
DWORD),D3DGETDATA_FLUSH)==S_FALSE) {}
161 while(afterCloud->GetData(&sunSamplesAfter,
sizeof(
DWORD),D3DGETDATA_FLUSH)==S_FALSE) {}
162 }
163 DWORD zwrite=0; HR(device->GetRenderState(D3DRS_ZWRITEENABLE,&zwrite),
"read restored state");
164 Check(zwrite==TRUE,"restore caller depth write state");
165 ComPtr<IDirect3DSurface9> restored; HR(device->GetRenderTarget(0,&restored),"read restored target");
166 Check(restored.Get()==
target.Get(),
"restore caller render target");
167 return read ? pixels() : std::vector<
DWORD>{};
168 };
169 const auto save=[&](const char* name) {
170 HR(D3DXSaveSurfaceToFileA(name,D3DXIFF_PNG,
target.Get(),
nullptr,
nullptr),
"save preview");
171 if(captureInputs)
172 {
173 D3DSURFACE_DESC desc{}; HR(
target->GetDesc(&desc),
"capture target description");
174 RenderCapture9::Capture(
renderer.Effect(),name,desc.Width,desc.Height,
175 desc.MultiSampleType==D3DMULTISAMPLE_NONE ? 1 : UINT(desc.MultiSampleType),
renderer.Seed(),capturedEye);
176 }
177 };
178 if(migrationReference)
179 {
180
181
182 const float latitude=D3DXToRadian(-19.3f),longitude=D3DXToRadian(9.3f);
183 const D3DXVECTOR3 radial(-std::cos(latitude)*std::sin(longitude),
184 std::cos(latitude)*std::cos(longitude),std::sin(latitude));
185 geographicEyeEnabled=
true;geographicEye=radial*(params.
radius+636);
186 backgroundColor=0xff000000;
187 for(int convection : {0,153,255})
188 {
189 const auto map=ConstantWeather(uint8_t(convection));
191 for(
int upload=0;upload<100 &&
renderer.WeatherFrame().current!=map;++upload) render(636,-radial,
false,
false);
192 Check(
renderer.WeatherFrame().current==map,
"migration reference weather complete");
194 for(int time=0;time<3;++time)
195 {
196 sun=time==0 ? -radial : time==1 ? D3DXVECTOR3(radial.y,-radial.x,0) : radial;
197 D3DXVec3Normalize(&sun,&sun);
198 light=time==2 ? D3DXCOLOR(0,0,0,1) : D3DXCOLOR(.94f,.96f,1,1);
199 ambient=glow=D3DXCOLOR(0,0,0,1);
201 render(636,-radial);
202 save(("Output/migration-636km-S19.3-E9.3-"+std::to_string(convection)+"-"+std::to_string(time)+".png").c_str());
203 }
204 }
205 renderer.OnDestroyDevice();DestroyWindow(window);
206 std::cout<<"PASS: nine deterministic 636 km geographic reference captures and shader/texture inputs\n";
207 return 0;
208 }
209 {
210 const auto savedSun=sun; const auto savedLight=light,savedAmbient=ambient,savedGlow=glow;
211 sun={0,1,0}; light=glow=D3DXCOLOR(0,0,0,1); ambient=D3DXCOLOR(.018f,.022f,.026f,1);
212 const D3DXVECTOR3 look(0,0,-1);
214 const auto off=render(5,look); save("Output/cloud-headlight-off.png");
216 const auto on=render(5,look); save("Output/cloud-headlight-on.png");
217 const auto energy=[&](const std::vector<DWORD>& a,const std::vector<DWORD>& b) {
218 double sum=0;
219 for(size_t i=0;i<a.size();++i) for(int shift:{0,8,16})
220 sum+=(std::max)(0,
int((a[i]>>shift)&255)-
int((b[i]>>shift)&255));
221 return sum;
222 };
223 const double lit=energy(on,off);
224 std::cout<<
"Headlight added brightness: "<<lit/(
Width*
Height*3)<<
" levels per pixel"<<std::endl;
225 Check(lit>Width*Height*.05,"headlight visibly scatters in cloud");
226 Check(on[Height/2*Width+Width/8]==off[Height/2*Width+Width/8],"cloud outside the narrow beam keeps its lighting");
227 Check(on==render(5,look),"stationary beam and density pockets remain stable");
229 Check(render(5,look)==off,"a rear-facing beam cannot light cloud ahead");
231 const auto distant=render(5,look);
232 const double distantEnergy=energy(distant,off);
233 std::cout<<
"Headlight after 150 m cloud path: "<<distantEnergy/(
Width*
Height*3)<<
" levels per pixel"<<std::endl;
234 Check(distantEnergy<lit*.25,"cloud between the source and receiving pocket extinguishes the beam");
236 const auto protectedFrame=render(5,look,true);
237 Check(protectedFrame[Height/2*Width+Width/8]==foregroundColor,"foreground geometry occludes illuminated cloud");
238 Check(protectedFrame[Height/2*Width+Width*7/8]==0xff203010,"headlight scattering preserves the cockpit stencil");
239
242 const auto crossing=render(5,look); save("Output/cloud-headlight-crossing.png");
243 Check(energy(crossing,off)>Width*Height*.02,"nearby ship's beam is visible off the camera axis");
244
245
246 const auto abruptEdges=[&](const std::vector<DWORD>& frame) {
247 int count=0;
248 const int tolerance=(std::max)(3,5760/Width);
250 {
251 const int i=y*
Width+x,g=
int((frame[i]>>8)&255);
252 count+=std::abs(g-int((frame[i-1]>>8)&255))>tolerance;
253 count+=std::abs(g-int((frame[i-Width]>>8)&255))>tolerance;
254 }
255 return count;
256 };
259 const auto side=render(5,look); save("Output/cloud-headlight-side.png");
260 std::cout<<"Side beam abrupt edges: "<<abruptEdges(side)<<std::endl;
261 Check(abruptEdges(side)<(std::max)(20,Width/50),"side-on beam has no isolated march discs");
262 cameraZoom=2; cameraRoll=.3f;
264 renderer.SetHeadlights({});
const auto closeNightOff=render(5,look);
266 const auto closeNight=render(5,look); save("Output/cloud-headlight-close-night.png");
267 std::cout<<"Close beam abrupt edges: "<<abruptEdges(closeNight)<<std::endl;
268 Check(abruptEdges(closeNight)<(std::max)(20,Width/50),"close beam stays smooth at planet-sized coordinates");
269 sun=daySun; light=savedLight; ambient=savedAmbient;
270 renderer.SetHeadlights({});
const auto closeDayOff=render(5,look);
272 const auto closeDay=render(5,look); save("Output/cloud-headlight-close-day.png");
273 const double nightEnergy=energy(closeNight,closeNightOff),dayEnergy=energy(closeDay,closeDayOff);
274 std::cout<<"Day/night beam added brightness ratio: "<<dayEnergy/nightEnergy<<std::endl;
275 Check(dayEnergy>0 && dayEnergy<nightEnergy*.5,"sunlit clouds reduce visible headlight scattering smoothly");
276 cameraZoom=1; cameraRoll=0;
277 sun={0,1,0}; light=D3DXCOLOR(0,0,0,1); ambient=D3DXCOLOR(.018f,.022f,.026f,1);
278 renderer.SetHeadlights({}); Check(render(5,look)==off,
"headlight off clears the previous frame's light");
279 const auto clear=render(.5f,look);
281 renderer.SetHeadlights({beam}); Check(render(.5f,look)==clear,
"no luminous cone is painted into empty air");
282
283
284 for(bool boundary:{false,true})
285 {
288 ComPtr<IDirect3DSurface9> opticalSurface,opticalReadback;
289 Check(
renderer.HeadlightOpticalDepth()!=
nullptr,
"light optical depth exists");
290 HR(
renderer.HeadlightOpticalDepth()->GetSurfaceLevel(0,&opticalSurface),
"read light depth surface");
291 HR(device->CreateOffscreenPlainSurface(64,512,D3DFMT_A16B16G16R16F,D3DPOOL_SYSTEMMEM,
292 &opticalReadback,nullptr),"create optical depth readback");
293 HR(device->GetRenderTargetData(opticalSurface.Get(),opticalReadback.Get()),"copy optical depth");
294 D3DLOCKED_RECT opticalLock{};
295 HR(opticalReadback->LockRect(&opticalLock,nullptr,D3DLOCK_READONLY),"lock optical depth");
296
297 D3DXVECTOR3 axis(-.20271004f/7,-1,-.20271004f/7); D3DXVec3Normalize(&axis,&axis);
298 for(int slice:{4,10,24,40,63})
299 {
300 const auto row=reinterpret_cast<const D3DXFLOAT16*>(static_cast<const char*>(opticalLock.pBits)+(slice*8+3)*opticalLock.Pitch);
301 float gpu=0; D3DXFloat16To32Array(&gpu,row+3*4,1);
302 const float distance=2.f*slice*slice/(63*63);
303 float cpu=0;
304 for(int i=0;i<1024;++i)
305 {
306 const auto p=beam.
position+axis*(distance*(i+.5f)/1024);
308 }
309 cpu=(std::min)(10.f,cpu);
310 std::cout<<"Headlight optical depth "<<(boundary ? "edge" : "core")<<" at "<<distance
311 <<" km GPU/CPU: "<<gpu<<" / "<<cpu<<std::endl;
312 Check(std::abs(gpu-cpu)<.12f+.15f*cpu,"headlight extinction agrees with independent density integration");
313 }
314 HR(opticalReadback->UnlockRect(),"unlock optical depth");
315 }
317 for(int count:{0,1,8})
318 {
320 renderer.SetHeadlights(std::vector<CloudVolumeRenderer::Headlight>(count,beam));
321 render(5,look);
322 const auto start=std::chrono::steady_clock::now();
323 for(int i=0;i<60;++i) render(5,look,false,false);
324 pixels();
325 std::cout<<
"Cloud headlights "<<count<<
" at "<<
Width<<
"x"<<
Height<<
": "
326 <<std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count()/60<<" ms"<<std::endl;
327 }
328 renderer.SetHeadlights(std::vector<CloudVolumeRenderer::Headlight>(12,beam)); render(5,look);
329 int bound=0; HR(
renderer.Effect()->GetInt(
"headlightCount",&bound),
"read bounded headlight count");
330 Check(bound==8,"headlights respect the fixed eight-light budget");
332 HR(
renderer.Effect()->GetInt(
"headlightCount",&bound),
"read orbital light count");
333 Check(bound==0,"orbital headlights skip the scattering prepass when they cannot reach cloud");
334
335
336 ambient={.09f,.10f,.12f,1}; glow=savedGlow;
339 render(params.
base+.24f,look); save(
"Output/cloud-headlight-base-off.png");
341 render(params.
base+.24f,look); save(
"Output/cloud-headlight-base-on.png");
343 sun=savedSun; light=savedLight; ambient=savedAmbient; glow=savedGlow;
344 if(headlightPreview) {
renderer.OnDestroyDevice(); DestroyWindow(window);
return 0; }
345 }
346 if(topPreview)
347 {
348 backgroundColor=0xffa5a5ff;
349 const float incident=std::exp(-.5f*std::exp(-params.
top/7.5f));
350 light=D3DXCOLOR(.941176f*incident,.960784f*incident,incident,1);
351 ambient=glow=D3DXCOLOR(0,0,0,1);
353 for(int strength : {0,77,153,255})
354 {
355 const auto weather=ConstantWeather(uint8_t(strength));
357 for(
int upload=0;upload<100 &&
renderer.WeatherFrame().current!=
weather;++upload)
358 render(500,{0,-1,0},false,false);
359 Check(
renderer.WeatherFrame().current==
weather,
"top preview uses the complete weather map");
361 for(int lighting=0;lighting<2;++lighting)
362 {
363 sun=lighting ? D3DXVECTOR3(-.86f,-.5f,0) : D3DXVECTOR3(0,-1,0);
364 D3DXVec3Normalize(&sun,&sun);
365 for(float altitude : {13.34f,117.f,1000.f,3000.f})
366 {
367 backgroundColor=altitude<100 ? 0xffa5a5ff : 0xff000000;
368 const auto frame=render(altitude,altitude<100 ? D3DXVECTOR3(1,-.28f,0)
369 : altitude<200 ? D3DXVECTOR3(.7f,-1,0) : D3DXVECTOR3(.25f,-1,0));
370 const std::string name="Output/cloud-tops-"+std::to_string(strength)+"-"
371 +std::to_string(lighting)+"-"+std::to_string(int(altitude))+".png";
372 save(name.c_str());
373 double sum=0,squares=0; int count=0;
374 for(
int y=Height/2;y<
Height*3/4;++y)
for(
int x=Width/4;x<
Width*3/4;++x)
375 {
376 const double value=(frame[y*
Width+x]>>8)&255;
377 sum+=value; squares+=value*value; ++count;
378 }
379 std::cout<<name<<" mean / deviation: "<<sum/count<<" / "
380 <<std::sqrt((std::max)(0.,squares/count-(sum/count)*(sum/count)))<<std::endl;
381 }
382 }
383 }
384 renderer.OnDestroyDevice(); DestroyWindow(window);
return 0;
385 }
386 if(orbitalPreview)
387 {
388 backgroundColor=0xff000000;
389 light=D3DXCOLOR(.94f,.96f,1,1); ambient=glow=D3DXCOLOR(0,0,0,1);
391 for(int region=0;region<2;++region)
392 {
393 const auto weather=region==0 ? ConstantWeather(153) : RegionalWeatherFixture();
395 for(
int upload=0;upload<100 &&
renderer.WeatherFrame().current!=
weather;++upload)
396 render(500,{0,-1,0},false,false);
397 Check(
renderer.WeatherFrame().current==
weather,
"orbital preview uses the complete weather map");
400 for(int lighting=0;lighting<2;++lighting)
401 {
402 sun=lighting ? D3DXVECTOR3(-.86f,-.5f,0) : D3DXVECTOR3(0,-1,0);
403 D3DXVec3Normalize(&sun,&sun);
404 for(int altitude : {117,500,3000})
405 {
406 const auto frame=render(float(altitude),altitude==3000 ? D3DXVECTOR3(.25f,-1,0) : D3DXVECTOR3(.7f,-1,0));
407 const std::string name="Output/cloud-orbital-"+std::to_string(region)+"-"+std::to_string(lighting)+"-"+std::to_string(altitude)+".png";
408 save(name.c_str());
409 std::cout<<name<<std::endl;
410 }
411 }
412 }
414 return 0;
415 }
416 const auto zeroWeather=render(117,{0,-1,0}); save("Output/clouds-no-weather-117km.png");
417 {
418
419
420 const auto savedParams=params; const auto savedSun=sun;
421 const auto savedLight=light,savedAmbient=ambient,savedGlow=glow;
422 const auto savedAir=atmosphereHaze;
const DWORD savedBackground=backgroundColor;
423 const auto weather=ConstantWeather(77);
425 for(
int upload=0;upload<100 &&
renderer.WeatherFrame().current!=
weather;++upload)
426 render(117,{0,-1,0},false,false);
427 Check(
renderer.WeatherFrame().current==
weather,
"weak-top fixture weather uploaded");
429 sun={0,-1,0};
430 const float incident=std::exp(-.5f*std::exp(-params.
top/7.5f));
431 light=D3DXCOLOR(.941176f*incident,.960784f*incident,incident,1);
432 ambient=glow=D3DXCOLOR(0,0,0,1);
434 backgroundColor=0xffa5a5ff;
435 for(float altitude : {13.34f,117.f})
436 {
437 const auto frame=render(altitude,altitude<100 ? D3DXVECTOR3(1,-.28f,0) : D3DXVECTOR3(.7f,-1,0));
438 save(altitude<100 ? "Output/cloud-tops-weak-near.png" : "Output/cloud-tops-weak-117km.png");
439 double sum=0,squares=0; int count=0;
440 for(
int y=Height/2;y<
Height*3/4;++y)
for(
int x=Width/4;x<
Width*3/4;++x)
441 {
442 const double value=(frame[y*
Width+x]>>8)&255;
443 sum+=value; squares+=value*value; ++count;
444 }
445 const double mean=sum/count;
446 const double deviation=std::sqrt((std::max)(0.,squares/count-mean*mean));
447 std::cout<<altitude<<" km weak overhead-lit top mean / contrast: "<<mean<<" / "<<deviation<<std::endl;
448 Check(deviation>(altitude<100 ? 1.5 : Width>=1920 ? 1.1 : .35),
449 "weak-convection cloud tops retain visible relief under overhead sun");
450 Check(mean>180 && mean<220 && deviation<12,
451 "shallow billows retain a bright soft stratus appearance");
452 }
454 sun=savedSun; light=savedLight; ambient=savedAmbient; glow=savedGlow;
455 atmosphereHaze=savedAir; backgroundColor=savedBackground;
456 }
457 {
458 const auto original=params;
459 const auto weather=ConstantWeather(153);
461 render(500,{0,-1,0},false,false);
465 measureSunQuery=true;
466 DWORD opaqueSamples=0;
467 for(float offset : {-.12f,-.04f,.04f})
468 {
469 render(top+offset,{0,1,0});
470 if(!opaqueSamples) opaqueSamples=sunSamplesBefore;
471 std::cout<<"Sun samples before/after cloud depth at top "<<offset<<" km: "
472 <<sunSamplesBefore<<" / "<<sunSamplesAfter<<std::endl;
473 Check(sunSamplesBefore==opaqueSamples && sunSamplesBefore>0,
474 "geometry-only sun query stays stable while leaving cloud wisps");
475 Check(sunSamplesAfter==sunSamplesBefore,
476 "cloud compositing leaves sun occlusion to integrated transmission, not opaque depth");
477 }
478 measureSunQuery=false;
479 params=original;
481 }
482 {
483 const auto oldSun=sun; const auto oldLight=light,oldAmbient=ambient;
484 const auto oldHaze=haze;
485 sun={0,-1,0};
486 const float incident=std::exp(-.5f*std::exp(-10.f/7.5f));
487 light=D3DXCOLOR(.941176f,.960784f,1,1)*incident;
488 double last=0;
489 for(float altitude : {.5f,1.79f,3.f,5.f,8.f,10.f,12.69f})
490 {
496 1,altitude,column.base,column.top);
497 ambient={color.x,color.y,color.z,1};
499 const auto frame=render(altitude,{0,altitude<2 ? 1.f : -1.f,0});
500 save(("Output/clouds-solar-ascent-"+std::to_string(int(altitude*1000))+"m.png").c_str());
501 double red=0,green=0,blue=0;
502 for(
DWORD pixel : frame) { red+=(pixel>>16)&255; green+=(pixel>>8)&255; blue+=pixel&255; }
503 red/=frame.size(); green/=frame.size(); blue/=frame.size();
504 const double mean=.2126*red+.7152*green+.0722*blue;
505 std::cout<<"Solar ascent "<<altitude<<" km rendered luminance: "<<mean<<std::endl;
506 if(altitude<2)
507 {
508 Check(std::abs(red-color.x*255)<4 && std::abs(green-color.y*255)<4 && std::abs(blue-color.z*255)<4,
509 "average cloud-base RGB matches fog including the shared airglow and depth attenuation");
510 }
511 else if(altitude>=3) Check(mean>last,"cloud interiors brighten toward the overhead-lit tops");
512 if(altitude==12.69f) Check(mean>180 && mean<245,"overhead-lit tops are bright without clipping to white");
513 last=mean;
514 }
515 sun=oldSun; light=oldLight; ambient=oldAmbient; haze=oldHaze;
516 }
517
518
519 const D3DXMATRIX initialProjection=proj;
520 D3DXMatrixPerspectiveFovRH(&proj,D3DX_PI/3,float(Width)/Height,.001f,384.f);
521 for(float altitude : {1.7f,2.f,10.f,13.95f,14.03f,21.95f,22.03f})
522 {
523 const auto frame=render(altitude,{0,altitude<2 ? 1.f : -1.f,0});
524 int visible=0;
525 for(
int y=Height/2;y<
Height;++y)
for(
int x=Width/4;x<
Width*3/4;++x)
526 visible+=frame[y*Width+x]!=backgroundColor;
527 std::cout<<altitude<<" km cloud pixels with client clip planes: "<<visible<<std::endl;
528 if(altitude==13.95f) save("Output/clouds-client-13950m.png");
529 Check(visible>Width*Height/8,"clouds remain visible inside the outer search shell with client clip planes");
530 }
531
532
533
534 const D3DXVECTOR4 foregroundPosition(0,0,-.05f,1);
535 D3DXVECTOR4 foregroundClip;
536 D3DXVec4Transform(&foregroundClip,&foregroundPosition,&proj);
537 foregroundDepth=foregroundClip.z/foregroundClip.w;
538 for(float altitude : {13.95f,14.03f,21.95f,22.03f}) for(float zoom : {.5f,1.f,2.f})
539 {
540 cameraZoom=zoom;
541 const auto frame=render(altitude,{1,-.5f,0},true);
542 Check(frame[(Height*3/4)*Width+Width/8]==0xff102030,
543 "nearby geometry occludes the actual cloud surface on both sides of 14 km, including zoom");
544 }
545 cameraZoom=1; foregroundDepth=0;
546 const auto transmissionAtDepth=[&](float altitude, float viewDistance, float offset=0) {
547 const D3DXVECTOR4 position(0,0,-viewDistance,1);
548 D3DXVECTOR4 clip;
549 D3DXVec4Transform(&clip,&position,&proj);
550 foregroundDepth=clip.z/clip.w;
551 foregroundColor=0xff000000;
552 const auto black=render(altitude,{0,-1,0},true,true,offset);
553 foregroundColor=0xffffffff;
554 const auto white=render(altitude,{0,-1,0},true,true,offset);
555 if (altitude==5)
556 save(("Output/clouds-object-"+std::to_string(int(viewDistance*1000))+"m.png").c_str());
557 const size_t pixel=(
Height/2)*Width+Width/8;
558 const float transmission=(
int(white[pixel]&255)-
int(black[pixel]&255))/255.f;
559 Check(white[(Height/2)*Width+Width*7/8]==0xff203010,"cloud extinction never covers cockpit stencil");
560 foregroundColor=0xff102030; foregroundDepth=0;
561 return transmission;
562 };
563 const float nearObject=transmissionAtDepth(5,.005f);
564 const float middleObject=transmissionAtDepth(5,.1f);
565 const float distantObject=transmissionAtDepth(5,1.f);
566 std::cout<<"In-cloud object transmission at 5 / 100 / 1000 m: "<<nearObject<<" / "<<middleObject<<" / "<<distantObject<<std::endl;
567 Check(nearObject>.5f && middleObject<nearObject-.2f && middleObject>distantObject+.01f && distantObject<.01f,
568 "scene geometry receives integrated cloud only between the eye and its actual depth");
569 Check(transmissionAtDepth(15,2)> .99f,"clear nearby object remains visible above the layer");
570 Check(transmissionAtDepth(15,8)<.01f,"clear observer cannot see an object through the deck");
571 {
572 float low=1,high=0,lowOffset=0,highOffset=0;
573 for(int i=0;i<800;++i)
574 {
577 if(t<low) { low=t; lowOffset=point.
x; }
578 if(t>high) { high=t; highOffset=point.
x; }
579 }
580 const float thin=transmissionAtDepth(5,.02f,highOffset);
581 const float dense=transmissionAtDepth(5,.02f,lowOffset);
582 std::cout<<"GPU 20 m wing thin/dense transmission: "<<thin<<" / "<<dense<<std::endl;
583 Check(thin>.65f && dense>.05f && dense<.4f,
584 "nearby geometry stays faintly visible in dense pockets and becomes clear in thin mist");
585 }
586 {
587 struct DropVertex {
float x,y,z;
DWORD color; };
588 ComPtr<IDirect3DVertexBuffer9> drops;
589 HR(device->CreateVertexBuffer(2*sizeof(DropVertex),0,D3DFVF_XYZ|D3DFVF_DIFFUSE,
590 D3DPOOL_MANAGED,&drops,nullptr),"create rain extinction fixture");
591 const auto rainBrightness=[&](float altitude,float distance) {
592 render(altitude,{0,-1,0},false,false);
593 DropVertex* vertices=nullptr;
594 HR(drops->Lock(0,0,reinterpret_cast<void**>(&vertices),0),"lock rain fixture");
595 vertices[0]={-distance*.2f,-distance,0,0xffffffff};
596 vertices[1]={distance*.2f,-distance,0,0xffffffff};
597 HR(drops->Unlock(),"unlock rain fixture");
598 HR(device->Clear(0,nullptr,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,0xff000000,1,0),"clear rain fixture");
599 device->SetFVF(D3DFVF_XYZ|D3DFVF_DIFFUSE);
600 device->SetStreamSource(0,drops.Get(),0,sizeof(DropVertex));
601 device->SetRenderState(D3DRS_STENCILENABLE,FALSE);
602 D3DXMATRIX world; D3DXMatrixIdentity(&world);
603 HR(device->BeginScene(),"begin rain fixture");
604 HR(
renderer.RenderRain(device.Get(),world,1),
"render cloud-attenuated rain");
605 HR(device->EndScene(),"end rain fixture");
606 const auto frame=pixels();
607 unsigned brightest=0;
608 for(auto pixel:frame) brightest=(std::max)(brightest,unsigned(pixel&255u));
609 return brightest;
610 };
611 const unsigned clearRain=rainBrightness(15,.1f),nearRain=rainBrightness(5,.005f),farRain=rainBrightness(5,.1f);
612 std::cout<<"Rain brightness clear / near cloud / distant cloud: "<<clearRain<<" / "<<nearRain<<" / "<<farRain<<std::endl;
613
614
615 const float minimumNearRain=255*std::exp(-100*.005f*std::sqrt(1.04f));
616 Check(clearRain>250 && nearRain+2>=minimumNearRain && nearRain<=clearRain
617 && farRain<nearRain*.7 && farRain>20,
618 "rain streaks respect near visibility and attenuate by their cloud path");
619 device->SetStreamSource(0,nullptr,0,0);
620 }
621 for(float altitude : {13.9995f,10.0005f})
622 {
623 const auto above=render(altitude,{1,-.5f,0});
624 const auto below=render(altitude-.001f,{1,-.5f,0});
625 double change=0;
626 for(size_t i=0;i<above.size();++i) for(int shift : {0,8,16})
627 change+=std::abs(int((above[i]>>shift)&255)-int((below[i]>>shift)&255));
628 change/=above.size()*3;
629 std::cout<<altitude<<" km descending change over 1 m: "<<change<<std::endl;
630 Check(change<1.5,"descent cannot switch off the visible deck at 14 or 10 km");
631 }
632 proj=initialProjection;
633
634
635 for(float altitude : {.05f,15.f,29.9995f,30.0005f,117.f,500.f})
636 {
637 render(altitude,{0,-1,0},false,false);
638 D3DXVECTOR4 cloudScreen;
639 HR(
renderer.Effect()->GetVector(
"screen",&cloudScreen),
"read cloud pixel footprint");
640 Check(cloudScreen.z==Width/2 && cloudScreen.w==Height/2,
641 "cloud resolution stays at half the screen throughout ascent and orbit");
642 }
643 backgroundColor=0xffff00ff;
644 const auto zeroOpaque=render(117,{0,-1,0}); backgroundColor=0xff6080b0;
645 int zeroLeak=0;
646 for(size_t i=0;i<zeroWeather.size();i+=97) for(int shift : {0,8,16})
647 zeroLeak=(std::max)(zeroLeak,std::abs(int((zeroWeather[i]>>shift)&255)-int((zeroOpaque[i]>>shift)&255)));
648 Check(zeroLeak<=2,"zero convection retains an opaque stratus deck");
649
650
651 const auto baseReference=[&](
const char*
path) {
652 const auto savedHaze=haze;
653 const auto savedBackground=backgroundColor;
654 haze={35.f/255,50.f/255,56.f/255,42.16f}; backgroundColor=0xff233238;
655 const auto base=render(.05f,{0,1,0});
656 double sum=0,squares=0;
657 for(
DWORD pixel : base)
658 {
659 const double value=(pixel>>8)&255;
660 sum+=value; squares+=value*value;
661 }
662 const double mean=sum/base.size();
663 const double deviation=std::sqrt((std::max)(0.,squares/base.size()-mean*mean));
664 Check(mean>48 && mean<52,"convection changes base contrast without shifting the horizon baseline");
665 render(.05f,{1,.65f,0}); save(path);
666 haze=savedHaze; backgroundColor=savedBackground;
667 return deviation;
668 };
669 const double calmBaseDeviation=baseReference("Output/clouds-base-calm-convection.png");
670 Check(calmBaseDeviation>.2,"calm bases keep subtle structure rather than a featureless plane");
671 for(float altitude : {117.f,500.f})
672 {
673 render(altitude,{0,-1,0});
674 save(altitude==117 ? "Output/clouds-calm-convection-117km.png" : "Output/clouds-calm-convection-500km.png");
675 }
676 for(int strength : {153,255})
677 {
678 const auto weather=ConstantWeather(uint8_t(strength));
680 for(
int upload=0;upload<100 &&
renderer.WeatherFrame().current!=
weather;++upload)
681 render(500,{0,-1,0},false,false);
682 Check(
renderer.WeatherFrame().current==
weather,
"convection comparison map reaches GPU");
684 const auto billows=render(strength==153 ? 13.f : 18.f,{1,-.15f,0});
685 save(strength==153 ? "Output/clouds-moderate-billows-13km.png" : "Output/clouds-strong-billows-18km.png");
686 if(strength==255 && Width==1920 && Height==1080)
687 {
688
689
690 int darkRidges=0;
691 for(int y=360;y<620;++y) for(int x=250;x<1700;++x)
692 {
693 const int center=(billows[y*
Width+x]>>16)&255;
694 const int above=(billows[(y-4)*
Width+x]>>16)&255;
695 const int below=(billows[(y+4)*
Width+x]>>16)&255;
696
697
698 const int neighbors=(std::min)(above,below);
699 darkRidges+=center+(std::max)(15,int(neighbors*.15f))<neighbors;
700 }
701 std::cout<<"Strong-billow dark ridge pixels: "<<darkRidges<<std::endl;
702 Check(darkRidges<550,"translucent wisps do not expose dark interior sampling bands");
703 }
704 for(float altitude : {117.f,500.f})
705 {
706 render(altitude,{0,-1,0});
707 save(strength==153
708 ? (altitude==117 ? "Output/clouds-moderate-convection-117km.png" : "Output/clouds-moderate-convection-500km.png")
709 : (altitude==117 ? "Output/clouds-strong-convection-117km.png" : "Output/clouds-strong-convection-500km.png"));
710 }
711 const double activeBaseDeviation=baseReference(strength==153
712 ? "Output/clouds-base-moderate-convection.png" : "Output/clouds-base-strong-convection.png");
713 std::cout<<"Base lighting deviation at "<<strength<<"/255 convection: "<<activeBaseDeviation
714 <<" (calm "<<calmBaseDeviation<<")"<<std::endl;
715 Check(activeBaseDeviation>calmBaseDeviation*1.3,"live convection increases visible underside relief");
716 Check(activeBaseDeviation<3,"active cloud bases retain restrained diffuse contrast");
717 }
719 const auto serverMap=RegionalWeatherFixture();
720 Check(!
renderer.WeatherFrame().current,
"GPU starts with black global convection");
721 renderer.UpdateWeather(serverMap,0);
722 for(
int upload=0;upload<100 && !
renderer.WeatherFrame().current;++upload) render(500,{0,-1,0},
false,
false);
723 Check(
renderer.WeatherFrame().current==serverMap,
"staged upload publishes the complete map");
724 Check(
renderer.WeatherFrame().blend==0,
"GPU publication starts at previous-map appearance");
725 renderer.UpdateWeather(serverMap,30);
726 Check(std::abs(
renderer.WeatherFrame().blend-.5f)<.001f,
"weather transitions gradually over one minute");
728 const auto populatedWeather=render(117,{0,-1,0});
729 Check(populatedWeather!=zeroWeather,"server map affects rendered cloud formations");
730 {
731
732
733 auto storm=std::make_shared<CloudWeather::Map>(); storm->revision=100;
734 storm->mips.push_back({2048,1024,std::vector<uint8_t>(2048*1024)});
735 for(int y=510;y<514;++y) for(int x=1022;x<1026;++x) storm->mips[0].pixels[y*2048+x]=255;
738 for(
int i=0;i<100 &&
renderer.WeatherFrame().current!=storm;++i) render(500,{0,-1,0},
false,
false);
740 sun={0,1,0}; light={0,0,0,1}; ambient={.003f,.004f,.006f,1};
741 const auto quiet=render(500,{0,-1,0}); save("Output/cloud-lightning-orbit-before.png");
742 const auto quietBase=render(.5f,{0,1,0});
743 int firstLight=0;
744 for(int i=0;i<200 && !firstLight;++i)
745 {
746 renderer.UpdateLightning(params,.001);
747 render(500,{0,-1,0},false,false);
748 HR(
renderer.Effect()->GetInt(
"lightningCount",&firstLight),
"read first visible flash count");
749 }
750 Check(firstLight>0,"scheduled local storm produces a visible flash");
751 renderer.UpdateLightning(params,.006);
752 render(500,{0,-1,0}); save("Output/cloud-lightning-single-orbit.png");
753 render(117,{0,-1,0}); save("Output/cloud-lightning-single-117km.png");
754 render(14,{1,-.2f,0}); save("Output/cloud-lightning-single-near-tops.png");
755 for(
int i=0;i<20;++i)
renderer.UpdateLightning(params,.01);
756 const auto flashing=render(500,{0,-1,0}); save("Output/cloud-lightning-orbit-after.png");
757 int lit=0,unchanged=0,peak=0;
758 for(size_t i=0;i<quiet.size();++i)
759 {
760 const int difference=
int((flashing[i]>>8)&255)-
int((quiet[i]>>8)&255);
761 lit+=difference>10; unchanged+=difference==0; peak=(std::max)(peak,difference);
762 }
763 std::cout<<"Orbital lightning: "<<lit<<" illuminated pixels, peak "<<peak<<"/255\n";
764 Check(lit>10 && peak>30,"embedded lightning visibly illuminates orbital cloud tops at night");
765 Check(unchanged>int(quiet.size()*.8),"orbital flash remains localized around its storm");
766 Check(flashing==render(500,{0,-1,0}),"rendering does not advance the event clock");
767 const auto upperFlashBase=render(.5f,{0,1,0});
768 int upperLeak=0;
769 for(size_t i=0;i<quietBase.size();++i) for(int shift : {0,8,16})
770 upperLeak=(std::max)(upperLeak,std::abs(int((quietBase[i]>>shift)&255)-int((upperFlashBase[i]>>shift)&255)));
771 std::cout<<"Upper storm flash reaching base: "<<upperLeak<<" levels\n";
772 Check(upperLeak<=2,"upper storm emission is extinguished through the opaque lower deck");
773 render(117,{0,-1,0}); save("Output/cloud-lightning-117km.png");
774 render(14,{1,-.2f,0}); save("Output/cloud-lightning-near-tops.png");
775 const auto protectedFrame=render(500,{0,-1,0},true);
776 Check(protectedFrame[Width/8+Height/2*Width]==foregroundColor,"foreground geometry occludes lightning with its clouds");
777 Check(protectedFrame[Width*7/8+Height/2*Width]==0xff203010,"lightning preserves the cockpit stencil");
778 const auto start=std::chrono::steady_clock::now();
779 for(int i=0;i<60;++i) render(500,{0,-1,0},false,false);
780 pixels();
781 std::cout<<"Concentrated lightning cloud frame average: "<<std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count()/60<<" ms\n";
782
783
784 renderer.SetLightningEnabled(
false);
785 Check(render(500,{0,-1,0})==quiet,"simulator disable immediately removes active ACL illumination");
787 Check(render(500,{0,-1,0})==quiet,"simulator disable prevents new ACL flashes");
789 Check(render(500,{0,-1,0})==quiet,"leaving simulator does not replay old flashes");
790 renderer.UpdateLightning(params,.2);
791 Check(render(500,{0,-1,0})!=quiet,"ordinary flight resumes fresh volumetric lightning");
792 renderer.SetLightningEnabled(
false);
794 for(float altitude : {.5f,5.f,7.5f,9.5f})
795 {
796 const D3DXVECTOR3 direction=altitude<1 ? D3DXVECTOR3(0,1,0) : D3DXVECTOR3(1,.02f,0);
798 const auto quietLocal=render(altitude,direction);
799 save(("Output/cloud-local-lightning-"+std::to_string(int(altitude*1000))+"m-before.png").c_str());
800
801
803 const auto litLocal=render(altitude,direction);
804 save(("Output/cloud-local-lightning-"+std::to_string(int(altitude*1000))+"m.png").c_str());
805 double difference=0;
806 for(size_t i=0;i<litLocal.size();++i)
807 difference+=
int((litLocal[i]>>8)&255)-
int((quietLocal[i]>>8)&255);
808 difference/=litLocal.size();
809 std::cout<<"Local lightning at "<<altitude<<" km: "<<difference<<" mean green levels\n";
810 Check(difference>5,"zero-alpha local strike illuminates the base and interior below 10 km");
811 Check(litLocal==render(altitude,direction),"cloud flash retains the bolt's supplied animation brightness");
813 Check(litLocal==render(altitude,direction),"light emission does not depend on color alpha");
815 Check(quietLocal==render(altitude,direction),"zero RGB brightness removes the local flash regardless of alpha");
816 int localLightCount=-1;
817 HR(
renderer.Effect()->GetInt(
"lightningCount",&localLightCount),
"read inactive local flash count");
818 Check(localLightCount==0,"zero-brightness local flash does not consume a shader light slot");
820 const auto protectedLocal=render(altitude,direction,true);
821 Check(protectedLocal[Width/8+Height/2*Width]==foregroundColor,"local cloud flash preserves foreground depth");
822 Check(protectedLocal[Width*7/8+Height/2*Width]==0xff203010,"local cloud flash preserves cockpit stencil");
823 renderer.SetLightningEnabled(
false);
824 Check(render(altitude,direction)==quietLocal,"simulator disable removes local cloud illumination");
826 Check(render(altitude,direction)==quietLocal,"simulator exit cannot replay a local flash");
827 }
829 renderer.UpdateWeather(serverMap,60);
830 for(
int i=0;i<100 && !
renderer.WeatherFrame().current;++i) render(500,{0,-1,0},
false,
false);
832 sun=daySun; light={.9f,.86f,.8f,1}; ambient={.4f,.46f,.55f,1};
833 }
834 const auto below=render(.5f,{1,.3f,0}); save("Output/clouds-below.png");
835 Check(below==render(.5f,{1,.3f,0}),"stationary render has no random flicker");
836 backgroundColor=0xff242d3e;
837 const auto unhazed=render(.5f,{1,.12f,0});
838 haze={36.f/255,45.f/255,62.f/255,30};
839 const auto hazed=render(.5f,{1,.12f,0}); save("Output/clouds-base-horizon-haze.png");
840 int matchedHorizon=0,visibleDetail=0;
841 for(size_t i=0;i<hazed.size();++i)
842 {
843 int oldError=0,newError=0;
844 for(int shift : {0,8,16})
845 {
846 oldError+=std::abs(int((unhazed[i]>>shift)&255)-int((backgroundColor>>shift)&255));
847 newError+=std::abs(int((hazed[i]>>shift)&255)-int((backgroundColor>>shift)&255));
848 }
849 matchedHorizon+=oldError>10 && newError<=3;
850
851
852 visibleDetail+=newError>6;
853 }
854 Check(matchedHorizon>100,"distant cloud color converges to the existing horizon haze");
855 Check(visibleDetail>100,"horizon blending preserves nearby cloud detail");
856
857
858
859 {
860 const auto savedBackground=backgroundColor;
861 const auto savedHaze=haze;
862 const D3DXCOLOR horizon(0xff39464a),zenith(0xff8b8be8);
863 haze={horizon.r,horizon.g,horizon.b,30};
864 for(float roll : {0.f,D3DXToRadian(67.f)})
865 {
866 cameraRoll=roll;
867 backgroundColor=zenith;
868 const auto blueSeam=render(.5f,{1,0,0},true);
869 if(roll!=0) save("Output/clouds-horizon-seam-before.png");
870 D3DXCOLOR background;
872 background.a=1; backgroundColor=background;
873 const auto corrected=render(.5f,{1,0,0},true);
874 if(roll!=0) save("Output/clouds-horizon-seam-after.png");
875 int uncovered=0;
876 for(size_t i=0;i<corrected.size();++i)
877 {
878 if(blueSeam[i]==
DWORD(zenith))
879 {
880 ++uncovered;
881 Check(corrected[i]==
DWORD(horizon),
"exposed sub-cloud horizon matches atmospheric haze");
882 }
883 }
884 Check(uncovered>Width*Height/100,"fixture exposes the blue horizon gap before correction");
885 Check(corrected[Width/8+Height/2*Width]==foregroundColor,"horizon correction preserves foreground");
886 Check(corrected[Width*7/8+Height/2*Width]==0xff203010,"horizon correction preserves cockpit");
887 std::cout<<"Horizon gap pixels corrected (roll "<<roll<<"): "<<uncovered<<std::endl;
888 }
889 float previous=0;
890 for(float altitude=0;altitude<=23;altitude+=.01f)
891 {
893 Check(blend>=previous && blend-previous<.003f,"background changes continuously through the cloud deck");
894 previous=blend;
895 }
897 "orbital clear color retains the existing zenith");
898 cameraRoll=0; backgroundColor=savedBackground; haze=savedHaze;
899 }
900
901
902
903 const D3DXMATRIX baseProjection=proj;
904 const float baseWidth=.001f*tanf(D3DXToRadian(115.f)*.5f);
905 D3DXMatrixPerspectiveRH(&proj,baseWidth,baseWidth*float(Height)/Width,.001f,384.f);
906 light=D3DXCOLOR(.06f,.06f,.065f,1); ambient=D3DXCOLOR(.06f,.085f,.12f,1);
907 haze={35.f/255,50.f/255,56.f/255,42.16f}; backgroundColor=0xff233238;
908 const auto dimBase=render(.05f,{1,.65f,0}); save("Output/clouds-base-dim-detail.png");
909 int detailedTiles=0,totalTiles=0;
910 double baseDetail=0;
911 for(int ty=0;ty<6;++ty) for(int tx=0;tx<8;++tx)
912 {
913 const int left=
Width*(tx+2)/12,right=Width*(tx+3)/12;
914 const int top=
Height*(ty+1)/10,bottom=Height*(ty+2)/10;
915 double sum=0,squares=0; int count=0;
916 for(int y=top;y<bottom;++y) for(int x=left;x<right;++x)
917 {
918 const double value=(dimBase[y*
Width+x]>>8)&255;
919 sum+=value; squares+=value*value; ++count;
920 }
921 const double deviation=std::sqrt((std::max)(0.,squares/count-(sum/count)*(sum/count)));
922 baseDetail+=deviation; detailedTiles+=deviation>.4; ++totalTiles;
923 }
924 std::cout<<"Dim base detail: "<<detailedTiles<<"/"<<totalTiles<<" tiles, mean local deviation "<<baseDetail/totalTiles<<std::endl;
925
926
927 Check(detailedTiles>0,"dim cloud bases retain visible structure");
928
929
930 const auto horizonBase=render(.05f,{0,1,0}); save("Output/clouds-base-horizon-neutral.png");
931 double meanModulation=0; int lighter=0,darker=0;
932 for(
DWORD pixel : horizonBase)
933 {
934 const float r=float((pixel>>16)&255),g=float((pixel>>8)&255),b=float(pixel&255);
935 meanModulation+=g/50;
936 lighter+=g>51; darker+=g<49;
937 Check(std::abs(r/35-g/50)<.06f && std::abs(b/56-g/50)<.06f,"base detail modulates brightness without shifting horizon hue");
938 }
939 meanModulation/=horizonBase.size();
940 std::cout<<"Mean horizon-color modulation: "<<meanModulation<<std::endl;
941 Check(meanModulation>.9 && meanModulation<1.1,"base detail is centered on neutral horizon brightness");
942 Check(lighter>100 && darker>100,"base detail both brightens and darkens the horizon color");
943 light=D3DXCOLOR(0,0,0,1); ambient=D3DXCOLOR(.4f,.4f,.4f,1); glow=D3DXCOLOR(0,0,0,1);
944 haze={0,0,0,0};
945 const auto diffuseBase=render(.05f,{0,1,0}); save("Output/clouds-base-diffuse.png");
946 std::vector<int> baseLevels;
947 for(
int y=Height/4;y<
Height*3/4;++y)
for(
int x=Width/4;x<
Width*3/4;++x)
948 baseLevels.push_back((diffuseBase[y*Width+x]>>8)&255);
949 std::sort(baseLevels.begin(),baseLevels.end());
950 const int baseLow=baseLevels[baseLevels.size()/20],baseHigh=baseLevels[baseLevels.size()*19/20];
951 std::cout<<"Diffuse base 5th/95th percentiles: "<<baseLow<<" / "<<baseHigh<<std::endl;
952 Check(baseHigh>=baseLow+2,"diffuse lighting preserves subtle underside relief");
953 Check(baseHigh<baseLow*1.65,"diffuse cloud recesses retain scattered light without extreme contrast");
954 glow=D3DXCOLOR(.125f,.375f,.25f,1);
955 proj=baseProjection; light=D3DXCOLOR(.9f,.86f,.8f,1); ambient=D3DXCOLOR(.4f,.46f,.55f,1);
956 haze={0,0,0,0}; backgroundColor=0xff6080b0;
958 const auto above=render(12.8f,{1,-.28f,0}); save("Output/clouds-above.png");
959 Check(above!=below,"above and below volumes differ");
961 Check(above==render(12.8f,{1,-.28f,0}),"clear tops have no duplicate atmosphere or uniform cloud tint");
962 haze={0,0,0,0};
963 const auto inside=render(5,{1,.01f,0}); save("Output/clouds-inside.png");
964 Check(inside!=above,"inside volume produces distinct extinction");
965
966
967 light=D3DXCOLOR(0,0,0,1); ambient=D3DXCOLOR(.003f,.004f,.006f,1); glow=D3DXCOLOR(0,0,0,1);
968 sun={0,-1,0};
969 const auto shadedDay=render(5,{1,.01f,0});
970 glow=D3DXCOLOR(.125f,.375f,.25f,1);
971 Check(shadedDay==render(5,{1,.01f,0}),"no green airglow in a deeply shadowed daytime cloud");
972 glow=D3DXCOLOR(0,0,0,1);
973 sun={0,1,0};
974 const auto dark=render(.5f,{1,.5f,0});
975 glow=D3DXCOLOR(.125f,.375f,.25f,1);
976 const auto glowing=render(.5f,{1,.5f,0}); save("Output/clouds-night-airglow.png");
978 Check(((glowing[middle]>>8)&255)>((dark[middle]>>8)&255)+5,"airglow reaches bases even without sunlight");
979 Check(((glowing[middle]>>8)&255)>((glowing[middle]>>16)&255),"airglow keeps exomoon blue-green color");
981 for(
int y=29;y<35;++y)
for(
int x=27;x<33;++x) city.
pixels[y*64+x]={80/255.f,48/255.f,32/255.f};
983 const auto litCity=render(.5f,{1,.5f,0}); save("Output/clouds-night-city.png");
984 int cityPixels=0,unlitPixels=0;
985 for(size_t i=0;i<litCity.size();++i)
986 {
987 cityPixels+=((litCity[i]>>16)&255)>((glowing[i]>>16)&255)+3;
988 unlitPixels+=litCity[i]==glowing[i];
989 }
990 Check(cityPixels>100 && unlitPixels>100,"city light is spatially localized on the bases");
992 sun=daySun;
993 light=D3DXCOLOR(.9f,.86f,.8f,1); ambient=D3DXCOLOR(.4f,.46f,.55f,1);
994 const auto stationary=render(.5f,{1,.3f,0});
996 const auto moving=render(.5f,{1,.3f,0}); save("Output/clouds-wind-after-60s.png");
997 Check(stationary!=moving,"wind visibly advects the volume at a stationary camera");
998 const auto orbital=render(500,{1,-.75f,0}); save("Output/clouds-orbit-500km.png");
999 const auto orbitalMoved=render(500,{1,-.75f,0},false,true,.05f);
1000 double orbitalChange=0; int orbitalPixels=0;
1001 for(
int y=Height*2/3;y<
Height*9/10;++y)
for(
int x=Width/4;x<
Width*3/4;++x)
1002 {
1003 for(int shift : {0,8,16})
1004 orbitalChange+=std::abs(int((orbital[y*Width+x]>>shift)&255)-int((orbitalMoved[y*Width+x]>>shift)&255));
1005 orbitalPixels+=3;
1006 }
1007 orbitalChange/=orbitalPixels;
1008 std::cout<<"500 km cloud change for 50 m camera motion (mean channel levels): "<<orbitalChange<<'\n';
1009 Check(orbitalChange<1,"orbital detail is stable for subpixel camera motion");
1010
1011
1012
1013
1014 const D3DXMATRIX ordinaryProjection=proj;
1015 D3DXMATRIX gameProjection,flip;
1016
1017 const float projectionWidth=.0001f*tanf(D3DXToRadian(115.f)*.5f);
1018 D3DXMatrixPerspectiveRH(&gameProjection,projectionWidth,projectionWidth*float(Height)/Width,.0001f,100000.f);
1019 D3DXMatrixRotationZ(&flip,D3DX_PI);
1020 proj=gameProjection;
1021
1022
1023 const auto ascentParams=params;
1024 for(float base : {1.8f,8.5f}) for(float altitude : {22.f,29.9995f,30.0005f,32.f})
1025 for(D3DXVECTOR3 direction : {D3DXVECTOR3(1,-.2f,0),D3DXVECTOR3(0,-1,0)})
1026 {
1028 params.
activity=base>8 ? 0.f : ascentParams.activity;
1029 backgroundColor=0xff000000;
1030 const auto black=render(altitude,direction);
1031 backgroundColor=0xffffffff;
1032 const auto white=render(altitude,direction);
1033 int maximumLeak=0,leakingPixels=0;
1034 double brightness=0; int count=0;
1035 for(
int y=Height/2;y<
Height*9/10;++y)
for(
int x=Width/4;x<
Width*3/4;++x)
1036 {
1037 int leak=0;
1038 for(int shift : {0,8,16})
1039 leak=(std::max)(leak,std::abs(int((black[y*Width+x]>>shift)&255)-int((white[y*Width+x]>>shift)&255)));
1040 maximumLeak=(std::max)(maximumLeak,leak);
1041 leakingPixels+=leak>2;
1042 brightness+=(black[y*
Width+x]>>8)&255; ++count;
1043 }
1044 std::cout<<altitude<<" km stratus (base "<<base<<", pitch "<<direction.y<<") background leak: "<<maximumLeak<<" levels, "<<leakingPixels
1045 <<" pixels; mean brightness "<<brightness/count<<std::endl;
1046 Check(maximumLeak<=2,"thick stratus hides background during ascent");
1047 if(altitude==32 && direction.x==1)
1048 save(base>8 ? "Output/clouds-high-ceiling-32km.png" : "Output/clouds-stratus-32km.png");
1049 }
1050 params=ascentParams;
1051 backgroundColor=0xff6080b0;
1052
1053
1054 for(float altitude : {9.9995f,12.f,12.7495f,13.9995f,21.9995f,29.9995f})
1055 {
1056 const auto start=render(altitude,{1,-.2f,0});
1057 const auto climbed=render(altitude+.001f,{1,-.2f,0});
1058 if(altitude==12) save("Output/clouds-ascent-12km.png");
1059 double change=0; int count=0;
1060 for(
int y=Height/2;y<
Height*9/10;++y)
for(
int x=Width/4;x<
Width*3/4;++x)
1061 for(int shift : {0,8,16})
1062 {
1063 change+=std::abs(int((start[y*Width+x]>>shift)&255)-int((climbed[y*Width+x]>>shift)&255));
1064 ++count;
1065 }
1066 change/=count;
1067 std::cout<<altitude<<" km ascent change for 1 m climb: "<<change<<std::endl;
1068 Check(change<1.5,"small altitude changes do not rapidly reshape visible cloud tops");
1069 }
1070 const auto nearOrbit=render(117,{1,-.75f,0});
1071 const auto nearOrbitMoved=render(117,{1,-.75f,0},false,true,.01f);
1072 double nearMotion=0; int nearSamples=0;
1073 for(
int y=Height/2;y<
Height*9/10;++y)
for(
int x=Width/4;x<
Width*3/4;++x)
1074 for(int shift : {0,8,16})
1075 {
1076 nearMotion+=std::abs(int((nearOrbit[y*Width+x]>>shift)&255)-int((nearOrbitMoved[y*Width+x]>>shift)&255));
1077 ++nearSamples;
1078 }
1079 nearMotion/=nearSamples;
1080 std::cout<<"117 km cloud change for 10 m camera motion: "<<nearMotion<<std::endl;
1081 Check(nearMotion<.5,"near-side cloud detail stays stable for subpixel movement at 117 km");
1082
1083 sun={-.96f,-.28f,0}; D3DXVec3Normalize(&sun,&sun);
1084 proj=gameProjection; backgroundColor=0xff000000;
1085 render(117,{1,-.75f,0}); save("Output/clouds-oblique-117km.png");
1086 render(500,{1,-.75f,0}); save("Output/clouds-oblique-500km.png");
1087 render(3000,{.25f,-1,0}); save("Output/clouds-oblique-3000km.png");
1088 sun=daySun; backgroundColor=0xff6080b0;
1089 for(float altitude : {.05f,117.f,500.f,3000.f})
1090 {
1091 double difference=0;
1092
1093
1094 for(int frame=0;frame<16;++frame)
1095 {
1096 const float offset=frame*5.f/60;
1097 proj=gameProjection;
1098 const D3DXVECTOR3 direction(altitude>=3000?.25f:1,altitude<1?.65f:altitude>=3000?-1:-.75f,0);
1099 const auto ordinary=render(altitude,direction,false,true,offset);
1100 if(frame==0 && altitude>1) save(altitude==117 ? "Output/clouds-filtered-117km.png"
1101 : altitude==500 ? "Output/clouds-filtered-500km.png" : "Output/clouds-filtered-3000km.png");
1102 D3DXMatrixMultiply(&proj,&flip,&gameProjection);
1103 const auto inverted=render(altitude,direction,false,true,offset);
1104 double frameError=0;
1105 for(size_t i=0;i<ordinary.size();++i) for(int shift : {0,8,16})
1106 frameError+=std::abs(int((ordinary[i]>>shift)&255)-int((inverted[inverted.size()-1-i]>>shift)&255));
1107 frameError/=ordinary.size()*3;
1108 difference+=frameError;
1109 Check(frameError<.1,"moving game camera retains the same cloud minification as the test camera");
1110 }
1111 std::cout<<altitude<<" km moving projection-rotation error (mean channel levels): "<<difference/16<<std::endl;
1112 }
1113 proj=ordinaryProjection;
1114
1115
1116
1117 backgroundColor=0xff000000;
1118 light=D3DXCOLOR(.94f,.96f,1,1); ambient=D3DXCOLOR(1,1,1,1);
1119 const auto luminance=[](
DWORD pixel) {
1120 return .2126*((pixel>>16)&255)+.7152*((pixel>>8)&255)+.0722*(pixel&255);
1121 };
1122
1123
1124 sun={0,-1,0}; glow=D3DXCOLOR(0,0,0,1); ambient=D3DXCOLOR(0,0,0,1);
1125 params.
activity=0;
const auto calmTops=render(500,{0,-1,0});
1126 params.
activity=1;
const auto activeTops=render(500,{0,-1,0});
1127 double calmMean=0,activeMean=0;
1128 for(size_t i=0;i<calmTops.size();++i)
1129 {
1130 calmMean+=luminance(calmTops[i]); activeMean+=luminance(activeTops[i]);
1131 }
1132 calmMean/=calmTops.size(); activeMean/=activeTops.size();
1133 save("Output/clouds-weather-500km.png");
1134 double tileLow=255,tileHigh=0;
1135 for(int ty=0;ty<4;++ty) for(int tx=0;tx<8;++tx)
1136 {
1137 double sum=0; int count=0;
1138 for(
int y=Height*ty/4;y<
Height*(ty+1)/4;++y)
for(
int x=Width*tx/8;x<
Width*(tx+1)/8;++x)
1139 { sum+=luminance(activeTops[y*Width+x]); ++count; }
1140 tileLow=(std::min)(tileLow,sum/count); tileHigh=(std::max)(tileHigh,sum/count);
1141 }
1142 std::cout<<"Regional top tile brightness range: "<<tileLow<<" / "<<tileHigh<<std::endl;
1143 Check(tileHigh-tileLow>activeMean*.04,"orbital tops show large-scale weather structure beyond fine noise");
1144 Check(tileHigh<tileLow*1.8,"overhead-lit weather regions avoid excessive broad light/dark contrast");
1145
1146
1148 for(float region : {0.f,700.f,-1100.f})
1149 {
1151 const auto regionalTops=render(117,{0,-1,0});
1152 if(region==0) save("Output/clouds-weather-117km.png");
1153 double low=255,high=0,mean=0;
1154 for(int ty=0;ty<4;++ty) for(int tx=0;tx<8;++tx)
1155 {
1156 double sum=0; int count=0;
1157 for(
int y=Height*ty/4;y<
Height*(ty+1)/4;++y)
for(
int x=Width*tx/8;x<
Width*(tx+1)/8;++x)
1158 { sum+=luminance(regionalTops[y*Width+x]); ++count; }
1159 const double tile=sum/count;
1160 low=(std::min)(low,tile); high=(std::max)(high,tile); mean+=tile/32;
1161 }
1162 std::cout<<"117 km regional tile range (offset "<<region<<"): "<<low<<" / "<<high<<std::endl;
1163 Check(high-low>mean*.025,"weather patterns remain visible at 117 km across multiple regions");
1164 }
1166 std::cout<<"Calm/active top sunlight: "<<calmMean<<" / "<<activeMean<<std::endl;
1167 Check(std::abs(activeMean-calmMean)<calmMean*.06,"cloud-top brightness follows local depth rather than absolute tower height");
1168 glow=D3DXCOLOR(.125f,.375f,.25f,1); ambient=D3DXCOLOR(1,1,1,1);
1169 for(float altitude : {117.f,500.f})
1170 {
1171 sun={0,-1,0};
1172 const auto day=render(altitude,{0,-1,0});
1173 sun={0,1,0};
1174 const auto night=render(altitude,{0,-1,0});
1175 save(altitude==117 ? "Output/clouds-night-117km.png" : "Output/clouds-night-500km.png");
1176
1177 sun={-1,.01f,0}; D3DXVec3Normalize(&sun,&sun);
1178 const auto sunset=render(altitude,{0,-1,0});
1179 save(altitude==117 ? "Output/clouds-sunset-117km.png" : "Output/clouds-sunset-500km.png");
1180 double dayMean=0,nightMean=0;
1181 int cloudPixels=0,litAtSunset=0,darkAtSunset=0;
1182 for(size_t i=0;i<day.size();++i) if(luminance(day[i])>100)
1183 {
1184 dayMean+=luminance(day[i]); nightMean+=luminance(night[i]); ++cloudPixels;
1185 litAtSunset+=luminance(sunset[i])>25;
1186 darkAtSunset+=luminance(sunset[i])<12;
1187 }
1188 Check(cloudPixels>100,"daylit cloud tops remain bright");
1189 dayMean/=cloudPixels; nightMean/=cloudPixels;
1190 std::cout<<altitude<<" km day/night cloud luminance (0..255): "<<dayMean<<" / "<<nightMean<<std::endl;
1191 Check(nightMean<dayMean*.08,"night-side tops stay dark even when the observer ambient is bright");
1192 Check(nightMean>1,"faint exomoon airglow remains visible on the night side");
1193 D3DXMATRIX solarOrbit;
1194 D3DXMatrixIdentity(&solarOrbit);
1195 solarOrbit._42=100000.f;
1197 Check(render(altitude,{0,-1,0})==night,"admin darkness matches the unlit hemisphere");
1199 const auto forcedDay=render(altitude,{0,-1,0});
1200 Check(forcedDay==day,"admin daylight matches the overhead sun across the cloud hemisphere");
1201 std::cout<<altitude<<" km sun position override day/night comparisons passed"<<std::endl;
1202 if(altitude>=500)
1203 Check(litAtSunset>100 && darkAtSunset>100,"sunset has both lit and dark cloud regions in one frame");
1204 }
1205 sun=daySun; light=D3DXCOLOR(.9f,.86f,.8f,1); ambient=D3DXCOLOR(.4f,.46f,.55f,1);
1206 backgroundColor=0xff6080b0;
1207
1208
1209
1210
1211 {
1213 const auto savedBackground=backgroundColor;
1214 backgroundColor=0xff000000;
1216 struct RingVertex {
float x,y,z;
DWORD color;
float u,v; };
1217 const D3DXVECTOR3 normal(0,1,0),north(0,0,1);
1218 D3DXMATRIX orientation,world;
1219 D3DXMatrixLookAtRH(&orientation,&zero,&normal,&north);
1220 D3DXMatrixInverse(&orientation,nullptr,&orientation);
1221 const auto savedProjection=proj;
1222 D3DXMatrixPerspectiveFovRH(&proj,D3DX_PI/3,float(Width)/Height,.001f,384.f);
1223 ComPtr<IDirect3DTexture9> atmosphere;
1224 HR(D3DXCreateTextureFromFileExA(device.Get(),"Textures/atmosphere.dds",D3DX_DEFAULT,D3DX_DEFAULT,
1225 1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_FILTER_NONE,D3DX_FILTER_NONE,0,nullptr,nullptr,&atmosphere),"load actual atmosphere ramp");
1226 ComPtr<IDirect3DVertexBuffer9> ring;
1227 HR(device->CreateVertexBuffer((segments*2+2)*sizeof(RingVertex),0,
1228 D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1,D3DPOOL_MANAGED,&ring,nullptr),"create orbital atmosphere geometry");
1229 ComPtr<IDirect3DTexture9> testCloud,testDistance;
1230 HR(device->CreateTexture(1,1,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,&testCloud,nullptr),"create atmosphere cloud mask");
1231 HR(device->CreateTexture(1,1,1,0,D3DFMT_R32F,D3DPOOL_MANAGED,&testDistance,nullptr),"create atmosphere cloud distance");
1232 D3DLOCKED_RECT maskLock{};
1233 HR(testDistance->LockRect(0,&maskLock,nullptr,0),"lock atmosphere cloud distance");
1234 *static_cast<float*>(maskLock.pBits)=60;
1235 HR(testDistance->UnlockRect(0),"unlock atmosphere cloud distance");
1236 const auto atmosphereFrame=[&](
float altitude,D3DXVECTOR3 sunlight,
bool occlude=
true,
int mask=-1) {
1237 const float observer=params.
radius+altitude,cloudRadius=params.
radius+10;
1238 const float angle=asinf(cloudRadius/observer),distance=(std::max)(256.f,cloudRadius/tanf(angle));
1239 const float inner=sinf(angle)*distance-52.5f,outer=inner+105;
1240 const float bury=observer-distance*cosf(angle),upper=-52.5f*sinf(angle);
1241 const float scale=256.f/observer;
1242 D3DXMATRIX compression;
1243 D3DXMatrixScaling(&compression,scale,scale,scale);
1244 world=orientation; world._42=-observer; world*=compression;
1245 const auto savedSun=sun;
1246 sun=sunlight;
1247 auto background=render(altitude,{1,altitude>200 ? -.75f : altitude>100 ? -.4f : -.02f,0},true);
1248 sun=savedSun;
1249 RingVertex* v=nullptr; HR(ring->Lock(0,0,reinterpret_cast<void**>(&v),0),"lock atmosphere geometry");
1250 for(int i=0;i<=segments;++i)
1251 {
1252 const float theta=i*D3DX_PI*2/segments,c=cosf(theta),s=sinf(theta);
1253 D3DXVECTOR3 direction(c*inner,s*inner,-upper-bury);
1254 D3DXVec3TransformNormal(&direction,&direction,&orientation);
1255 D3DXVec3Normalize(&direction,&direction);
1256 const float bright=
CloudVolume::Saturate((-D3DXVec3Dot(&direction,&sunlight)-altitude/70000+.3f)/.3f);
1257 const DWORD color=D3DXCOLOR(.24f*bright,.49f*bright,.85f*bright,1);
1258 *v++={c*inner,s*inner,-upper-bury,color,float(i),1};
1259 *v++={c*outer,s*outer,upper-bury,color,float(i),0};
1260 }
1261 HR(ring->Unlock(),"unlock atmosphere geometry");
1262 device->SetTransform(D3DTS_VIEW,&view); device->SetTransform(D3DTS_PROJECTION,&proj);
1263 device->SetRenderState(D3DRS_LIGHTING,TRUE);
1264 device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
1265 device->SetRenderState(D3DRS_STENCILFUNC,D3DCMP_NEVER);
1266 device->SetTextureStageState(0,D3DTSS_COLORARG2,D3DTA_TFACTOR);
1267 device->SetTextureStageState(0,D3DTSS_ALPHAOP,D3DTOP_DISABLE);
1268 HR(device->BeginScene(),"begin atmosphere frame");
1269 if(mask>=0)
1270 {
1271 const float opacity=
mask/255.f;
1272 const D3DXCOLOR cloud(.4f*opacity,.3f*opacity,.2f*opacity,opacity);
1273 const D3DXCOLOR sky(backgroundColor);
1274 const D3DXCOLOR composite(cloud.r+(1-opacity)*sky.r,cloud.g+(1-opacity)*sky.g,
1275 cloud.b+(1-opacity)*sky.b,1);
1277 HR(device->Clear(1,&middle,D3DCLEAR_TARGET,composite,1,0),"set controlled premultiplied cloud background");
1278 for(
int y=0;y<
Height;++y)
for(
int x=Width/4;x<
Width*3/4;++x) background[y*Width+x]=
DWORD(composite);
1279 HR(testCloud->LockRect(0,&maskLock,nullptr,0),"lock atmosphere cloud mask");
1280 *
static_cast<DWORD*
>(maskLock.pBits)=
DWORD(cloud);
1281 HR(testCloud->UnlockRect(0),"unlock atmosphere cloud mask");
1282 renderer.Effect()->SetTexture(
"cloudImage",testCloud.Get());
1283 renderer.Effect()->SetTexture(
"cloudDistance",testDistance.Get());
1285 occlude ?
renderer.Effect() :
nullptr,scale),
"draw controlled cloud occlusion");
1286 renderer.Effect()->SetTexture(
"cloudImage",
nullptr);
1287 renderer.Effect()->SetTexture(
"cloudDistance",
nullptr);
1288 }
1289 else HR(occlude ?
renderer.RenderSkyRing(device.Get(),atmosphere.Get(),ring.Get(),world,segments,scale)
1290 :
SkyRingRenderer::Draw(device.Get(),atmosphere.Get(),ring.Get(),world,segments),
"draw atmosphere after volume");
1291 HR(device->EndScene(),"end atmosphere frame");
1292 DWORD stencil=0; device->GetRenderState(D3DRS_STENCILFUNC,&stencil);
1293 Check(stencil==D3DCMP_NEVER,"atmosphere restores caller state");
1294 const auto result=pixels();
1295 int affected=0,maxChange=0;
1296 for(
int y=0;y<
Height;++y)
for(
int x=0;x<
Width;++x)
1297 {
1298 if(x>=Width*3/4 || (occlude && x<Width/4))
1299 Check(result[y*Width+x]==background[y*Width+x],"atmosphere protects foreground and cockpit");
1300 else if(x>=Width/4)
1301 {
1302 int change=0;
1303 for(int shift : {0,8,16}) change=(std::max)(change,
1304 std::abs(int((result[y*Width+x]>>shift)&255)-int((background[y*Width+x]>>shift)&255)));
1305 affected+=change>2;
1306 maxChange=(std::max)(maxChange,change);
1307 }
1308 }
1309 std::cout<<altitude<<" km atmosphere, cloud occlusion "<<occlude<<": "<<affected
1310 <<" affected pixels, maximum channel change "<<maxChange<<std::endl;
1311 if(mask==255) Check(maxChange==0,"opaque clouds hide the sky backdrop even beyond 52.5 km");
1312 else if(altitude<11 && occlude) Check(maxChange<=2,"nearby opaque clouds extinguish the skyring");
1313 else if(sunlight.y>.7f && sunlight.x>=0 && occlude)
1314 Check(maxChange<=1,"unlit ring cannot paint bright haze onto the night side");
1315 else Check(affected>100,"atmosphere ramp remains visible without a foreground cloud");
1316 return result;
1317 };
1318 const auto dayRing=atmosphereFrame(500,sun); save("Output/clouds-orbit-atmosphere.png");
1319 const auto legacyOrbit=atmosphereFrame(500,sun,false);
1320 double limbChange=0;
1321 for(
int y=0;y<
Height;++y)
for(
int x=Width/4;x<
Width*3/4;++x)
for(
int shift : {0,8,16})
1322 limbChange+=std::abs(int((dayRing[y*Width+x]>>shift)&255)-int((legacyOrbit[y*Width+x]>>shift)&255));
1323 limbChange/=double(Width/2)*
Height*3;
1324 std::cout<<"Orbital haze change versus existing ramp: "<<limbChange<<" channel levels"<<std::endl;
1325
1326
1327 const auto clearOrbit=atmosphereFrame(500,sun,true,0);
1328 const auto clearLegacy=atmosphereFrame(500,sun,false,0);
1329 for(
int y=0;y<
Height;++y)
for(
int x=Width/4;x<
Width*3/4;++x)
for(
int shift : {0,8,16})
1330 Check(std::abs(int((clearOrbit[y*Width+x]>>shift)&255)-int((clearLegacy[y*Width+x]>>shift)&255))<=1,
1331 "unobstructed orbital atmosphere preserves the original ramp within 8-bit rounding");
1332 Check(dayRing!=atmosphereFrame(500,-sun),"atmosphere retains directional sunlight response");
1333 const auto highDay=atmosphereFrame(1000,{0,-1,0});
1334 const auto highNight=atmosphereFrame(1000,{0,1,0});
1335 const auto highTwilight=atmosphereFrame(1000,{-.5f,.8f,-.4f});
1336 save("Output/clouds-1000km-twilight-atmosphere.png");
1337 const auto meanView=[&](const std::vector<DWORD>& frame) {
1338 double sum=0;
1339 for(
int y=0;y<
Height;++y)
for(
int x=Width/4;x<
Width*3/4;++x) sum+=(frame[y*Width+x]>>8)&255;
1341 };
1342 const double dayMean=meanView(highDay),nightMean=meanView(highNight),twilightMean=meanView(highTwilight);
1343 std::cout<<"1000 km day/twilight/night luminance: "<<dayMean<<" / "<<twilightMean<<" / "<<nightMean<<'\n';
1344 Check(nightMean<dayMean*.05 && twilightMean>nightMean && twilightMean<dayMean*.8,
1345 "1000 km haze follows the sun angle and preserves a dark hemisphere with a twilight rim");
1346 atmosphereFrame(117,sun); save("Output/clouds-117km-atmosphere.png");
1347 atmosphereFrame(13.13f,sun); save("Output/clouds-13130m-atmosphere.png");
1348 const auto hazyTops=render(13.13f,{1,-.02f,0});
1349 atmosphereHaze={0,0,0,0};
1350 const auto clearTops=render(13.13f,{1,-.02f,0});
1352 const auto hazeChange=[&](int y0,int y1) {
1353 double error=0; int count=0;
1354 for(
int y=y0;y<y1;++y)
for(
int x=Width/4;x<
Width*3/4;++x)
if(clearTops[y*Width+x]!=backgroundColor)
1355 for(int shift : {0,8,16})
1356 {
1357 error+=std::abs(int((hazyTops[y*Width+x]>>shift)&255)-int((clearTops[y*Width+x]>>shift)&255));
1358 ++count;
1359 }
1360 Check(count>100,"cloud haze fixture contains formations at both distances");
1361 return error/count;
1362 };
1363 const double farHaze=hazeChange(Height*11/20,Height*3/5),nearHaze=hazeChange(Height*4/5,Height*9/10);
1364 std::cout<<"13.13 km atmospheric near/far cloud change: "<<nearHaze<<" / "<<farHaze<<std::endl;
1365 Check(farHaze>nearHaze+1,"air builds with cloud distance without a projected ring stripe");
1366 atmosphereFrame(13.13f,sun,true,255);
1367 atmosphereFrame(117,sun,true,255);
1368 const auto thin=atmosphereFrame(13.13f,sun,true,128);
1369 const auto clear=atmosphereFrame(13.13f,sun,true,0);
1370 Check(thin!=clear,"thin cloud transmits a reduced sky backdrop");
1371 for(
int y=0;y<
Height;++y)
for(
int x=Width/4;x<
Width*3/4;++x)
for(
int channel=0;channel<3;++channel)
1372 {
1373 const int shift=channel*8;
1374 const float cloudColor[]={.2f,.3f,.4f};
1375 const float expected=cloudColor[channel]*128+(127.f/255)*int((clear[y*Width+x]>>shift)&255);
1376 Check(std::abs(int((thin[y*Width+x]>>shift)&255)-expected)<2.5f,
1377 "ring behind a translucent cloud preserves its premultiplied radiance without an outline");
1378 }
1379 atmosphereFrame(10.33f,sun,false); save("Output/clouds-10330m-ring-before.png");
1380 atmosphereFrame(10.33f,sun); save("Output/clouds-10330m-ring-after.png");
1381 proj=savedProjection;
1382 atmosphereHaze={0,0,0,0};
1383 backgroundColor=savedBackground;
1384 device->SetRenderState(D3DRS_STENCILFUNC,D3DCMP_ALWAYS);
1385 }
1386
1387 const auto masked=render(.5f,{1,.3f,0},true);
1388 for(
int y=0;y<
Height;++y)
for(
int x=0;x<
Width;++x)
1389 {
1390 if(x<Width/4) Check((masked[y*Width+x]&0xffffff)==0x102030,"foreground preserved");
1391 if(x>=Width*3/4) Check((masked[y*Width+x]&0xffffff)==0x203010,"cockpit preserved");
1392 }
1393
1394
1395 const auto probeParams=params;
1396 const auto probeStorm=ConstantWeather(255);
1397 renderer.UpdateWeather(probeStorm,60);
1398 for(
int i=0;i<100 &&
renderer.WeatherFrame().current!=probeStorm;++i) render(500,{0,-1,0},
false,
false);
1400 render(500,{0,-1,0},false,false);
1402 for(int z=0;z<256;z+=8) for(int x=0;x<256;x+=8)
1403 {
1407 }
1408 Check(peakTop>20,"GPU regression fixture contains a tower above 20 km");
1409 for(float base : {1.8f,8.5f}) for(float probeAltitude : {1.85f,10.f,11.f,18.f,21.f})
1410 {
1412 D3DXVECTOR4 probeEye(-12.3f,params.
radius+probeAltitude,9.7f,0);
1413 if(probeAltitude>=18)
1414 {
1416 probeEye={point.
x,point.
y,point.
z,0};
1417 }
1418 renderer.Effect()->SetVector(
"eye",&probeEye);
1420 renderer.Effect()->SetVector(
"layer",&probeLayer);
1421 struct Vertex{float x,y,z,w,u,v;};
1422 const Vertex quad[]={{-.5f,-.5f,0,1,0,0},{
Width-.5f,-.5f,0,1,1,0},
1423 {-.5f,
Height-.5f,0,1,0,1},{
Width-.5f,
Height-.5f,0,1,1,1}};
1424 device->SetRenderState(D3DRS_ZENABLE,FALSE); device->SetRenderState(D3DRS_STENCILENABLE,FALSE);
1425 device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE); device->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);
1426 device->SetFVF(D3DFVF_XYZRHW|D3DFVF_TEX1);
1427 HR(device->BeginScene(),
"begin density probe"); HR(
renderer.Effect()->Begin(
nullptr,0),
"begin probe effect");
1428 HR(
renderer.Effect()->BeginPass(2),
"begin probe shader");
1429 HR(device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP,2,quad,sizeof(Vertex)),"draw density probe");
1430 HR(
renderer.Effect()->EndPass(),
"end probe pass"); HR(
renderer.Effect()->End(),
"end probe effect");
1431 HR(device->EndScene(),"end density probe");
1432 const auto probe=pixels();
1433 float maxError=0,maxExtinctionError=0;
1434 for(
int y=0;y<
Height;y+=5)
for(
int x=0;x<
Width;x+=5)
1435 {
1437 probeEye.y+((y+.5f)/Height-.5f)*8,probeEye.z};
1439 const float gpu=float(probe[y*Width+x]&255)/255;
1440 maxError=(std::max)(maxError,std::abs(cpu-gpu));
1442 const float gpuExtinction=float((probe[y*Width+x]>>16)&255)/255;
1443 maxExtinctionError=(std::max)(maxExtinctionError,std::abs(cpuExtinction-gpuExtinction));
1444 }
1445 std::cout<<probeAltitude<<" km (base "<<base<<") maximum CPU/GPU density difference: "<<maxError<<'\n';
1446 Check(maxError<.025f,"CPU and GPU sample the same cloud structure");
1447 Check(maxExtinctionError<.055f,"CPU lights and GPU geometry share dense-pocket extinction");
1448 }
1449 params=probeParams;
1450 renderer.UpdateWeather(serverMap,60);
1451 for(
int i=0;i<100 &&
renderer.WeatherFrame().current!=serverMap;++i) render(500,{0,-1,0},
false,
false);
1453
1454
1455 device->SetRenderState(D3DRS_ZENABLE,TRUE);
1456 for(float altitude : {.5f,5.f,12.8f,150.f,500.f,3000.f})
1457 {
1458 const D3DXVECTOR3 dir(altitude>=3000?.25f:1,altitude<2?.3f:altitude>=3000?-1:altitude>=500?-.75f:-.28f,0);
1459 render(altitude,dir);
1460 const auto start=std::chrono::steady_clock::now();
1461 for(int i=0;i<20;++i) render(altitude,dir);
1462 const double ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count()/20;
1463 std::cout<<
"Completed "<<
Width<<
"x"<<
Height<<
" frame + readback at "<<altitude<<
" km: "<<ms<<
" ms\n";
1464 const auto batchStart=std::chrono::steady_clock::now();
1465 for(int i=0;i<60;++i) render(altitude,dir,false,false);
1466 pixels();
1467 const double batchMs=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-batchStart).count()/60;
1468 std::cout<<"Cloud frame average (60 frames, one GPU fence): "<<batchMs<<" ms\n";
1469 }
1470 for(float altitude : {13.13f,500.f}) for(bool air : {false,true})
1471 {
1473 const D3DXVECTOR3 direction(1,altitude>100 ? -.75f : -.02f,0);
1474 render(altitude,direction);
1475 const auto start=std::chrono::steady_clock::now();
1476 for(int frame=0;frame<60;++frame) render(altitude,direction,false,false);
1477 pixels();
1478 std::cout<<altitude<<" km cloud frame with physical air "<<air<<": "
1479 <<std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count()/60<<" ms\n";
1480 }
1481 atmosphereHaze={0,0,0,0};
1482 if(SUCCEEDED(d3d->CheckDeviceMultiSampleType(0,D3DDEVTYPE_HAL,D3DFMT_A8R8G8B8,TRUE,D3DMULTISAMPLE_4_SAMPLES,nullptr)) &&
1483 SUCCEEDED(d3d->CheckDeviceMultiSampleType(0,D3DDEVTYPE_HAL,D3DFMT_D24S8,TRUE,D3DMULTISAMPLE_4_SAMPLES,nullptr)))
1484 {
1485 const auto savedProjection=proj;
1486 D3DXMatrixPerspectiveFovRH(&proj,D3DX_PI/3,float(Width)/Height,.001f,384.f);
1487 const float singleNear=transmissionAtDepth(5,.005f),singleFar=transmissionAtDepth(5,1);
1488 target.Reset(); depth.Reset();
1489 HR(device->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,D3DMULTISAMPLE_4_SAMPLES,0,FALSE,&target,nullptr),"create MSAA target");
1490 HR(device->CreateDepthStencilSurface(Width,Height,D3DFMT_D24S8,D3DMULTISAMPLE_4_SAMPLES,0,TRUE,&depth,nullptr),"create MSAA depth");
1491 HR(device->SetDepthStencilSurface(nullptr),"detach old depth");
1492 HR(device->SetRenderTarget(0,
target.Get()),
"bind MSAA target");
1493 HR(device->SetDepthStencilSurface(depth.Get()),"bind MSAA depth");
1494 const auto aa=render(.5f,{1,.3f,0},true);
1495 Check(aa[Width/8+Height/2*Width]==0xff102030,"MSAA foreground preserved");
1496 Check(aa[Width*7/8+Height/2*Width]==0xff203010,"MSAA cockpit preserved");
1497 Check(aa[Width/2+Height/2*Width]!=0xff6080b0,"MSAA cloud visible");
1498 const float aaNear=transmissionAtDepth(5,.005f),aaFar=transmissionAtDepth(5,1);
1499 std::cout<<"MSAA near/far transmission: "<<aaNear<<" / "<<aaFar
1500 <<"; single-sample: "<<singleNear<<" / "<<singleFar<<std::endl;
1501
1502
1503
1504 Check(std::abs(aaNear-singleNear)<.015f && std::abs(aaFar-singleFar)<.015f
1505 && aaNear>aaFar+.02f && aaFar<.01f,
1506 "MSAA depth clips integration at nearby objects and obscures distant objects");
1507 const auto darkBeam=render(5,{0,0,-1},true);
1508 renderer.SetHeadlights({{{0,params.
radius+5,-.017f},{0,0,-1},{1,1,.75f,1},2}});
1509 const auto aaBeam=render(5,{0,0,-1},true);
1510 Check(aaBeam!=darkBeam,"headlight prepass and composite work with MSAA");
1511 Check(aaBeam[Width/8+Height/2*Width]==foregroundColor && aaBeam[Width*7/8+Height/2*Width]==0xff203010,
1512 "MSAA headlight preserves opaque foreground and cockpit");
1513 proj=savedProjection;
1514 std::cout<<"PASS: 4x MSAA target and depth restoration\n";
1515 }
1516
1518 HR(device->Reset(&pp),"reset device after releasing cloud resources");
1519 HR(
renderer.Initialize(device.Get()),
"recreate clouds after reset");
1520 Check(
renderer.Ready(),
"clouds ready after reset");
1521 HR(device->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,D3DMULTISAMPLE_NONE,0,FALSE,&target,nullptr),"create post-reset target");
1522 HR(device->SetRenderTarget(0,
target.Get()),
"bind post-reset target");
1523 Check(render(5,{1,.01f,0})!=below,"render after a real device reset");
1524 renderer.SetHeadlights({});
const auto resetDark=render(5,{0,0,-1});
1525 renderer.SetHeadlights({{{0,params.
radius+5,-.017f},{0,0,-1},{1,1,.75f,1},2}});
1526 Check(render(5,{0,0,-1})!=resetDark,"headlight attenuation resources recreate after device reset");
1529 SetEnvironmentVariableA("RISE_VOLUMETRIC_CLOUDS","0");
1530 Check(
renderer.Initialize(device.Get())==S_FALSE && !
renderer.Ready(),
"legacy rollback switch");
1531 SetEnvironmentVariableA("RISE_VOLUMETRIC_CLOUDS",nullptr);
1532 readback.Reset(); device.Reset(); d3d.Reset(); DestroyWindow(window);
1533 std::cout<<"PASS: "<<checks<<" checks (density, TCP seam, rendering, occlusion, state restoration, device reset).\n";
1534}
SCRIPT_CONTROL SCRIPT_STATE const void int
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
SCRIPT_CONTROL SCRIPT_STATE const void DWORD
Point Scale(Point p, float s)
float AtmosphericHazeDistanceKm(float nominalTop)
float BackgroundZenithWeight(float altitude, const Parameters ¶ms)
Point Add(Point a, Point b)
void Advect(Parameters ¶ms, Point physicalWindKms, double elapsed)
constexpr float ClearVisibilityKm
float Transmittance(Point from, Point to, const Parameters ¶ms, uint32_t seed=DefaultSeed)
float DiffuseSunTransmission(Point p, Point towardSun, const Parameters ¶ms, uint32_t seed=DefaultSeed)
Column Boundaries(Point p, const Parameters ¶ms, uint32_t seed=DefaultSeed)
Medium SampleMedium(Point p, const Parameters ¶ms, uint32_t seed=DefaultSeed)
float Density(Point p, const Parameters ¶ms, uint32_t seed=DefaultSeed)
Point ScatteredSunlight(Point incident, float sunCosine, float transmission)
Point WithAirglow(Point scattered, Point airglow, float sunCosine, float altitude, float base, float top)
HRESULT Draw(Rendering::RenderDevice *device, Rendering::RenderTexture *texture, Rendering::RenderBuffer *vertices, const RiseMath::Matrix &world, UINT segments, Rendering::RenderMaterial *volumeEffect=nullptr, float physicalScale=1)
constexpr unsigned Segments
void Apply(float mode, const RiseMath::Vector3 &outwardNormal, RiseMath::Matrix &sunWorld, RiseMath::Vector3 &incomingLight)
std::array< Point, 64 *64 > pixels
CloudWeather::Frame weather
RiseMath::Vector3 position
RiseMath::Vector3 direction