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

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

1#include "../Rendering/Device11.h"
2#include "../Rendering/Sprite11.h"
3#include <d3dx9.h>
4#include <d3d11sdklayers.h>
5#include <cstring>
6#include <cmath>
7#include <fstream>
8#include <iostream>
9#include <stdexcept>
10using namespace Rendering;
11using Microsoft::WRL::ComPtr;
12namespace
13{
14 constexpr UINT Width=320,Height=240;
15 void HR(HRESULT hr,const char* what){if(FAILED(hr))throw std::runtime_error(std::string(what)+": "+std::to_string(hr));}
16 void Check(bool value,const char* what){if(!value)throw std::runtime_error(what);}
17 struct Fixture
18 {
19 Device11 gpu;
20 Sprite11 sprite;
21 ComPtr<IDirect3D9> api;
22 ComPtr<IDirect3DDevice9> old;
23 ComPtr<ID3DXSprite> oldSprite;
24 ComPtr<IDirect3DTexture9> oldTexture;
25 ComPtr<IDirect3DTexture9> oldAlternate;
26 ComPtr<IDirect3DSurface9> oldTarget,oldStaging;
27 ComPtr<ID3D11Texture2D> target,staging;
28 ComPtr<ID3D11RenderTargetView> rtv;
29 ComPtr<ID3D11ShaderResourceView> texture;
30 ComPtr<ID3D11ShaderResourceView> alternate;
31 HWND window=nullptr;
32 std::filesystem::path folder;
33 std::ofstream metrics;
34 unsigned failures=0;
35 Fixture(bool warp,bool debug)
36 {
37 folder=std::string("outputs/direct3d11/sprite-")+(warp ? "warp" : "hardware");std::filesystem::create_directories(folder);
38 metrics.open(folder/"metrics.csv");metrics<<"case,mean_rgb,mean_alpha,fraction_over_3,max_rgb\n";
39 HR(gpu.Create({warp ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE,debug}),"native device");std::cout<<gpu.Status()<<std::endl;
40 HR(sprite.Initialize(gpu.Device(),"outputs/direct3d11/shaders"),"native sprite");
41 window=CreateWindowW(L"STATIC",L"Sprite parity",WS_POPUP,0,0,Width,Height,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);Check(window!=nullptr,"window");
42 api.Attach(Direct3DCreate9(D3D_SDK_VERSION));Check(bool(api),"reference API");D3DPRESENT_PARAMETERS pp{};
43 pp.Windowed=TRUE;pp.SwapEffect=D3DSWAPEFFECT_DISCARD;pp.BackBufferWidth=Width;pp.BackBufferHeight=Height;pp.hDeviceWindow=window;
44 HR(api->CreateDevice(0,D3DDEVTYPE_HAL,window,D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_FPU_PRESERVE,&pp,&old),"reference device");
45 HR(D3DXCreateSprite(old.Get(),&oldSprite),"reference sprite");
46 HR(old->CreateRenderTarget(Width,Height,D3DFMT_A8R8G8B8,D3DMULTISAMPLE_NONE,0,FALSE,&oldTarget,nullptr),"reference target");
47 HR(old->CreateOffscreenPlainSurface(Width,Height,D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&oldStaging,nullptr),"reference staging");
48 D3D11_TEXTURE2D_DESC desc{};desc.Width=Width;desc.Height=Height;desc.ArraySize=desc.MipLevels=1;
49 desc.Format=DXGI_FORMAT_B8G8R8A8_UNORM;desc.SampleDesc.Count=1;desc.BindFlags=D3D11_BIND_RENDER_TARGET;
50 HR(gpu.Device()->CreateTexture2D(&desc,nullptr,&target),"native target");HR(gpu.Device()->CreateRenderTargetView(target.Get(),nullptr,&rtv),"native RTV");
51 desc.BindFlags=0;desc.Usage=D3D11_USAGE_STAGING;desc.CPUAccessFlags=D3D11_CPU_ACCESS_READ;HR(gpu.Device()->CreateTexture2D(&desc,nullptr,&staging),"native staging");
52 std::array<DWORD,32*32> pixels{};for(UINT y=0;y<32;++y)for(UINT x=0;x<32;++x)pixels[y*32+x]=D3DCOLOR_ARGB((x+y)%7 ? 64+x*6 : 0,32+x*7,32+y*7,96+(x+y)*2);
53 HR(old->CreateTexture(32,32,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,&oldTexture,nullptr),"reference image");D3DLOCKED_RECT rect{};
54 HR(oldTexture->LockRect(0,&rect,nullptr,0),"image lock");for(UINT y=0;y<32;++y)memcpy(static_cast<char*>(rect.pBits)+y*rect.Pitch,pixels.data()+y*32,128);oldTexture->UnlockRect(0);
55 desc.Width=desc.Height=32;desc.Usage=D3D11_USAGE_IMMUTABLE;desc.CPUAccessFlags=0;desc.BindFlags=D3D11_BIND_SHADER_RESOURCE;
56 const D3D11_SUBRESOURCE_DATA data{pixels.data(),128,0};ComPtr<ID3D11Texture2D> image;
57 HR(gpu.Device()->CreateTexture2D(&desc,&data,&image),"native image");HR(gpu.Device()->CreateShaderResourceView(image.Get(),nullptr,&texture),"native image SRV");
58 for(auto& pixel:pixels)pixel^=0x00ffffff;
59 HR(old->CreateTexture(32,32,1,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,&oldAlternate,nullptr),"reference alternate");
60 HR(oldAlternate->LockRect(0,&rect,nullptr,0),"alternate lock");
61 for(UINT y=0;y<32;++y)memcpy(static_cast<char*>(rect.pBits)+y*rect.Pitch,pixels.data()+y*32,128);oldAlternate->UnlockRect(0);
62 image.Reset();HR(gpu.Device()->CreateTexture2D(&desc,&data,&image),"native alternate");
63 HR(gpu.Device()->CreateShaderResourceView(image.Get(),nullptr,&alternate),"native alternate SRV");
64 }
65 ~Fixture(){sprite.Reset();gpu.Context()->ClearState();oldSprite.Reset();old.Reset();api.Reset();if(window)DestroyWindow(window);}
66 void Draw(unsigned scenario,bool native)
67 {
68 const unsigned amount=scenario==5 ? 1100 : 4;
69 for(unsigned i=0;i<amount;++i)
70 {
71 D3DXMATRIX transform;D3DXMatrixIdentity(&transform);
72 D3DXVECTOR3 position(30.f+i*17,35.f+i*23,float(i%2)*.6f+.2f),center(0,0,0);
73 // Texture-address sorting only promises batching; order between
74 // different API texture objects is not a shared identity.
75 if(scenario>=7)position.y=35.f+i*26;
76 RECT source{3,5,27,29};
77 DWORD color=0xb0ffb060+i*0x080008;
78 if(scenario==1)
79 {
80 D3DXMATRIX scale,rotation;D3DXMatrixScaling(&scale,1.5f,.75f,1);D3DXMatrixRotationZ(&rotation,.15f*i);
81 transform=scale*rotation;center={12,12,0};
82 }
83 if(scenario==3 || scenario==4)position={50.f+i*5,60.f+i*5,float((i*3)%4)*.2f+.1f};
84 if(scenario>=9)
85 {
86 // Cockpit fonts place their layer in SetTransform, while
87 // instrument artwork passes it through Draw's position.
88 position={50.f+i*5,60.f+i*5,0};
89 transform._43=float((i*3)%4)*.2f+.1f;
90 if(i%2){position.z=transform._43;transform._43=0;}
91 }
92 if(scenario==5)
93 {
94 D3DXMatrixScaling(&transform,.125f,.125f,1);
95 position={float(i%80)*32,float(i/80)*32,.2f};source={0,0,32,32};color=0xafffffff;
96 }
97 if(native)
98 {
99 Sprite11::Matrix matrix;memcpy(&matrix,&transform,sizeof(matrix));sprite.SetTransform(matrix);
100 const Sprite11::Vector at(position.x,position.y,position.z),pivot(center.x,center.y,center.z);
101 HR(sprite.Draw(scenario>=7 && i%2 ? alternate.Get() : texture.Get(),&source,&pivot,&at,color),"native draw");
102 }
103 else {oldSprite->SetTransform(&transform);HR(oldSprite->Draw(scenario>=7 && i%2 ? oldAlternate.Get() : oldTexture.Get(),&source,&center,&position,color),"reference draw");}
104 if(scenario==2 && i==1)
105 {
106 const RECT clip{95,52,145,141};
107 if(native){HR(sprite.Flush(),"native flush");gpu.Context()->RSSetScissorRects(1,&clip);}
108 else {HR(oldSprite->Flush(),"reference flush");old->SetScissorRect(&clip);}
109 }
110 }
111 }
112 void Save(const std::vector<uint32_t>& pixels,const std::string& name)
113 {
114 D3DLOCKED_RECT lock{};HR(oldStaging->LockRect(&lock,nullptr,0),"save map");for(UINT y=0;y<Height;++y)memcpy(static_cast<char*>(lock.pBits)+y*lock.Pitch,pixels.data()+y*Width,Width*4);
115 oldStaging->UnlockRect();HR(D3DXSaveSurfaceToFileW((folder/name).c_str(),D3DXIFF_PNG,oldStaging.Get(),nullptr,nullptr),"save PNG");
116 }
117 void Compare(unsigned scenario)
118 {
119 old->SetRenderTarget(0,oldTarget.Get());old->SetDepthStencilSurface(nullptr);
120 D3DVIEWPORT9 vp9{0,0,Width,Height,0,1};
121 // D3D9 Clear observes both the viewport and scissor; D3D11's RTV clear does not.
122 old->SetViewport(&vp9);old->SetRenderState(D3DRS_SCISSORTESTENABLE,FALSE);
123 old->Clear(0,nullptr,D3DCLEAR_TARGET,0xff203040,1,0);
124 if(scenario==2)vp9={20,30,Width-40,Height-60,0,1};
125 old->SetViewport(&vp9);old->SetRenderState(D3DRS_ZENABLE,FALSE);old->SetRenderState(D3DRS_ALPHABLENDENABLE,FALSE);
126 old->SetRenderState(D3DRS_SCISSORTESTENABLE,scenario==2);const RECT clip{25,30,160,165};old->SetScissorRect(&clip);
127 old->BeginScene();
128 DWORD flags=scenario==6 ? 0 : D3DXSPRITE_ALPHABLEND;if(scenario==3)flags|=D3DXSPRITE_SORT_DEPTH_FRONTTOBACK;if(scenario==4)flags|=D3DXSPRITE_SORT_DEPTH_BACKTOFRONT;
129 if(scenario==7)flags|=D3DXSPRITE_SORT_TEXTURE;
130 if(scenario==9)flags|=D3DXSPRITE_SORT_DEPTH_FRONTTOBACK;
131 if(scenario>=10)flags|=D3DXSPRITE_SORT_DEPTH_BACKTOFRONT;
132 if(scenario==11)flags|=D3DXSPRITE_SORT_TEXTURE;
133 HR(oldSprite->Begin(flags),"reference begin");Draw(scenario,false);HR(oldSprite->End(),"reference end");old->EndScene();
134 HR(old->GetRenderTargetData(oldTarget.Get(),oldStaging.Get()),"reference read");D3DLOCKED_RECT locked{};
135 HR(oldStaging->LockRect(&locked,nullptr,D3DLOCK_READONLY),"reference map");std::vector<uint32_t> expected(Width*Height);
136 for(UINT y=0;y<Height;++y)memcpy(expected.data()+y*Width,static_cast<char*>(locked.pBits)+y*locked.Pitch,Width*4);oldStaging->UnlockRect();
137 auto* context=gpu.Context();context->ClearState();auto* renderTarget=rtv.Get();context->OMSetRenderTargets(1,&renderTarget,nullptr);
138 D3D11_VIEWPORT viewport{float(vp9.X),float(vp9.Y),float(vp9.Width),float(vp9.Height),0,1};context->RSSetViewports(1,&viewport);
139 D3D11_DEPTH_STENCIL_DESC ds{};ds.DepthFunc=D3D11_COMPARISON_ALWAYS;ComPtr<ID3D11DepthStencilState> depthState;HR(gpu.Device()->CreateDepthStencilState(&ds,&depthState),"native disabled depth");context->OMSetDepthStencilState(depthState.Get(),0);
140 D3D11_RASTERIZER_DESC rs{};rs.FillMode=D3D11_FILL_SOLID;rs.CullMode=D3D11_CULL_FRONT;rs.DepthClipEnable=TRUE;rs.ScissorEnable=scenario==2;
141 ComPtr<ID3D11RasterizerState> raster;HR(gpu.Device()->CreateRasterizerState(&rs,&raster),"native raster");context->RSSetState(raster.Get());context->RSSetScissorRects(1,&clip);
142 context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP);
143 const float clear[]={32.f/255,48.f/255,64.f/255,1};context->ClearRenderTargetView(renderTarget,clear);
144 SpriteOptions11 options;options.alphaBlend=scenario!=6;if(scenario==3)options.sort=SpriteSort11::FrontToBack;if(scenario==4)options.sort=SpriteSort11::BackToFront;
145 if(scenario==7)options.sort=SpriteSort11::Texture;
146 if(scenario==9)options.sort=SpriteSort11::FrontToBack;
147 if(scenario>=10)options.sort=SpriteSort11::BackToFront;
148 if(scenario==11)options.sortTextures=true;
149 HR(sprite.Begin(context,options),"native begin");Draw(scenario,true);HR(sprite.End(),"native end");
150 ComPtr<ID3D11RasterizerState> restored;context->RSGetState(&restored);Check(restored==raster,"caller raster state restored");
151 D3D11_PRIMITIVE_TOPOLOGY topology{};context->IAGetPrimitiveTopology(&topology);Check(topology==D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP,"caller topology restored");
152 context->OMSetRenderTargets(0,nullptr,nullptr);context->CopyResource(staging.Get(),target.Get());D3D11_MAPPED_SUBRESOURCE mapped{};
153 HR(context->Map(staging.Get(),0,D3D11_MAP_READ,0,&mapped),"native map");std::vector<uint32_t> actual(Width*Height),difference(Width*Height);
154 double error=0,alpha=0;unsigned over=0,maximum=0,active=0;
155 for(UINT y=0;y<Height;++y)for(UINT x=0;x<Width;++x)
156 {
157 const auto a=expected[y*Width+x],b=reinterpret_cast<uint32_t*>(static_cast<char*>(mapped.pData)+y*mapped.RowPitch)[x];actual[y*Width+x]=b;
158 if(a!=0xff203040 || b!=0xff203040)++active;
159 unsigned worst=0;for(int shift:{0,8,16}){const auto delta=unsigned(std::abs(int((a>>shift)&255)-int((b>>shift)&255)));error+=delta;worst=(std::max)(worst,delta);}
160 alpha+=std::abs(int(a>>24)-int(b>>24));maximum=(std::max)(maximum,worst);if(worst>3)++over;difference[y*Width+x]=0xff000000|((std::min)(255u,worst*8)*0x10101);
161 }
162 context->Unmap(staging.Get(),0);Check(active>0,"nonempty sprite fixture");
163 error/=active*3.;alpha/=active;const double fraction=double(over)/active;
164 const bool passed=error<=1 && alpha<=1 && fraction<=.01;std::cout<<(passed ? "PASS: " : "FAIL: ")<<"sprite "<<scenario<<" mean="<<error<<" alpha="<<alpha<<" over3="<<fraction<<" max="<<maximum<<std::endl;
165 metrics<<scenario<<','<<error<<','<<alpha<<','<<fraction<<','<<maximum<<'\n';metrics.flush();
166 const auto prefix="sprite-"+std::to_string(scenario);Save(expected,prefix+"-d3d9.png");Save(actual,prefix+"-d3d11.png");Save(difference,prefix+"-diff8x.png");
167 if(!passed)++failures;
168 }
169 void DebugCheck()
170 {
171 ComPtr<ID3D11InfoQueue> queue;if(FAILED(gpu.Device()->QueryInterface(IID_PPV_ARGS(&queue))))return;
172 for(UINT64 i=0;i<queue->GetNumStoredMessages();++i)
173 {
174 SIZE_T size=0;queue->GetMessage(i,nullptr,&size);std::vector<char> bytes(size);auto* message=reinterpret_cast<D3D11_MESSAGE*>(bytes.data());
175 HR(queue->GetMessage(i,message,&size),"debug message");if(message->Severity<=D3D11_MESSAGE_SEVERITY_WARNING)throw std::runtime_error(message->pDescription);
176 }
177 }
178 };
179}
180int main(int argc,char** argv)
181{
182 try
183 {
184 bool warp=false,debug=true;for(int i=1;i<argc;++i){if(!strcmp(argv[i],"--warp"))warp=true;else if(!strcmp(argv[i],"--no-debug-layer"))debug=false;else throw std::runtime_error("unknown argument");}
185 Fixture test(warp,debug);for(unsigned i=0;i<12;++i)test.Compare(i);test.DebugCheck();
186 std::cout<<"12 sprite fixtures; "<<test.failures<<" failures\n";return test.failures ? 1 : 0;
187 }
188 catch(const std::exception& error){std::cerr<<"FAIL: "<<error.what()<<std::endl;return 1;}
189}
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
SCRIPT_CONTROL SCRIPT_STATE const void DWORD
ID3D11DeviceContext * Context() const
Definition Device11.h:66
ID3D11Device * Device() const
Definition Device11.h:65
const std::string & Status() const
Definition Device11.h:75
HRESULT Create(const DeviceOptions11 &options={})
Definition Device11.cpp:84
HRESULT Initialize(ID3D11Device *device, const std::filesystem::path &shaderDirectory={})
Definition Sprite11.cpp:26
void SetTransform(const Matrix &value)
Definition Sprite11.h:21
HRESULT Draw(ID3D11ShaderResourceView *texture, const RECT *source=nullptr, const Vector *center=nullptr, const Vector *position=nullptr, uint32_t color=0xffffffff)
Definition Sprite11.cpp:100
HRESULT Begin(ID3D11DeviceContext *context, const SpriteOptions11 &options={})
Definition Sprite11.cpp:47
constexpr float Width
constexpr float Height
HRESULT Draw(Rendering::RenderDevice *device, Rendering::RenderTexture *texture, Rendering::RenderBuffer *vertices, const RiseMath::Matrix &world, UINT segments, Rendering::RenderMaterial *volumeEffect=nullptr, float physicalScale=1)