1#include "../Rendering/ClientRenderer11.h"
2#include "../Rendering/FrameProfiler11.h"
3#include "../Rendering/Window11.h"
4#include "../UI/Controls.h"
5#include "../Viewscreen/CloudVolume.h"
6#include "../Viewscreen/RunwayEdgeLights.h"
7#include "../Rendering/RunwayLights11.h"
8#include "../Viewscreen/SignalLightAttenuation.h"
9#include "../Viewscreen/ShipLightSprites.h"
10#include "../Viewscreen/LandingLights.h"
11#include "../Viewscreen/WindshieldRainRenderer.h"
12#include <d3d11sdklayers.h>
13#include <wincodec.h>
14#include <cmath>
15#include <iostream>
16#include <stdexcept>
18using Microsoft::WRL::ComPtr;
19#include "CityLighting.generated.h"
20namespace {
21 unsigned checks=0;
22 void Check(bool ok,const char* message) {++checks;if(!ok)throw std::runtime_error(message);}
23 void HR(
HRESULT hr,
const char* message)
24 {
25 if(FAILED(hr))std::cerr<<message<<" HRESULT=0x"<<std::hex<<hr<<std::dec<<'\n';
26 Check(SUCCEEDED(hr),message);
27 }
29 {
30 ComPtr<ID3D11InfoQueue> queue;
if(FAILED(gpu.
Device()->QueryInterface(IID_PPV_ARGS(&queue))))
return;
31 unsigned errors=0;
32 for(UINT64 i=0;i<queue->GetNumStoredMessages();++i)
33 {
34 SIZE_T size=0;queue->GetMessage(i,nullptr,&size);std::vector<uint8_t> data(size);
35 auto* message=reinterpret_cast<D3D11_MESSAGE*>(data.data());HR(queue->GetMessage(i,message,&size),"read debug message");
36 if(message->Severity<=D3D11_MESSAGE_SEVERITY_WARNING){++errors;std::cerr<<message->pDescription<<'\n';}
37 }
38 Check(!errors,"D3D11 debug layer is clean");queue->ClearStoredMessages();
39 }
41 {
42 D3D11_TEXTURE2D_DESC desc{};gpu.
SceneColor()->GetDesc(&desc);
43 ID3D11Texture2D* source=gpu.
SceneColor();ComPtr<ID3D11Texture2D> resolved;
44 if(desc.SampleDesc.Count>1)
45 {
46 desc.SampleDesc={1,0};desc.BindFlags=0;
47 HR(gpu.
Device()->CreateTexture2D(&desc,
nullptr,&resolved),
"create multisample readback resolve");
48 gpu.
Context()->ResolveSubresource(resolved.Get(),0,source,0,desc.Format);source=resolved.Get();
49 }
50 Check(desc.SampleDesc.Count==1,"readback fixture is single sample");
51 desc.Usage=D3D11_USAGE_STAGING;desc.BindFlags=0;desc.CPUAccessFlags=D3D11_CPU_ACCESS_READ;desc.MiscFlags=0;
52 ComPtr<ID3D11Texture2D> staging;HR(gpu.
Device()->CreateTexture2D(&desc,
nullptr,&staging),
"create readback");
53 gpu.
Context()->CopyResource(staging.Get(),source);
54 D3D11_MAPPED_SUBRESOURCE map{};HR(gpu.
Context()->Map(staging.Get(),0,D3D11_MAP_READ,0,&map),
"map readback");
55 std::vector<uint32_t> result(size_t(desc.Width)*desc.Height);
56 for(UINT y=0;y<desc.Height;++y)memcpy(result.data()+size_t(y)*desc.Width,static_cast<uint8_t*>(map.pData)+size_t(y)*map.RowPitch,desc.Width*4);
57 gpu.
Context()->Unmap(staging.Get(),0);
58 Check(desc.Format==DXGI_FORMAT_R8G8B8A8_UNORM,"native scene color format");
59 for(auto& pixel:result)pixel=(pixel&0xff00ff00)|((pixel&255)<<16)|((pixel>>16)&255);
60 return result;
61 }
62
63 void CheckEncodedImage(
ImageBuffer& bytes,UINT expectedWidth,UINT expectedHeight,
DWORD expectedColor,
int tolerance)
64 {
65 ComPtr<IWICImagingFactory> factory;HR(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory)),"capture decoder factory");
66 ComPtr<IWICStream> stream;HR(factory->CreateStream(&stream),"capture decoder stream");
67 HR(stream->InitializeFromMemory(bytes.
bytes.data(),UINT(bytes.
bytes.size())),
"encoded capture stream");
68 ComPtr<IWICBitmapDecoder> decoder;HR(factory->CreateDecoderFromStream(stream.Get(),nullptr,WICDecodeMetadataCacheOnLoad,&decoder),"decode captured image");
69 ComPtr<IWICBitmapFrameDecode> frame;HR(decoder->GetFrame(0,&frame),"capture image frame");
70 UINT width=0,height=0;HR(frame->GetSize(&width,&height),"capture dimensions");Check(width==expectedWidth && height==expectedHeight,"capture crop dimensions");
71 ComPtr<IWICFormatConverter> converter;HR(factory->CreateFormatConverter(&converter),"capture pixel converter");
72 HR(converter->Initialize(frame.Get(),GUID_WICPixelFormat32bppBGRA,WICBitmapDitherTypeNone,nullptr,0,WICBitmapPaletteTypeCustom),"capture BGRA pixels");
73 std::vector<DWORD> pixels(size_t(width)*height);HR(converter->CopyPixels(nullptr,width*4,UINT(pixels.size()*4),reinterpret_cast<BYTE*>(pixels.data())),"capture decoded pixels");
74 bool equal=
true;
for(
DWORD pixel:pixels)
for(UINT shift:{0u,8u,16u})equal&=std::abs(
int((pixel>>shift)&255)-
int((expectedColor>>shift)&255))<=tolerance;
75 Check(equal,"capture retains color channels and crop origin");
76 }
77
78#include "CockpitInteriorRenderFixture.h"
79#include "IomereLighting11Tests.h"
80#include "ThrustConeBlend11Tests.h"
81
82void CityNightLighting(
Window11& host)
83{
84
85
86 for(float sun:{-.5f,0.f,.25f,1.f}) for(float thickness:{0.f,8.f}) for(float rain:{.4f,1.f})
87 {
88 const auto legacy=CityWeatherLight(false,sun,thickness,rain,.8f);
89 const auto volume=CityWeatherLight(true,sun,thickness,rain,.8f);
90 Check(std::abs(volume.a-legacy.a)<1e-6f,"volumetric lighting preserves the weather night-light control");
91 }
96 struct Vertex {float x,y,z,u,v,overlayU=0,overlayV=0;};
97 const Vertex quad[]={{-1,1,.1f,0,0},{1,1,.1f,1,0},{-1,-1,.1f,0,1},{1,-1,.1f,1,1}};
98 ComPtr<RenderBuffer> vertices;void* memory=nullptr;
100 HR(vertices->Lock(0,0,&memory,0),"lock city quad");memcpy(memory,quad,sizeof(quad));HR(vertices->Unlock(),"upload city quad");
101 HR(device.SetStreamSource(0,vertices.Get(),0,sizeof(Vertex)),"bind city quad");
104 HR(material.SetMatrix("matWorld",&identity),"city world");HR(material.SetMatrix("matWorldViewProj",&identity),"city projection");
106 HR(material.SetInt("LandingLightCount",0),"disable landing lights");
107 for(const char* name:{"Features","shiplight","WeapPos"})HR(material.SetVector(name,&zero),"disable unrelated city lighting");
108 ComPtr<RenderTexture> base,lights;
109 HR(
LoadTexture(&device,L
"Textures/Cities/AAAoffice.dds",&base),
"load actual city facade");
110 HR(
LoadTexture(&device,L
"Textures/Cities/AAAofficeLIGHT.dds",&lights),
"load actual city light layer");
111 HR(material.SetTexture("ColorMap",base.Get()),"bind city facade");
112 for(UINT pass:{2u,3u}) for(float sun:{-.5f,.25f,1.f})
113 {
114 const auto weather=CityWeatherLight(
true,sun,0,1,1);
117 HR(material.SetVector("ambient",&ambient),"city weather illumination");
118 HR(material.SetVector("clouduv",&blend),"city night-light blend");
119 const auto render=[&](bool powered) {
121 HR(material.SetTexture("ColorMap2",powered ? lights.Get() : nullptr),"district power selects city light layer");
122 HR(material.Begin(nullptr,0),"begin city material");HR(material.BeginPass(pass),"city near/far pass");
124 HR(material.EndPass(),"end city pass");HR(material.End(),"end city material");
126 };
127 const auto dark=render(false),lit=render(true),offAgain=render(false);
128 Check(dark==offAgain,"district power loss removes the light layer on the next draw");
129 unsigned brighter=0;
130 for(size_t i=0;i<lit.size();++i)if((lit[i]&0xffffff)>(dark[i]&0xffffff))++brighter;
131 Check(sun==1 ? lit==dark : brighter>100,"powered city windows illuminate at night/twilight and fade in daylight");
132 }
133 DebugClean(host.
Device());
134}
135
136#include "ShipLightSprite11Tests.h"
137
138void RunwayLightSprites(
Window11& host)
139{
141 HR(device.BeginScene(),"begin runway light fixture");
145 const float size=16;
DWORD sizeBits;memcpy(&sizeBits,&size,
sizeof(size));
152 ComPtr<RenderTexture> texture;
153 HR(
LoadTexture(&device,L
"Textures/pointsprite.dds",&texture),
"actual running-light texture");
154 HR(device.SetTexture(0,texture.Get()),"bind runway light texture");
155 struct Vertex {
float x,y,z;
DWORD color;};
156 const Vertex point={0,0,.5f,0xffffffff};
157 const Vertex triangle[]={{-.75f,.75f,.5f,0xffffffff},{.75f,.75f,.5f,0xffffffff},{0,-.75f,.5f,0xffffffff}};
159 std::vector<uint32_t> reference;
161 {
163 HR(device.Clear(0,
nullptr,
ClearFlags::TARGET,0xff000000,1,0),
"clear approach light frame");
164 HR(device.DrawPrimitiveUP(
Primitive::PointList,1,&point,
sizeof(point)),
"draw approach light point");
166 unsigned lit=0;for(auto pixel:pixels)if(pixel&0xffffff)++lit;
167 std::cout<<"Runway light cull="<<cull<<": "<<lit<<" lit pixels\n";
168 Check(lit>20,"approach light remains visible with world culling");
169 if(reference.empty())reference=pixels;
170 else Check(pixels==reference,"world winding does not change point sprite pixels");
172 Check(saved==cull,"point sprite preserves caller culling state");
173
174
178 const bool triangleVisible=(
Pixels(host.
Device())[24*64+32]&0xffffff)!=0;
179 Check(triangleVisible==(cull!=
Cull::CW),
"triangle culling survives point sprite draw");
181 }
182
183
185 for(
DWORD color:{0xffffffffu,0xffff8040u,0xff4080ffu,0xff080402u})
186 {
188 const auto render=[&](float transmission,bool corrected,bool isSimulator=false) {
189 auto legacy=emission;
190 legacy.r*=transmission;legacy.g*=transmission;legacy.b*=transmission;
191 legacy.a=transmission;
194 HR(device.Clear(0,
nullptr,
ClearFlags::TARGET,0xff000000,1,0),
"clear signal extinction frame");
195 HR(device.DrawPrimitiveUP(
Primitive::PointList,1,&point,
sizeof(point)),
"draw attenuated signal");
197 };
198 const auto clear=render(1,false);
199 Check(render(1,true)==clear,"single extinction preserves clear-air pixels");
200 for(float transmission:{0.f,.001f,.01f,.03f,.1f,.5f,1.f})
201 {
202 const auto attenuated=render(transmission,true);
203 bool matches=
true;
unsigned sum=0,peak=0;
204 for(size_t i=0;i<clear.size();++i)for(unsigned shift:{0u,8u,16u})
205 {
206 const unsigned original=(clear[i]>>shift)&255;
207 const unsigned actual=(attenuated[i]>>shift)&255;
208 matches &= std::abs(
float(actual)-
float(original)*transmission)<=2.f;
209 sum+=actual;peak=(std::max)(peak,original);
210 }
211 Check(matches,"normal flight applies signal transmission once");
212 const auto simulator=render(transmission,true,true);
213 Check(simulator==render(transmission,false),"simulator pixels exactly match the packed baseline after normal flight");
214 Check(render(transmission,true)==attenuated,"leaving the simulator immediately restores single extinction");
215 if(transmission==0)Check(sum==0,"zero transmission emits no signal light");
216 if(float(peak)*transmission>=2)Check(sum>0,"faint transmitted signal survives color quantization");
217 }
218 Check(render(1,false)==clear,"ordinary texture-factor setter restores subsequent draws");
219 }
220 HR(device.EndScene(),"finish runway light fixture");
221 DebugClean(host.
Device());
222}
223
224void RunwayEdgeSources(
Window11& host)
225{
227 for(unsigned row=0;row<3;++row)for(unsigned column=0;column<3;++column)
228 surface.
points[row][column]={
float(column)*.5f,float(row)*.5f,float(row*row+column*column)*.03f};
229 unsigned count=0;
231 Check((u>.7367412f && u<.73857f)||(u>.76143f && u<.7632588f),"edge core stays in the painted shoulder strip");
232 Check(v>.25f && v<1,"edge core stays between thresholds");
233 const float textureU=(u-.7367412f)*565.6621f,textureV=v*67.f;
234 Check(std::abs(textureU-std::floor(textureU)-.5f)<.0001f &&
235 std::abs(textureV-std::floor(textureV)-.5f)<.0001f,"edge source sits at an actual DDS core center");
237
238 const float expectedZ=.03f+(u-.5f)*.18f+(v<.5f ? v*.06f : .03f+(v-.5f)*.18f);
239 Check(std::abs(p.x-u)<1e-6f && std::abs(p.y-v)<1e-6f && std::abs(p.z-expectedZ)<1e-6f,
240 "edge sources follow both terrain subdivisions without flattening their height");
241 ++count;
242 });
243 Check(count==100,"the ground texture defines fifty lights on each runway edge");
246 Check(distant.diameter==3 && farther.diameter==3 && farther.intensity<distant.intensity,
247 "minimum pixel coverage still fades distant edge lights");
249
251 for(UINT samples:{1u,4u})
252 {
253 HR(host.
SetSamples(samples),
"edge source sample configuration");
255 HR(device.BeginScene(),"begin edge source fixture");
265 ComPtr<RenderTexture> texture;
266 HR(
LoadTexture(&device,L
"Textures/RTS/RunwayEdgeLight.dds",&texture),
"load the production runway ground-light DDS");
267 HR(device.SetTexture(0,texture.Get()),"bind core reference texture");
268 struct Vertex {float x,y,z,u=.5f,v=.5f;};
269 const Vertex quad[]={{-1,1,.75f},{1,1,.75f},{-1,-1,.75f},{1,-1,.75f}};
274 Check((core&0xffffff)!=0,"authored edge-light core has visible color");
276 std::vector<RunwayLightInstance11> lamps={{{0,0,.5f},4,1}};
277 for(bool isSimulator:{false,true}) for(float transmission:{1.f,.1f,.01f,0.f})
278 {
280 const float expectedTransmission=isSimulator ? transmission*transmission : transmission;
282 HR(batch.
Draw(host.
Draws(),texture->View(),lamps),
"draw native edge source");
284 for(unsigned shift:{0u,8u,16u})Check(std::abs(float((pixel>>shift)&255)-float((core>>shift)&255)*expectedTransmission)<=2,
285 "edge source keeps DDS hue with normal-flight T or simulator T-squared extinction");
286 Check(!memcmp(&saved,&host.
Draws().
Pipeline(),
sizeof(saved)),
"edge batch restores the caller's raster/depth/blend state");
287 Check((pixel>>24)==255,"edge sources preserve scene alpha");
288 }
289 lamps[0].intensity=1;
290 unsigned minimumEnergy=UINT_MAX,maximumEnergy=0;
291 for(float offset:{0.f,.25f,.5f,.75f})
292 {
293 lamps[0]={{offset*2/64,offset*2/48,.5f},3,.55f};
295 HR(batch.
Draw(host.
Draws(),texture->View(),lamps),
"draw moving distant edge core");
296 unsigned energy=0;
for(
auto pixel:
Pixels(host.
Device()))energy+=pixel&255;
297 minimumEnergy=(std::min)(minimumEnergy,energy);maximumEnergy=(std::max)(maximumEnergy,energy);
298 }
299 Check(minimumEnergy>0 && float(minimumEnergy)/maximumEnergy>.85f,"subpixel motion keeps edge-light energy stable");
300 lamps[0]={{0,0,.5f},4,1};
302 HR(batch.
Draw(host.
Draws(),texture->View(),lamps),
"draw hidden edge source");
304 Check(std::all_of(hidden.begin(),hidden.end(),[](
DWORD p){return !(p&0xffffff);}),
"terrain occludes the complete edge source");
305
307 HR(batch.
Draw(host.
Draws(),texture->View(),lamps),
"edge source before later geometry");
308 HR(device.Clear(0,
nullptr,
ClearFlags::TARGET,0xff000000,1,0),
"retain depth after edge source");
310 HR(device.DrawPrimitiveUP(
Primitive::TriangleStrip,2,quad,
sizeof(Vertex)),
"geometry behind the previous edge source");
311 Check((
Pixels(host.
Device())[24*64+32]&0xffffff)==(core&0xffffff),
"edge sources do not write depth or corrupt subsequent draws");
312
313 lamps={{{-.5f,0,.5f},4,.5f},{{.5f,0,.5f},4,1}};
315 HR(batch.
Draw(host.
Draws(),texture->View(),lamps),
"draw two differently attenuated edge instances");
317 Check((pair[24*64+16]&255)>0 && (pair[24*64+48]&255)>(pair[24*64+16]&255),"one batch retains distinct light positions and intensities");
318 HR(device.EndScene(),"end runway edge fixture");
319 DebugClean(host.
Device());
320 std::cout<<"Runway edge sprites: texture hue, attenuation, occlusion and batch checks at "<<samples<<"x MSAA\n";
321 }
322 HR(host.
SetSamples(1),
"restore suite sample count");
323}
324
325void WindshieldElmoOverlay(
Window11& host)
326{
328 HR(device.BeginScene(),"begin windshield overlay fixture");
334 struct Vertex {float x,y,z,nx,ny,nz,u,v;};
335 const Vertex quad[]={{-1,1,.1f,0,0,-1,0,0},{1,1,.1f,0,0,-1,1,0},
336 {-1,-1,.1f,0,0,-1,0,1},{1,-1,.1f,0,0,-1,1,1}};
337 ComPtr<RenderBuffer> vertices;void* memory=nullptr;
338 HR(device.CreateVertexBuffer(
sizeof(quad),0,0,
ResourcePool::Managed,&vertices,
nullptr),
"windshield quad");
339 HR(vertices->Lock(0,0,&memory,0),"lock windshield quad");memcpy(memory,quad,sizeof(quad));
340 HR(vertices->Unlock(),"upload windshield quad");
341 HR(device.SetStreamSource(0,vertices.Get(),0,sizeof(Vertex)),"bind windshield quad");
344 HR(material.SetMatrix("matWorldViewProj",&identity),"windshield projection");
345
346
347 constexpr DWORD emission=0xff204060;
348 ComPtr<RenderTexture> elmo;
350 LockedRectangle lock;HR(elmo->LockRect(0,&lock,
nullptr,0),
"write Elmo fixture");
351 for(unsigned y=0;y<8;++y)
352 std::fill_n(
reinterpret_cast<DWORD*
>(
static_cast<char*
>(lock.
pBits)+y*lock.
Pitch),8,emission);
353 HR(elmo->UnlockRect(0),"upload Elmo fixture");
354 HR(material.SetTexture("ColorMap2",elmo.Get()),"bind Elmo texture");
356 HR(material.SetVector("Features",®ion),"Elmo windshield region");
357 for(
DWORD background:{0xff102030u,0xffa0b0c0u})
358 {
359 const auto render=[&](
float mode,
float side,
DWORD stencil,
float depth=1.f) {
361 background,depth,stencil),"clear world and cockpit mask");
363 HR(material.SetVector("clouduv",&control),"windshield overlay mode");
364 HR(material.Begin(nullptr,0),"begin windshield material");HR(material.BeginPass(9),"windshield material pass");
367 }),"draw overlay through production cockpit mask");
368 HR(material.EndPass(),"end windshield pass");HR(material.End(),"end windshield material");
370 };
371 for(
DWORD stencil:{0u,3u})
for(
float side:{-1.f,1.f})
372 {
373 const auto actual=render(1,side,stencil);
374 for(unsigned y=0;y<48;++y) for(unsigned x=0;x<64;++x) for(unsigned shift:{0u,8u,16u})
375 {
376
377
378
379 if(x==16 || x==48 || y==12 || y==36)continue;
380 const bool inside=x>16 && x<48 && y>12 && y<36;
381 const float source=inside ? float((emission>>shift)&255) : 0.f;
382 const auto expected=std::lround(source+float((background>>shift)&255)*(1-source/255));
383 if(std::abs(long((actual[y*64+x]>>shift)&255)-expected)>1)
384 std::cerr<<"Elmo mismatch x="<<x<<" y="<<y<<" stencil="<<stencil<<" side="<<side
385 <<" actual=0x"<<std::hex<<actual[y*64+x]<<std::dec<<" channel="<<shift<<" expected="<<expected<<'\n';
386 Check(std::abs(long((actual[y*64+x]>>shift)&255)-expected)<=1,
387 "St. Elmo emission stays inside its windshield region and preserves outside color");
388 }
389 }
390 for(const auto& inactive:{render(1,0,0),render(0,1,0),render(2,1,0),render(1,1,4),render(1,1,3,0)})
391 Check(std::all_of(inactive.begin(),inactive.end(),[&](
DWORD pixel){return pixel==background;}),
392 "inactive/retired overlays, cockpit surfaces and foreground wipers preserve the scene");
393 }
394 HR(device.EndScene(),
"finish windshield overlay fixture");DebugClean(host.
Device());
395}
396
398{
399 WindshieldElmoOverlay(host);
400 ShipLightSpriteTests(host);
401 RunwayLightSprites(host);
402 RunwayEdgeSources(host);
403 CityNightLighting(host);
405 HR(device.BeginScene(),"begin frame");
407 Viewport cockpitViewport{8,8,16,16,.001f,.01f};HR(device.SetViewport(&cockpitViewport),
"cockpit depth viewport");
409 auto pixels=
Pixels(host.
Device());Check(pixels[0]==0xff102030 && pixels[12*64+12]==0x804080c0,
"subviewport clear preserves surrounding pixels and alpha");
410 Viewport full{0,0,64,48,0,1};HR(device.SetViewport(&full),
"restore full viewport");
411 HR(device.Clear(0,
nullptr,
ClearFlags::TARGET,0xff000000,1,0),
"clear for authored geometry");
420 struct Vertex{
float x,y,z,w;
DWORD color;};
421 const Vertex quad[]={{8,8,.5f,1,0xffd02f63},{56,8,.5f,1,0xffd02f63},{56,40,.5f,1,0xffd02f63},{8,40,.5f,1,0xffd02f63}};
422 ComPtr<RenderBuffer> vertices;HR(device.CreateVertexBuffer(
sizeof(quad),0,0,
ResourcePool::Managed,&vertices,
nullptr),
"create engine geometry");
423 void* memory=nullptr;HR(vertices->Lock(0,0,&memory,0),"edit authored geometry");memcpy(memory,quad,sizeof(quad));HR(vertices->Unlock(),"unlock authored geometry");
425 HR(device.SetStreamSource(0,vertices.Get(),0,sizeof(Vertex)),"bind engine geometry");
427 Check(
Pixels(host.
Device())[20*64+20]==0xffd02f63,
"engine draw reaches native scene");
428 ComPtr<RenderStateSnapshot> snapshot;HR(device.CreateStateBlock(0,&snapshot),"save engine draw state");
429 HR(device.SetStreamSource(0,
nullptr,0,0),
"unbind geometry");HR(device.SetFVF(
VertexFormat::XYZ),
"change layout");
430 HR(snapshot->Apply(),
"restore engine draw state");HR(device.DrawPrimitive(
Primitive::TriangleFan,0,2),
"restored geometry and layout draw");
433 for(UINT y=0;y<8;++y){
auto row=
reinterpret_cast<DWORD*
>(
static_cast<BYTE*
>(lock.
pBits)+y*lock.
Pitch);std::fill(row,row+8,0xff50a0f0);}
434 HR(texture->UnlockRect(0),"upload instrument pixels");
435 RECT region{2,2,4,4};HR(texture->LockRect(0,&lock,®ion,0),"map image subrectangle");
436 *
static_cast<DWORD*
>(lock.
pBits)=0xffe04020;HR(texture->UnlockRect(0),
"upload image subrectangle");
438 Check(*
static_cast<DWORD*
>(lock.
pBits)==0xff50a0f0,
"subrectangle preserves surrounding image");
439 Check(*
reinterpret_cast<DWORD*
>(
static_cast<BYTE*
>(lock.
pBits)+2*lock.
Pitch+8)==0xffe04020,
"subrectangle updates intended pixel");
440 HR(texture->UnlockRect(0),"finish image read");
441 HR(device.EndScene(),"end scene before instrument pass");
442 ComPtr<RenderSurface> surface;HR(texture->GetSurfaceLevel(0,&surface),"native instrument surface");
444 HR(
target->BeginScene(surface.Get(),
nullptr),
"begin instrument pass");
446 HR(
target->EndScene(0),
"end instrument pass");
447 Viewport restored;HR(device.GetViewport(&restored),
"read restored viewport");Check(restored.
Width==64 && restored.
Height==48,
"instrument pass restores scene target and viewport");
448 HR(device.BeginScene(),
"resume scene");HR(device.Clear(0,
nullptr,
ClearFlags::TARGET,0xff000000,1,0),
"clear sprite destination");
450 {
451 ComPtr<ImageBuffer> encoded;RECT crop{1,2,6,7};
452 HR(
SaveSurfaceToMemory(&encoded,format,surface.Get(),
nullptr,&crop),
"encode instrument crop");
453 CheckEncodedImage(*encoded.Get(),5,5,0xff20c040,format==
ImageFile::JPEG ? 3 : 0);
454 }
455 ComPtr<RenderSurface> backbuffer;HR(device.GetBackBuffer(0,0,0,&backbuffer),"capture scene surface");
456 HR(device.SetViewport(&cockpitViewport),
"capture region viewport");HR(device.Clear(0,
nullptr,
ClearFlags::TARGET,0xffb03070,1,0),
"capture colored region");
457 HR(device.SetViewport(&full),"capture restore viewport");
458 ComPtr<ImageBuffer> capture;RECT captureCrop{9,10,15,16};HR(
SaveSurfaceToMemory(&capture,
ImageFile::PNG,backbuffer.Get(),
nullptr,&captureCrop),
"encode RGBA scene crop");
459 CheckEncodedImage(*capture.Get(),6,6,0xffb03070,0);backbuffer.Reset();
460 D3D11_TEXTURE2D_DESC msaa{};msaa.Width=msaa.Height=16;msaa.MipLevels=msaa.ArraySize=1;msaa.SampleDesc.Count=4;
461 msaa.Format=DXGI_FORMAT_R8G8B8A8_UNORM;msaa.BindFlags=D3D11_BIND_RENDER_TARGET;
462 ComPtr<ID3D11Texture2D> color;HR(device.Native()->CreateTexture2D(&msaa,nullptr,&color),"MSAA capture target");
463 ComPtr<RenderSurface> msaaSurface;msaaSurface.Attach(
new RenderSurface);HR(msaaSurface->Initialize(device,color.Get(),0),
"MSAA capture surface");
464 const float clear[]={.2f,.4f,.8f,1};device.Context()->ClearRenderTargetView(msaaSurface->Target(),clear);
465 capture.Reset();HR(
SaveSurfaceToMemory(&capture,
ImageFile::PNG,msaaSurface.Get(),
nullptr,
nullptr),
"encode MSAA color resolve");CheckEncodedImage(*capture.Get(),16,16,0xff3366cc,0);
466 ComPtr<RenderTexture> bitmap;HR(
LoadTextureResource(&device,GetModuleHandleW(
nullptr),MAKEINTRESOURCEW(6101),&bitmap,1),
"load original BITMAP resource");
467 SurfaceDescription bitmapSize;HR(bitmap->GetLevelDesc(0,&bitmapSize),
"bitmap dimensions");Check(bitmapSize.
Width>0 && bitmapSize.
Height>0,
"bitmap resource produces native image");
468 ComPtr<RenderTexture> cityImage;HR(
LoadTexture(&device,L
"Textures/RTS/city2playerN.dds",&cityImage,
DefaultSize),
"load compressed city texture with generated mipmaps");
469 HR(cityImage->GetLevelDesc(0,&bitmapSize),"city texture description");
470 Check(cityImage->GetLevelCount()==11 && bitmapSize.
Width==1440 && bitmapSize.
Format==
ImageFormat::BC3,
"city texture retains authored dimensions and compression with complete mipmaps");
471 ComPtr<RenderTexture> matImage;HR(
LoadTexture(&device,L
"Textures/RTS/Marston1.dds",&matImage,
DefaultSize,57,28),
"load authored landing mat crop");
472 HR(matImage->GetLevelDesc(0,&bitmapSize),"landing mat dimensions");
473 Check(matImage->GetLevelCount()==6 && bitmapSize.
Width==60 && bitmapSize.
Height==28 && bitmapSize.
Format==
ImageFormat::BC2,
"landing mat preserves the reference loader crop and compression");
474 ComPtr<RenderSprite> sprite;HR(
CreateSprite(&device,&sprite),
"native game sprite");
477 RiseMath::Vector3 position(2,2,0);HR(sprite->Draw(texture.Get(),
nullptr,
nullptr,&position,0xffffffff),
"draw instrument texture");HR(sprite->End(),
"finish instrument sprite");
478 Check(
Pixels(host.
Device())[20*64+20]==0xff20c040,
"render-to-texture instrument appears in scene");
480 HR(device.DrawPrimitive(
Primitive::TriangleFan,0,2),
"interleaved GUI rectangle changes index and vertex buffers");
481 HR(device.Clear(0,
nullptr,
ClearFlags::TARGET,0xff000000,1,0),
"clear interleaved geometry");
482 for(unsigned i=0;i<8;++i)HR(sprite->Draw(texture.Get(),nullptr,nullptr,&position,0xffffffff),"queue sprites after GUI geometry");
483 HR(sprite->End(),"restore sprite buffers after interleaved rectangle");
484 Check(
Pixels(host.
Device())[20*64+20]==0xff20c040,
"queued sprites survive an intervening geometry draw");
485 HR(device.Clear(0,
nullptr,
ClearFlags::TARGET,0xff102030,1,0),
"clear custom blend destination");
488 HR(sprite->Begin(0),"begin sprite inheriting game blend");HR(sprite->Draw(texture.Get(),nullptr,nullptr,&position,0xffffffff),"draw custom blended sprite");HR(sprite->End(),"finish custom blend");
489 Check(
Pixels(host.
Device())[20*64+20]==0xff30e070,
"sprite without alpha flag retains caller blend equation");
490 HR(device.Clear(0,
nullptr,
ClearFlags::TARGET,0xff102030,1,0),
"clear dynamic sprite clipping");
492 RECT instrumentClip{12,12,24,24};HR(device.SetScissorRect(&instrumentClip),"change clip during sprite batch");
494 HR(sprite->Draw(texture.Get(),nullptr,nullptr,&position,0xffffffff),"clipped instrument draw");HR(sprite->Flush(),"flush clipped instrument");
495 pixels=
Pixels(host.
Device());Check(pixels[20*64+20]==0xff20c040 && pixels[28*64+28]==0xff102030,
"instrument clip applies within the active batch");
497 HR(sprite->Draw(texture.Get(),nullptr,nullptr,&position,0xffffffff),"unclipped instrument draw");HR(sprite->End(),"finish dynamic clipping");
498 Check(
Pixels(host.
Device())[28*64+28]==0xff20c040,
"next sprite uses restored clipping");
500 for(UINT y=0;y<8;++y)for(UINT x=0;x<8;++x)reinterpret_cast<DWORD*>(
static_cast<BYTE*
>(lock.
pBits)+y*lock.
Pitch)[x]=x<4 ? 0xffff0000 : 0xff0000ff;
501 HR(texture->UnlockRect(0),"upload wrap fixture");
508 HR(sprite->Draw(texture.Get(),&repeated,nullptr,&wrapPosition,0xffffffff),"draw repeated source rectangle");HR(sprite->Flush(),"flush repeated image");
510 HR(sprite->Draw(texture.Get(),&repeated,nullptr,&wrapPosition,0xffffffff),"draw clamped source rectangle");HR(sprite->End(),"end wrapping batch");
511 pixels=
Pixels(host.
Device());Check(pixels[2*64+1]==0xffff0000 && pixels[2*64+17]==0xff0000ff,
"login cloud wrap and restore affect the current sprite batch");
512 ComPtr<RenderFont> font;HR(
CreateFontW(&device,16,0,FW_NORMAL,1,FALSE,DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH,L
"Arial",&font),
"native game font");
513 RECT measured{};Check(font->DrawTextW(nullptr,L"AWAKEN",-1,&measured,DT_CALCRECT,0xffffffff)>0 && measured.right>0,"font layout without sprite");
514 RECT textRect{0,0,64,48};Check(font->DrawTextW(nullptr,L"Rise",-1,&textRect,DT_LEFT|DT_TOP,0xffffffff)>0,"font automatically owns its native sprite");
515 RenderMaterial material(device);UINT passes=0;HR(material.Begin(&passes,0),
"begin scene materials");Check(passes==15,
"all production TShader passes available");
516 HR(device.SetRenderState(
RenderState::ZENABLE,TRUE),
"game state inside material block");HR(material.End(),
"end scene materials");
517 DWORD state=0;HR(device.GetRenderState(
RenderState::ZENABLE,&state),
"read game state after material block");Check(state==TRUE,
"material end preserves caller render-state changes");
518 struct MaterialVertex{float x,y,z,nx,ny,nz,u,v,overlayU=0,overlayV=0;};
519 const MaterialVertex triangle[]={{-.5f,-.5f,.5f,0,0,-1,0,0},{0,.5f,.5f,0,0,-1,.5f,1},{.5f,-.5f,.5f,0,0,-1,1,0}};
520 ComPtr<RenderBuffer> buildingVertices;HR(device.CreateVertexBuffer(
sizeof(triangle),0,0,
ResourcePool::Managed,&buildingVertices,
nullptr),
"create building material fixture");
521 HR(buildingVertices->Lock(0,0,&memory,0),"lock building fixture");memcpy(memory,triangle,sizeof(triangle));HR(buildingVertices->Unlock(),"upload building fixture");
522 HR(device.SetStreamSource(0,buildingVertices.Get(),0,sizeof(MaterialVertex)),"bind building fixture");
524 HR(material.SetMatrix("matWorldViewProj",&identity),"building matrix");
525 HR(material.SetTexture("ColorMap3",texture.Get()),"retain earlier pass two-dimensional auxiliary image");
526 HR(material.Begin(nullptr,0),"begin far building effect");HR(material.BeginPass(3),"select far building material");
527 HR(device.DrawPrimitive(
Primitive::TriangleList,0,1),
"far building tolerates a 2D auxiliary image left by another pass");
528 HR(material.EndPass(),"end far building material");HR(material.End(),"end building fixture effect");
529 struct VehicleVertex{float x,y,z,nx,ny,nz,u,v,overlayU,overlayV;};
530 const VehicleVertex vehicleTriangle[]={{-.5f,-.5f,.5f,0,0,-1,0,0,1,1},{0,.5f,.5f,0,0,-1,.5f,1,.5f,0},{.5f,-.5f,.5f,0,0,-1,1,0,0,1}};
531 ComPtr<RenderBuffer> vehicleVertices;HR(device.CreateVertexBuffer(
sizeof(vehicleTriangle),0,0,
ResourcePool::Managed,&vehicleVertices,
nullptr),
"create vehicle material fixture");
532 HR(vehicleVertices->Lock(0,0,&memory,0),"lock vehicle fixture");memcpy(memory,vehicleTriangle,sizeof(vehicleTriangle));HR(vehicleVertices->Unlock(),"upload vehicle fixture");
533 HR(device.SetStreamSource(0,vehicleVertices.Get(),0,sizeof(VehicleVertex)),"bind vehicle fixture");
535 HR(material.Begin(nullptr,0),"begin vehicle effect");
536 for(UINT pass:{4u,5u})
537 {
538 HR(material.BeginPass(pass),"select below or above cloud vehicle material");
539 HR(device.DrawPrimitive(
Primitive::TriangleList,0,1),
"vehicle material accepts both authored coordinate sets");
540 HR(material.EndPass(),"end vehicle material");
541 }
542 HR(material.End(),"end vehicle fixture effect");
543 HR(device.EndScene(),"finish test scene");
544 HR(host.
Resize(384,256),
"resize for native controls");
548 HR(dialog.
AddButton(1,L
"AWAKEN",10,10,120,32),
"create native button");
549 RiseEditBox* edit=
nullptr;HR(dialog.
AddEditBox(2,L
"Flight",10,54,180,32,
false,
false,&edit),
"create native edit control");
550 HR(dialog.
AddCheckBox(3,L
"Rain",10,96,120,24,
true),
"create native checkbox");
551 HR(dialog.
AddSlider(4,10,132,180,20,0,100,50),
"create native slider");
553 HR(combo->
AddItem(L
"YSP",
nullptr),
"populate native combo");
554 HR(resources.
OnCreateDevice(&device),
"create native control fonts and atlas");HR(resources.
OnResetDevice(),
"create native UI saved state");
555 HR(device.BeginScene(),"begin native UI frame");
557 HR(dialog.
OnRender(.016f),
"render native controls");
558 HR(device.EndScene(),"end native UI frame");
559 pixels=
Pixels(host.
Device());Check(std::count_if(pixels.begin(),pixels.end(),[](
DWORD p){return p!=0xff102030;})>1000,
"native controls paint visible atlas and text");
560 edit->
SetText(L
"Orbit");Check(!wcscmp(edit->
GetText(),L
"Orbit"),
"edit control text survives native port");
561
562
564 for(unsigned i=0;i<5;++i)
565 {
567 HR(panels[i].AddRadioButton(10+i,1,L"Dock",2,18,56,20,i==0),"create nested dialog control");
568 }
569 HR(device.BeginScene(),"begin multi-dialog frame");
578 HR(sprite->SetTransform(&identity),"unscaled dialog frame sprites");
579 HR(sprite->Begin(0),"begin shared dialog frame batch");
580 const RECT panelRect{0,0,60,60};
581 for(unsigned i=0;i<5;++i)
582 {
584 HR(sprite->Draw(texture.Get(),&panelRect,nullptr,&at,0xffffffff),"queue dialog frame");
585 HR(sprite->Flush(),"flush frame before nested controls");
586 HR(panels[i].OnRender(.016f),"render nested dialog controls");
587 }
589 HR(sprite->Draw(texture.Get(),&panelRect,nullptr,&overlayAt,0xffffffff),"queue overlay after dialogs");
590 HR(sprite->End(),"finish dialogs and overlay");
591 HR(device.EndScene(),"end multi-dialog frame");
593 for(unsigned i=0;i<5;++i)Check(pixels[185*384+10+74*i+20]==0xff0000ff,"every dialog frame survives nested control state restoration");
594 Check(pixels[105*384+30]==0xff0000ff,"overlay drawn after dialogs remains visible");
596 DebugClean(host.
Device());
597}
598}
600{
601 for (unsigned repeat = 0; repeat < 4; ++repeat)
602 {
604 unsigned destroys = 0;
606 callbacks.
destroy = [&] { Check(host.
Device().
Context() !=
nullptr,
"game cleanup retains the graphics context"); ++destroys; };
607 HR(host.
Create(options, std::move(callbacks)),
"create shutdown test window");
609 ComPtr<RenderTexture> texture;
612 HR(texture->LockRect(0, &lock,
nullptr,
LockFlags::DISCARD),
"leave texture mapped at shutdown");
613 *
static_cast<DWORD*
>(lock.
pBits) = 0xff204060;
616 texture.Reset();
618 DebugClean(host.
Device());
620 Check(destroys == 1, "shutdown callbacks run exactly once");
623 }
624
625 Window11 host; HR(host.
Create(options, {}),
"create abandoned mapping test window");
626 ComPtr<RenderTexture> texture;
627 {
631 }
632 host.
Destroy(); texture.Reset();
633}
634
635int main(
int argc,
char** argv)
636{
637 const HRESULT com=CoInitializeEx(
nullptr,COINIT_APARTMENTTHREADED);
638 struct ComLifetime {
HRESULT hr;~ComLifetime(){
if(SUCCEEDED(hr))CoUninitialize();}} lifetime{com};
639 try {
641 bool shutdownOnly = false; bool iomereOnly = false; bool thrustOnly = false;
642 for(
int i=1;i<argc;++i){
if(!strcmp(argv[i],
"--thrust-only"))thrustOnly=
true;
else if(!strcmp(argv[i],
"--warp"))options.
warp=
true;
else if(!strcmp(argv[i],
"--no-debug-layer"))options.
debugLayer=
false;
else if(!strcmp(argv[i],
"--iomere-only"))iomereOnly=
true;
else if(!strcmp(argv[i],
"--shutdown-only"))shutdownOnly=
true;}
643 if(!iomereOnly && !thrustOnly) ShutdownLifetimeTests(options);
644 if(shutdownOnly){std::cout << "PASS: " << checks << " native shutdown/mapped-texture lifetime checks\n";return 0;}
645 Window11 host;HR(host.
Create(options,{}),
"create native test window");HR(host.
Resize(64,48),
"exact test viewport");
646 ThrustConeBlending(host);if(thrustOnly)return 0;
647 IomereLighting(host);if(iomereOnly)return 0;
648 CockpitInteriors(host);Exercise(host);std::cout<<
"PASS: "<<checks<<
" client renderer checks on "<<(options.
warp ?
"WARP" :
"hardware")<<
'\n';
return 0;
649 } catch(const std::exception& error){std::cerr<<"FAIL: "<<error.what()<<'\n';return 1;}
650}
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
SCRIPT_CONTROL SCRIPT_STATE const void DWORD
ID3D11Texture2D * SceneColor() const
ID3D11DeviceContext * Context() const
ID3D11Device * Device() const
std::vector< uint8_t > bytes
HRESULT Draw(DrawContext11 &draws, ID3D11ShaderResourceView *groundLightTexture, const std::vector< RunwayLightInstance11 > &lights)
void StopCallbacksAndWindow()
HRESULT Create(const WindowOptions11 &options, Callbacks callbacks)
HRESULT SetSamples(UINT samples)
HRESULT Resize(UINT width, UINT height)
HRESULT AddItem(const WCHAR *strText, void *pData)
void Init(RiseDialogResourceManager *pManager, bool bRegisterDialog=true)
HRESULT AddComboBox(int ID, int x, int y, int width, int height, UINT nHotKey=0, bool bIsDefault=false, RiseComboBox **ppCreated=NULL)
void EnableKeyboardInput(bool bEnable)
HRESULT AddCheckBox(int ID, LPCWSTR strText, int x, int y, int width, int height, bool bChecked=false, UINT nHotkey=0, bool bIsDefault=false, RiseCheckBox **ppCreated=NULL)
void SetSize(int width, int height)
void SetLocation(int x, int y)
HRESULT OnRender(float fElapsedTime)
HRESULT AddEditBox(int ID, LPCWSTR strText, int x, int y, int width, int height, bool bIsDefault=false, bool bIsPassword=false, RiseEditBox **ppCreated=NULL)
HRESULT AddButton(int ID, LPCWSTR strText, int x, int y, int width, int height, UINT nHotkey=0, bool bIsDefault=false, RiseButton **ppCreated=NULL)
HRESULT AddSlider(int ID, int x, int y, int width, int height, int min=0, int max=100, int value=50, bool bIsDefault=false, RiseSlider **ppCreated=NULL)
HRESULT OnCreateDevice(Rendering::RenderDevice *pd3dDevice)
void SetText(LPCWSTR wszText, bool bSelected=false)
static HRESULT DrawCockpitGlass(Rendering::RenderDevice *device, Draw draw)
renderer(Viewscreen *ptr)
constexpr uint32_t INVSRCALPHA
constexpr uint32_t SRCCOLOR
constexpr uint32_t INVSRCCOLOR
constexpr uint32_t SRCALPHA
constexpr uint32_t RENDERTARGET
constexpr uint32_t TARGET
constexpr uint32_t ZBUFFER
constexpr uint32_t STENCIL
constexpr uint32_t LINEAR
constexpr uint32_t READONLY
constexpr uint32_t DISCARD
constexpr uint8_t Pixels[262144]
constexpr uint32_t SRCBLEND
constexpr uint32_t STENCILFUNC
constexpr uint32_t POINTSPRITEENABLE
constexpr uint32_t CULLMODE
constexpr uint32_t ALPHABLENDENABLE
constexpr uint32_t STENCILENABLE
constexpr uint32_t STENCILPASS
constexpr uint32_t SCISSORTESTENABLE
constexpr uint32_t POINTSIZE
constexpr uint32_t DESTBLEND
constexpr uint32_t TEXTUREFACTOR
constexpr uint32_t LIGHTING
constexpr uint32_t ZENABLE
constexpr uint32_t ADDRESSU
constexpr uint32_t MIPFILTER
constexpr uint32_t MAGFILTER
constexpr uint32_t MINFILTER
constexpr DWORD AlphaBlend
constexpr uint32_t TFACTOR
constexpr uint32_t DIFFUSE
constexpr uint32_t TEXTURE
constexpr uint32_t SELECTARG1
constexpr uint32_t MODULATE
constexpr uint32_t SELECTARG2
constexpr uint32_t COLOROP
constexpr uint32_t COLORARG1
constexpr uint32_t ALPHAARG2
constexpr uint32_t ALPHAOP
constexpr uint32_t COLORARG2
HRESULT CreateRenderToSurface(RenderDevice *owner, UINT width, UINT height, ImageFormat format, BOOL depth, ImageFormat depthFormat, RenderToTexture **result)
void AttachClientRuntime(Window11 *window, RenderDevice *device)
HRESULT SaveSurfaceToMemory(ImageBuffer **result, ImageFile format, RenderSurface *surface, const void *, const RECT *crop)
HRESULT CreateFontW(RenderDevice *owner, INT height, UINT width, UINT weight, UINT mipLevels, BOOL italic, DWORD charset, DWORD precision, DWORD quality, DWORD pitch, const wchar_t *face, RenderFont **result)
HRESULT LoadTextureResource(RenderDevice *owner, HMODULE module, LPCWSTR id, RenderTexture **result, UINT levels)
HRESULT CreateSprite(RenderDevice *owner, RenderSprite **result)
constexpr unsigned DefaultSize
HRESULT LoadTexture(RenderDevice *owner, const wchar_t *path, RenderTexture **result, UINT levels=0, UINT width=0, UINT height=0)
HRESULT CreateTexture(RenderDevice *owner, UINT width, UINT height, UINT levels, DWORD usage, ImageFormat format, ResourcePool pool, RenderTexture **result)
Matrix * MatrixIdentity(Matrix *out)
Matrix * MatrixScaling(Matrix *out, float x, float y, float z)
Appearance SizeAndIntensity(float distanceKm, float displayScale, float night)
void ForEachAnchor(Emit emit)
Vector SurfacePoint(const RtsTerrain::Surface< Vector > &surface, float u, float v)
void Apply(Rendering::RenderDevice &device, const RiseMath::Color &emission, float transmission, bool isSimulator)
float EmissionTransmission(float transmission, bool isSimulator)
std::function< void()> destroy