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

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

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>
17using namespace Rendering;
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 }
28 void DebugClean(Device11& gpu)
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 }
40 std::vector<uint32_t> Pixels(Device11& gpu)
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 // Compile the actual weather producer: alpha is a day/night control, not
85 // opacity. Cloud RGB must not force powered cities into the daytime state.
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 }
92 RenderDevice device(host.Draws());RenderMaterial material(device);
93 HR(device.SetRenderState(RenderState::ZENABLE,FALSE),"city light fixture depth");
94 HR(device.SetRenderState(RenderState::CULLMODE,Cull::NONE),"city light fixture culling");
95 HR(device.SetRenderState(RenderState::LIGHTING,FALSE),"city light fixture lighting");
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;
99 HR(device.CreateVertexBuffer(sizeof(quad),0,0,ResourcePool::Managed,&vertices,nullptr),"city quad");
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");
102 HR(device.SetFVF(VertexFormat::XYZ|VertexFormat::TEX2),"city quad layout");
103 RiseMath::Matrix identity;RiseMath::MatrixIdentity(&identity);
104 HR(material.SetMatrix("matWorld",&identity),"city world");HR(material.SetMatrix("matWorldViewProj",&identity),"city projection");
105 const RiseMath::Vector4 zero(0,0,0,0);
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);
115 const RiseMath::Vector4 ambient(weather.r,weather.g,weather.b,1000);
116 const RiseMath::Vector4 blend(0,0,0,std::pow(1-weather.a,2.f));
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) {
120 HR(device.Clear(0,nullptr,ClearFlags::TARGET,0xff000000,1,0),"clear city frame");
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");
123 HR(device.DrawPrimitive(Primitive::TriangleStrip,0,2),"draw city facade");
124 HR(material.EndPass(),"end city pass");HR(material.End(),"end city material");
125 return Pixels(host.Device());
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{
140 RenderDevice device(host.Draws());
141 HR(device.BeginScene(),"begin runway light fixture");
142 HR(device.SetRenderState(RenderState::LIGHTING,FALSE),"unlit runway lights");
143 HR(device.SetRenderState(RenderState::ZENABLE,FALSE),"runway fixture depth");
144 HR(device.SetRenderState(RenderState::POINTSPRITEENABLE,TRUE),"runway point sprites");
145 const float size=16;DWORD sizeBits;memcpy(&sizeBits,&size,sizeof(size));
146 HR(device.SetRenderState(RenderState::POINTSIZE,sizeBits),"runway sprite size");
147 HR(device.SetRenderState(RenderState::ALPHABLENDENABLE,TRUE),"runway additive blend");
148 HR(device.SetRenderState(RenderState::SRCBLEND,Blend::SRCCOLOR),"runway source blend");
149 HR(device.SetRenderState(RenderState::DESTBLEND,Blend::ONE),"runway destination blend");
150 HR(device.SetRenderState(RenderState::TEXTUREFACTOR,0xffffffff),"white approach light");
151 HR(device.SetTextureStageState(0,TextureState::COLORARG2,TextureArgument::TFACTOR),"runway light color");
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}};
158 HR(device.SetFVF(VertexFormat::XYZ|VertexFormat::DIFFUSE),"running-light vertex format");
159 std::vector<uint32_t> reference;
161 {
162 HR(device.SetRenderState(RenderState::CULLMODE,cull),"inherited world culling");
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");
165 const auto pixels=Pixels(host.Device());
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");
171 DWORD saved=0;HR(device.GetRenderState(RenderState::CULLMODE,&saved),"read culling after point");
172 Check(saved==cull,"point sprite preserves caller culling state");
173
174 // The point override must not leak into the next triangle draw.
175 HR(device.SetTextureStageState(0,TextureState::COLOROP,TextureOperation::SELECTARG2),"solid triangle probe");
176 HR(device.Clear(0,nullptr,ClearFlags::TARGET,0xff000000,1,0),"clear triangle probe");
177 HR(device.DrawPrimitiveUP(Primitive::TriangleList,1,triangle,sizeof(Vertex)),"triangle after point sprite");
178 const bool triangleVisible=(Pixels(host.Device())[24*64+32]&0xffffff)!=0;
179 Check(triangleVisible==(cull!=Cull::CW),"triangle culling survives point sprite draw");
180 HR(device.SetTextureStageState(0,TextureState::COLOROP,TextureOperation::MODULATE),"restore runway texture");
181 }
182 // Exercise the production factor through the actual texture, point shader,
183 // and SRC_COLOR blend. Output should scale with T, including faint lights.
184 HR(device.SetRenderState(RenderState::CULLMODE,Cull::NONE),"signal extinction culling");
185 for(DWORD color:{0xffffffffu,0xffff8040u,0xff4080ffu,0xff080402u})
186 {
187 const RiseMath::Color emission(color);
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;
192 HR(device.SetRenderState(RenderState::TEXTUREFACTOR,legacy),"baseline attenuated signal color");
193 if(corrected)SignalLightAttenuation::Apply(device,emission,transmission,isSimulator);
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");
196 return Pixels(host.Device());
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;
230 RunwayEdgeLights::ForEachAnchor([&](float u,float v) {
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");
236 const auto p=RunwayEdgeLights::SurfacePoint(surface,u,v);
237 // A piecewise planar height field with different slopes in both rows.
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");
244 const auto distant=RunwayEdgeLights::SizeAndIntensity(10,1,1);
245 const auto farther=RunwayEdgeLights::SizeAndIntensity(20,1,1);
246 Check(distant.diameter==3 && farther.diameter==3 && farther.intensity<distant.intensity,
247 "minimum pixel coverage still fades distant edge lights");
248 Check(RunwayEdgeLights::SizeAndIntensity(1,1,0).intensity==0,"edge points share the ground texture's daylight fade");
249
250 RunwayLights11 batch;
251 for(UINT samples:{1u,4u})
252 {
253 HR(host.SetSamples(samples),"edge source sample configuration");
254 RenderDevice device(host.Draws());
255 HR(device.BeginScene(),"begin edge source fixture");
256 HR(device.SetRenderState(RenderState::LIGHTING,FALSE),"unlit core color reference");
257 HR(device.SetRenderState(RenderState::ZENABLE,FALSE),"core reference depth");
258 HR(device.SetRenderState(RenderState::CULLMODE,Cull::NONE),"core reference culling");
259 HR(device.SetRenderState(RenderState::ALPHABLENDENABLE,FALSE),"unblended core reference");
260 HR(device.SetTextureStageState(0,TextureState::COLOROP,TextureOperation::SELECTARG1),"sample the DDS directly");
261 HR(device.SetTextureStageState(0,TextureState::COLORARG1,TextureArgument::TEXTURE),"actual edge DDS color");
262 HR(device.SetSamplerState(0,SamplerState::MAGFILTER,Filter::LINEAR),"core reference bilinear magnification");
263 HR(device.SetSamplerState(0,SamplerState::MINFILTER,Filter::LINEAR),"core reference bilinear minification");
264 HR(device.SetSamplerState(0,SamplerState::MIPFILTER,Filter::NONE),"authored core mip");
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}};
270 HR(device.SetFVF(VertexFormat::XYZ|VertexFormat::TEX1),"core reference vertex format");
271 HR(device.Clear(0,nullptr,ClearFlags::TARGET|ClearFlags::ZBUFFER,0xff000000,1,0),"clear core reference");
272 HR(device.DrawPrimitiveUP(Primitive::TriangleStrip,2,quad,sizeof(Vertex)),"render exact texture core reference");
273 const auto core=Pixels(host.Device())[24*64+32];
274 Check((core&0xffffff)!=0,"authored edge-light core has visible color");
275 const auto saved=host.Draws().Pipeline();
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 {
279 lamps[0].intensity=SignalLightAttenuation::EmissionTransmission(transmission,isSimulator);
280 const float expectedTransmission=isSimulator ? transmission*transmission : transmission;
281 HR(device.Clear(0,nullptr,ClearFlags::TARGET|ClearFlags::ZBUFFER,0xff000000,1,0),"clear transmitted edge source");
282 HR(batch.Draw(host.Draws(),texture->View(),lamps),"draw native edge source");
283 const auto pixel=Pixels(host.Device())[24*64+32];
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};
294 HR(device.Clear(0,nullptr,ClearFlags::TARGET|ClearFlags::ZBUFFER,0xff000000,1,0),"clear subpixel motion fixture");
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};
301 HR(device.Clear(0,nullptr,ClearFlags::TARGET|ClearFlags::ZBUFFER,0xff000000,.4f,0),"opaque terrain in front of edge source");
302 HR(batch.Draw(host.Draws(),texture->View(),lamps),"draw hidden edge source");
303 const auto hidden=Pixels(host.Device());
304 Check(std::all_of(hidden.begin(),hidden.end(),[](DWORD p){return !(p&0xffffff);}),"terrain occludes the complete edge source");
305
306 HR(device.Clear(0,nullptr,ClearFlags::TARGET|ClearFlags::ZBUFFER,0xff000000,1,0),"clear edge depth-write probe");
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");
309 HR(device.SetRenderState(RenderState::ZENABLE,TRUE),"test later geometry against scene depth");
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}};
314 HR(device.Clear(0,nullptr,ClearFlags::TARGET|ClearFlags::ZBUFFER,0xff000000,1,0),"clear multi-instance edge batch");
315 HR(batch.Draw(host.Draws(),texture->View(),lamps),"draw two differently attenuated edge instances");
316 const auto pair=Pixels(host.Device());
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{
327 RenderDevice device(host.Draws());RenderMaterial material(device);
328 HR(device.BeginScene(),"begin windshield overlay fixture");
329 HR(device.SetRenderState(RenderState::CULLMODE,Cull::NONE),"windshield fixture culling");
330 HR(device.SetRenderState(RenderState::ALPHABLENDENABLE,TRUE),"enable windshield blend");
331 HR(device.SetRenderState(RenderState::SRCBLEND,Blend::ONE),"Elmo source blend");
332 HR(device.SetRenderState(RenderState::DESTBLEND,Blend::INVSRCCOLOR),"Elmo world complement");
333 HR(device.SetRenderState(RenderState::STENCILPASS,StencilOperation::KEEP),"preserve cockpit mask");
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");
342 HR(device.SetFVF(VertexFormat::XYZ|VertexFormat::NORMAL|VertexFormat::TEX1),"windshield quad layout");
343 RiseMath::Matrix identity;RiseMath::MatrixIdentity(&identity);
344 HR(material.SetMatrix("matWorldViewProj",&identity),"windshield projection");
345 // Synthetic 2D emission keeps this shared-pass regression independent of
346 // the retired volume animation. Production plasma has its own renderer tests.
347 constexpr DWORD emission=0xff204060;
348 ComPtr<RenderTexture> elmo;
349 HR(CreateTexture(&device,8,8,1,0,ImageFormat::BGRA8,ResourcePool::Managed,&elmo),"Elmo fixture texture");
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");
355 const RiseMath::Vector4 region(.25f,.25f,.75f,.75f);
356 HR(material.SetVector("Features",&region),"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");
362 const RiseMath::Vector4 control(mode,.5f,.25f,side);
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");
366 return device.DrawPrimitive(Primitive::TriangleStrip,0,2);
367 }),"draw overlay through production cockpit mask");
368 HR(material.EndPass(),"end windshield pass");HR(material.End(),"end windshield material");
369 return Pixels(host.Device());
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 // The material path retains legacy integer-centered UV sampling.
377 // Exact region edges can round to either side of a strict float
378 // comparison; verify every interior/exterior sample beyond them.
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
397void Exercise(Window11& host)
398{
399 WindshieldElmoOverlay(host);
400 ShipLightSpriteTests(host);
401 RunwayLightSprites(host);
402 RunwayEdgeSources(host);
403 CityNightLighting(host);
404 RenderDevice device(host.Draws());
405 HR(device.BeginScene(),"begin frame");
406 HR(device.Clear(0,nullptr,ClearFlags::TARGET|ClearFlags::ZBUFFER|ClearFlags::STENCIL,0xff102030,1,0),"clear scene");
407 Viewport cockpitViewport{8,8,16,16,.001f,.01f};HR(device.SetViewport(&cockpitViewport),"cockpit depth viewport");
408 HR(device.Clear(0,nullptr,ClearFlags::TARGET|ClearFlags::ZBUFFER|ClearFlags::STENCIL,0x804080c0,1,3),"partial viewport clear");
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");
412 HR(device.SetRenderState(RenderState::LIGHTING,FALSE),"unlit geometry");
413 HR(device.SetRenderState(RenderState::ZENABLE,FALSE),"disable depth");
414 HR(device.SetRenderState(RenderState::STENCILENABLE,FALSE),"disable stencil");
415 HR(device.SetRenderState(RenderState::CULLMODE,Cull::NONE),"disable cull");
416 HR(device.SetTextureStageState(0,TextureState::COLOROP,TextureOperation::SELECTARG2),"diffuse RGB");
417 HR(device.SetTextureStageState(0,TextureState::ALPHAOP,TextureOperation::SELECTARG2),"diffuse alpha");
418 HR(device.SetTextureStageState(0,TextureState::COLORARG2,TextureArgument::DIFFUSE),"diffuse RGB source");
419 HR(device.SetTextureStageState(0,TextureState::ALPHAARG2,TextureArgument::DIFFUSE),"diffuse alpha source");
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");
424 HR(device.SetFVF(VertexFormat::XYZRHW|VertexFormat::DIFFUSE),"authored screen layout");
425 HR(device.SetStreamSource(0,vertices.Get(),0,sizeof(Vertex)),"bind engine geometry");
426 HR(device.DrawPrimitive(Primitive::TriangleFan,0,2),"draw 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");
431 ComPtr<RenderTexture> texture;HR(CreateTexture(&device,8,8,1,BufferUsage::RENDERTARGET,ImageFormat::BGRA8,ResourcePool::Device,&texture),"instrument texture");
432 LockedRectangle lock;HR(texture->LockRect(0,&lock,nullptr,LockFlags::DISCARD),"map instrument pixels");
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,&region,0),"map image subrectangle");
436 *static_cast<DWORD*>(lock.pBits)=0xffe04020;HR(texture->UnlockRect(0),"upload image subrectangle");
437 HR(texture->LockRect(0,&lock,nullptr,LockFlags::READONLY),"read image");
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");
443 ComPtr<RenderToTexture> target;HR(CreateRenderToSurface(&device,8,8,ImageFormat::BGRA8,TRUE,ImageFormat::Depth24Stencil8,&target),"native instrument pass");
444 HR(target->BeginScene(surface.Get(),nullptr),"begin instrument pass");
445 HR(device.Clear(0,nullptr,ClearFlags::TARGET|ClearFlags::ZBUFFER,0xff20c040,1,0),"paint instrument");
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");
475 RiseMath::Matrix transform;RiseMath::MatrixScaling(&transform,4,4,1);HR(sprite->SetTransform(&transform),"instrument sprite scale");
476 HR(sprite->Begin(SpriteFlags::AlphaBlend),"begin instrument 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");
479 HR(sprite->Begin(SpriteFlags::AlphaBlend),"begin sprite batch around immediate GUI geometry");
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");
486 HR(device.SetRenderState(RenderState::ALPHABLENDENABLE,TRUE),"custom sprite blending enabled");
487 HR(device.SetRenderState(RenderState::SRCBLEND,Blend::ONE),"custom source blend");HR(device.SetRenderState(RenderState::DESTBLEND,Blend::ONE),"custom destination blend");
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");
491 HR(sprite->Begin(SpriteFlags::AlphaBlend),"begin instrument clipping batch");
492 RECT instrumentClip{12,12,24,24};HR(device.SetScissorRect(&instrumentClip),"change clip during sprite batch");
493 HR(device.SetRenderState(RenderState::SCISSORTESTENABLE,TRUE),"enable 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");
496 HR(device.SetRenderState(RenderState::SCISSORTESTENABLE,FALSE),"disable active clip");
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");
499 HR(texture->LockRect(0,&lock,nullptr,LockFlags::DISCARD),"write wrap fixture");
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");
502 RiseMath::Matrix identity;RiseMath::MatrixIdentity(&identity);HR(sprite->SetTransform(&identity),"unscaled wrap fixture");
503 HR(sprite->Begin(SpriteFlags::AlphaBlend),"begin login cloud wrap batch");
504 HR(device.SetSamplerState(0,SamplerState::ADDRESSU,Address::WRAP),"sprite wrap inside batch");
505 HR(device.SetSamplerState(0,SamplerState::MINFILTER,Filter::POINT),"sprite point min filter");
506 HR(device.SetSamplerState(0,SamplerState::MAGFILTER,Filter::POINT),"sprite point mag filter");
507 RECT repeated{8,0,16,8};RiseMath::Vector3 wrapPosition(0,0,0);
508 HR(sprite->Draw(texture.Get(),&repeated,nullptr,&wrapPosition,0xffffffff),"draw repeated source rectangle");HR(sprite->Flush(),"flush repeated image");
509 HR(device.SetSamplerState(0,SamplerState::ADDRESSU,Address::CLAMP),"restore sprite clamp");wrapPosition.x=16;
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");
523 HR(device.SetFVF(VertexFormat::XYZ|VertexFormat::NORMAL|VertexFormat::TEX2),"building vertex layout");
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");
534 HR(device.SetFVF(VertexFormat::XYZ|VertexFormat::NORMAL|VertexFormat::TEX2),"vehicle hull and overlay coordinate layout");
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");
545 device.Reset();Rendering::AttachClientRuntime(&host,&device);
546 RiseDialogResourceManager resources;RiseDialog dialog;
547 dialog.Init(&resources);dialog.SetLocation(0,0);dialog.SetSize(384,256);dialog.EnableKeyboardInput(true);
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");
552 RiseComboBox* combo=nullptr;HR(dialog.AddComboBox(5,200,10,170,32,0,false,&combo),"create native combo");
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");
556 HR(device.Clear(0,nullptr,ClearFlags::TARGET|ClearFlags::ZBUFFER,0xff102030,1,0),"clear native UI scene");
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 // Production keeps one frame/text sprite batch open across every dialog's
562 // nested control batch, then draws overlays such as the F1 keyboard chart.
563 RiseDialog panels[5];
564 for(unsigned i=0;i<5;++i)
565 {
566 panels[i].Init(&resources);panels[i].SetLocation(10+74*i,180);panels[i].SetSize(60,60);
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");
570 HR(device.Clear(0,nullptr,ClearFlags::TARGET|ClearFlags::ZBUFFER,0xff102030,1,0),"clear multi-dialog frame");
571 HR(device.SetRenderState(RenderState::ZENABLE,FALSE),"disable overlay depth");
572 HR(device.SetRenderState(RenderState::CULLMODE,Cull::CW),"world culling before overlay batch");
573 HR(device.SetRenderState(RenderState::STENCILENABLE,TRUE),"cockpit stencil before overlay batch");
574 HR(device.SetRenderState(RenderState::STENCILFUNC,Compare::NEVER),"world stencil excludes screen overlays");
575 HR(device.SetRenderState(RenderState::ALPHABLENDENABLE,TRUE),"enable overlay blend");
576 HR(device.SetRenderState(RenderState::SRCBLEND,Blend::SRCALPHA),"overlay source alpha");
577 HR(device.SetRenderState(RenderState::DESTBLEND,Blend::INVSRCALPHA),"overlay destination alpha");
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 {
583 const RiseMath::Vector3 at(float(10+74*i),180,0);
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 }
588 const RiseMath::Vector3 overlayAt(10,100,0);
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");
592 pixels=Pixels(host.Device());
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");
595 resources.OnLostDevice();resources.OnDestroyDevice();Rendering::AttachClientRuntime(nullptr,nullptr);
596 DebugClean(host.Device());
597}
598}
599static void ShutdownLifetimeTests(const WindowOptions11& options)
600{
601 for (unsigned repeat = 0; repeat < 4; ++repeat)
602 {
603 Window11 host;
604 unsigned destroys = 0;
605 Window11::Callbacks callbacks;
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;
610 HR(CreateTexture(&renderer, 8, 8, 1, 0, ImageFormat::BGRA8, ResourcePool::Managed, &texture), "create shutdown texture");
611 LockedRectangle lock;
612 HR(texture->LockRect(0, &lock, nullptr, LockFlags::DISCARD), "leave texture mapped at shutdown");
613 *static_cast<DWORD*>(lock.pBits) = 0xff204060;
615 Check(!host.Handle() && host.Device().Context() && host.Draws().Owner(), "callbacks stop before game resource destruction");
616 texture.Reset(); // destructor must unmap the abandoned update
617 renderer.Reset();
618 DebugClean(host.Device());
620 Check(destroys == 1, "shutdown callbacks run exactly once");
621 host.Destroy(); host.Destroy();
622 Check(!host.Device().Device() && !host.Device().Context(), "final shutdown releases the device");
623 }
624 // A retained mapping must also clean up without borrowing a dead owner.
625 Window11 host; HR(host.Create(options, {}), "create abandoned mapping test window");
626 ComPtr<RenderTexture> texture;
627 {
629 HR(CreateTexture(&renderer, 8, 8, 1, 0, ImageFormat::BGRA8, ResourcePool::Managed, &texture), "create abandoned mapping texture");
630 LockedRectangle lock; HR(texture->LockRect(0, &lock, nullptr, LockFlags::DISCARD), "map abandoned texture");
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 {
640 WindowOptions11 options;options.visible=false;options.width=64;options.height=48;options.debugLayer=true;
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
Definition Device11.h:69
ID3D11DeviceContext * Context() const
Definition Device11.h:66
ID3D11Device * Device() const
Definition Device11.h:65
Device11 * Owner() const
std::vector< uint8_t > bytes
HRESULT Draw(DrawContext11 &draws, ID3D11ShaderResourceView *groundLightTexture, const std::vector< RunwayLightInstance11 > &lights)
DrawContext11 & Draws()
Definition Window11.h:52
void StopCallbacksAndWindow()
Definition Window11.cpp:220
HRESULT Create(const WindowOptions11 &options, Callbacks callbacks)
Definition Window11.cpp:24
HRESULT SetSamples(UINT samples)
Definition Window11.cpp:90
HRESULT Resize(UINT width, UINT height)
Definition Window11.cpp:74
HWND Handle() const
Definition Window11.h:50
Device11 & Device()
Definition Window11.h:51
HRESULT AddItem(const WCHAR *strText, void *pData)
void Init(RiseDialogResourceManager *pManager, bool bRegisterDialog=true)
Definition Controls.cpp:176
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)
Definition Controls.h:320
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)
Definition Controls.h:285
void SetLocation(int x, int y)
Definition Controls.h:281
HRESULT OnRender(float fElapsedTime)
Definition Controls.cpp:526
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)
Definition Controls.cpp:306
LPCWSTR GetText()
Definition Controls.h:1269
void SetText(LPCWSTR wszText, bool bSelected=false)
static HRESULT DrawCockpitGlass(Rendering::RenderDevice *device, Draw draw)
renderer(Viewscreen *ptr)
Definition renderer.cpp:21
short r
Definition weather.h:50
constexpr uint32_t CLAMP
constexpr uint32_t WRAP
constexpr uint32_t INVSRCALPHA
constexpr uint32_t SRCCOLOR
constexpr uint32_t INVSRCCOLOR
constexpr uint32_t ONE
constexpr uint32_t SRCALPHA
constexpr uint32_t RENDERTARGET
constexpr uint32_t TARGET
constexpr uint32_t ZBUFFER
constexpr uint32_t STENCIL
constexpr uint32_t NEVER
constexpr uint32_t CW
constexpr uint32_t NONE
constexpr uint32_t CCW
constexpr uint32_t POINT
constexpr uint32_t LINEAR
constexpr uint32_t NONE
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
constexpr uint32_t TEX1
constexpr uint32_t NORMAL
constexpr uint32_t XYZRHW
constexpr uint32_t DIFFUSE
constexpr uint32_t XYZ
constexpr uint32_t TEX2
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)
matches(path, entry)
Matrix * MatrixIdentity(Matrix *out)
Definition ClientMath.h:115
Matrix * MatrixScaling(Matrix *out, float x, float y, float z)
Definition ClientMath.h:124
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
Definition Window11.h:26