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

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

1// Offscreen integration test: no game login or production data.
2#include "Reference9/WindshieldRainRenderer.h"
3#include <cstdlib>
4#include <iostream>
5#include <fstream>
6#include <string>
7#include <set>
8#include <memory>
9using Microsoft::WRL::ComPtr;
11static constexpr int Width=960, Height=540;
12static void Check(bool ok, const char* message)
13{
14 if (!ok) { std::cerr << "FAIL: " << message << '\n'; std::exit(1); }
15}
16static void HR(HRESULT hr, const char* message)
17{
18 if (FAILED(hr)) std::cerr << "HRESULT: " << std::hex << hr << std::dec << '\n';
19 Check(SUCCEEDED(hr),message);
20}
21static float MeanDifference(const std::vector<DWORD>& a, const std::vector<DWORD>& b)
22{
23 double total=0;
24 for(size_t i=0;i<a.size();++i) for(int shift : {0,8,16})
25 total+=std::abs(int((a[i]>>shift)&255)-int((b[i]>>shift)&255));
26 return float(total/(a.size()*3));
27}
28static float MeanBrightness(const std::vector<DWORD>& pixels)
29{
30 double total=0;
31 for(DWORD pixel:pixels) for(int shift : {0,8,16}) total+=(pixel>>shift)&255;
32 return float(total/(pixels.size()*3));
33}
34static std::vector<Vertex> Quad(float left, float right, float top, float bottom)
35{
36 return {{left,top,0,0,0,1,0,0},{right,top,0,0,0,1,1,0},{left,bottom,0,0,0,1,0,1},
37 {right,top,0,0,0,1,1,0},{right,bottom,0,0,0,1,1,1},{left,bottom,0,0,0,1,0,1}};
38}
39template<class T> static T Read(std::ifstream& file, std::streamoff offset)
40{
41 T result{}; file.seekg(offset); file.read(reinterpret_cast<char*>(&result),sizeof(result));
42 Check(file.good(),"read shipped mesh"); return result;
43}
44static std::vector<Vertex> Glass(const char* name, int normalAxis, bool positiveNormal=false)
45{
46 std::ifstream dix(std::string("Meshes/")+name+".dix",std::ios::binary);
47 std::ifstream daw(std::string("Meshes/")+name+".daw",std::ios::binary);
48 Check(dix.good() && daw.good(),"open shipped cockpit");
49 const int vertexCount=Read<unsigned short>(daw,0);
50 daw.seekg(0,std::ios::end);
51 const int stride=int((std::streamoff(daw.tellg())-4)/vertexCount);
52 Check(stride==32 || stride==40,"supported shipped DAW vertex layout");
53 std::vector<Vertex> vertices;
54 const int count=Read<short>(dix,0);
55 for(int c=0;c<count;++c)
56 {
57 const int offset=99+c*100;
58 if(Read<unsigned char>(dix,offset+58)!=5) continue;
59 const int start=Read<short>(dix,offset), triangles=Read<short>(dix,offset+2);
60 for(int t=0;t<triangles;++t)
61 {
62 Vertex tri[3];
63 for(int i=0;i<3;++i) tri[i]=Read<Vertex>(daw,2+stride*(start+t*3+i));
64 const float n[]={tri[0].nx,tri[0].ny,tri[0].nz};
65 if(normalAxis>=0 && n[normalAxis]*(positiveNormal ? 1.f : -1.f)<.5f) continue;
66 vertices.insert(vertices.end(),std::begin(tri),std::end(tri));
67 }
68 }
69 Check(!vertices.empty(),"front glass found"); return vertices;
70}
71static D3DXVECTOR3 GlassRotation(const char* name)
72{
73 std::ifstream dix(std::string("Meshes/")+name+".dix",std::ios::binary);
74 const int count=Read<short>(dix,0);
75 for(int c=0;c<count;++c) if(Read<unsigned char>(dix,99+c*100+58)==5)
76 return Read<D3DXVECTOR3>(dix,99+c*100+16);
77 Check(false,"glass component rotation found");return {};
78}
79struct WindshieldRainTestAccess
80{
81 static WindshieldRain::Surface& Water(WindshieldRainRenderer& r, size_t i=0) { return r.panes[i].water; }
82 static WindshieldRain::Point Map(const WindshieldRainRenderer& r, D3DXVECTOR3 p)
83 {
84 const auto& pane=r.panes[0]; const auto d=p-pane.origin;
85 return {D3DXVec3Dot(&d,&pane.u)*1000,D3DXVec3Dot(&d,&pane.v)*1000};
86 }
87};
88static WindshieldRain::Drop Largest(const WindshieldRain::Surface& water)
89{
90 Check(!water.Drops().empty(),"fixture retains a parent bead");
91 return *std::max_element(water.Drops().begin(),water.Drops().end(),[](const auto& a,const auto& b) { return a.radius<b.radius; });
92}
93static void CheckShippedWiperDisplacement()
94{
95 std::ifstream dix("Meshes/C-2 Dasher INT.dix",std::ios::binary),daw("Meshes/C-2 Dasher INT.daw",std::ios::binary);
96 const int count=Read<short>(dix,0), vertexCount=Read<unsigned short>(daw,0);
97 daw.seekg(0,std::ios::end);const int stride=int((std::streamoff(daw.tellg())-4)/vertexCount);
98 Check(stride==32 || stride==40,"C-2 wiper vertex layout");
99 struct Component {int type;D3DXVECTOR3 xyz,ypr,extend,axis,hinge;float extent;};
100 std::vector<Component> components(count);std::vector<D3DXMATRIX> transforms(count);
101 WindshieldRainRenderer rain;int blades=0;
102 for(int i=0;i<count;++i)
103 {
104 const int o=99+i*100;auto& c=components[i];c.type=Read<unsigned char>(dix,o+58);
105 c.xyz=Read<D3DXVECTOR3>(dix,o+4);c.ypr=Read<D3DXVECTOR3>(dix,o+16);c.extend=Read<D3DXVECTOR3>(dix,o+32);
106 c.axis=Read<D3DXVECTOR3>(dix,o+63);c.hinge=Read<D3DXVECTOR3>(dix,o+75);c.extent=Read<float>(dix,o+87);
107 if(c.type!=5 && c.type!=47)continue;
108 const int first=Read<short>(dix,o),n=Read<short>(dix,o+2)*3;
109 std::vector<Vertex> vertices(n);
110 for(int j=0;j<n;++j)vertices[j]=Read<Vertex>(daw,2+stride*(first+j));
111 if(c.type==5)rain.AddGlass(i,vertices.data(),vertices.size());
112 else {rain.AddWiper(i,vertices.data(),vertices.size());++blades;}
113 }
114 Check(blades>0,"shipped C-2 contains animated blades");rain.FinishGeometry();
115 const auto pose=[&](float phase) {
116 for(int i=0;i<count;++i)
117 {
118 const auto& c=components[i];const float e=c.type==47 ? .5f-.5f*std::cos(phase*D3DX_PI*2):0;
119 D3DXMATRIX rotation,shift,hinge,end;
120 D3DXMatrixRotationYawPitchRoll(&rotation,c.ypr.x,c.ypr.y,c.ypr.z);
121 D3DXMatrixTranslation(&shift,-c.hinge.x,-c.hinge.y,-c.hinge.z);D3DXMatrixIdentity(&hinge);
122 if(D3DXVec3LengthSq(&c.axis)>.000001f)D3DXMatrixRotationAxis(&hinge,&c.axis,e*c.extent);
123 const auto p=c.xyz+c.hinge+c.extend*e;D3DXMatrixTranslation(&end,p.x,p.y,p.z);
124 transforms[i]=rotation*shift*hinge*end;
125 }
126 };
127 pose(.1f);rain.Update(.00001f,0,{},{},transforms,1,false);
128 double volumeBefore=0;
129 for(size_t i=0;i<rain.PaneCount();++i)
130 {
131 auto& water=WindshieldRainTestAccess::Water(rain,i);
132 for(int y=0;y<30;++y)for(int x=0;x<30;++x)
133 water.Impact({(x+.5f)*water.Width()/30,(y+.5f)*water.Height()/30},.0015f,false);
134 water.Rebuild();for(const auto& d:water.Drops())volumeBefore+=d.radius*d.radius*d.radius;
135 }
136 pose(.14f);rain.Update(.00001f,0,{},{},transforms,1,true);
137 double volumeAfter=0;size_t displaced=0,stationary=0;
138 for(size_t i=0;i<rain.PaneCount();++i)for(const auto& d:WindshieldRainTestAccess::Water(rain,i).Drops())
139 {
140 volumeAfter+=d.radius*d.radius*d.radius;
141 if(std::hypot(d.velocity.x,d.velocity.y)>.1f)++displaced;else ++stationary;
142 }
143 Check(displaced>10 && stationary>100,"authored C-2 blade transforms displace only contacted water");
144 Check(volumeAfter>volumeBefore*.95 && volumeAfter<=volumeBefore*1.00001,
145 "C-2 sweep retains collected water rather than erasing it");
146 std::cout<<"PASS: shipped C-2 blades displace "<<displaced<<" beads; "<<stationary<<" untouched; volume retained "<<volumeAfter/volumeBefore<<".\n";
147}
148static void CheckConnectedGlass()
149{
150 auto glass=Glass("C-2 Dasher INT",2);
151 WindshieldRainRenderer rain; rain.AddGlass(0,glass.data(),glass.size()); rain.FinishGeometry();
152 Check(rain.PaneCount()==1,"C-2 bent front windshield has one continuous rain chart");
153 // The authored shared edge is at DAW x=1.012 m, z=1.110 m.
154 const auto above=WindshieldRainTestAccess::Map(rain,{.00105f,.0014f,.00112f});
155 const auto below=WindshieldRainTestAccess::Map(rain,{.00097f,.0014f,.001085f});
156 auto& water=WindshieldRainTestAccess::Water(rain);
157 water.Impact(above,.0025f);
158 WindshieldRain::Point force{below.x-above.x,below.y-above.y};
159 const float length=std::hypot(force.x,force.y); force.x*=11.27f/length; force.y*=11.27f/length;
160 for(int i=0;i<60;++i) water.Update(1.f/30,0,force,{},1.f);
161 const auto d=Largest(water).position;
162 Check((d.x-above.x)*force.x+(d.y-above.y)*force.y > length*11.27f,
163 "C-2 bead continues onto lower glass instead of disappearing at the bend");
164 // Wiping must test distance to the authored facet, not the average chart.
165 water.Clear();
166 const auto& a=glass[6]; const auto& b=glass[7]; const auto& c=glass[8];
167 const D3DXVECTOR3 center((a.x+b.x+c.x)/3,(a.y+b.y+c.y)/3,(a.z+b.z+c.z)/3);
168 water.Impact(WindshieldRainTestAccess::Map(rain,center),.0015f); water.Rebuild();
169 rain.AddWiper(1,glass.data()+6,3);
170 D3DXMATRIX identity; D3DXMatrixIdentity(&identity);
171 std::vector<D3DXMATRIX> transforms(2,identity);
172 rain.Update(.00001f,0,{0,0,0},{0,0,0},transforms,1.f,false);
173 transforms[1]._41=.0000001f;
174 rain.Update(.00001f,0,{0,0,0},{0,0,0},transforms,1.f,true);
175 Check(!rain.Wet(),"wiper on bent C-2 facet clears the shared rain chart");
176 // Two tilted quads without a shared edge remain separate, even in one module.
177 auto first=Quad(-.001f,0,.001f,0), second=Quad(.0001f,.0011f,.001f,0);
178 for(auto& v:second) v.z=v.x*.2f;
179 rain.Clear(); rain.AddGlass(0,first.data(),first.size()); rain.AddGlass(0,second.data(),second.size()); rain.FinishGeometry();
180 Check(rain.PaneCount()==2,"a bezel/gap is not joined into one rain chart");
181 // Include the small quarter windows and both halves of each main side
182 // pane. Their small km-squared cross products normalized to zero on Win32.
183 for (bool left : {false,true})
184 {
185 const auto side=Glass("C-2 Dasher INT",1,left);
186 rain.Clear(); rain.AddGlass(0,side.data(),side.size()); rain.FinishGeometry();
187 Check(rain.PaneCount()==1,"all coplanar C-2 side triangles have a valid shared water chart");
188 for (size_t t=0;t<side.size();t+=3) for (int e=0;e<3;++e)
189 {
190 const auto& a=side[t+e]; const auto& b=side[t+(e+1)%3];
191 const auto p=WindshieldRainTestAccess::Map(rain,{a.x,a.y,a.z});
192 const auto q=WindshieldRainTestAccess::Map(rain,{b.x,b.y,b.z});
193 const D3DXVECTOR3 edge(a.x-b.x,a.y-b.y,a.z-b.z);
194 Check(std::abs(std::hypot(p.x-q.x,p.y-q.y)-1000*D3DXVec3Length(&edge))<.0001f,
195 "small quarter/main side facets retain metric size instead of collapsing to a line");
196 }
197 }
198 std::cout << "PASS: C-2 continuous bent glass and separated-window isolation.\n";
199}
200// The real scene mixes cockpit and world depth ranges in one depth buffer.
201// Nearby ground used to cut off rain at a fixed line despite being BEHIND glass.
202static void CheckParkedGroundDepth(IDirect3DDevice9* device, ID3DXEffect* effect,
203 D3DMULTISAMPLE_TYPE samples, const char* output)
204{
205 using DepthLayout=WindshieldRainRenderer::DepthLayout;
206 ComPtr<IDirect3DStateBlock9> saved;
207 HR(device->CreateStateBlock(D3DSBT_ALL,&saved),"save parked test state");
208 ComPtr<IDirect3DSurface9> oldTarget,oldDepth,target,depth,resolved,readback;
209 HR(device->GetRenderTarget(0,&oldTarget),"save parked target");
210 device->GetDepthStencilSurface(&oldDepth);
211 HR(device->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,samples,0,FALSE,&target,nullptr),"create parked target");
212 HR(device->CreateDepthStencilSurface(Width,Height,D3DFMT_D24S8,samples,0,TRUE,&depth,nullptr),"create parked depth");
213 HR(device->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,D3DMULTISAMPLE_NONE,0,FALSE,&resolved,nullptr),"create parked resolve");
214 HR(device->CreateOffscreenPlainSurface(Width,Height,D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&readback,nullptr),"create parked readback");
215 HR(device->SetRenderTarget(0,target.Get()),"bind parked target");
216 HR(device->SetDepthStencilSurface(depth.Get()),"bind parked depth");
217 D3DXMATRIX identity,view,cockpitProjection,worldProjection;
218 D3DXMatrixIdentity(&identity);
219 // Kilometres: exactly the near/far ranges from SetProjectionMatrices.
220 D3DXMatrixPerspectiveFovRH(&cockpitProjection,1.3f,float(Width)/Height,.000025f,.16f);
221 D3DXMatrixPerspectiveFovRH(&worldProjection,1.3f,float(Width)/Height,.001f,384.f);
222 const auto depthAt=[](const D3DXMATRIX& projection,float distance) {
223 return (-distance*projection._33+projection._43)/distance;
224 };
225 Check(depthAt(worldProjection,.01f)<depthAt(cockpitProjection,.001f),
226 "fixture reproduces 10 m ground falsely testing nearer than 1 m glass");
227 for(bool left : {true,false})
228 {
229 const auto glass=Glass("e10cockpit1",0,left);
230 WindshieldRainRenderer rain; rain.AddGlass(0,glass.data(),glass.size()); rain.FinishGeometry();
231 const D3DXVECTOR3 eye(0,.0011f,.0011f),at(left ? -.001f : .001f,.0011f,.0009f),up(0,0,1);
232 D3DXMatrixLookAtRH(&view,&eye,&at,&up);
233 std::vector<D3DXMATRIX> transforms(1,identity);
234 for(int i=0;i<90;++i) rain.Update(1.f/30,1,{0,0,-11.27f},{0,0,0},transforms,1188.f/1013.25f,false);
235 const auto frame=[&](bool ground,DepthLayout layout,const char* suffix,bool material=false) {
236 HR(device->Clear(0,nullptr,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,0xff808080,1,0),"clear parked frame");
237 HR(device->BeginScene(),"begin parked frame");
238 device->SetVertexShader(nullptr); device->SetPixelShader(nullptr);
239 device->SetRenderState(D3DRS_LIGHTING,FALSE); device->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);
240 device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE); device->SetRenderState(D3DRS_ALPHATESTENABLE,FALSE);
241 device->SetRenderState(D3DRS_ZENABLE,TRUE); device->SetRenderState(D3DRS_ZWRITEENABLE,TRUE);
242 device->SetRenderState(D3DRS_ZFUNC,D3DCMP_ALWAYS);
243 device->SetRenderState(D3DRS_STENCILENABLE,TRUE); device->SetRenderState(D3DRS_STENCILFUNC,D3DCMP_ALWAYS);
244 device->SetRenderState(D3DRS_STENCILPASS,D3DSTENCILOP_REPLACE);
245 device->SetRenderState(D3DRS_STENCILFAIL,D3DSTENCILOP_KEEP); device->SetRenderState(D3DRS_STENCILZFAIL,D3DSTENCILOP_KEEP);
246 device->SetTextureStageState(0,D3DTSS_COLOROP,D3DTOP_SELECTARG1);
247 device->SetTextureStageState(0,D3DTSS_COLORARG1,D3DTA_DIFFUSE);
248 device->SetTextureStageState(0,D3DTSS_ALPHAOP,D3DTOP_SELECTARG1);
249 device->SetTextureStageState(0,D3DTSS_ALPHAARG1,D3DTA_DIFFUSE);
250 device->SetTextureStageState(1,D3DTSS_COLOROP,D3DTOP_DISABLE);
251 device->SetFVF(D3DFVF_XYZRHW|D3DFVF_DIFFUSE);
252 // Interior (4), foreground wiper (3), and exterior cowl behind glass (3).
253 struct ScreenVertex {float x,y,z,rhw;DWORD color;};
254 for(int part=0;part<3;++part)
255 {
256 device->SetRenderState(D3DRS_STENCILREF,part==0 ? 4 : 3);
257 const float x=float(Width/2-180+part*130),z=depthAt(cockpitProjection,part==2 ? .004f : .0005f);
258 const DWORD color=part==2 ? 0xff808080 : 0xffb02020;
259 const ScreenVertex quad[]={{x-.5f,219.5f,z,1,color},{x+79.5f,219.5f,z,1,color},
260 {x-.5f,319.5f,z,1,color},{x+79.5f,319.5f,z,1,color}};
261 HR(device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP,2,quad,sizeof(ScreenVertex)),"draw cockpit masks");
262 }
263 if(ground)
264 {
265 device->SetRenderState(D3DRS_STENCILREF,3); device->SetRenderState(D3DRS_STENCILFUNC,D3DCMP_GREATER);
266 device->SetRenderState(D3DRS_STENCILPASS,D3DSTENCILOP_KEEP); device->SetRenderState(D3DRS_ZFUNC,D3DCMP_LESS);
267 device->SetFVF(D3DFVF_XYZ|D3DFVF_DIFFUSE);
268 device->SetTransform(D3DTS_WORLD,&identity); device->SetTransform(D3DTS_VIEW,&view);
269 device->SetTransform(D3DTS_PROJECTION,&worldProjection);
270 struct GroundVertex {float x,y,z;DWORD color;};
271 const GroundVertex terrain[]={{-.1f,-.1f,0,0xff808080},{.1f,-.1f,0,0xff808080},
272 {-.1f,.1f,0,0xff808080},{.1f,.1f,0,0xff808080}};
273 HR(device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP,2,terrain,sizeof(GroundVertex)),"draw nearby world ground");
274 }
275 device->SetRenderState(D3DRS_ZFUNC,D3DCMP_ALWAYS);
276 device->SetRenderState(D3DRS_STENCILREF,4); device->SetRenderState(D3DRS_STENCILFUNC,D3DCMP_GREATER);
277 device->SetRenderState(D3DRS_STENCILPASS,D3DSTENCILOP_KEEP);
278 HR(rain.Render(device,effect,transforms,view*cockpitProjection,1,layout),"rain over mixed depth ranges");
279 if (material)
280 {
281 // The real glass/overlay passes share this draw policy. Paint
282 // solid white to detect even one pixel over a foreground part.
283 effect->SetTechnique("WindshieldRain");
284 const auto wvp=view*cockpitProjection; effect->SetMatrix("matWorldViewProj",&wvp);
285 device->SetFVF(D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1);
286 HR(effect->Begin(nullptr,0),"begin glass visibility check");
287 HR(effect->BeginPass(1),"begin glass visibility pass");
289 return device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,UINT(glass.size()/3),glass.data(),sizeof(Vertex));
290 }),"draw glass with shared visibility");
291 HR(effect->EndPass(),"end glass visibility pass"); HR(effect->End(),"end glass visibility check");
292 effect->SetTechnique("TShader");
293 }
294 DWORD value;
295 device->GetRenderState(D3DRS_ZFUNC,&value); Check(value==D3DCMP_ALWAYS,"restore parked depth comparison");
296 device->GetRenderState(D3DRS_ZWRITEENABLE,&value); Check(value==TRUE,"restore parked depth writes");
297 device->GetRenderState(D3DRS_STENCILREF,&value); Check(value==4,"restore parked stencil reference");
298 device->GetRenderState(D3DRS_STENCILFUNC,&value); Check(value==D3DCMP_GREATER,"restore parked stencil comparison");
299 HR(device->EndScene(),"end parked frame");
300 HR(device->StretchRect(target.Get(),nullptr,resolved.Get(),nullptr,D3DTEXF_NONE),"resolve parked frame");
301 HR(device->GetRenderTargetData(resolved.Get(),readback.Get()),"read parked frame");
302 if(output && samples==D3DMULTISAMPLE_NONE)
303 HR(D3DXSaveSurfaceToFileA((std::string(output)+(left ? "-parked-left-" : "-parked-right-")+suffix+".png").c_str(),D3DXIFF_PNG,readback.Get(),nullptr,nullptr),"save parked preview");
304 D3DLOCKED_RECT lock{}; HR(readback->LockRect(&lock,nullptr,D3DLOCK_READONLY),"lock parked frame");
305 std::vector<DWORD> pixels(Width*Height);
306 for(int y=0;y<Height;++y) memcpy(pixels.data()+y*Width,static_cast<char*>(lock.pBits)+y*lock.Pitch,Width*4);
307 HR(readback->UnlockRect(),"unlock parked frame"); return pixels;
308 };
309 const auto reference=frame(false,DepthLayout::Unified,"reference");
310 const auto broken=frame(true,DepthLayout::Unified,"before");
311 const auto corrected=frame(true,DepthLayout::CockpitAndWorld,"after");
312 size_t lost=0,changed=0,behindWet=0;
313 for(size_t i=0;i<reference.size();++i) {lost+=broken[i]!=reference[i];changed+=corrected[i]!=reference[i];}
314 for(int y=225;y<315;++y) for(int x=Width/2-175;x<Width/2+25;++x)
315 if(x<Width/2-105 || x>=Width/2-45) Check(corrected[y*Width+x]==0xffb02020,"interior and foreground wiper remain sharp");
316 for(int y=225;y<315;++y) for(int x=Width/2+85;x<Width/2+155;++x)
317 behindWet+=corrected[y*Width+x]!=0xff808080;
318 std::cout << "Parked E-10 " << (left ? "left" : "right") << " " << int(samples)
319 << "x: old missing/changed=" << lost << "; corrected differences=" << changed << "; wet cowl=" << behindWet << std::endl;
320 Check(lost>1000,"nearby ground reproduces the fixed rain cutoff");
321 Check(changed==0,"ground behind glass cannot cut off the rain or its refraction mask");
322 Check(behindWet>20,"cockpit exterior behind glass still refracts");
323 const auto visibleMaterial=frame(false,DepthLayout::CockpitAndWorld,"-material",true);
324 Check(frame(true,DepthLayout::CockpitAndWorld,"-material-ground",true)==visibleMaterial,
325 "glass markings/overlays stay visible over ground with a different depth projection");
326 for(int y=225;y<315;++y) for(int x=Width/2-175;x<Width/2+25;++x)
327 if(x<Width/2-105 || x>=Width/2-45) Check(visibleMaterial[y*Width+x]==0xffb02020,
328 "glass material cannot expose buried glass over cockpit interior or exterior foreground");
329 size_t visibleCowl=0;
330 for(int y=225;y<315;++y) for(int x=Width/2+85;x<Width/2+155;++x)
331 visibleCowl+=(visibleMaterial[y*Width+x]&0xffffff)==0xffffff;
332 Check(visibleCowl>20,"glass material remains visible in front of the exterior cowl");
333
334 }
335 HR(device->SetRenderTarget(0,oldTarget.Get()),"restore parked target");
336 HR(device->SetDepthStencilSurface(oldDepth.Get()),"restore parked depth");
337 HR(saved->Apply(),"restore parked test state");
338}
339static void CheckWetFilmClarity(IDirect3DDevice9* device, ID3DXEffect* effect)
340{
341 ComPtr<IDirect3DStateBlock9> saved;
342 HR(device->CreateStateBlock(D3DSBT_ALL,&saved),"save film test state");
343 const auto technique=effect->GetCurrentTechnique();
344 ComPtr<IDirect3DSurface9> target,readback;
345 HR(device->GetRenderTarget(0,&target),"get film target");
346 HR(device->CreateOffscreenPlainSurface(Width,Height,D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&readback,nullptr),"create film readback");
347 ComPtr<IDirect3DTexture9> scene,water,mask;
348 HR(device->CreateTexture(Width,Height,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,&scene,nullptr),"create fine detail scene");
349 HR(device->CreateTexture(1,1,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,&water,nullptr),"create flat water film");
350 HR(device->CreateTexture(1,1,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,&mask,nullptr),"create visible glass mask");
351 D3DLOCKED_RECT lock{};
352 HR(scene->LockRect(0,&lock,nullptr,0),"lock fine detail scene");
353 for(int y=0;y<Height;++y) for(int x=0;x<Width;++x)
354 reinterpret_cast<DWORD*>(static_cast<char*>(lock.pBits)+y*lock.Pitch)[x]=
355 ((x/5+y/5)%2)?0xffe0e0e0:0xff202020;
356 HR(scene->UnlockRect(0),"unlock fine detail scene");
357 HR(mask->LockRect(0,&lock,nullptr,0),"lock mask");
358 *static_cast<DWORD*>(lock.pBits)=0xffffffff;
359 HR(mask->UnlockRect(0),"unlock mask");
360 D3DXMATRIX identity; D3DXMatrixIdentity(&identity);
361 const D3DXVECTOR4 u(.5f,0,0,.5f),v(0,-.5f,0,.5f),texel(1.f/Width,1.f/Height,0,0);
362 effect->SetTechnique("WindshieldRain"); effect->SetMatrix("matWorldViewProj",&identity);
363 effect->SetVector("RainU",&u); effect->SetVector("RainV",&v); effect->SetVector("RainSceneTexel",&texel);
364 effect->SetTexture("RainScene",scene.Get()); effect->SetTexture("RainWater",water.Get());
365 const D3DXVECTOR4 filmExtent(1,1,1,1); // constant 1x1 water texture
366 effect->SetVector("RainExtent",&filmExtent);
367 effect->SetTexture("RainVisibility",mask.Get());
368 device->SetRenderState(D3DRS_ZENABLE,FALSE); device->SetRenderState(D3DRS_STENCILENABLE,FALSE);
369 device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE); device->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);
370 device->SetFVF(D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1);
371 const auto glass=Quad(-1,1,1,-1);
372 const auto contrast=[&](unsigned int height) {
373 HR(water->LockRect(0,&lock,nullptr,0),"lock water film");
374 *static_cast<DWORD*>(lock.pBits)=0xff800080u | (height<<8);
375 HR(water->UnlockRect(0),"unlock water film");
376 HR(device->BeginScene(),"begin film frame");
377 HR(effect->Begin(nullptr,0),"begin film effect"); HR(effect->BeginPass(0),"begin film pass");
378 HR(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,glass.data(),sizeof(Vertex)),"render flat film");
379 HR(effect->EndPass(),"end film pass"); HR(effect->End(),"end film effect");
380 HR(device->EndScene(),"end film frame");
381 HR(device->GetRenderTargetData(target.Get(),readback.Get()),"read film frame");
382 HR(readback->LockRect(&lock,nullptr,D3DLOCK_READONLY),"lock film frame");
383 double contrast=0;
384 for(int y=20;y<Height-20;++y) for(int x=20;x<Width-20;++x)
385 contrast+=std::abs(int(reinterpret_cast<DWORD*>(static_cast<char*>(lock.pBits)+y*lock.Pitch)[x]&255)-128);
386 HR(readback->UnlockRect(),"unlock film frame");
387 return contrast/((Width-40)*(Height-40));
388 };
389 const double dry=contrast(0),light=contrast(25),thin=contrast(77),heavy=contrast(230);
390 std::cout << "Flat-film detail contrast: dry=" << dry << " light=" << light << " thin=" << thin << " heavy=" << heavy << '\n';
391 Check(dry>90 && light==dry && thin==dry && heavy<dry*.9 && heavy>dry*.45,
392 "thin residue stays sharp while thicker water adds restrained local blur");
393 effect->SetTexture("RainScene",nullptr); effect->SetTexture("RainWater",nullptr); effect->SetTexture("RainVisibility",nullptr);
394 effect->SetTechnique(technique); HR(saved->Apply(),"restore film test state");
395}
396static void CheckCockpitForceDirection()
397{
398 D3DXMATRIX pitch,yaw,upright,inverse;
399 D3DXMatrixRotationX(&pitch,D3DX_PI*.5f);
400 D3DXMatrixRotationY(&yaw,D3DX_PI);
401 D3DXMatrixRotationZ(&upright,D3DX_PI); // actual SetProjectionMatrices convention
402 const auto display=pitch*yaw*upright;
403 const auto physics=WindshieldRainRenderer::ToPhysicsTransform(pitch*yaw);
404 D3DXMatrixInverse(&inverse,nullptr,&physics);
405 for(const char* cockpit : {"C-2A Dasher INT","e11cockpit1"})
406 {
407 const auto glass=Glass(cockpit,2);
408 float slowest=1.f,largestSideRatio=0;
409 for(size_t t=0;t<glass.size();t+=3)
410 {
411 const auto pos=[](const Vertex& v) {return D3DXVECTOR3(v.x,v.y,v.z);};
412 auto u=pos(glass[t+1])-pos(glass[t]);
413 const auto e2=pos(glass[t+2])-pos(glass[t]);
414 D3DXVECTOR3 n,v;
415 D3DXVec3Cross(&n,&u,&e2); D3DXVec3Normalize(&n,&n);
416 D3DXVec3Normalize(&u,&u); D3DXVec3Cross(&v,&n,&u);
417 for(float windSpeed : {0.f,-4.f,4.f}) for(float pressure : {1188.f,2630.397f})
418 {
419 D3DXVECTOR3 gravity(0,-11.27f,0), wind(0,0,windSpeed);
420 const auto force=WindshieldRainRenderer::ProjectAcceleration(gravity,inverse,n,u,v);
421 D3DXVec3TransformNormal(&wind,&wind,&inverse);
422 auto water=std::make_unique<WindshieldRain::Surface>();
423 water->Impact({.5f,.5f},.007f);
424 for(int i=0;i<30;++i) water->Update(1.f/30,0,force,
425 {D3DXVec3Dot(&wind,&u),D3DXVec3Dot(&wind,&v)},pressure/1013.25f);
426 const auto p=Largest(*water).position;
427 D3DXVECTOR3 motion=u*(p.x-.5f)+v*(p.y-.5f);
428 D3DXVec3TransformNormal(&motion,&motion,&display);
429 Check(motion.y<-.01f,"front panes drain visibly DOWN at rest in calm/4 m/s head or tailwind");
430 Check(std::abs(motion.x)<-motion.y*.35f,"glass roughness and low wind deflect runoff without overpowering downward gravity");
431 slowest=(std::min)(slowest,-motion.y);
432 largestSideRatio=(std::max)(largestSideRatio,std::abs(motion.x)/-motion.y);
433 }
434 const auto sideways=WindshieldRainRenderer::ProjectAcceleration({20,0,0},inverse,n,u,v);
435 D3DXVECTOR3 motion=u*sideways.x+v*sideways.y;
436 D3DXVec3TransformNormal(&motion,&motion,&display);
437 Check(motion.x>1,"lateral vehicle acceleration still moves water sideways");
438 WindshieldRain::Surface oneG,twoG;
439 for(auto* w:{&oneG,&twoG}) w->Impact({.5f,.5f},.0025f);
440 const auto load1=WindshieldRainRenderer::ProjectAcceleration({0,-9.80665f,0},inverse,n,u,v);
441 const auto load2=WindshieldRainRenderer::ProjectAcceleration({0,-19.6133f,0},inverse,n,u,v);
442 oneG.Update(.25f,0,load1,{},1.f); twoG.Update(.25f,0,load2,{},1.f);
443 const auto p1=Largest(oneG).position,p2=Largest(twoG).position;
444 auto m1=u*(p1.x-.5f)+v*(p1.y-.5f),m2=u*(p2.x-.5f)+v*(p2.y-.5f);
445 D3DXVec3TransformNormal(&m1,&m1,&display); D3DXVec3TransformNormal(&m2,&m2,&display);
446 Check(m1.y<0 && m2.y<m1.y*1.8f,"positive liftoff G increases downward flow on actual front glass");
447 }
448 std::cout << "PASS: " << cockpit << " minimum downward travel " << slowest*100 << " cm/s; sideways/down ratio "
449 << largestSideRatio << "; 1188/2630 mB, 11.27 m/s2 gravity, calm/4 m/s head/tailwind.\n";
450 }
451}
452static void CheckForwardAirflow()
453{
454 D3DXMATRIX pitch,yaw,upright,inverse;
455 D3DXMatrixRotationX(&pitch,D3DX_PI*.5f); D3DXMatrixRotationY(&yaw,D3DX_PI);
456 D3DXMatrixRotationZ(&upright,D3DX_PI);
457 const auto display=pitch*yaw*upright;
458 const auto physics=WindshieldRainRenderer::ToPhysicsTransform(pitch*yaw);
459 D3DXMatrixInverse(&inverse,nullptr,&physics);
460 // Propulsion reports forward TAS as -relativeWindTrueKms.z.
461 for(const char* cockpit : {"C-2 Dasher INT","C-2A Dasher INT","e11cockpit1","stratomaster_06-hex"})
462 {
463 auto glass=Glass(cockpit,2);
464 if(std::string(cockpit)=="C-2 Dasher INT")
465 {
466 const auto ypr=GlassRotation("C-2 Dasher INT");
467 D3DXMATRIX nominal;D3DXMatrixRotationYawPitchRoll(&nominal,ypr.x,ypr.y,ypr.z);
468 for(auto& vertex:glass)
469 {
470 D3DXVECTOR3 p(vertex.x,vertex.y,vertex.z);
471 D3DXVec3TransformCoord(&p,&p,&nominal);vertex.x=p.x;vertex.y=p.y;vertex.z=p.z;
472 }
473 }
474 float slowest=1000;
475 for(size_t t=0;t<glass.size();t+=3)
476 {
477 const auto pos=[](const Vertex& v) {return D3DXVECTOR3(v.x,v.y,v.z);};
478 auto u=pos(glass[t+1])-pos(glass[t]); const auto e2=pos(glass[t+2])-pos(glass[t]);
479 D3DXVECTOR3 n,v; D3DXVec3Cross(&n,&u,&e2); D3DXVec3Normalize(&n,&n);
480 D3DXVec3Normalize(&u,&u); D3DXVec3Cross(&v,&n,&u);
481 const auto force=WindshieldRainRenderer::ProjectAcceleration({0,-11.27f,0},inverse,n,u,v);
482 for(float pressure : {1188.f,2630.397f}) for(float headwind : {-103.f,103.f,-80.f/3.6f})
483 {
484 D3DXVECTOR3 wind(0,0,headwind); D3DXVec3TransformNormal(&wind,&wind,&inverse);
485 auto water=std::make_unique<WindshieldRain::Surface>(2.f,2.f);
486 water->Impact({1,1},.0025f);
487 for(int i=0;i<3;++i) water->Update(1.f/30,0,force,
488 {D3DXVec3Dot(&wind,&u),D3DXVec3Dot(&wind,&v)},pressure/1013.25f,std::abs(headwind));
489 Check(water->Drops().size()==1,"airflow test retains a brief-lived impact");
490 const auto velocity=water->Drops()[0].velocity;
491 D3DXVECTOR3 motion=u*velocity.x+v*velocity.y; D3DXVec3TransformNormal(&motion,&motion,&display);
492 const float minimum=std::abs(headwind)>100 ? .25f : .003f;
493 if (!(headwind<0 ? motion.y>minimum : motion.y<-minimum)) std::cout << "Airflow failure " << cockpit << " tri " << t/3 << " pressure " << pressure << " wind " << headwind << " vertical " << motion.y << std::endl;
494 Check(headwind<0 ? motion.y>minimum : motion.y<-minimum,"headwind drives UP at 80 kph and 200 knots; reversed airflow moves DOWN");
495 if(headwind<0) slowest=(std::min)(slowest,motion.y);
496 }
497 }
498 std::cout << "PASS: " << cockpit << " 80 kph/200-knot headwind; minimum upward speed " << slowest << " m/s.\n";
499 }
500}
501static void CheckForegroundOcclusion(IDirect3DDevice9* device, ID3DXEffect* effect, D3DMULTISAMPLE_TYPE samples)
502{
503 ComPtr<IDirect3DSurface9> oldTarget,oldDepth,target,depth,resolved,readback;
504 HR(device->GetRenderTarget(0,&oldTarget),"save target");
505 device->GetDepthStencilSurface(&oldDepth);
506 ComPtr<IDirect3DStateBlock9> saved;
507 HR(device->CreateStateBlock(D3DSBT_ALL,&saved),"save occlusion test state");
508 HR(device->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,samples,0,FALSE,&target,nullptr),"create occlusion target");
509 HR(device->CreateDepthStencilSurface(Width,Height,D3DFMT_D24S8,samples,0,TRUE,&depth,nullptr),"create cockpit depth/stencil");
510 HR(device->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,D3DMULTISAMPLE_NONE,0,FALSE,&resolved,nullptr),"create occlusion resolve");
511 HR(device->CreateOffscreenPlainSurface(Width,Height,D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&readback,nullptr),"create occlusion readback");
512 HR(device->SetRenderTarget(0,target.Get()),"bind occlusion target");
513 HR(device->SetDepthStencilSurface(depth.Get()),"bind cockpit depth/stencil");
514 auto vertices=Quad(-.0008f,.0008f,.0004f,-.0004f);
516 rain.AddGlass(0,vertices.data(),vertices.size()); rain.FinishGeometry();
517 D3DXMATRIX identity,projection;
518 D3DXMatrixIdentity(&identity); D3DXMatrixOrthoLH(&projection,.002f,.001125f,-1,1);
519 std::vector<D3DXMATRIX> transforms(1,identity);
520 // D3DXVECTOR3's empty constructor leaves components uninitialized: pass explicit zero airflow.
521 for(int i=0;i<300;++i) rain.Update(1.f/30,1,{0,-11.27f,0},{0,0,0},transforms,1.f,false);
522 const auto frame=[&](int left,float objectDepth,bool stencil,bool wet) {
523 HR(device->Clear(0,nullptr,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,0xff283d4e,1,0),"clear occlusion frame");
524 for(int y=0;y<Height;y+=12) for(int x=0;x<Width;x+=12)
525 {
526 D3DRECT rect{x,y,(std::min)(x+12,Width),(std::min)(y+12,Height)};
527 HR(device->Clear(1,&rect,D3DCLEAR_TARGET,((x/12+y/12)%2)?0xff62798e:0xff283d4e,1,0),"paint exterior grid");
528 }
529 HR(device->BeginScene(),"begin occlusion frame");
530 HR(device->SetVertexShader(nullptr),"use fixed foreground vertex path");
531 HR(device->SetPixelShader(nullptr),"use fixed foreground color path");
532 HR(device->SetFVF(D3DFVF_XYZRHW|D3DFVF_DIFFUSE),"set foreground FVF");
533 device->SetRenderState(D3DRS_LIGHTING,FALSE);
534 device->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);
535 device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
536 device->SetRenderState(D3DRS_ZENABLE,TRUE);
537 device->SetRenderState(D3DRS_ZWRITEENABLE,TRUE);
538 device->SetRenderState(D3DRS_ZFUNC,D3DCMP_LESS);
539 device->SetRenderState(D3DRS_STENCILENABLE,stencil);
540 device->SetRenderState(D3DRS_STENCILREF,4);
541 device->SetRenderState(D3DRS_STENCILFUNC,D3DCMP_ALWAYS);
542 device->SetRenderState(D3DRS_STENCILPASS,D3DSTENCILOP_REPLACE);
543 device->SetTextureStageState(0,D3DTSS_COLOROP,D3DTOP_SELECTARG1);
544 device->SetTextureStageState(0,D3DTSS_COLORARG1,D3DTA_DIFFUSE);
545 device->SetTextureStageState(0,D3DTSS_ALPHAOP,D3DTOP_SELECTARG1);
546 device->SetTextureStageState(0,D3DTSS_ALPHAARG1,D3DTA_DIFFUSE);
547 device->SetTextureStageState(1,D3DTSS_COLOROP,D3DTOP_DISABLE);
548 struct ScreenVertex {float x,y,z,rhw;DWORD color;};
549 for(int x=left;x<left+180;x+=6)
550 {
551 const DWORD color=((x-left)/6)%2?0xfff01818:0xff901010;
552 const float a=float(x)-.5f,b=float(x+6)-.5f;
553 const ScreenVertex quad[]={{a,149.5f,objectDepth,1,color},{b,149.5f,objectDepth,1,color},
554 {a,389.5f,objectDepth,1,color},{b,389.5f,objectDepth,1,color}};
555 HR(device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP,2,quad,sizeof(ScreenVertex)),"draw opaque object");
556 }
557 // Real cockpit glass inherits ALWAYS and the cockpit stencil exclusion.
558 device->SetRenderState(D3DRS_ZFUNC,D3DCMP_ALWAYS);
559 device->SetRenderState(D3DRS_STENCILFUNC,D3DCMP_GREATER);
560 device->SetRenderState(D3DRS_STENCILPASS,D3DSTENCILOP_KEEP);
561 if(wet) HR(rain.Render(device,effect,transforms,projection),"render rain over occlusion fixture");
562 DWORD state;
563 HR(device->GetRenderState(D3DRS_ZFUNC,&state),"read depth comparison");
564 Check(state==D3DCMP_ALWAYS,"rain restores caller's depth comparison");
565 HR(device->GetRenderState(D3DRS_ZWRITEENABLE,&state),"read depth writes");
566 Check(state==TRUE,"rain does not leak its depth-write state");
567 HR(device->EndScene(),"end occlusion frame");
568 HR(device->StretchRect(target.Get(),nullptr,resolved.Get(),nullptr,D3DTEXF_NONE),"resolve occlusion frame");
569 HR(device->GetRenderTargetData(resolved.Get(),readback.Get()),"read occlusion pixels");
570 D3DLOCKED_RECT lock{}; HR(readback->LockRect(&lock,nullptr,D3DLOCK_READONLY),"lock occlusion pixels");
571 std::vector<DWORD> pixels(Width*Height);
572 for(int y=0;y<Height;++y) memcpy(pixels.data()+y*Width,static_cast<char*>(lock.pBits)+y*lock.Pitch,Width*4);
573 HR(readback->UnlockRect(),"unlock occlusion pixels");
574 return pixels;
575 };
576 for(bool stencil : {true,false}) for(int left : {230,410,590})
577 {
578 const auto dry=frame(left,.25f,stencil,false),wet=frame(left,.25f,stencil,true);
579 size_t leaked=0,changedForeground=0,changedGlass=0;
580 for(int y=80;y<460;++y) for(int x=100;x<860;++x)
581 {
582 const int i=y*Width+x;
583 const bool foreground=x>=left && x<left+180 && y>=150 && y<390;
584 if(foreground) changedForeground+=wet[i]!=dry[i];
585 else
586 {
587 changedGlass+=wet[i]!=dry[i];
588 if(x<left-1 || x>left+180 || y<149 || y>390)
589 leaked+=int((wet[i]>>16)&255)>int((wet[i]>>8)&255)+8;
590 }
591 }
592 std::cout << "Occlusion " << int(samples) << "x stencil=" << stencil << " x=" << left
593 << " foreground changed=" << changedForeground << " leaked=" << leaked << " exterior=" << changedGlass << "\n";
594 Check(changedForeground==0,"objects IN FRONT of glass remain pixel-identical");
595 Check(leaked==0,"foreground colors never leak into refracted glass beside the silhouette");
596 Check(changedGlass>1000,"visible glass still distorts the exterior");
597 }
598 const auto behindDry=frame(410,.75f,false,false),behindWet=frame(410,.75f,false,true);
599 size_t behindChanged=0;
600 for(int y=160;y<380;++y) for(int x=420;x<580;++x) behindChanged+=behindDry[y*Width+x]!=behindWet[y*Width+x];
601 Check(behindChanged>100,"objects BEHIND glass still refract");
602 const auto beforeReset=frame(410,.25f,true,true);
603 rain.OnLostDevice();
604 Check(frame(410,.25f,true,true)==beforeReset,"mask resources recreate without changing water");
605 HR(device->SetRenderTarget(0,oldTarget.Get()),"restore target");
606 HR(device->SetDepthStencilSurface(oldDepth.Get()),"restore depth/stencil");
607 HR(saved->Apply(),"restore occlusion test state");
608 std::cout << "PASS: moving foreground silhouettes, depth/stencil isolation, background refraction and resource recreation (" << int(samples) << "x).\n";
609}
610// Terrain enables depth writes inside TShader Begin/End, before vehicles render.
611// A state declaration on ANY pass (even unused windshield P9) changes what End
612// restores, so test the shared effect as well as the resulting opaque pixels.
613static void CheckOpaqueDepthAfterTerrain(IDirect3DDevice9* device, ID3DXEffect* effect, D3DMULTISAMPLE_TYPE samples)
614{
615 ComPtr<IDirect3DStateBlock9> saved;
616 HR(device->CreateStateBlock(D3DSBT_ALL,&saved),"save opaque test state");
617 ComPtr<IDirect3DSurface9> oldTarget,oldDepth,target,depth,resolved,readback;
618 HR(device->GetRenderTarget(0,&oldTarget),"save opaque target");
619 device->GetDepthStencilSurface(&oldDepth);
620 HR(device->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,samples,0,FALSE,&target,nullptr),"create opaque target");
621 HR(device->CreateDepthStencilSurface(Width,Height,D3DFMT_D24S8,samples,0,TRUE,&depth,nullptr),"create opaque depth");
622 HR(device->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,D3DMULTISAMPLE_NONE,0,FALSE,&resolved,nullptr),"create opaque resolve");
623 HR(device->CreateOffscreenPlainSurface(Width,Height,D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&readback,nullptr),"create opaque readback");
624 HR(device->SetRenderTarget(0,target.Get()),"bind opaque target");
625 HR(device->SetDepthStencilSurface(depth.Get()),"bind opaque depth");
626 for(bool farFirst : {false,true})
627 {
628 HR(device->Clear(0,nullptr,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,0xff000000,1,0),"clear opaque frame");
629 HR(device->BeginScene(),"begin opaque frame");
630 device->SetRenderState(D3DRS_ZENABLE,TRUE);
631 device->SetRenderState(D3DRS_ZFUNC,D3DCMP_ALWAYS);
632 device->SetRenderState(D3DRS_ZWRITEENABLE,FALSE);
633 effect->SetTechnique("TShader");
634 HR(effect->Begin(nullptr,0),"begin terrain technique");
635 HR(effect->BeginPass(11),"begin RTS pass");
636 HR(effect->EndPass(),"end RTS pass");
637 device->SetRenderState(D3DRS_ZFUNC,D3DCMP_LESSEQUAL);
638 device->SetRenderState(D3DRS_ZWRITEENABLE,TRUE);
639 HR(effect->End(),"end terrain technique");
640 DWORD writes;
641 HR(device->GetRenderState(D3DRS_ZWRITEENABLE,&writes),"read post-terrain depth writes");
642 // Use simple opaque silhouettes to isolate depth from vehicle materials.
643 device->SetVertexShader(nullptr); device->SetPixelShader(nullptr);
644 device->SetFVF(D3DFVF_XYZRHW|D3DFVF_DIFFUSE);
645 device->SetRenderState(D3DRS_LIGHTING,FALSE);
646 device->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);
647 device->SetRenderState(D3DRS_STENCILENABLE,FALSE);
648 device->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
649 device->SetRenderState(D3DRS_ALPHATESTENABLE,FALSE);
650 device->SetTextureStageState(0,D3DTSS_COLOROP,D3DTOP_SELECTARG1);
651 device->SetTextureStageState(0,D3DTSS_COLORARG1,D3DTA_DIFFUSE);
652 device->SetTextureStageState(1,D3DTSS_COLOROP,D3DTOP_DISABLE);
653 const auto draw=[&](float left,float right,float z,DWORD color) {
654 struct ScreenVertex {float x,y,z,rhw;DWORD color;};
655 const ScreenVertex quad[]={{left,149.5f,z,1,color},{right,149.5f,z,1,color},
656 {left,389.5f,z,1,color},{right,389.5f,z,1,color}};
657 HR(device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP,2,quad,sizeof(ScreenVertex)),"draw opaque silhouette");
658 };
659 if(farFirst) draw(299.5f,699.5f,.7f,0xffff0000);
660 draw(199.5f,599.5f,.3f,0xff00ff00); // nearer hull/shroud
661 if(!farFirst) draw(299.5f,699.5f,.7f,0xffff0000); // car/nacelle behind it
662 HR(device->EndScene(),"end opaque frame");
663 HR(device->StretchRect(target.Get(),nullptr,resolved.Get(),nullptr,D3DTEXF_NONE),"resolve opaque frame");
664 HR(device->GetRenderTargetData(resolved.Get(),readback.Get()),"read opaque frame");
665 D3DLOCKED_RECT lock{}; HR(readback->LockRect(&lock,nullptr,D3DLOCK_READONLY),"lock opaque frame");
666 size_t hidden=0,visible=0;
667 for(int y=160;y<380;++y)
668 {
669 const auto row=reinterpret_cast<const DWORD*>(static_cast<const char*>(lock.pBits)+y*lock.Pitch);
670 for(int x=310;x<590;++x) hidden+=(row[x]&0xffffff)==0x00ff00;
671 for(int x=610;x<690;++x) visible+=(row[x]&0xffffff)==0xff0000;
672 }
673 HR(readback->UnlockRect(),"unlock opaque frame");
674 std::cout << "Opaque depth " << int(samples) << "x farFirst=" << farFirst << " writes=" << writes
675 << " hidden=" << hidden << "/61600 visible=" << visible << "/17600" << std::endl;
676 Check(writes==TRUE,"shared technique must preserve terrain's explicit enable of depth writes");
677 Check(hidden==61600 && visible==17600,"near hull hides far geometry regardless of draw order");
678 }
679 HR(device->SetRenderTarget(0,oldTarget.Get()),"restore opaque target");
680 HR(device->SetDepthStencilSurface(oldDepth.Get()),"restore opaque depth");
681 HR(saved->Apply(),"restore opaque test state");
682}
683// The cloud overlay is coplanar with rain. Matrix multiplication grouping and
684// 24-bit depth rounding must not make transparent glass occlude its own beads.
685static void CheckCloudGlassDepth(IDirect3DDevice9* device, ID3DXEffect* effect, D3DMULTISAMPLE_TYPE samples)
686{
687 ComPtr<IDirect3DStateBlock9> saved;
688 HR(device->CreateStateBlock(D3DSBT_ALL,&saved),"save cloud test state");
689 ComPtr<IDirect3DSurface9> oldTarget,oldDepth,target,depth,resolved,readback;
690 HR(device->GetRenderTarget(0,&oldTarget),"save cloud target");
691 device->GetDepthStencilSurface(&oldDepth);
692 HR(device->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,samples,0,FALSE,&target,nullptr),"create cloud target");
693 HR(device->CreateDepthStencilSurface(Width,Height,D3DFMT_D24S8,samples,0,TRUE,&depth,nullptr),"create cloud depth");
694 HR(device->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,D3DMULTISAMPLE_NONE,0,FALSE,&resolved,nullptr),"create cloud resolve");
695 HR(device->CreateOffscreenPlainSurface(Width,Height,D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&readback,nullptr),"create cloud readback");
696 HR(device->SetRenderTarget(0,target.Get()),"bind cloud target");
697 HR(device->SetDepthStencilSurface(depth.Get()),"bind cloud depth");
698 const auto glass=Quad(-.0008f,.0008f,.0004f,-.0004f);
699 WindshieldRainRenderer rain; rain.AddGlass(0,glass.data(),glass.size()); rain.FinishGeometry();
700 D3DXMATRIX identity,projection;
701 D3DXMatrixIdentity(&identity);
702 D3DXMatrixPerspectiveFovRH(&projection,1.3f,float(Width)/Height,.000025f,.16f);
703 std::vector<D3DXMATRIX> world(1,identity);
704 for(int i=0;i<150;++i) rain.Update(1.f/30,1,{0,-11.27f,0},{0,0,0},world,1.f,false);
705 const auto frame=[&](int angle,int overlay,DWORD initialWrites=TRUE) {
706 D3DXMATRIX view,rotation,translation;
707 D3DXMatrixRotationYawPitchRoll(&rotation,.12f,.23f,-.06f);
708 D3DXMatrixTranslation(&translation,.000017f,.000028f,-.0011f);
709 world[0]=rotation*translation;
710 D3DXMatrixRotationYawPitchRoll(&view,(angle-6)*.007f,.04f,-.03f);
711 const auto viewProjection=view*projection;
712 HR(device->Clear(0,nullptr,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,0xff808080,1,0),"clear cloud frame");
713 HR(device->BeginScene(),"begin cloud frame");
714 device->SetRenderState(D3DRS_ZENABLE,TRUE);
715 device->SetRenderState(D3DRS_ZFUNC,D3DCMP_ALWAYS);
716 device->SetRenderState(D3DRS_ZWRITEENABLE,initialWrites);
717 device->SetRenderState(D3DRS_STENCILENABLE,FALSE);
718 device->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);
719 device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
720 device->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA);
721 device->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA);
722 device->SetFVF(D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1);
723 if(overlay)
724 {
725 const auto wvp=world[0]*view*projection; // same grouping as the game's overlay
726 const D3DXVECTOR4 cloud(1,0,0,0);
727 effect->SetTechnique("TShader"); effect->SetVector("clouduv",&cloud);
728 effect->SetMatrix("matWorldViewProj",&wvp);
729 // Match the caller's local scope in Viewscreen/render.cpp.
730 DWORD overlayDepthWrites;
731 HR(device->GetRenderState(D3DRS_ZWRITEENABLE,&overlayDepthWrites),"save overlay depth writes");
732 HR(device->SetRenderState(D3DRS_ZWRITEENABLE,FALSE),"disable transparent depth writes");
733 HR(effect->Begin(nullptr,0),"begin cloud overlay");
734 HR(effect->BeginPass(9),"begin actual cloud glass pass");
735 if(overlay==2) device->SetRenderState(D3DRS_ZWRITEENABLE,TRUE); // reproduce old behavior
736 HR(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,glass.data(),sizeof(Vertex)),"draw transparent cloud glass");
737 HR(effect->EndPass(),"end cloud pass"); HR(effect->End(),"end cloud overlay");
738 HR(device->SetRenderState(D3DRS_ZWRITEENABLE,overlayDepthWrites),"restore overlay depth writes");
739 }
740 HR(rain.Render(device,effect,world,viewProjection),"render rain after cloud glass");
741 DWORD writes; HR(device->GetRenderState(D3DRS_ZWRITEENABLE,&writes),"read restored cloud depth writes");
742 Check(writes==initialWrites,"cloud/rain passes restore caller depth-write state");
743 HR(device->EndScene(),"end cloud frame");
744 HR(device->StretchRect(target.Get(),nullptr,resolved.Get(),nullptr,D3DTEXF_NONE),"resolve cloud frame");
745 HR(device->GetRenderTargetData(resolved.Get(),readback.Get()),"read cloud frame");
746 D3DLOCKED_RECT lock{}; HR(readback->LockRect(&lock,nullptr,D3DLOCK_READONLY),"lock cloud frame");
747 std::vector<DWORD> pixels(Width*Height);
748 for(int y=0;y<Height;++y) memcpy(pixels.data()+y*Width,static_cast<char*>(lock.pBits)+y*lock.Pitch,Width*4);
749 HR(readback->UnlockRect(),"unlock cloud frame"); return pixels;
750 };
751 size_t legacyLost=0,changed=0;
752 for(int angle=0;angle<12;++angle)
753 {
754 const auto clear=frame(angle,0),cloud=frame(angle,1),legacy=frame(angle,2);
755 Check(frame(angle,1,FALSE)==clear,"overlay preserves a caller with depth writes already disabled");
756 for(size_t i=0;i<clear.size();++i)
757 {
758 legacyLost+=clear[i]!=legacy[i]; changed+=clear[i]!=cloud[i];
759 }
760 }
761 std::cout << "Cloud overlay " << int(samples) << "x: old depth differences=" << legacyLost
762 << "; corrected=" << changed << std::endl;
763 Check(legacyLost>100,"cloud fixture reproduces droplet loss with old transparent depth writes");
764 Check(changed==0,"cloud overlay cannot flicker or erase rain across changing view angles");
765 HR(device->SetRenderTarget(0,oldTarget.Get()),"restore cloud target");
766 HR(device->SetDepthStencilSurface(oldDepth.Get()),"restore cloud depth");
767 HR(saved->Apply(),"restore cloud test state");
768}
769int main(int argc,char** argv)
770{
771 CheckShippedWiperDisplacement();
772 CheckConnectedGlass();
773 CheckCockpitForceDirection();
774 CheckForwardAirflow();
775 std::ifstream e11Daw("Meshes/e11cockpit1.daw",std::ios::binary);
776 Check(Read<unsigned short>(e11Daw,0)==7095,"E-11 cockpit has 7095 geometry vertices");
777 const auto allE11=Glass("e11cockpit1",-1);
778 WindshieldRainRenderer e11Geometry;
779 e11Geometry.AddGlass(0,allE11.data(),allE11.size()); e11Geometry.FinishGeometry();
780 Check(allE11.size()==24 && e11Geometry.PaneCount()==3,"E-11 has three glass patches independent of cockpit vertex count");
781 std::cout << "PASS: E-11 7095 cockpit vertices; 24 glass vertices; 3 patches with area-scaled bead budgets (8192 hard limit per patch).\n";
782 HWND window=CreateWindowW(L"STATIC",L"Rain test",WS_POPUP,0,0,Width,Height,nullptr,nullptr,nullptr,nullptr);
783 Check(window!=nullptr,"create hidden window");
784 ComPtr<IDirect3D9> d3d; d3d.Attach(Direct3DCreate9(D3D_SDK_VERSION)); Check(d3d!=nullptr,"create D3D9");
785 D3DPRESENT_PARAMETERS pp{}; pp.Windowed=TRUE; pp.SwapEffect=D3DSWAPEFFECT_DISCARD;
786 pp.hDeviceWindow=window; pp.BackBufferWidth=Width; pp.BackBufferHeight=Height;
787 ComPtr<IDirect3DDevice9> device;
788 HR(d3d->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,window,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&pp,&device),"create HAL device");
789 ComPtr<ID3DXEffect> effect; ComPtr<ID3DXBuffer> errors;
790 HRESULT compiled=D3DXCreateEffectFromFileA(device.Get(),"CustomUI.fx",nullptr,nullptr,0,nullptr,&effect,&errors);
791 if(errors) std::cout << static_cast<const char*>(errors->GetBufferPointer());
792 HR(compiled,"compile shipped effect"); HR(effect->SetTechnique("TShader"),"select original technique");
793 CheckParkedGroundDepth(device.Get(),effect.Get(),D3DMULTISAMPLE_NONE,argc>1 ? argv[1] : nullptr);
794 CheckOpaqueDepthAfterTerrain(device.Get(),effect.Get(),D3DMULTISAMPLE_NONE);
795 CheckCloudGlassDepth(device.Get(),effect.Get(),D3DMULTISAMPLE_NONE);
796 CheckForegroundOcclusion(device.Get(),effect.Get(),D3DMULTISAMPLE_NONE);
797 ComPtr<IDirect3DSurface9> target,readback;
798 HR(device->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,D3DMULTISAMPLE_NONE,0,FALSE,&target,nullptr),"create target");
799 HR(device->CreateOffscreenPlainSurface(Width,Height,D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&readback,nullptr),"create readback");
800 HR(device->SetRenderTarget(0,target.Get()),"bind target");
801 CheckWetFilmClarity(device.Get(),effect.Get());
802 HR(device->SetRenderState(D3DRS_ZENABLE,FALSE),"disable depth");
803 HR(device->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE),"disable culling");
804 D3DXMATRIX identity; D3DXMatrixIdentity(&identity);
805 D3DXMATRIX projection; D3DXMatrixOrthoLH(&projection,.002f,.001125f,-1,1);
806 std::vector<D3DXMATRIX> transforms(2,identity);
807 const auto glass=Quad(-.0008f,.0008f,.0004f,-.0004f);
809 rain.AddGlass(0,glass.data(),glass.size()); rain.FinishGeometry();
810 Check(rain.PaneCount()==1,"coplanar triangles share one persistent water surface");
811 ComPtr<IDirect3DTexture9> markings;
812 HR(device->CreateTexture(128,128,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,&markings,nullptr),"create glass markings");
813 D3DLOCKED_RECT markingLock{};
814 HR(markings->LockRect(0,&markingLock,nullptr,0),"lock glass markings");
815 for(int y=0;y<128;++y) for(int x=0;x<128;++x)
816 {
817 DWORD color=0;
818 if(x>=28 && x<33) color=0xffff8000; // opaque window stripe
819 if(x>=48 && x<82 && y>=40 && y<88) color=((x/3+y/3)%2)?0xffe040c0:0xff401080; // sticker
820 if(x>=96) color=(y/2)%2?0x80c0c0c0:0x80404040; // translucent grime detail
821 reinterpret_cast<DWORD*>(static_cast<char*>(markingLock.pBits)+y*markingLock.Pitch)[x]=color;
822 }
823 HR(markings->UnlockRect(0),"unlock glass markings");
824 const auto drawMarkings=[&]() {
825 const D3DXVECTOR4 ambient(1,1,1,0),noLight(0,0,0,1),features(0,0,0,0);
826 const auto wvp=transforms[0]*projection;
827 effect->SetMatrix("matWorld",&transforms[0]); effect->SetMatrix("matWorldViewProj",&wvp);
828 effect->SetVector("ambient",&ambient); effect->SetVector("Sunlight",&noLight);
829 effect->SetVector("Radiosity",&noLight); effect->SetVector("Features",&features);
830 effect->SetTexture("ColorMap",markings.Get());
831 device->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE);
832 device->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA);
833 device->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA);
834 device->SetFVF(D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1);
835 HR(effect->Begin(nullptr,0),"begin actual glass material");
836 HR(effect->BeginPass(8),"begin glass/dirt/markings pass");
837 HR(device->DrawPrimitiveUP(D3DPT_TRIANGLELIST,2,glass.data(),sizeof(Vertex)),"draw glass material over rain");
838 HR(effect->EndPass(),"end glass material pass"); HR(effect->End(),"end glass material");
839 };
840 auto render=[&](WindshieldRainRenderer& renderer,bool withMarkings=false,bool oldOrder=false,DWORD flat=0,float altitudeKm=0,float cockpitLight=0) {
841 for(int y=0;y<Height;y+=12) for(int x=0;x<Width;x+=12)
842 {
843 D3DRECT rect{x,y,(std::min)(x+12,Width),(std::min)(y+12,Height)};
844 const DWORD color=flat ? flat : (((x/12+y/12)%2) ? 0xff62798e : 0xff283d4e);
845 HR(device->Clear(1,&rect,D3DCLEAR_TARGET,color,1,0),"paint background grid");
846 }
847 HR(device->BeginScene(),"begin frame");
848 if(withMarkings && oldOrder) drawMarkings();
849 HR(renderer.Render(device.Get(),effect.Get(),transforms,projection,WindshieldRain::AltitudeRainFactor(altitudeKm),WindshieldRainRenderer::DepthLayout::Unified,cockpitLight),"render persistent rain");
850 if(withMarkings && !oldOrder) drawMarkings();
851 HR(device->EndScene(),"end frame");
852 Check(effect->GetCurrentTechnique()==effect->GetTechniqueByName("TShader"),"rain restores original technique");
853 DWORD depth; HR(device->GetRenderState(D3DRS_ZWRITEENABLE,&depth),"read state");
854 Check(depth==TRUE,"rain restores depth write state");
855 D3DSURFACE_DESC targetDesc{}; HR(target->GetDesc(&targetDesc),"read target description");
856 ComPtr<IDirect3DSurface9> resolved;
857 if(targetDesc.MultiSampleType!=D3DMULTISAMPLE_NONE)
858 {
859 HR(device->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,D3DMULTISAMPLE_NONE,0,FALSE,&resolved,nullptr),"create readback resolve");
860 HR(device->StretchRect(target.Get(),nullptr,resolved.Get(),nullptr,D3DTEXF_NONE),"resolve readback");
861 }
862 HR(device->GetRenderTargetData(resolved ? resolved.Get() : target.Get(),readback.Get()),"read frame");
863 D3DLOCKED_RECT lock{}; HR(readback->LockRect(&lock,nullptr,D3DLOCK_READONLY),"lock frame");
864 std::vector<DWORD> pixels(Width*Height);
865 for(int y=0;y<Height;++y) memcpy(pixels.data()+y*Width,static_cast<const char*>(lock.pBits)+y*lock.Pitch,Width*4);
866 HR(readback->UnlockRect(),"unlock frame"); return pixels;
867 };
868 auto save=[&](const char* suffix) {
869 if(argc>1) HR(D3DXSaveSurfaceToFileA((std::string(argv[1])+suffix+".png").c_str(),D3DXIFF_PNG,readback.Get(),nullptr,nullptr),"save preview");
870 };
871 const auto dry=render(rain);
872 const auto markedDry=render(rain,true); save("-markings-dry");
873 // Compare actual beads/runoff at the same view and forces. Faster drainage
874 // reduces residence time, but maximum rain must still be stronger than
875 // medium rain without rebuilding the rejected mottled splash background.
876 WindshieldRainRenderer mediumRain,downpourRain;
877 for(auto* renderer:{&mediumRain,&downpourRain}) {
878 renderer->AddGlass(0,glass.data(),glass.size()); renderer->FinishGeometry();
879 }
880 for(int i=0;i<300;++i) {
881 mediumRain.Update(1.f/30,.5f,{0,-9.8f,0},{0,0,0},transforms,1.f,false);
882 downpourRain.Update(1.f/30,1.f,{0,-9.8f,0},{0,0,0},transforms,1.f,false);
883 }
884 const auto mediumFrame=render(mediumRain); save("-medium");
885 const auto downpourFrame=render(downpourRain); save("-downpour");
886 const float mediumDifference=MeanDifference(mediumFrame,dry);
887 const float downpourDifference=MeanDifference(downpourFrame,dry);
888 std::cout << "Medium/downpour exterior image difference: " << mediumDifference << "/" << downpourDifference << std::endl;
889 Check(downpourDifference>mediumDifference*1.2f,
890 "heavy beads and moving runoff remain more visible than medium rain");
891 auto& downpourWater=WindshieldRainTestAccess::Water(downpourRain);
892 downpourWater.WipeTriangle({0,0},{2,0},{2,2});
893 downpourWater.WipeTriangle({0,0},{2,2},{0,2}); downpourWater.Rebuild();
894 Check(render(downpourRain)==dry,"wipers fully restore the clear view after maximum-rain runoff");
895
896 // Texture reuse must not freeze impacts, runoff or wiper changes, and a
897 // device reset must recreate uploads even when simulation is paused.
899 cached.AddGlass(0,glass.data(),glass.size()); cached.FinishGeometry();
900 auto& cachedWater=WindshieldRainTestAccess::Water(cached);
901 cachedWater.Impact({.4f,.3f},.015f); cachedWater.Rebuild();
902 const auto initialCache=render(cached);
903 transforms[0]._41=1.f; // kilometres: wholly outside this small orthographic view
904 Check(render(cached)==dry,"looking away from every wet pane produces a dry frame");
905 cachedWater.Update(1.f/30,0,{0,11.27f},{},1.f);
906 Check(render(cached)==dry,"hidden panes can advance without drawing stale water");
907 transforms[0]._41=0.f;
908 Check(render(cached)!=dry,"looking back restores current wet glass");
909 cachedWater.Clear(); cachedWater.Impact({.4f,.3f},.015f); cachedWater.Rebuild();
910 Check(render(cached)==initialCache,"culling does not corrupt water or render state");
911 const auto revision=cachedWater.Revision();
912 cachedWater.Update(1.f/144,0,{0,11.27f},{},1.f);
913 Check(cachedWater.Revision()==revision && render(cached)==initialCache,
914 "sub-step and repeated rendering reuse unchanged water without altering pixels");
915 cachedWater.Impact({1.1f,.3f},.015f);
916 const auto newImpact=render(cached);
917 Check(newImpact!=initialCache,"new impacts refresh cached bead uploads immediately");
918 cachedWater.WipeTriangle({0,0},{.8f,0},{0,.8f});
919 const auto wipedCache=render(cached);
920 Check(wipedCache!=newImpact,"wiping refreshes cached uploads while paused");
921 cachedWater.Update(1.f/30,0,{0,11.27f},{},1.f);
922 const auto movedCache=render(cached);
923 Check(movedCache!=wipedCache,"rain-off runoff refreshes cached bead and film uploads");
924 cached.OnLostDevice();
925 Check(render(cached)==movedCache,"device resource recreation preserves paused water exactly");
926 cachedWater.Clear();
927 Check(render(cached)==dry,"clearing water returns to the dry image");
928 cachedWater.Impact({.8f,.4f},.015f);
929 Check(render(cached)!=dry,"new rain after clearing cannot reuse stale textures");
930 std::cout << "PASS: cached uploads preserve repeated frames and refresh impacts, runoff, wipes, clear/re-wet and device recreation.\n";
931
933 single.AddGlass(0,glass.data(),glass.size()); single.FinishGeometry();
934 // A 3 mm diameter bead at a close driver-like view must not inflate to
935 // the coarse texture footprint (the old filter made this about 25 pixels).
936 const auto ordinaryProjection=projection;
937 D3DXMatrixOrthoLH(&projection,.0004f,.000225f,-1,1);
938 WindshieldRainTestAccess::Water(single).Impact(WindshieldRainTestAccess::Map(single,{0,0,0}),.0015f);
939 WindshieldRainTestAccess::Water(single).Rebuild();
940 const auto oneDrop=render(single); save("-single-drop");
941 size_t singleChanged=0;
942 int left=Width,right=0,top=Height,bottom=0;
943 for(int y=0;y<Height;++y) for(int x=0;x<Width;++x) if(oneDrop[y*Width+x]!=dry[y*Width+x])
944 {
945 ++singleChanged; left=(std::min)(left,x); right=(std::max)(right,x);
946 top=(std::min)(top,y); bottom=(std::max)(bottom,y);
947 }
948 Check(singleChanged>0 && singleChanged<100 && right-left<=9 && bottom-top<=9,
949 "one bead affects only its small footprint; the rest of the pane is pixel-identical");
950 std::cout << "PASS: one drop changes " << singleChanged << " pixels in " << right-left+1 << "x" << bottom-top+1 << "; all others unchanged.\n";
951 // Refraction cannot reveal a bead against a featureless sky. Its curved
952 // surface must produce both a dark rim and a light reflection of its own.
953 const auto flatBead=render(single,false,false,0xff808080); save("-bead-flat");
954 int darkest=128,brightest=128;
955 for(DWORD pixel:flatBead) {darkest=(std::min)(darkest,int(pixel&255));brightest=(std::max)(brightest,int(pixel&255));}
956 std::cout << "Isolated bead on flat gray: " << darkest << ".." << brightest << std::endl;
957 Check(darkest<=108 && brightest>=148,"bead silhouette has a visible dark rim and bright reflection on a smooth sky");
958 const auto dimBead=render(single,false,false,0xff080808);
959 for(DWORD pixel:dimBead) Check((pixel&255)<=16,"dimly lit beads do not acquire daylight highlights");
960 const auto blackBead=render(single,false,false,0xff000000);
961 for(DWORD pixel:blackBead) Check((pixel&0x00ffffff)==0,"unlit water does not emit light");
962 const auto litBead=render(single,false,false,0xff000000,0,1); save("-dome-lit-bead");
963 const auto halfLit=render(single,false,false,0xff000000,0,.5f);
964 size_t glarePixels=0;
965 for(size_t i=0;i<litBead.size();++i)
966 {
967 glarePixels+=(litBead[i]&0xffffff)!=0;
968 if(oneDrop[i]==dry[i]) Check((litBead[i]&0xffffff)==0,"dome light cannot put a veil on dry glass");
969 Check((halfLit[i]&255)<=(litBead[i]&255),"wet reflections follow available cockpit power");
970 }
971 Check(glarePixels>10,"interior light reveals droplets against an unlit exterior");
972 int nightPeak=0;
973 for (DWORD pixel:litBead) nightPeak=(std::max)(nightPeak,int((pixel>>16)&255));
974 Check(nightPeak>5 && nightPeak<45,"night dome reflection is visible but cannot make white bead rings");
975 float previousGlare=MeanDifference(litBead,blackBead);
976 for (DWORD brightness : {0xff202020u,0xff808080u,0xffe0e0e0u})
977 {
978 const auto unlit=render(single,false,false,brightness);
979 const auto lit=render(single,false,false,brightness,0,1);
980 const float delta=MeanDifference(lit,unlit);
981 std::cout << "Dome glare at outside gray " << (brightness&255) << ": " << delta << std::endl;
982 Check(delta<previousGlare,"increasing exterior brightness reduces dome reflection contrast");
983 previousGlare=delta;
984 }
985
986 Check(render(single,false,false,0xff000000)==blackBead,"switching dome off restores unlit droplets immediately");
987 WindshieldRainRenderer splashFixture;
988 splashFixture.AddGlass(0,glass.data(),glass.size()); splashFixture.FinishGeometry();
989 auto& splashWater=WindshieldRainTestAccess::Water(splashFixture);
990 splashWater.Splash(WindshieldRainTestAccess::Map(splashFixture,{0,0,0}),.0025f);
991 splashWater.Rebuild();
992 const auto splashImage=render(splashFixture,false,false,0xff808080); save("-impact-splash");
993 auto& splashes=const_cast<std::vector<WindshieldRain::Drop>&>(splashWater.Drops());
994 splashes.erase(std::remove_if(splashes.begin(),splashes.end(),[](const auto& d){return d.radius<.0007f;}),splashes.end());
995 splashWater.Rebuild();const auto parentOnly=render(splashFixture,false,false,0xff808080);
996 size_t satellitePixels=0;
997 for(size_t i=0;i<splashImage.size();++i) satellitePixels+=std::abs(int(splashImage[i]&255)-int(parentOnly[i]&255))>=4;
998 Check(satellitePixels>=6,"small splash satellites are actually visible beyond the parent footprint");
999 std::cout << "PASS: powered dome reflection on wet pixels only; splash satellite pixels=" << satellitePixels << std::endl;
1000 WindshieldRainRenderer widePane;
1001 const auto wideGlass=Quad(-.0016f,.0016f,.0008f,-.0008f);
1002 widePane.AddGlass(0,wideGlass.data(),wideGlass.size()); widePane.FinishGeometry();
1003 WindshieldRainTestAccess::Water(widePane).Impact(WindshieldRainTestAccess::Map(widePane,{0,0,0}),.0015f);
1004 WindshieldRainTestAccess::Water(widePane).Rebuild();
1005 Check(MeanDifference(render(widePane,false,false,0xff808080),flatBead)<.001f,
1006 "same physical bead has same footprint on a pane twice as large");
1007 // Runoff must not flatten the raised bead's rim or remove its refraction.
1008 auto& singleWater=WindshieldRainTestAccess::Water(single);
1009 auto& film=const_cast<WindshieldRain::Surface::Field&>(singleWater.Residue());
1010 std::fill(film.begin(),film.end(),.6f); singleWater.Rebuild();
1011 const auto beadOnFilm=render(single,false,false,0xff808080); save("-bead-on-film");
1012 int filmDarkest=128,filmBrightest=128;
1013 for(DWORD pixel:beadOnFilm) {filmDarkest=(std::min)(filmDarkest,int(pixel&255));filmBrightest=(std::max)(filmBrightest,int(pixel&255));}
1014 std::cout << "Bead over runoff on flat gray: " << filmDarkest << ".." << filmBrightest << std::endl;
1015 Check(filmBrightest-filmDarkest>=(brightest-darkest)*.8f && filmDarkest<=96 && filmBrightest>=152,
1016 "a bead keeps strong rim/reflection contrast over accumulated runoff");
1017 WindshieldRainRenderer runoffFixture;
1018 runoffFixture.AddGlass(0,glass.data(),glass.size()); runoffFixture.FinishGeometry();
1019 auto& runoffWater=WindshieldRainTestAccess::Water(runoffFixture);
1020 runoffWater.Impact(WindshieldRainTestAccess::Map(runoffFixture,{-.0001f,.00005f,0}),.0025f);
1021 for(int i=0;i<30;++i) runoffWater.Update(1.f/30,0,{0,11.27f},{},1.f);
1022 // The active wake must be a narrow visible rivulet even over a flat sky.
1023 // Old residue is deliberately weaker than this fresh moving water.
1024 const auto rollingFilm=render(runoffFixture,false,false,0xff808080); save("-runoff-relief");
1025 int trailDark=128,trailLight=128,x0=Width,x1=0,y0=Height,y1=0;
1026 size_t trailPixels=0;
1027 for(int y=0;y<Height;++y) for(int x=0;x<Width;++x)
1028 {
1029 const int value=int(rollingFilm[y*Width+x]&255);
1030 trailDark=(std::min)(trailDark,value); trailLight=(std::max)(trailLight,value);
1031 if(std::abs(value-128)>=5)
1032 {
1033 ++trailPixels; x0=(std::min)(x0,x); x1=(std::max)(x1,x);
1034 y0=(std::min)(y0,y); y1=(std::max)(y1,y);
1035 }
1036 }
1037 std::cout << "Runoff on flat sky: " << trailDark << ".." << trailLight << "; " << trailPixels
1038 << " visible pixels, " << x1-x0+1 << "x" << y1-y0+1 << std::endl;
1039 Check(trailDark<=120 && trailLight>=136 && trailPixels>50 && y1-y0>5*(x1-x0),
1040 "rolling water leaves a narrow visible streak against a featureless sky");
1041 const_cast<std::vector<WindshieldRain::Drop>&>(runoffWater.Drops()).clear();
1042 std::fill(const_cast<WindshieldRain::Surface::Field&>(runoffWater.Residue()).begin(),
1043 const_cast<WindshieldRain::Surface::Field&>(runoffWater.Residue()).end(),.6f);
1044 runoffWater.Rebuild();
1045 for(DWORD p:render(runoffFixture,false,false,0xff808080))
1046 Check((p&0xffffff)==0x808080,"flat residue adds no pane-wide lighting or opacity veil");
1047 // Close neighbouring rivulets must not chop each other into lookup-cell
1048 // rectangles. Compare their nonoverlapping visible pixels with each alone.
1049 const auto setWakes=[&](bool a,bool b) {
1050 runoffWater.Clear();
1051 if(a) {runoffWater.Impact({.795f,.43f},.0025f);const_cast<WindshieldRain::Drop&>(runoffWater.Drops().back()).wake={.783f,.37f};}
1052 if(b) {runoffWater.Impact({.804f,.43f},.0025f);const_cast<WindshieldRain::Drop&>(runoffWater.Drops().back()).wake={.792f,.37f};}
1053 runoffWater.Rebuild();
1054 };
1055 setWakes(true,false);const auto wakeA=render(runoffFixture,false,false,0xff808080);
1056 setWakes(false,true);const auto wakeB=render(runoffFixture,false,false,0xff808080);
1057 setWakes(true,true);const auto wakeBoth=render(runoffFixture,false,false,0xff808080);save("-neighbouring-wakes");
1058 size_t exclusive=0,missing=0;
1059 for(size_t i=0;i<wakeBoth.size();++i)
1060 {
1061 const bool a=std::abs(int(wakeA[i]&255)-128)>=8,b=std::abs(int(wakeB[i]&255)-128)>=8;
1062 if(a!=b) {++exclusive;missing+=std::abs(int(wakeBoth[i]&255)-128)<4;}
1063 }
1064 std::cout << "Adjacent wakes: " << exclusive << " isolated edge pixels, " << missing << " lost in combined lookup" << std::endl;
1065 Check(exclusive>100 && missing<exclusive/50,"neighbouring wakes retain continuous rounded edges across lookup cells");
1066 // Magnify a thin vertical trail. Bilinear heights have a triangular
1067 // cross-section: their derivative flips abruptly at each texel centre.
1068 // Require a visible rounded ridge, not flat facets or a hidden streak.
1069 runoffWater.Clear();
1070 auto& ridge=const_cast<WindshieldRain::Surface::Field&>(runoffWater.Residue());
1071 constexpr int fieldSize=WindshieldRain::Surface::Resolution;
1072 for(int y=0;y<fieldSize;++y) ridge[y*fieldSize+fieldSize/2]=.6f;
1073 runoffWater.Rebuild();
1074 const auto roundedTrail=render(runoffFixture,false,false,0xff808080); save("-trail-profile");
1075 int ridgeDark=128,ridgeLight=128,largestStep=0;
1076 for(int x=1;x<Width;++x)
1077 {
1078 const int value=int(roundedTrail[(Height/2)*Width+x]&255);
1079 ridgeDark=(std::min)(ridgeDark,value); ridgeLight=(std::max)(ridgeLight,value);
1080 largestStep=(std::max)(largestStep,std::abs(value-int(roundedTrail[(Height/2)*Width+x-1]&255)));
1081 }
1082 std::cout << "Magnified trail profile: " << ridgeDark << ".." << ridgeLight
1083 << "; largest adjacent-pixel step=" << largestStep << std::endl;
1084 Check(ridgeDark<=120 && ridgeLight>=136 && largestStep<=6,
1085 "magnified runoff has visible smoothly rounded lighting instead of texel facets");
1086 projection=ordinaryProjection;
1087 for(float speed:{100.f,120.f})
1088 {
1089 runoffWater.Clear(); runoffWater.Impact({.8f,.65f},.0008f);
1090 for(int i=0;i<6;++i) runoffWater.Update(1.f/30,0,{0,11.27f},{0,-speed*.8f},1188.f/1013.25f,speed);
1091 const auto fastFirst=render(runoffFixture,false,false,0xff808080);
1092 runoffWater.Update(1.f/30,0,{0,11.27f},{0,-speed*.8f},1188.f/1013.25f,speed);
1093 const auto fastNext=render(runoffFixture,false,false,0xff808080); save(speed==100 ? "-wake-100mps" : "-wake-120mps");
1094 size_t visible=0,moved=0;
1095 for(size_t i=0;i<fastNext.size();++i)
1096 {
1097 visible+=std::abs(int(fastNext[i]&255)-128)>=3;
1098 moved+=fastNext[i]!=fastFirst[i];
1099 }
1100 std::cout << "Fast wake " << speed << " m/s: visible=" << visible << ", moving pixels=" << moved << std::endl;
1101 Check(visible>=10 && moved>10,"100/120 m/s water has a readable moving wake, not isolated popping dots");
1102 }
1103 // A distant bead spans only a few screen pixels. Check multiple sub-pixel
1104 // alignments against the dark, nearly uniform sky in Bill's approach video.
1105 for(float phase : {0.f,.25f,.5f,.75f})
1106 {
1107 singleWater.Clear();
1108 singleWater.Impact(WindshieldRainTestAccess::Map(single,{phase*.002f/Width,phase*.001125f/Height,0}),.0015f);
1109 std::fill(film.begin(),film.end(),.6f); singleWater.Rebuild();
1110 const auto distant=render(single,false,false,0xff404040);
1111 int contrast=0; size_t visible=0;
1112 for(DWORD pixel:distant)
1113 {
1114 const int delta=std::abs(int(pixel&255)-64);
1115 contrast=(std::max)(contrast,delta); visible+=delta>=12;
1116 }
1117 std::cout << "Distant wet bead phase " << phase << ": contrast=" << contrast << ", visible pixels=" << visible << std::endl;
1118 Check(visible>0,"a small wet bead remains distinguishable against a dark overcast sky");
1119 }
1120 for(int i=0;i<300;++i) rain.Update(1.f/30,1,{0,-9.8f,0},{0,0,0},transforms,1.f,true);
1121 render(rain,false,false,0xffb0b0b0); save("-beads-overcast");
1122 const auto wet=render(rain); save("-stopped");
1123 Check(render(rain,false,false,0,10)==dry && render(rain,false,false,0,12)==dry,
1124 "existing beads and residue are invisible at/above 10 km");
1125 Check(render(rain,false,false,0,5)==wet,"full rain appearance is retained at/below 5 km");
1126 const float fullDifference=MeanDifference(wet,dry);
1127 const float halfway=MeanDifference(render(rain,false,false,0,7.5f),dry);
1128 Check(halfway>fullDifference*.45f && halfway<fullDifference*.55f,
1129 "7.5 km smoothly blends half the droplet/refraction effect");
1130 float previousDifference=0;
1131 for(float altitude : {9.9f,9.f,8.f,7.5f,7.f,6.f,5.f})
1132 {
1133 const auto faded=render(rain,false,false,0,altitude);
1134 const float difference=MeanDifference(faded,dry);
1135 Check(difference>=previousDifference,"descent increases rain visibility monotonically");
1136 Check(render(rain,false,false,0,altitude)==faded,"altitude fade does not flicker between renders");
1137 previousDifference=difference;
1138 }
1139 Check(render(rain)==wet,"altitude fading preserves the underlying water state");
1140 std::cout << "PASS: altitude fade 10..5 km; halfway/full image difference " << halfway << "/" << fullDifference << std::endl;
1141 const auto markedWet=render(rain,true); save("-markings-wet");
1142 const auto oldMarkedWet=render(rain,true,true); save("-markings-old-order");
1143 size_t oldMarkingChanges=0,newMarkingChanges=0,visibleWater=0;
1144 int grimeError=0;
1145 for(int y=160;y<380;++y) for(int x=100;x<860;++x)
1146 {
1147 const int i=y*Width+x;
1148 // Interior of the opaque sticker; avoid material filtering at its edge.
1149 if(x>=400 && x<580 && y>=210 && y<330)
1150 {
1151 oldMarkingChanges+=oldMarkedWet[i]!=markedDry[i];
1152 newMarkingChanges+=markedWet[i]!=markedDry[i];
1153 }
1154 // The grime contribution stays fixed; only the scene behind its alpha changes.
1155 if(x>=700 && x<830) for(int shift : {0,8,16})
1156 {
1157 const int plainDelta=int((wet[i]>>shift)&255)-int((dry[i]>>shift)&255);
1158 const int layeredDelta=int((markedWet[i]>>shift)&255)-int((markedDry[i]>>shift)&255);
1159 grimeError=(std::max)(grimeError,int(std::abs(layeredDelta-plainDelta*(127.f/255.f))+.5f));
1160 }
1161 if(x>=110 && x<230) visibleWater+=markedWet[i]!=markedDry[i];
1162 }
1163 std::cout << "Glass layers: old marking changes=" << oldMarkingChanges << " new=" << newMarkingChanges
1164 << "; translucent grime error=" << grimeError << "\n";
1165 Check(oldMarkingChanges>100 && newMarkingChanges==0 && grimeError<=2 && visibleWater>100,
1166 "rain refracts the exterior before sharp opaque markings and unchanged translucent grime are composited");
1167 const auto domeMarked=render(rain,true,false,0xff080808,0,1); save("-dome-wet-glass");
1168 const auto unlitMarked=render(rain,true,false,0xff080808);
1169 size_t domeChanged=0;
1170 for(int y=0;y<Height;++y) for(int x=0;x<Width;++x)
1171 {
1172 const int i=y*Width+x;
1173 if(x>=400 && x<580 && y>=210 && y<330)
1174 Check(domeMarked[i]==unlitMarked[i],"dome reflections leave opaque glass stickers sharp and unchanged");
1175 domeChanged+=domeMarked[i]!=unlitMarked[i];
1176 }
1177 Check(domeChanged>100,"cockpit lighting visibly increases glare on accumulated wet glass");
1178 size_t changed=0;
1179 for(size_t i=0;i<wet.size();++i) changed+=wet[i]!=dry[i];
1180 std::cout << "Affected pixels: " << changed << '\n';
1181 Check(changed>500 && std::abs(MeanBrightness(wet)-MeanBrightness(dry))<4.f,
1182 "heavy rain obscures detail while preserving scene brightness");
1183 for(int y=0;y<Height;++y) for(int x=0;x<Width;++x)
1184 if(x<Width/10-2 || x>Width*9/10+2 || y<75 || y>465)
1185 Check(wet[y*Width+x]==dry[y*Width+x],"water never escapes glass geometry");
1186 Check(render(rain)==wet,"water does not crawl between renders without a simulation step");
1187 rain.OnLostDevice(); Check(render(rain)==wet,"lost/reset resources preserve CPU water state");
1188 projection._41=.1f;
1189 Check(render(rain)!=wet,"camera movement projects water with the glass");
1190 projection._41=0;
1191 Check(render(rain)==wet,"camera return preserves exact droplet placement");
1192 for(int i=0;i<60;++i) rain.Update(1.f/30,1,{0,-9.8f,0},{50,70,0},transforms,1.f,true);
1193 Check(render(rain)!=wet,"moving air changes rendered streaks"); save("-wind");
1194 WindshieldRainRenderer vacuumWind, calmAir, surfaceWind;
1195 for(auto* sample : {&vacuumWind,&calmAir,&surfaceWind})
1196 {
1197 sample->AddGlass(0,glass.data(),glass.size());
1198 sample->FinishGeometry();
1199 }
1200 for(int i=0;i<60;++i)
1201 {
1202 vacuumWind.Update(1.f/30,1,{0,-9.8f,0},{50,70,0},transforms,0.f,true);
1203 calmAir.Update(1.f/30,1,{0,-9.8f,0},{0,0,0},transforms,2630.397f/1013.25f,true);
1204 surfaceWind.Update(1.f/30,1,{0,-9.8f,0},{50,70,0},transforms,2630.397f/1013.25f,true);
1205 }
1206 Check(render(vacuumWind)==render(calmAir),"renderer passes zero density through: wind in vacuum matches calm air");
1207 Check(render(surfaceWind)!=render(calmAir),"surface atmosphere produces visible wind-driven streaks");
1208 WindshieldRainRenderer normalImpact;
1209 normalImpact.AddGlass(0,glass.data(),glass.size()); normalImpact.FinishGeometry();
1210 for(int i=0;i<90;++i) normalImpact.Update(1.f/30,1,{0,0,0},{0,0,-103},transforms,1188.f/1013.25f,false);
1211 Check(render(normalImpact)!=dry,"normal high-speed impacts remain briefly visible");
1212 for(int i=0;i<60;++i) normalImpact.Update(1.f/30,0,{0,0,0},{0,0,-103},transforms,1188.f/1013.25f,false);
1213 Check(!normalImpact.Wet() && render(normalImpact)==dry,
1214 "renderer forwards full airspeed: normal impacts shed without tangent flow");
1215 std::cout << "PASS: renderer density propagation, vacuum/calm equivalence and surface wind.\n";
1216 rain.Clear(); rain.AddGlass(0,glass.data(),glass.size());
1217 const auto blade=Quad(-.0001f,.0001f,.0005f,-.0005f);
1218 rain.AddWiper(1,blade.data(),blade.size()); rain.FinishGeometry();
1219 transforms[1]._41=-.002f;
1220 for(int i=0;i<300;++i) rain.Update(1.f/30,1,{0,-9.8f,0},{0,0,0},transforms,1.f,true);
1221 Check(rain.Wet(),"rain collected before wipe");
1222 const auto beforeRigidMove=render(rain);
1223 transforms[0]._41=.004f; transforms[1]._41=.002f;
1224 rain.Update(.00001f,0,{0,0,0},{0,0,0},transforms,1.f,true);
1225 // Render from the original view to compare unchanged water placement.
1226 transforms[0]._41=0;
1227 Check(render(rain)==beforeRigidMove,"moving the whole cockpit never wipes water with a parked blade");
1228 transforms[1]._41=-.002f;
1229 rain.Update(.00001f,0,{0,0,0},{0,0,0},transforms,1.f,true);
1230 const auto beforeDisabledWipe=render(rain);
1231 transforms[1]._41=.002f;
1232 rain.Update(.00001f,0,{0,0,0},{0,0,0},transforms,1.f,false);
1233 Check(render(rain)==beforeDisabledWipe,"wipers OFF cannot clear beads or trails even if blade transforms change");
1234 transforms[1]._41=-.002f;
1235 rain.Update(.00001f,0,{0,0,0},{0,0,0},transforms,1.f,false);
1236 transforms[1]._41=.002f; rain.Update(1.f/30,0,{0,-9.8f,0},{0,0,0},transforms,1.f,true);
1237 Check(!rain.Wet() && render(rain)==dry,"actual blade motion clears the swept glass and trails");
1238 transforms[1]=identity;
1239 const struct {const char* name;int axis;const char* suffix;bool positiveNormal=false;} cockpits[]={
1240 {"T-120 Steerhead-stock INT",2,"-t120"},{"mammoth-int",1,"-mammoth"},{"e10cockpit1",2,"-e10"},{"e11cockpit1",2,"-e11"},{"C-2A Dasher INT",2,"-c2a"},{"C-2 Dasher INT",2,"-c2"},{"stratomaster_06-hex",2,"-t19"},
1241 {"C-2 Dasher INT",1,"-c2-left",true},{"C-2 Dasher INT",1,"-c2-right"},
1242 {"e10cockpit1",0,"-e10-left",true},{"e10cockpit1",0,"-e10-right"},
1243 {"e11cockpit1",0,"-e11-left",true},{"e11cockpit1",0,"-e11-right"}};
1244 for(const auto& cockpit:cockpits)
1245 {
1246 auto vertices=Glass(cockpit.name,cockpit.axis,cockpit.positiveNormal);
1247 if(std::string(cockpit.name)=="C-2 Dasher INT")
1248 {
1249 // C-2 glass component's authored nominal rotation, from its DIX.
1250 const auto ypr=GlassRotation("C-2 Dasher INT");
1251 D3DXMATRIX nominal; D3DXMatrixRotationYawPitchRoll(&nominal,ypr.x,ypr.y,ypr.z);
1252 for(auto& vertex:vertices)
1253 {
1254 D3DXVECTOR3 p(vertex.x,vertex.y,vertex.z),n(vertex.nx,vertex.ny,vertex.nz);
1255 D3DXVec3TransformCoord(&p,&p,&nominal); D3DXVec3TransformNormal(&n,&n,&nominal);
1256 vertex.x=p.x; vertex.y=p.y; vertex.z=p.z; vertex.nx=n.x; vertex.ny=n.y; vertex.nz=n.z;
1257 }
1258 }
1259 rain.Clear(); rain.AddGlass(0,vertices.data(),vertices.size()); rain.FinishGeometry();
1260 // Side windows are viewed in DAW Y/Z; their authored X is constant.
1261 const bool side=cockpit.axis==0 || (std::string(cockpit.name)=="C-2 Dasher INT" && cockpit.axis==1);
1262 const auto horizontal=[&](const Vertex& v) { return side ? v.y : v.x; };
1263 float minX=horizontal(vertices[0]),maxX=minX,minZ=vertices[0].z,maxZ=minZ;
1264 for(const auto& v:vertices) {minX=(std::min)(minX,horizontal(v));maxX=(std::max)(maxX,horizontal(v));minZ=(std::min)(minZ,v.z);maxZ=(std::max)(maxZ,v.z);}
1265 const float scale=(std::min)(1.8f*Width/Height/(maxX-minX),1.8f/(maxZ-minZ));
1266 projection=D3DXMATRIX(side ? 0 : scale*Height/Width,0,0,0,
1267 side ? scale*Height/Width : 0,0,0,0, 0,scale,0,0,
1268 -(minX+maxX)*.5f*scale*Height/Width,-(minZ+maxZ)*.5f*scale,.5f,1);
1269 // Use the cockpit's actual DAW-to-vehicle rotations. A stopped vehicle
1270 // supplies downward inertial acceleration in vehicle axes, not raw DAW Z.
1271 D3DXMATRIX pitch, yaw, inverse;
1272 D3DXMatrixRotationX(&pitch,D3DX_PI*.5f);
1273 D3DXMatrixRotationY(&yaw,D3DX_PI);
1274 transforms[0]=WindshieldRainRenderer::ToPhysicsTransform(pitch*yaw);
1275 D3DXMatrixInverse(&inverse,nullptr,&transforms[0]);
1276 projection=inverse*projection;
1277 const auto baseline=render(rain);
1278 for(int i=0;i<300;++i) rain.Update(1.f/30,1,{0,-9.80665f,0},{0,0,0},transforms,2630.397f/1013.25f,false);
1279 const auto result=render(rain); save(cockpit.suffix);
1280 size_t difference=0, strongLeft=0, strongRight=0;
1281 for(size_t i=0;i<result.size();++i)
1282 {
1283 difference+=result[i]!=baseline[i];
1284 int delta=0;
1285 for(int shift : {0,8,16}) delta=(std::max)(delta,
1286 std::abs(int((result[i]>>shift)&255)-int((baseline[i]>>shift)&255)));
1287 if(delta>=8) (i%Width<Width/2 ? strongLeft : strongRight)++;
1288 }
1289 std::cout << "Strongly refracted pixels L/R=" << strongLeft << "/" << strongRight
1290 << "; mean RGB difference=" << MeanDifference(result,baseline) << "\n";
1291 if(std::string(cockpit.name)=="e11cockpit1" && cockpit.axis==2)
1292 Check(strongLeft>3000 && strongRight>3000,"E-11 front glass has visible distortion across both halves");
1293 if(cockpit.axis==0)
1294 {
1295 // The real side pane narrows toward its lower end. Count only
1296 // the lowest fifth: clipping at a chart/triangle boundary must
1297 // not leave that part of the window dry.
1298 const int lower=int(Height*(.5f+.15f*(maxZ-minZ)*scale));
1299 size_t lowerWet=0;
1300 for(int y=lower;y<Height;++y) for(int x=0;x<Width;++x)
1301 lowerWet+=result[y*Width+x]!=baseline[y*Width+x];
1302 std::cout << cockpit.suffix << " lower window wet pixels=" << lowerWet << '\n';
1303 Check(lowerWet>100,"rain covers the lower end of E-10/E-11 side glass");
1304 }
1305 std::cout << cockpit.name << " panes=" << rain.PaneCount() << " wet=" << rain.Wet() << " changed=" << difference << std::endl;
1306 Check(difference>100,"visible water on shipped windshield");
1307 std::cout << "Scene brightness delta=" << MeanBrightness(result)-MeanBrightness(baseline) << std::endl;
1308 Check(std::abs(MeanBrightness(result)-MeanBrightness(baseline))<4.f,
1309 "wet shipped windshield preserves scene brightness without a dark overlay");
1310 if(std::string(cockpit.name)=="e11cockpit1" || std::string(cockpit.name)=="C-2A Dasher INT")
1311 {
1312 for(int i=0;i<600;++i) rain.Update(1.f/30,0,{0,-9.80665f,0},{0,0,0},transforms,2630.397f/1013.25f,false);
1313 const auto runoff=render(rain); save((std::string(cockpit.suffix)+"-after-20s").c_str());
1314 size_t residual=0,moved=0;
1315 for(size_t i=0;i<runoff.size();++i) {residual+=runoff[i]!=baseline[i];moved+=runoff[i]!=result[i];}
1316 Check(rain.Wet() && residual>100 && moved>100,
1317 "parked glass keeps visible moving beads/residue twenty seconds after rain stops");
1318 std::cout << "PASS: " << cockpit.name << " parked in calm surface atmosphere; after 20 s without rain, "
1319 << residual << " wet pixels, " << moved << " changed pixels.\n";
1320 }
1321 for(int i=0;i<90;++i) rain.Update(1.f/30,1,{0,-9.80665f,0},{0,0,-103},transforms,1188.f/1013.25f,false);
1322 const auto cruise=render(rain); save((std::string(cockpit.suffix)+"-200kt").c_str());
1323 size_t fastPixels=0;
1324 for(size_t i=0;i<cruise.size();++i) fastPixels+=cruise[i]!=baseline[i];
1325 Check(fastPixels>0,"200-knot shipped glass shows visible impacts and short wakes");
1326 for(int i=0;i<60;++i) rain.Update(1.f/30,0,{0,-9.80665f,0},{0,0,-103},transforms,1188.f/1013.25f,false);
1327 Check(!rain.Wet() && render(rain)==baseline,"high-speed water clears from shipped glass within two seconds of leaving rain");
1328 std::cout << "PASS: " << cockpit.name << " at 200 knots: " << fastPixels << " affected pixels vs " << difference << " parked.\n";
1329 std::cout << "PASS: " << cockpit.name << "; " << rain.PaneCount() << " planar patches; " << difference << " refracted pixels\n";
1330 }
1331 // Exercise the multisampled backbuffer path used by anti-aliasing settings.
1332 if(SUCCEEDED(d3d->CheckDeviceMultiSampleType(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,
1333 D3DFMT_A8R8G8B8,TRUE,D3DMULTISAMPLE_4_SAMPLES,nullptr)))
1334 {
1335 CheckOpaqueDepthAfterTerrain(device.Get(),effect.Get(),D3DMULTISAMPLE_4_SAMPLES);
1336 CheckParkedGroundDepth(device.Get(),effect.Get(),D3DMULTISAMPLE_4_SAMPLES,nullptr);
1337 CheckCloudGlassDepth(device.Get(),effect.Get(),D3DMULTISAMPLE_4_SAMPLES);
1338 CheckForegroundOcclusion(device.Get(),effect.Get(),D3DMULTISAMPLE_4_SAMPLES);
1339 ComPtr<IDirect3DSurface9> multisampled;
1340 HR(device->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,D3DMULTISAMPLE_4_SAMPLES,0,FALSE,&multisampled,nullptr),"create MSAA target");
1341 target=multisampled; HR(device->SetRenderTarget(0,target.Get()),"bind MSAA target");
1342 for(int i=0;i<30;++i) rain.Update(1.f/30,1,{0,-9.80665f,0},{0,0,-103},transforms,1188.f/1013.25f,false);
1343 const auto aa=render(rain);
1344 Check(aa!=dry,"MSAA scene capture retains rain refraction");
1345 std::cout << "PASS: 4x MSAA scene resolve\n";
1346 }
1347 else std::cout << "SKIP: adapter has no 4x MSAA support\n";
1348 rain.Clear(); effect.Reset(); device.Reset(); d3d.Reset(); DestroyWindow(window);
1349 std::cout << "PASS: shader, refraction, geometry clipping, camera stability, wind, wiper geometry, device resource recreation, and seven shipped cockpits\n";
1350}
SCRIPT_CONTROL SCRIPT_STATE const void int
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
SCRIPT_CONTROL SCRIPT_STATE const void DWORD
const std::vector< Drop > & Drops() const
std::vector< float > Field
static constexpr int Resolution
void Impact(Point position, float radius, bool coalesce=true)
void Update(float elapsed, float rain, Point acceleration, Point wind, float airDensity, float airSpeed=-1.f, AirJet airJet={})
static WindshieldRain::Point ProjectAcceleration(const RiseMath::Vector3 &acceleration, const RiseMath::Matrix &inverse, const RiseMath::Vector3 &normal, const RiseMath::Vector3 &u, const RiseMath::Vector3 &v)
HRESULT Render(Rendering::RenderDevice *device, Rendering::RenderMaterial *material, const std::vector< RiseMath::Matrix > &world, const RiseMath::Matrix &viewProjection, float opacity=1, DepthLayout layout=DepthLayout::Unified, float cockpitLight=0, ID3D11RenderTargetView *adExclusion=nullptr)
void AddGlass(int component, const Vertex *vertices, size_t count)
Rendering::WindshieldRain11::Vertex Vertex
Rendering::WindshieldRain11::DepthLayout DepthLayout
static RiseMath::Matrix ToPhysicsTransform(const RiseMath::Matrix &value)
void AddWiper(int component, const Vertex *vertices, size_t count)
void Update(float elapsed, float rain, const RiseMath::Vector3 &acceleration, const RiseMath::Vector3 &wind, const std::vector< RiseMath::Matrix > &transforms, float density, bool wiping, float rainAir=0)
static HRESULT DrawCockpitGlass(Rendering::RenderDevice *device, Draw draw)
constexpr float Width
constexpr float Height
float AltitudeRainFactor(float altitudeKm)
type
Definition erin.py:143