1#include "../Rendering/WindshieldRain11.h"
2#include "../Rendering/Device11.h"
3#include "../Rendering/FixedFunction11.h"
4#include "Reference9/WindshieldRainRenderer.h"
5#include <d3d11sdklayers.h>
6#include <fstream>
7#include <iostream>
8#include <stdexcept>
9#include <cstring>
10#include "../Viewscreen/RainAir.h"
11using Microsoft::WRL::ComPtr;
14{
15 struct WindshieldRain11TestAccess
16 {
17 static bool MaskTargets(WindshieldRain11& rain,UINT width,UINT height,UINT samples,DXGI_FORMAT format,bool compact)
18 {
19 rain.ReleaseTargets();rain.compactVisibility=compact;
20 D3D11_TEXTURE2D_DESC scene{};scene.Width=width;scene.Height=height;scene.Format=format;scene.SampleDesc={samples,0};
21 if(FAILED(rain.PrepareTargets(scene)))return false;
22 D3D11_TEXTURE2D_DESC resolved{},multisampled{};
23 rain.visibility.texture->GetDesc(&resolved);rain.visibilitySamples.texture->GetDesc(&multisampled);
24 const bool narrow=compact && (format==DXGI_FORMAT_B8G8R8A8_UNORM || format==DXGI_FORMAT_R8G8B8A8_UNORM);
25 const auto expected=narrow ? DXGI_FORMAT_R8_UNORM : format;
26 return resolved.Format==expected && multisampled.Format==expected && rain.visibilityFormat==expected
27 && resolved.Width==width && resolved.Height==height && resolved.SampleDesc.Count==1
28 && multisampled.Width==width && multisampled.Height==height && multisampled.SampleDesc.Count==samples;
29 }
30 static bool MaskReleased(const WindshieldRain11& rain)
31 {return !rain.visibility.texture && !rain.visibilitySamples.texture && rain.visibilityFormat==DXGI_FORMAT_UNKNOWN;}
32 static WindshieldRain::Surface& Water(WindshieldRain11& rain,size_t i=0){return rain.panes[i].water;}
33 static DirectX::XMFLOAT3 WorldDelta(WindshieldRain11& rain,size_t i,WindshieldRain::Point delta,
34 const std::vector<WindshieldRain11::Matrix>& transforms)
35 {
36 using namespace Math11;
37 const auto& p=rain.panes[i];
return TransformVector(p.u*delta.
x+p.v*delta.
y,transforms[p.component]);
38 }
39 static DirectX::XMFLOAT3
Normal(WindshieldRain11& rain,
size_t i,
40 const std::vector<WindshieldRain11::Matrix>& transforms)
41 {
42 const auto& p=rain.panes[i];return Math11::TransformVector(p.normal,transforms[p.component]);
43 }
44 static DirectX::XMFLOAT3
Acceleration(WindshieldRain11& rain,
size_t i,
45 const DirectX::XMFLOAT3& acceleration,const std::vector<WindshieldRain11::Matrix>& transforms)
46 {
47 const auto& p=rain.panes[i];WindshieldRain11::Matrix inverse;
48 Math11::Inverse(inverse,transforms[p.component]);
49 return WorldDelta(rain,i,WindshieldRain11::ProjectAcceleration(acceleration,inverse,p.normal,p.u,p.v),transforms);
50 }
51 static std::array<WindshieldRain::Point,3> VerticalSamples(WindshieldRain11& rain,size_t i,
52 const std::vector<WindshieldRain11::Matrix>& transforms)
53 {
54 using namespace Math11;
55 const auto& p=rain.panes[i];
56 const float uy=WorldDelta(rain,i,{1,0},transforms).y,vy=WorldDelta(rain,i,{0,1},transforms).y;
57 WindshieldRain::Point low{},high{},center{};
58 float bottom=1.e10f,top=-1.e10f;
59 for(const auto& vertex:p.vertices)
60 {
61 const auto delta=(
Vector{vertex.x,vertex.y,vertex.z}-p.origin)*1000.f;
62 const WindshieldRain::Point chart{
Dot(delta,p.u),
Dot(delta,p.v)};
63 const float height=chart.
x*uy+chart.
y*vy;
64 if(height<bottom){bottom=height;low=chart;}
65 if(height>top){top=height;high=chart;}
66 center.x+=chart.
x;center.y+=chart.
y;
67 }
68 center.x/=p.vertices.size();center.y/=p.vertices.size();
69
70 return {{{low.x*.7f+center.x*.3f,low.y*.7f+center.y*.3f},center,
71 {high.x*.7f+center.x*.3f,high.y*.7f+center.y*.3f}}};
72 }
73 };
74}
75struct WindshieldRainTestAccess
76{
77 static WindshieldRain::Surface& Water(WindshieldRainRenderer& rain,size_t i=0){return rain.panes[i].water;}
78};
79namespace
80{
82 constexpr const char* ShaderDirectory=sizeof(void*)==8 ? "x64/Release/NativeShaders11" : "outputs/direct3d11/shaders";
83 void Check(bool value,const char* reason){if(!value)throw std::runtime_error(reason);}
84 void HR(
HRESULT hr,
const char* reason){
if(FAILED(hr))
throw std::runtime_error(std::string(reason)+
": "+std::to_string(hr));}
86 template<class T> T Read(std::ifstream& file,std::streamoff offset)
87 {
88 T value{};file.seekg(offset);file.read(reinterpret_cast<char*>(&value),sizeof(value));
89 Check(file.good(),"read authored cockpit");return value;
90 }
91 void AuthoredWipers()
92 {
94 std::ifstream dix("Meshes/C-2 Dasher INT.dix",std::ios::binary),daw("Meshes/C-2 Dasher INT.daw",std::ios::binary);
95 Check(dix.good() && daw.good(),"open C-2 glass and blades");
96 const int count=Read<short>(dix,0),vertexCount=Read<unsigned short>(daw,0);
97 daw.seekg(0,std::ios::end);Check(vertexCount>0,"authored vertices");
98 const int stride=
int((std::streamoff(daw.tellg())-4)/vertexCount);Check(stride==32 || stride==40,
"authored vertex stride");
99 struct Component {
int type;D3DXVECTOR3 xyz,ypr,extend,axis,hinge;
float extent;};
100 std::vector<Component> components(count);std::vector<D3DXMATRIX> oldTransforms(count);
101 std::vector<WindshieldRain11::Matrix> transforms(count);unsigned 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 Check(first>=0 && n>=0 && first+n<=vertexCount,"authored glass/blade bounds");
110 std::vector<Vertex> vertices(n);std::vector<WindshieldRain11::Vertex> nativeVertices(n);
111 for(int j=0;j<n;++j)vertices[j]=Read<Vertex>(daw,2+stride*(first+j));
112 memcpy(nativeVertices.data(),vertices.data(),vertices.size()*sizeof(Vertex));
113 if(c.type==5){oldRain.
AddGlass(i,vertices.data(),vertices.size());rain.AddGlass(i,nativeVertices.data(),nativeVertices.size());}
114 else {oldRain.
AddWiper(i,vertices.data(),vertices.size());rain.AddWiper(i,nativeVertices.data(),nativeVertices.size());++blades;}
115 }
116 oldRain.
FinishGeometry();rain.FinishGeometry();Check(blades>0 && rain.PaneCount()>0,
"authored glass/blades found");
117 Check(oldRain.
PaneCount()==rain.PaneCount(),
"authored curved pane count");
118 const auto pose=[&](float phase) {
119 for(int i=0;i<count;++i)
120 {
121 const auto& c=components[i];const float e=c.type==47 ? .5f-.5f*std::cos(phase*D3DX_PI*2):0;
122 D3DXMATRIX rotation,shift,hinge,end;
123 D3DXMatrixRotationYawPitchRoll(&rotation,c.ypr.x,c.ypr.y,c.ypr.z);
124 D3DXMatrixTranslation(&shift,-c.hinge.x,-c.hinge.y,-c.hinge.z);D3DXMatrixIdentity(&hinge);
125 if(D3DXVec3LengthSq(&c.axis)>.000001f)D3DXMatrixRotationAxis(&hinge,&c.axis,e*c.extent);
126 const auto p=c.xyz+c.hinge+c.extend*e;D3DXMatrixTranslation(&end,p.x,p.y,p.z);
127 oldTransforms[i]=rotation*shift*hinge*end;memcpy(&transforms[i],&oldTransforms[i],sizeof(transforms[i]));
128 }
129 };
130 pose(.1f);oldRain.
Update(.00001f,0,{},{},oldTransforms,1,
false);rain.Update(.00001f,0,{},{},transforms,1,
false);
131 double volumeBefore=0;
132 for(size_t i=0;i<rain.PaneCount();++i)
133 {
134 auto& original=WindshieldRainTestAccess::Water(oldRain,i);auto& native=Rendering::WindshieldRain11TestAccess::Water(rain,i);
135 Check(std::abs(original.Width()-native.Width())<.00001f && std::abs(original.Height()-native.Height())<.00001f,"authored pane dimensions");
136 for(int y=0;y<30;++y)for(int x=0;x<30;++x)original.Impact({(x+.5f)*original.Width()/30,(y+.5f)*original.Height()/30},.0015f,false);
137 original.Rebuild();native=original;
138 for(const auto& d:native.Drops())volumeBefore+=d.radius*d.radius*d.radius;
139 }
140
141 oldRain.
Update(.00001f,0,{},{},oldTransforms,1,
true);rain.Update(.00001f,0,{},{},transforms,1,
true);
142 for(size_t i=0;i<rain.PaneCount();++i)Check(Rendering::WindshieldRain11TestAccess::Water(rain,i).Drops().size()==900,"parked blade retains water");
143 pose(.14f);oldRain.
Update(.00001f,0,{},{},oldTransforms,1,
true);rain.Update(.00001f,0,{},{},transforms,1,
true);
144 unsigned displaced=0,stationary=0;double volumeAfter=0,worst=0;
145 for(size_t i=0;i<rain.PaneCount();++i)
146 {
147 const auto& a=WindshieldRainTestAccess::Water(oldRain,i).Drops();const auto& b=Rendering::WindshieldRain11TestAccess::Water(rain,i).Drops();
148 Check(a.size()==b.size(),"authored wiper bead count parity");
149 for(size_t j=0;j<b.size();++j)
150 {
151 worst=(std::max)(worst,double(std::hypot(a[j].position.x-b[j].position.x,a[j].position.y-b[j].position.y)));
152 Check(std::abs(a[j].radius-b[j].radius)<.00005f,"authored swept bead radius");
153 volumeAfter+=b[j].radius*b[j].radius*b[j].radius;
154 if(std::hypot(b[j].velocity.x,b[j].velocity.y)>.1f)++displaced;else ++stationary;
155 }
156 }
157 Check(worst<.00005,"authored wiper bead motion parity");
158 Check(displaced>10 && stationary>100,"authored native blade displaces only contacted water");
159 Check(volumeAfter>volumeBefore*.95 && volumeAfter<=volumeBefore*1.00001,"authored sweep preserves water volume");
160 std::cout<<"PASS: authored C-2 curved glass and "<<blades<<" blades; "<<displaced<<" displaced beads; "<<stationary<<" untouched; max delta="<<worst<<" m\n";
161 }
162 void RainAirChecks()
163 {
169 Check(
Flow(
Evaluate(0,
true,
true,1,
true))==0.f,
"failed selected unit cannot blow rain off glass");
170 Check(
Evaluate(0,
true,
false,1,
true)==
State::Off,
"no failure indication before VDAT or in excluded vehicles");
173 Check(
Evaluate(-1,
true,
true,1,
true)==
State::Off,
"absent equipment has no CAS indication");
175 Check(
Evaluate(127,
true,
false,1,
true)==
State::Off,
"simulators and inactive vehicles excluded");
176 auto transition=
Evaluate(127,
true,
true,1,
true);
177 Check(
Flow(transition)==1.f,
"installed E-10 equipment supplies air outside the simulator");
178 transition=
Evaluate(127,
true,
false,1,
true);
180 "simulator entry suppresses selected equipment without retaining flow or thrust loss");
181 transition=
Evaluate(127,
false,
true,1,
true);
182 Check(
Flow(transition)==0.f,
"simulator exit cannot replay deselected rain air");
183 transition=
Evaluate(127,
true,
true,1,
true);
184 Check(
Flow(transition)==1.f,
"rain protection works again when selected outside the simulator");
186 Check(std::abs(10000.f*bleed-9950.f)<.01f,"rain air costs 0.5 percent delivered thrust");
187 Check(std::abs(2000.f*bleed-1990.f)<.01f,"partial thrust loses the same fraction, not rated thrust");
188 Check(std::abs(-2000.f*bleed+1990.f)<.01f,"reverse thrust loses magnitude without changing direction");
189 Check(0.f*bleed==0.f,"rain air cannot create thrust at idle");
190 Check(std::abs((10000.f-500.f)*bleed-9452.5f)<.01f,"rain bleed stacks after existing anti-ice loss");
192 Check(
ThrustMultiplier(state)==1.f,
"no bleed penalty when air is off or unavailable");
195 std::cout<<"PASS: rain-air supply and thrust loss (forward, partial, reverse, idle, anti-ice, off/unavailable)\n";
196 for(const char* model:{"e10cockpit1","e11cockpit1","stratomaster_06-hex","manx-int-hex"})
197 {
198 WindshieldRain11 protectedRain,control;
199 std::ifstream dix(std::string("Meshes/")+model+".DIX",std::ios::binary);
200 std::ifstream daw(std::string("Meshes/")+model+".DAW",std::ios::binary);
201 Check(dix.good()&&daw.good(),"open pneumatic rain-removal cockpit");
202 const int count=Read<short>(dix,0),vertexCount=Read<unsigned short>(daw,0);
203 daw.seekg(0,std::ios::end);
const int stride=
int((std::streamoff(daw.tellg())-4)/vertexCount);
204 Check(stride==32||stride==40,"rain-air mesh stride");
205 std::vector<WindshieldRain11::Matrix> transforms(count);
206 for(int i=0;i<count;++i)
207 {
208 const int o=99+i*100;
209 const auto xyz=Read<DirectX::XMFLOAT3>(dix,o+4),ypr=Read<DirectX::XMFLOAT3>(dix,o+16);
210 DirectX::XMStoreFloat4x4(&transforms[i],DirectX::XMMatrixRotationRollPitchYaw(ypr.y,ypr.x,ypr.z)
211 *DirectX::XMMatrixTranslation(xyz.x,xyz.y,xyz.z)*DirectX::XMMatrixRotationX(DirectX::XM_PIDIV2)
212 *DirectX::XMMatrixRotationY(DirectX::XM_PI)*DirectX::XMMatrixScaling(-1,-1,-1));
213 if(Read<unsigned char>(dix,o+58)!=5)continue;
214 const int first=Read<short>(dix,o),n=Read<short>(dix,o+2)*3;
215 std::vector<WindshieldRain11::Vertex> vertices(n);
216 for(int j=0;j<n;++j)vertices[j]=Read<WindshieldRain11::Vertex>(daw,2+stride*(first+j));
217 protectedRain.AddGlass(i,vertices.data(),vertices.size());control.AddGlass(i,vertices.data(),vertices.size());
218 }
219 protectedRain.FinishGeometry();control.FinishGeometry();
220 Check(protectedRain.PaneCount()>0,"aircraft has wettable glass");
221 for(size_t i=0;i<protectedRain.PaneCount();++i)
222 {
223 auto& a=Rendering::WindshieldRain11TestAccess::Water(protectedRain,i);
224 for(const auto& position:Rendering::WindshieldRain11TestAccess::VerticalSamples(protectedRain,i,transforms))
225 a.Impact(position,.002f,false);
226 a.Rebuild();
227 Rendering::WindshieldRain11TestAccess::Water(control,i)=a;
228 }
229 protectedRain.Update(1.f/30,0,{0,-11,0},{},transforms,2.6f,false,1);
230 control.Update(1.f/30,0,{0,-11,0},{},transforms,2.6f,false);
231 unsigned blown=0,untouched=0;
232 for(size_t i=0;i<protectedRain.PaneCount();++i)
233 {
234 const auto& a=Rendering::WindshieldRain11TestAccess::Water(protectedRain,i).Drops();
235 const auto& b=Rendering::WindshieldRain11TestAccess::Water(control,i).Drops();
236 Check(a.size()==3 && b.size()==3,"switch-on moves water rather than instantly erasing it");
237 std::array<float,3> upward{};
238 float totalDelta=0;
239 const auto samples=Rendering::WindshieldRain11TestAccess::VerticalSamples(protectedRain,i,transforms);
240 for(size_t sample=0;sample<a.size();++sample)
241 {
242
243
244 const auto nearest=[&](
const std::vector<WindshieldRain::Drop>& drops) ->
const WindshieldRain::Drop& {
246 const float x=d.position.x-samples[sample].x,y=d.position.y-samples[sample].y;
247 return x*x+y*y;
248 };
249 return *std::min_element(drops.begin(),drops.end(),[&](const auto& l,const auto& r) {return distance(l)<distance(r);});
250 };
251 const auto& actual=nearest(a);const auto& baseline=nearest(b);
252 const auto delta=Rendering::WindshieldRain11TestAccess::WorldDelta(protectedRain,i,
253 {actual.position.x-baseline.position.x,actual.position.y-baseline.position.y},transforms);
254 upward[sample]=delta.y;
255 totalDelta+=std::abs(delta.x)+std::abs(delta.y)+std::abs(delta.z);
256 }
257 if(upward[0]>.00001f)
258 {
259 ++blown;
260 Check(upward[0]>upward[1] && upward[1]>upward[2],"authored glass jet weakens from aircraft-bottom to top");
261 }
262 else {Check(totalDelta<1.e-7f,"unprotected panes unchanged");++untouched;}
263 }
264 Check(blown>0 && untouched>0,"forward glass blown up; side glass untouched");
265 double protectedArea=0,controlArea=0;
266 for(int tick=0;tick<90;++tick)
267 {
268 protectedRain.Update(1.f/30,1,{0,-11,0},{},transforms,2.6f,false,1);
269 control.Update(1.f/30,1,{0,-11,0},{},transforms,2.6f,false);
270 }
271 for(size_t i=0;i<protectedRain.PaneCount();++i)
272 {
273 protectedArea+=Rendering::WindshieldRain11TestAccess::Water(protectedRain,i).Wetness();
274 controlArea+=Rendering::WindshieldRain11TestAccess::Water(control,i).Wetness();
275 }
276 std::cout<<model<<" rain-air/control wetness "<<protectedArea<<"/"<<controlArea<<"\n";
277 Check(protectedArea<controlArea,"air curtain reduces water buildup in heavy rain");
278 std::cout<<"PASS: "<<model<<" rain air; "<<blown<<" forward panes, "<<untouched<<" unchanged panes\n";
279 }
280 }
281 void RunoffDirectionChecks()
282 {
284 using Access=Rendering::WindshieldRain11TestAccess;
285 for(const char* model:{"manx-int-hex","C-2 Dasher INT","e11cockpit1","p13-cockpit1"})
286 {
288 std::ifstream dix(std::string("Meshes/")+model+".dix",std::ios::binary);
289 std::ifstream daw(std::string("Meshes/")+model+".daw",std::ios::binary);
290 Check(dix.good()&&daw.good(),"open authored runoff cockpit");
291 const int count=Read<short>(dix,0),vertexCount=Read<unsigned short>(daw,0);
292 daw.seekg(0,std::ios::end);
const int stride=
int((std::streamoff(daw.tellg())-4)/vertexCount);
293 Check(stride==32||stride==40,"runoff mesh stride");
294 std::vector<WindshieldRain11::Matrix> transforms(count);
295 for(int i=0;i<count;++i)
296 {
297 const int o=99+i*100;
298 const auto xyz=Read<Vector>(dix,o+4),ypr=Read<Vector>(dix,o+16);
300 DirectX::XMStoreFloat4x4(&cockpitToView,DirectX::XMMatrixRotationRollPitchYaw(ypr.y,ypr.x,ypr.z)
301 *DirectX::XMMatrixTranslation(xyz.x,xyz.y,xyz.z)*DirectX::XMMatrixRotationX(DirectX::XM_PIDIV2)
302 *DirectX::XMMatrixRotationY(DirectX::XM_PI));
304 if(Read<unsigned char>(dix,o+58)!=5)continue;
305 const int first=Read<short>(dix,o),n=Read<short>(dix,o+2)*3;
306 Check(first>=0&&n>=0&&first+n<=vertexCount,"runoff mesh bounds");
307 std::vector<WindshieldRain11::Vertex> vertices(n);
308 for(int j=0;j<n;++j)vertices[j]=Read<WindshieldRain11::Vertex>(daw,2+stride*(first+j));
309 rain.
AddGlass(i,vertices.data(),vertices.size());
310 }
312 unsigned sides=0,fronts=0;float worstDrift=0;
314 {
315 const auto normal=
Normalize(Access::Normal(rain,i,transforms));
316 const bool side=std::abs(normal.x)>std::abs(normal.z);
317 side ? ++sides : ++fronts;
318 const auto force=Access::Acceleration(rain,i,{0,-11.27f,0},transforms);
319 Check(force.y<-.1f,"authored glass drains downward under local gravity");
320 Check(std::abs(side ? force.z : force.x)<.0001f,
321 "side runoff has no fore/aft slant; front runoff has no lateral fanning");
322 Check(std::abs(
Dot(force,normal))<.0001f,
"runoff follows the glass surface");
323 const auto doubleLoad=Access::Acceleration(rain,i,{0,-22.54f,0},transforms);
324 Check(
Length(doubleLoad-force*2)<.0001f,
"vertical load scaling is preserved");
325 const Vector maneuver{3,0,4};
326 const auto inertial=Access::Acceleration(rain,i,maneuver,transforms);
327 Check(
Length(inertial-(maneuver-normal*
Dot(maneuver,normal)))<.0001f,
328 "lateral and longitudinal maneuver forces retain their tangential projection");
329 auto& water=Access::Water(rain,i);
330 const auto center=Access::VerticalSamples(rain,i,transforms)[1];
331 water.Impact(center,.0025f,false);
332 }
333
334
335 for(
int tick=0;tick<6;++tick)rain.
Update(1.f/30,0,{0,-11.27f,0},{},transforms,2.6f,
false);
337 {
338 const auto& drops=Access::Water(rain,i).Drops();Check(!drops.empty(),"runoff retains tracked water");
339 const auto& drop=*std::max_element(drops.begin(),drops.end(),[](const auto& a,const auto& b){return a.radius<b.radius;});
340 const auto center=Access::VerticalSamples(rain,i,transforms)[1];
341 const auto motion=Access::WorldDelta(rain,i,{drop.position.x-center.x,drop.position.y-center.y},transforms);
342 const auto normal=Access::Normal(rain,i,transforms);
343 const bool side=std::abs(normal.x)>std::abs(normal.z);
344 Check(motion.y<-.001f,"beads visibly descend on authored panes");
345 const float drift=std::abs(side ? motion.z : motion.x)/-motion.y;
346 worstDrift=(std::max)(worstDrift,drift);
347 Check(drift<.25f,"roughness does not restore the broad diagonal runoff");
348 }
349 if(!strcmp(model,"manx-int-hex"))Check(sides>=2&&fronts>=1,"Manx includes both side windows and front glass");
350 Check(rain.
Wet(),
"normal flight accumulates water");
352 Check(!rain.
Wet()&&rain.
Wetness()==0,
"simulator entry clears beads and residue");
354 rain.
Update(.25f,1,{0,-11.27f,0},{0,0,-100},transforms,2.6f,
true,1);
355 Check(!rain.
Wet()&&rain.
PaneCount()==panes,
"simulator blocks impacts, wind and rain air while retaining geometry");
356 Matrix identity;DirectX::XMStoreFloat4x4(&identity,DirectX::XMMatrixIdentity());
357
358 Access::Water(rain,0).Impact({.5f,.5f},.0025f);Access::Water(rain,0).Rebuild();
359 Check(rain.
Render(
nullptr,
nullptr,
nullptr,{},transforms,identity)==S_FALSE,
"simulator suppresses rain rendering");
360 Access::Water(rain,0).Clear();
362 Check(!rain.
Wet(),
"simulator exit cannot replay old water");
363 rain.
Update(.25f,1,{0,-11.27f,0},{},transforms,2.6f,
false);
364 Check(rain.
Wet(),
"new real-world rain resumes after simulator exit");
365 rain.
SetSimulator(
true);Check(!rain.
Wet(),
"repeated simulator entry clears new water");
366 std::cout<<"PASS: "<<model<<" runoff; "<<sides<<" side / "<<fronts<<" front panes; max drift/down="
367 <<worstDrift<<"; simulator entry, update, render and exit\n";
368 }
369 }
370 struct Fixture
371 {
372 Rendering::Device11 gpu;
373 Rendering::SceneDepth11 depth;
374 Rendering::FixedFunction11 fixed;
375 WindshieldRainRenderer oldRain;
376 WindshieldRain11 rain;
377 ComPtr<IDirect3D9> api;
378 ComPtr<IDirect3DDevice9> old;
379 ComPtr<ID3DXEffect> effect;
380 ComPtr<IDirect3DSurface9> oldTarget,oldStaging,oldDepth;
381 ComPtr<ID3D11Texture2D>
target,staging;
382 ComPtr<ID3D11RenderTargetView> rtv;
383 ComPtr<ID3D11RasterizerState> raster;
384 ComPtr<ID3D11BlendState> depthOnly;
385 std::vector<uint32_t> background;
386 D3DXMATRIX identity,world,projection;
387 WindshieldRain11::Matrix nativeWorld,nativeProjection;
388 HWND window=nullptr;
389 std::filesystem::path folder;
390 std::ofstream metrics;
391 unsigned failures=0;
392 Fixture(bool warp,bool debug)
393 {
394 folder=std::string("outputs/direct3d11/windshield-")+(warp ? "warp" : "hardware");
395 std::filesystem::create_directories(folder);metrics.open(folder/"metrics.csv");
396 metrics<<"case,mean_rgb,mean_alpha,fraction_over_3,max_rgb\n";
397 HR(gpu.
Create({warp ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE,debug}),
"native device");std::cout<<gpu.
Status()<<std::endl;
399 HR(fixed.
Initialize(gpu.
Device(),ShaderDirectory),
"native screen geometry");
400 window=CreateWindowW(L"STATIC",L"Windshield comparison",WS_POPUP,0,0,Width,Height,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
401 Check(window!=nullptr,"window");api.Attach(Direct3DCreate9(D3D_SDK_VERSION));Check(bool(api),"reference API");
402 D3DPRESENT_PARAMETERS present{};present.Windowed=TRUE;present.SwapEffect=D3DSWAPEFFECT_DISCARD;
403 present.BackBufferWidth=
Width;present.BackBufferHeight=
Height;present.hDeviceWindow=window;
404 HR(api->CreateDevice(0,D3DDEVTYPE_HAL,window,D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_FPU_PRESERVE,&present,&old),"reference device");
405 ComPtr<ID3DXBuffer> errors;
406 const HRESULT compiled=D3DXCreateEffectFromFileW(old.Get(),L
"CustomUI.fx",
nullptr,
nullptr,D3DXSHADER_OPTIMIZATION_LEVEL3,
nullptr,&effect,&errors);
407 if(errors)std::cout<<static_cast<const char*>(errors->GetBufferPointer());HR(compiled,"reference effect");
408 HR(old->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,D3DMULTISAMPLE_NONE,0,FALSE,&oldTarget,nullptr),"reference target");
409 HR(old->CreateOffscreenPlainSurface(Width,Height,D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&oldStaging,nullptr),"reference staging");
410 HR(old->CreateDepthStencilSurface(Width,Height,D3DFMT_D24S8,D3DMULTISAMPLE_NONE,0,FALSE,&oldDepth,nullptr),"reference depth");
411 D3D11_TEXTURE2D_DESC desc{};desc.Width=
Width;desc.Height=
Height;desc.ArraySize=desc.MipLevels=1;desc.Format=DXGI_FORMAT_B8G8R8A8_UNORM;
412 desc.SampleDesc.Count=1;desc.BindFlags=D3D11_BIND_RENDER_TARGET;
413 HR(gpu.
Device()->CreateTexture2D(&desc,
nullptr,&target),
"native target");HR(gpu.
Device()->CreateRenderTargetView(
target.Get(),
nullptr,&rtv),
"native RTV");
414 desc.Usage=D3D11_USAGE_STAGING;desc.BindFlags=0;desc.CPUAccessFlags=D3D11_CPU_ACCESS_READ;
415 HR(gpu.
Device()->CreateTexture2D(&desc,
nullptr,&staging),
"native staging");
416 HR(depth.
Create(gpu.
Device(),Width,Height,{1,0}),
"native depth");
417 D3D11_RASTERIZER_DESC rs{};rs.FillMode=D3D11_FILL_SOLID;rs.CullMode=D3D11_CULL_NONE;rs.DepthClipEnable=TRUE;
418 HR(gpu.
Device()->CreateRasterizerState(&rs,&raster),
"native raster");
419 const D3D11_BLEND_DESC blend{};HR(gpu.
Device()->CreateBlendState(&blend,&depthOnly),
"depth-only blend");
420 background.resize(Width*Height);
421 for(UINT y=0;y<
Height;++y)
for(UINT x=0;x<
Width;++x)
422 background[y*Width+x]=0xff000000|((32+x*191/Width)<<16)|((32+y*191/
Height)<<8)|(((x/17+y/17)%2) ? 190 : 45);
423 D3DXMatrixIdentity(&identity);D3DXMatrixTranslation(&world,0,0,-.5f);D3DXMatrixOrthoRH(&projection,.0024f,.0014f,0,1);
424 memcpy(&nativeWorld,&world,sizeof(world));memcpy(&nativeProjection,&projection,sizeof(projection));
425 const Vertex glass[]={{-.001f,.0005f,0,0,0,-1,0,0},{.001f,.0005f,0,0,0,-1,1,0},{-.001f,-.0005f,0,0,0,-1,0,1},
426 {.001f,.0005f,0,0,0,-1,1,0},{.001f,-.0005f,0,0,0,-1,1,1},{-.001f,-.0005f,0,0,0,-1,0,1}};
427 std::vector<WindshieldRain11::Vertex> nativeGlass(std::size(glass));
428 static_assert(sizeof(Vertex)==sizeof(WindshieldRain11::Vertex));memcpy(nativeGlass.data(),glass,sizeof(glass));
431 for(unsigned i=0;i<120;++i)
432 {
433 const D3DXVECTOR3 acceleration(0,9.8f,0),wind(2,1,-8);
434 oldRain.
Update(1.f/30,.7f,acceleration,wind,{identity},1,
false);
435 WindshieldRain11::Matrix nativeIdentity;memcpy(&nativeIdentity,&identity,sizeof(identity));
436 rain.
Update(1.f/30,.7f,{0,9.8f,0},{2,1,-8},{nativeIdentity},1,
false);
437 }
438 const auto& oldWater=WindshieldRainTestAccess::Water(oldRain);const auto& nativeWater=Rendering::WindshieldRain11TestAccess::Water(rain);
439 Check(oldWater.Drops().size()==nativeWater.Drops().size(),"drop count parity");
440 double worst=0;
441 for(size_t i=0;i<oldWater.Drops().size();++i)
442 {
443 const auto& a=oldWater.Drops()[i];const auto& b=nativeWater.Drops()[i];
444 worst=(std::max)(worst,double(std::abs(a.position.x-b.position.x)));
445 worst=(std::max)(worst,double(std::abs(a.position.y-b.position.y)));
446 worst=(std::max)(worst,double(std::abs(a.radius-b.radius)));
447 }
448
449
450
451 Check(std::abs(oldWater.Width()-nativeWater.Width())<1.e-6f && std::abs(oldWater.Height()-nativeWater.Height())<1.e-6f,"chart dimensions");
452 Check(worst<.00005,"water motion parity");std::cout<<"PASS: 120 native water frames; "<<oldWater.Drops().size()<<" drops; maximum position/radius delta="<<worst<<" m\n";
453
454 Rendering::WindshieldRain11TestAccess::Water(rain)=oldWater;
455 }
456 ~Fixture(){rain.
ResetDevice();gpu.
Context()->ClearState();oldRain.
Clear();effect.Reset();old.Reset();api.Reset();
if(window)DestroyWindow(window);}
457 void Save(const std::vector<uint32_t>& pixels,const std::string& name)
458 {
459 D3DLOCKED_RECT lock{};HR(oldStaging->LockRect(&lock,nullptr,0),"save map");
460 for(UINT y=0;y<Height;++y)memcpy(static_cast<char*>(lock.pBits)+y*lock.Pitch,pixels.data()+y*
Width,
Width*4);
461 oldStaging->UnlockRect();HR(D3DXSaveSurfaceToFileW((folder/name).c_str(),D3DXIFF_PNG,oldStaging.Get(),nullptr,nullptr),"save image");
462 }
463 void MaskNative(const RECT& rect,float z,UINT reference)
464 {
465 auto* context=gpu.
Context();D3D11_DEPTH_STENCIL_DESC ds{};
466 ds.DepthEnable=TRUE;ds.DepthWriteMask=D3D11_DEPTH_WRITE_MASK_ALL;ds.DepthFunc=D3D11_COMPARISON_ALWAYS;
467 ds.StencilEnable=TRUE;ds.StencilReadMask=ds.StencilWriteMask=255;
468 ds.FrontFace=ds.BackFace={D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_REPLACE,D3D11_COMPARISON_ALWAYS};
469 ComPtr<ID3D11DepthStencilState> state;HR(gpu.
Device()->CreateDepthStencilState(&ds,&state),
"mask depth state");
470 context->OMSetDepthStencilState(state.Get(),reference);context->OMSetBlendState(depthOnly.Get(),nullptr,0xffffffff);
471 std::array<Rendering::FixedVertex11,4> vertices;
472 for(unsigned i=0;i<4;++i)vertices[i].position={float((i&1) ? rect.right : rect.left),float((i&2) ? rect.bottom : rect.top),z,1};
473 D3D11_BUFFER_DESC buffer{};buffer.ByteWidth=sizeof(vertices);buffer.Usage=D3D11_USAGE_IMMUTABLE;buffer.BindFlags=D3D11_BIND_VERTEX_BUFFER;
474 const D3D11_SUBRESOURCE_DATA initial{vertices.data(),0,0};ComPtr<ID3D11Buffer> geometry;
475 HR(gpu.
Device()->CreateBuffer(&buffer,&initial,&geometry),
"mask geometry");
auto* vb=geometry.Get();
476 const UINT stride=sizeof(Rendering::FixedVertex11),offset=0;context->IASetVertexBuffers(0,1,&vb,&stride,&offset);
477 context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
478 Rendering::FixedState11 fixedState;fixedState.
viewport={0,0,float(Width),float(Height)};
480 HR(fixed.
Bind(context,fixedState),
"mask shader");context->Draw(4,0);
481 }
482 void Compare(unsigned scenario)
483 {
484 const bool mixed=scenario==1;const float opacity=scenario==2 ? .45f : 1.f,cockpitLight=scenario==3 ? .8f : 0;
485 D3DLOCKED_RECT lock{};HR(oldStaging->LockRect(&lock,nullptr,0),"background map");
486 for(UINT y=0;y<Height;++y)memcpy(static_cast<char*>(lock.pBits)+y*lock.Pitch,background.data()+y*
Width,
Width*4);
487 oldStaging->UnlockRect();HR(old->UpdateSurface(oldStaging.Get(),nullptr,oldTarget.Get(),nullptr),"reference background");
488 old->SetRenderTarget(0,oldTarget.Get());old->SetDepthStencilSurface(mixed ? oldDepth.Get() : nullptr);
489 const D3DVIEWPORT9 vp{0,0,
Width,
Height,0,1};old->SetViewport(&vp);
490 old->SetRenderState(D3DRS_STENCILENABLE,FALSE);old->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);
491 const RECT masks[]={{140,90,210,270},{260,90,330,270},{390,90,460,270}};
492 if(mixed)
493 {
494 HR(old->Clear(0,nullptr,D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,0,.1f,0),"world clear");
495 for(unsigned i=0;i<3;++i)
496 {
497 const D3DRECT rect{masks[i].left,masks[i].top,masks[i].right,masks[i].bottom};
498 HR(old->Clear(1,&rect,D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,0,i==2 ? .8f : .2f,i==0 ? 4 : 3),"reference cockpit mask");
499 }
500 }
501 HR(old->BeginScene(),"reference scene");
502 HR(oldRain.
Render(old.Get(),effect.Get(),{world},projection,opacity,mixed ? WindshieldRainRenderer::DepthLayout::CockpitAndWorld : WindshieldRainRenderer::DepthLayout::Unified,cockpitLight),
"reference water");
503 HR(old->EndScene(),"reference end");HR(old->GetRenderTargetData(oldTarget.Get(),oldStaging.Get()),"reference readback");
504 HR(oldStaging->LockRect(&lock,nullptr,D3DLOCK_READONLY),"reference map");std::vector<uint32_t> expected(Width*Height);
505 for(UINT y=0;y<
Height;++y)memcpy(expected.data()+y*Width,
static_cast<char*
>(lock.pBits)+y*lock.Pitch,Width*4);oldStaging->UnlockRect();
506 auto* context=gpu.
Context();context->ClearState();context->UpdateSubresource(
target.Get(),0,
nullptr,background.data(),Width*4,0);
507 auto* targetView=rtv.Get();context->OMSetRenderTargets(1,&targetView,mixed ? depth.
WriteView() :
nullptr);
508 const D3D11_VIEWPORT viewport{0,0,float(Width),float(Height),0,1};context->RSSetViewports(1,&viewport);context->RSSetState(raster.Get());
509 if(mixed)
510 {
511 context->ClearDepthStencilView(depth.
WriteView(),D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL,.1f,0);
512 for(unsigned i=0;i<3;++i)MaskNative(masks[i],i==2 ? .8f : .2f,i==0 ? 4 : 3);
513 }
514 context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
515 HR(rain.
Render(context,rtv.Get(),mixed ? depth.
ReadView() :
nullptr,viewport,{nativeWorld},nativeProjection,opacity,
516 mixed ? WindshieldRain11::DepthLayout::CockpitAndWorld : WindshieldRain11::DepthLayout::Unified,cockpitLight),"native water");
517 D3D11_PRIMITIVE_TOPOLOGY restored{};context->IAGetPrimitiveTopology(&restored);Check(restored==D3D11_PRIMITIVE_TOPOLOGY_LINELIST,"caller state restored");
518 context->OMSetRenderTargets(0,
nullptr,
nullptr);context->CopyResource(staging.Get(),
target.Get());
519 D3D11_MAPPED_SUBRESOURCE mapped{};HR(context->Map(staging.Get(),0,D3D11_MAP_READ,0,&mapped),"native readback");
520 std::vector<uint32_t> actual(Width*Height),difference(Width*Height);double error=0,alpha=0;unsigned over=0,maximum=0,changed=0;
521 for(UINT y=0;y<
Height;++y)
for(UINT x=0;x<
Width;++x)
522 {
523 const auto a=expected[y*
Width+x],b=
reinterpret_cast<const uint32_t*
>(
static_cast<const char*
>(mapped.pData)+y*mapped.RowPitch)[x];
524 actual[y*
Width+x]=b;changed+=b!=background[y*
Width+x];
unsigned worst=0;
525 for(int shift:{0,8,16}){const auto d=unsigned(std::abs(int((a>>shift)&255)-int((b>>shift)&255)));error+=d;worst=(std::max)(worst,d);}
526 alpha+=std::abs(int(a>>24)-int(b>>24));maximum=(std::max)(maximum,worst);over+=worst>3;
527 difference[y*
Width+x]=0xff000000|((std::min)(255u,worst*8)*0x10101);
528 if(mixed && y>=90 && y<270 && ((x>=140 && x<210) || (x>=260 && x<330)))
529 Check(b==background[y*Width+x],"opaque interior and foreground wiper remain unchanged");
530 }
531 context->Unmap(staging.Get(),0);Check(changed>100,"wet glass visibly rendered");
533 const bool passed=error<=1 && alpha<=1 && fraction<=.01;
534 std::cout<<(passed ? "PASS: " : "FAIL: ")<<"windshield "<<scenario<<" mean="<<error<<" alpha="<<alpha<<" over3="<<fraction<<" max="<<maximum<<std::endl;
535 metrics<<scenario<<','<<error<<','<<alpha<<','<<fraction<<','<<maximum<<'\n';
536 const auto prefix="windshield-"+std::to_string(scenario);Save(expected,prefix+"-d3d9.png");Save(actual,prefix+"-d3d11.png");Save(difference,prefix+"-diff8x.png");
537 if(!passed)++failures;
538 }
539 void AuthoredVisibility(const char* model)
540 {
541 using namespace Rendering::Math11;
542 WindshieldRain11 wet;
544 std::ifstream dix(std::string("Meshes/")+model+".dix",std::ios::binary),daw(std::string("Meshes/")+model+".daw",std::ios::binary);
545 Check(dix.good()&&daw.good(),"open authored visibility cockpit");
546 const int count=Read<short>(dix,0),vc=Read<unsigned short>(daw,0);
547 daw.seekg(0,std::ios::end);
const int stride=
int((std::streamoff(daw.tellg())-4)/vc);
548 Check(stride==32||stride==40,"visibility mesh stride");
549 std::vector<Matrix> transforms(count);
550 std::vector<Rendering::FixedVertex11> interior;
551 for(int i=0;i<count;++i)
552 {
553 const int o=99+i*100,first=Read<short>(dix,o),n=Read<short>(dix,o+2)*3;
554 Check(first>=0&&n>=0&&first+n<=vc,"visibility mesh bounds");
555 const int type=Read<unsigned char>(dix,o+58);
556 const auto xyz=Read<Vector>(dix,o+4),ypr=Read<Vector>(dix,o+16);
557 DirectX::XMStoreFloat4x4(&transforms[i],DirectX::XMMatrixRotationRollPitchYaw(ypr.y,ypr.x,ypr.z)
558 *DirectX::XMMatrixTranslation(xyz.x,xyz.y,xyz.z)*DirectX::XMMatrixRotationX(DirectX::XM_PIDIV2)
559 *DirectX::XMMatrixRotationY(DirectX::XM_PI));
560 std::vector<WindshieldRain11::Vertex> vertices(n);
561 for(int j=0;j<n;++j)
562 {
563 vertices[j]=Read<WindshieldRain11::Vertex>(daw,2+stride*(first+j));
564 if(type!=5 && type!=51 && type!=251 && Read<short>(dix,o+44)>=0 && Read<short>(dix,o+91)==0)
565 {
566 const auto& p=vertices[j];
const auto v=
TransformPoint({p.x,p.y,p.z},transforms[i]);
567 Rendering::FixedVertex11 f;f.position={v.x,v.y,v.z,1};interior.push_back(f);
568 }
569 }
570 if(type==5)wet.
AddGlass(i,vertices.data(),vertices.size());
571 }
573 Check(wet.
PaneCount()==8,
"P-13's five glass components produce eight panes");
574 std::vector<Matrix> physics;
for(
const auto& transform:transforms)physics.push_back(wet.
ToPhysicsTransform(transform));
575 for(
int tick=0;tick<150;++tick)wet.
Update(1.f/30,1,{0,-11.27f,0},{},physics,2.6f,
false);
577 D3D11_BUFFER_DESC bd{};bd.ByteWidth=UINT(interior.size()*sizeof(interior[0]));bd.Usage=D3D11_USAGE_IMMUTABLE;bd.BindFlags=D3D11_BIND_VERTEX_BUFFER;
578 const D3D11_SUBRESOURCE_DATA init{interior.data(),0,0};ComPtr<ID3D11Buffer> geometry;
579 HR(gpu.
Device()->CreateBuffer(&bd,&init,&geometry),
"authored interior");
580 for(UINT samples:{1u,4u})
581 {
582 D3D11_TEXTURE2D_DESC sceneDesc{};
target->GetDesc(&sceneDesc);sceneDesc.SampleDesc={samples,0};
583 ComPtr<ID3D11Texture2D> authoredTarget;ComPtr<ID3D11RenderTargetView> authoredView;
584 HR(gpu.
Device()->CreateTexture2D(&sceneDesc,
nullptr,&authoredTarget),
"authored scene target");
585 HR(gpu.
Device()->CreateRenderTargetView(authoredTarget.Get(),
nullptr,&authoredView),
"authored scene view");
586 Rendering::SceneDepth11 authoredDepth;HR(authoredDepth.
Create(gpu.
Device(),Width,Height,{samples,0}),
"authored depth");
587 for(int pan:{-60,0,60})for(bool mask:{false,true})
588 {
589 context->ClearState();
590 const float clear[]={64.f/255,96.f/255,128.f/255,1};
591 context->ClearRenderTargetView(authoredView.Get(),clear);
592 auto* targetView=authoredView.Get();context->OMSetRenderTargets(1,&targetView,authoredDepth.
WriteView());
593 context->ClearDepthStencilView(authoredDepth.
WriteView(),D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL,1,0);
594 const D3D11_VIEWPORT vp{0,0,float(Width),float(Height),0,1};context->RSSetViewports(1,&vp);
595 D3D11_RASTERIZER_DESC rs{};rs.FillMode=D3D11_FILL_SOLID;rs.CullMode=D3D11_CULL_BACK;
596 rs.FrontCounterClockwise=TRUE;rs.DepthClipEnable=TRUE;
597 ComPtr<ID3D11RasterizerState> poseRaster;HR(gpu.
Device()->CreateRasterizerState(&rs,&poseRaster),
"authored raster");context->RSSetState(poseRaster.Get());
598 Matrix project;DirectX::XMStoreFloat4x4(&project,DirectX::XMMatrixRotationY(DirectX::XMConvertToRadians(
float(pan)))
599 *DirectX::XMMatrixRotationZ(DirectX::XM_PI)
600 *DirectX::XMMatrixPerspectiveRH(.000025f*std::tan(DirectX::XMConvertToRadians(115.f)*.5f),
601 .000025f*std::tan(DirectX::XMConvertToRadians(115.f)*.5f)*float(Height)/Width,.000025f,.16f));
602 if(mask)
603 {
604 D3D11_DEPTH_STENCIL_DESC ds{};ds.DepthEnable=TRUE;ds.DepthWriteMask=D3D11_DEPTH_WRITE_MASK_ALL;ds.DepthFunc=D3D11_COMPARISON_LESS;
605 ds.StencilEnable=TRUE;ds.StencilReadMask=ds.StencilWriteMask=255;
606 ds.FrontFace=ds.BackFace={D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_KEEP,D3D11_STENCIL_OP_REPLACE,D3D11_COMPARISON_ALWAYS};
607 ComPtr<ID3D11DepthStencilState> state;HR(gpu.
Device()->CreateDepthStencilState(&ds,&state),
"authored stencil");
608 context->OMSetDepthStencilState(state.Get(),4);context->OMSetBlendState(depthOnly.Get(),nullptr,UINT_MAX);
610 HR(fixed.
Bind(context,f),
"authored interior shader");
auto* vb=geometry.Get();
const UINT bytes=
sizeof(Rendering::FixedVertex11),offset=0;
611 context->IASetVertexBuffers(0,1,&vb,&bytes,&offset);context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);context->Draw(UINT(interior.size()),0);
612 }
613 const HRESULT result=wet.
Render(context,authoredView.Get(),authoredDepth.
ReadView(),vp,transforms,project,1,WindshieldRain11::DepthLayout::CockpitAndWorld);
614 HR(result,"authored water draw");context->OMSetRenderTargets(0,nullptr,nullptr);
615 if(samples>1)context->ResolveSubresource(
target.Get(),0,authoredTarget.Get(),0,sceneDesc.Format);
616 else context->CopyResource(
target.Get(),authoredTarget.Get());
617 context->CopyResource(staging.Get(),
target.Get());
618 D3D11_MAPPED_SUBRESOURCE mapped{};HR(context->Map(staging.Get(),0,D3D11_MAP_READ,0,&mapped),"authored pixels");
619 std::vector<uint32_t> pixels(Width*Height);unsigned changed=0;
620 for(UINT y=0;y<
Height;++y)
for(UINT x=0;x<
Width;++x)
621 {pixels[y*
Width+x]=
reinterpret_cast<const uint32_t*
>(
static_cast<const char*
>(mapped.pData)+y*mapped.RowPitch)[x];changed+=(pixels[y*
Width+x]&0xffffff)!=0x406080;}
622 context->Unmap(staging.Get(),0);
623 Check(result==S_OK && changed>100,"natural rain is visible on authored P-13 front and side glass");
624 std::cout<<
"PASS: "<<model<<
" samples="<<samples<<
" pan="<<pan<<
" interior="<<
mask<<
" rain pixels="<<changed<<std::endl;
625 Save(pixels,std::string(model)+"-msaa"+std::to_string(samples)+"-pan"+std::to_string(pan)+"-"+std::to_string(mask)+".png");
626 }
627 }
628 }
629 void MaskFormatCheck()
630 {
631 using Access=Rendering::WindshieldRain11TestAccess;
632
633
634 for(UINT samples:{1u,4u})for(bool compact:{false,true})
635 for(auto format:{DXGI_FORMAT_B8G8R8A8_UNORM,DXGI_FORMAT_R8G8B8A8_UNORM,
636 DXGI_FORMAT_B8G8R8A8_UNORM_SRGB,DXGI_FORMAT_R16G16B16A16_FLOAT})
637 for(UINT width:{64u,127u})
638 Check(Access::MaskTargets(rain,width,73,samples,format,compact),"visibility mask format/resize regression");
639 rain.
ReleaseTargets();Check(Access::MaskReleased(rain),
"visibility mask released on reset");
640 std::cout<<"PASS: 32 visibility-mask format/resize cases; compact, reference, sRGB and HDR; release\n";
641 }
642 void DebugCheck()
643 {
644 ComPtr<ID3D11InfoQueue>
messages;
if(FAILED(gpu.
Device()->QueryInterface(IID_PPV_ARGS(&messages))))
return;
645 for(UINT64 i=0;i<
messages->GetNumStoredMessages();++i)
646 {
647 SIZE_T size=0;
messages->GetMessage(i,
nullptr,&size);std::vector<char> data(size);
auto* message=
reinterpret_cast<D3D11_MESSAGE*
>(data.data());
648 HR(
messages->GetMessage(i,message,&size),
"debug message");
649 if(message->Severity<=D3D11_MESSAGE_SEVERITY_WARNING)throw std::runtime_error(message->pDescription);
650 }
651 }
652 };
653}
654int main(
int argc,
char** argv)
655{
656 try
657 {
658 bool warp=false,debug=true,physicsOnly=false,authored=false;for(int i=1;i<argc;++i)
659 {if(!strcmp(argv[i],"--warp"))warp=true;else if(!strcmp(argv[i],"--no-debug-layer"))debug=false;
660 else if(!strcmp(argv[i],"--physics-only"))physicsOnly=true;else if(!strcmp(argv[i],"--authored"))authored=true;else throw std::runtime_error("unknown argument");}
661 if(authored){Fixture fixture(warp,debug);fixture.AuthoredVisibility("p13-cockpit1");fixture.DebugCheck();return 0;}
662 RunoffDirectionChecks();RainAirChecks();AuthoredWipers();if(physicsOnly)return 0;
663 Fixture fixture(warp,debug);for(unsigned i=0;i<4;++i)fixture.Compare(i);
664 fixture.AuthoredVisibility("p13-cockpit1");fixture.MaskFormatCheck();fixture.DebugCheck();return fixture.failures ? 1 : 0;
665 }
666 catch(const std::exception& error){std::cerr<<"FAIL: "<<error.what()<<'\n';return 1;}
667}
SCRIPT_CONTROL SCRIPT_STATE const void int
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
ID3D11DeviceContext * Context() const
ID3D11Device * Device() const
const std::string & Status() const
HRESULT Create(const DeviceOptions11 &options={})
HRESULT Initialize(ID3D11Device *device, const std::filesystem::path &shaderDirectory={})
HRESULT Bind(ID3D11DeviceContext *context, const FixedState11 &state, bool pointList=false)
HRESULT Create(ID3D11Device *device, UINT width, UINT height, DXGI_SAMPLE_DESC samples)
ID3D11DepthStencilView * ReadView() const
ID3D11DepthStencilView * WriteView() const
void SetSimulator(bool value)
HRESULT Initialize(ID3D11Device *device, const std::filesystem::path &shaderDirectory={})
HRESULT Render(ID3D11DeviceContext *context, ID3D11RenderTargetView *target, ID3D11DepthStencilView *depth, const D3D11_VIEWPORT &viewport, const std::vector< Matrix > &world, const Matrix &viewProjection, float opacity=1, DepthLayout depthLayout=DepthLayout::Unified, float cockpitLight=0, ID3D11RenderTargetView *adExclusion=nullptr)
static Matrix ToPhysicsTransform(const Matrix &cockpitToView)
void Update(float elapsed, float rain, const Vector &acceleration, const Vector &relativeWind, const std::vector< Matrix > &transforms, float airDensity, bool wiping, float rainAir=0)
void AddGlass(int component, const Vertex *vertices, size_t count)
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
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)
float Dot(const Vector3 &a, const Vector3 &b)
State Evaluate(int equipment, bool selected, bool operating, float power, bool engineAvailable)
float ThrustMultiplier(State state)
Vector TransformPoint(const Vector &a, const Matrix &matrix)
float Length(const Vector &a)
Vector Normalize(const Vector &a)
Vector TransformVector(const Vector &a, const Matrix &matrix)
DirectX::XMFLOAT4X4 Matrix
float Dot(const Vector &a, const Vector &b)
Vec Acceleration(const Body &b, const Motion &m)
DirectX::XMFLOAT4X4 projection
DirectX::XMFLOAT4 viewport