Rise
The Vieneo Province
Loading...
Searching...
No Matches
Device11.cpp
Go to the documentation of this file.
1#include "Device11.h"
2#include "FrameProfiler11.h"
3#include <cstdio>
4#include <utility>
5
6using Microsoft::WRL::ComPtr;
7namespace Rendering
8{
9 namespace
10 {
11 constexpr DXGI_FORMAT ColorFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
12 bool Supports(ID3D11Device* device, DXGI_FORMAT format, UINT required)
13 {
14 UINT flags = 0;
15 return device && SUCCEEDED(device->CheckFormatSupport(format, &flags))
16 && (flags & required) == required;
17 }
18 }
19
20 HRESULT SceneDepth11::Create(ID3D11Device* device, UINT width, UINT height, DXGI_SAMPLE_DESC samples)
21 {
22 if (!device || !width || !height || !samples.Count) return E_INVALIDARG;
23 UINT qualityLevels = 0;
24 HRESULT hr = device->CheckMultisampleQualityLevels(DXGI_FORMAT_D24_UNORM_S8_UINT,
25 samples.Count, &qualityLevels);
26 if (FAILED(hr)) return hr;
27 if (!qualityLevels || samples.Quality >= qualityLevels) return DXGI_ERROR_UNSUPPORTED;
28 if (!Supports(device, DXGI_FORMAT_R24_UNORM_X8_TYPELESS,
29 D3D11_FORMAT_SUPPORT_TEXTURE2D | D3D11_FORMAT_SUPPORT_SHADER_LOAD |
30 (samples.Count > 1 ? D3D11_FORMAT_SUPPORT_MULTISAMPLE_LOAD : 0)))
31 return DXGI_ERROR_UNSUPPORTED;
32
33 // Construct a complete replacement first; a failed resize leaves the
34 // existing offscreen resource usable by its owner.
35 SceneDepth11 next;
36 auto& desc = next.description;
37 desc.Width = width; desc.Height = height;
38 desc.MipLevels = desc.ArraySize = 1;
39 desc.Format = DXGI_FORMAT_R24G8_TYPELESS;
40 desc.SampleDesc = samples;
41 desc.Usage = D3D11_USAGE_DEFAULT;
42 desc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
43 if (FAILED(hr = device->CreateTexture2D(&desc, nullptr, &next.texture))) return hr;
44 D3D11_DEPTH_STENCIL_VIEW_DESC dsv{};
45 dsv.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
46 dsv.ViewDimension = samples.Count == 1 ? D3D11_DSV_DIMENSION_TEXTURE2D : D3D11_DSV_DIMENSION_TEXTURE2DMS;
47 if (FAILED(hr = device->CreateDepthStencilView(next.texture.Get(), &dsv, &next.writable))) return hr;
48 dsv.Flags = D3D11_DSV_READ_ONLY_DEPTH | D3D11_DSV_READ_ONLY_STENCIL;
49 if (FAILED(hr = device->CreateDepthStencilView(next.texture.Get(), &dsv, &next.readOnly))) return hr;
50 D3D11_SHADER_RESOURCE_VIEW_DESC srv{};
51 srv.Format = DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
52 srv.ViewDimension = samples.Count == 1 ? D3D11_SRV_DIMENSION_TEXTURE2D : D3D11_SRV_DIMENSION_TEXTURE2DMS;
53 if (samples.Count == 1) srv.Texture2D.MipLevels = 1;
54 if (FAILED(hr = device->CreateShaderResourceView(next.texture.Get(), &srv, &next.shaderView))) return hr;
55 // Optional stencil sampling lets clouds reject cockpit samples before
56 // expensive shader work. Keep the existing hardware stencil fallback
57 // on adapters that cannot expose the stencil plane to shaders.
58 srv.Format = DXGI_FORMAT_X24_TYPELESS_G8_UINT;
59 if (Supports(device, srv.Format, D3D11_FORMAT_SUPPORT_TEXTURE2D | D3D11_FORMAT_SUPPORT_SHADER_LOAD |
60 (samples.Count > 1 ? D3D11_FORMAT_SUPPORT_MULTISAMPLE_LOAD : 0)))
61 {
62 if (FAILED(hr = device->CreateShaderResourceView(next.texture.Get(), &srv, &next.stencilView))) return hr;
63 }
64 *this = std::move(next);
65 return S_OK;
66 }
67
69 {
70 stencilView.Reset(); shaderView.Reset(); readOnly.Reset(); writable.Reset(); texture.Reset(); description = {};
71 }
72
73 HRESULT Device11::Fail(const char* stage, HRESULT hr)
74 {
75 char detail[512]{};
76 char adapter[160]{};
77 WideCharToMultiByte(CP_UTF8, 0, adapterDescription.Description, -1, adapter, sizeof(adapter), nullptr, nullptr);
78 sprintf_s(detail, "D3D11 adapter=%s featureLevel=0x%04x stage=%s HRESULT=0x%08lx",
79 adapter, UINT(featureLevel), stage, static_cast<unsigned long>(hr));
80 status = detail;
81 return hr;
82 }
83
85 {
86 Reset();
87 constexpr D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_0};
88 UINT flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
89 if (options.debugLayer) flags |= D3D11_CREATE_DEVICE_DEBUG;
90 HRESULT hr = D3D11CreateDevice(nullptr, options.driver, nullptr, flags, levels,
91 ARRAYSIZE(levels), D3D11_SDK_VERSION, &device, &featureLevel, &context);
92 // Missing optional Graphics Tools must never prevent normal execution.
93 if (hr == DXGI_ERROR_SDK_COMPONENT_MISSING && options.debugLayer)
94 {
95 flags &= ~D3D11_CREATE_DEVICE_DEBUG;
96 device.Reset(); context.Reset();
97 hr = D3D11CreateDevice(nullptr, options.driver, nullptr, flags, levels,
98 ARRAYSIZE(levels), D3D11_SDK_VERSION, &device, &featureLevel, &context);
99 }
100 if (FAILED(hr)) return Fail("create device (requires feature level 11.0)", hr);
101 debugEnabled = (flags & D3D11_CREATE_DEVICE_DEBUG) != 0;
102 ComPtr<IDXGIDevice> dxgiDevice;
103 ComPtr<IDXGIAdapter> adapter;
104 ComPtr<IDXGIAdapter1> adapter1;
105 if (FAILED(hr = device.As(&dxgiDevice)) || FAILED(hr = dxgiDevice->GetAdapter(&adapter))
106 || FAILED(hr = adapter.As(&adapter1)) || FAILED(hr = adapter1->GetDesc1(&adapterDescription)))
107 return Fail("read adapter", hr);
108 Fail(debugEnabled ? "ready (debug layer enabled)" : "ready (debug layer disabled)", S_OK);
109 return S_OK;
110 }
111
112 bool Device11::SupportsSamples(UINT count) const
113 {
114 if (!device || count == 0 || count > D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT) return false;
115 UINT colorLevels = 0, depthLevels = 0;
116 return SUCCEEDED(device->CheckMultisampleQualityLevels(ColorFormat, count, &colorLevels)) && colorLevels
117 && SUCCEEDED(device->CheckMultisampleQualityLevels(DXGI_FORMAT_D24_UNORM_S8_UINT, count, &depthLevels)) && depthLevels
118 && Supports(device.Get(), DXGI_FORMAT_R24_UNORM_X8_TYPELESS,
119 D3D11_FORMAT_SUPPORT_TEXTURE2D | D3D11_FORMAT_SUPPORT_SHADER_LOAD |
120 (count > 1 ? D3D11_FORMAT_SUPPORT_MULTISAMPLE_LOAD : 0))
121 && (count == 1 || Supports(device.Get(), ColorFormat, D3D11_FORMAT_SUPPORT_MULTISAMPLE_RESOLVE));
122 }
123
124 UINT Device11::SelectSamples(UINT requested) const
125 {
126 for (UINT count : {8u, 4u, 2u, 1u})
127 if (count <= requested && SupportsSamples(count)) return count;
128 return SupportsSamples(1) ? 1 : 0;
129 }
130
132 {
133 if (!SupportsSamples(1)
134 || !Supports(device.Get(), DXGI_FORMAT_R32_FLOAT, D3D11_FORMAT_SUPPORT_RENDER_TARGET | D3D11_FORMAT_SUPPORT_SHADER_LOAD)
135 || !Supports(device.Get(), DXGI_FORMAT_R16_FLOAT, D3D11_FORMAT_SUPPORT_TEXTURE3D | D3D11_FORMAT_SUPPORT_SHADER_SAMPLE)
136 || !Supports(device.Get(), DXGI_FORMAT_R16G16B16A16_FLOAT, D3D11_FORMAT_SUPPORT_RENDER_TARGET | D3D11_FORMAT_SUPPORT_SHADER_SAMPLE)
137 || !Supports(device.Get(), DXGI_FORMAT_R8_UNORM, D3D11_FORMAT_SUPPORT_TEXTURE2D | D3D11_FORMAT_SUPPORT_SHADER_SAMPLE))
138 return DXGI_ERROR_UNSUPPORTED;
139 return S_OK;
140 }
141
142 HRESULT Device11::AttachWindow(HWND window, UINT newWidth, UINT newHeight, UINT samples)
143 {
144 if (!device || !window || !newWidth || !newHeight || swapChain) return E_INVALIDARG;
145 ComPtr<IDXGIDevice> dxgiDevice;
146 ComPtr<IDXGIAdapter> adapter;
147 ComPtr<IDXGIFactory2> factory;
148 HRESULT hr = device.As(&dxgiDevice);
149 if (FAILED(hr) || FAILED(hr = dxgiDevice->GetAdapter(&adapter))
150 || FAILED(hr = adapter->GetParent(IID_PPV_ARGS(&factory)))) return Fail("create swap-chain factory", hr);
151 DXGI_SWAP_CHAIN_DESC1 desc{};
152 desc.Width = newWidth; desc.Height = newHeight; desc.Format = ColorFormat;
153 desc.SampleDesc.Count = 1; // Flip model is always single sample.
154 desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
155 desc.BufferCount = 2; desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
156 if (FAILED(hr = factory->CreateSwapChainForHwnd(device.Get(), window, &desc, nullptr, nullptr, &swapChain)))
157 return Fail("create flip swap chain", hr);
158 // The application owns fullscreen transitions and their callbacks.
159 if (FAILED(hr = factory->MakeWindowAssociation(window, DXGI_MWA_NO_ALT_ENTER))) return Fail("window association", hr);
160 return Resize(newWidth, newHeight, samples);
161 }
162
164 {
165 if (!context) return;
166 ID3D11ShaderResourceView* empty[D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT]{};
167 context->VSSetShaderResources(0, ARRAYSIZE(empty), empty);
168 context->HSSetShaderResources(0, ARRAYSIZE(empty), empty);
169 context->DSSetShaderResources(0, ARRAYSIZE(empty), empty);
170 context->GSSetShaderResources(0, ARRAYSIZE(empty), empty);
171 context->PSSetShaderResources(0, ARRAYSIZE(empty), empty);
172 context->CSSetShaderResources(0, ARRAYSIZE(empty), empty);
173 }
174
176 {
177 if (context)
178 {
180 context->OMSetRenderTargets(0, nullptr, nullptr);
181 }
182 depth.Reset(); sceneTarget.Reset(); sceneColor.Reset(); backBuffer.Reset();
183 width = height = sampleCount = 0;
184 }
185
186 HRESULT Device11::CreateTargets(UINT newWidth, UINT newHeight, UINT samples)
187 {
188 const UINT selected = SelectSamples(samples);
189 if (!selected) return Fail("select multisampling", DXGI_ERROR_UNSUPPORTED);
190 HRESULT hr = swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer));
191 if (FAILED(hr)) return Fail("get back buffer", hr);
192 D3D11_TEXTURE2D_DESC desc{};
193 backBuffer->GetDesc(&desc);
194 // Keep the scene separate even at 1x: postprocessing may sample scene
195 // color, while Present only consumes this completed image.
196 desc.SampleDesc = {selected, 0};
197 desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
198 if (FAILED(hr = device->CreateTexture2D(&desc, nullptr, &sceneColor))) return Fail("create scene color", hr);
199 if (FAILED(hr = device->CreateRenderTargetView(sceneColor.Get(), nullptr, &sceneTarget))) return Fail("create scene RTV", hr);
200 if (FAILED(hr = depth.Create(device.Get(), newWidth, newHeight, desc.SampleDesc))) return Fail("create shader-readable scene depth", hr);
201 width = newWidth; height = newHeight; sampleCount = selected;
202 BindScene();
203 char stage[120]{};
204 sprintf_s(stage, "targets ready %ux%u requestedMSAA=%u actualMSAA=%u depth=D24S8 Texture2D%s",
205 width, height, samples, selected, selected > 1 ? "MS" : "");
206 Fail(stage, S_OK);
207 return S_OK;
208 }
209
210 HRESULT Device11::Resize(UINT newWidth, UINT newHeight, UINT samples)
211 {
212 if (!swapChain) return E_UNEXPECTED;
213 if (!newWidth || !newHeight) { suspended = true; return S_FALSE; }
214 suspended = false;
215 if (newWidth == width && newHeight == height && SelectSamples(samples) == sampleCount) return S_OK;
217 // Drop deferred runtime references to the old flip buffer as well.
218 context->Flush();
219 HRESULT hr = swapChain->ResizeBuffers(0, newWidth, newHeight, DXGI_FORMAT_UNKNOWN, 0);
220 if (FAILED(hr)) return Fail("ResizeBuffers (release all back-buffer references)", hr);
221 hr = CreateTargets(newWidth, newHeight, samples);
222 if (FAILED(hr)) ReleaseTargets();
223 return hr;
224 }
225
227 {
228 if (!context || !sceneTarget) return;
230 auto* target = sceneTarget.Get();
231 context->OMSetRenderTargets(1, &target, depth.WriteView());
232 const D3D11_VIEWPORT viewport{0, 0, float(width), float(height), 0, 1};
233 context->RSSetViewports(1, &viewport);
234 }
235
237 {
238 if (!context || !sceneTarget) return;
239 auto* target = sceneTarget.Get();
240 context->OMSetRenderTargets(1, &target, depth.ReadView());
241 }
242
243 HRESULT Device11::Present(UINT syncInterval)
244 {
245 if (!swapChain || !sceneColor) return E_UNEXPECTED;
246 if (suspended) return S_FALSE;
247 ProfileScope11 resolveTiming("MSAA resolve or copy");
249 context->OMSetRenderTargets(0, nullptr, nullptr);
250 if (sampleCount > 1)
251 context->ResolveSubresource(backBuffer.Get(), 0, sceneColor.Get(), 0, ColorFormat);
252 else context->CopyResource(backBuffer.Get(), sceneColor.Get());
253 resolveTiming.Stop();
255 ProfileScope11 presentTiming("Present wait",false);
256 const HRESULT hr = swapChain->Present(syncInterval, 0);
257 if (FAILED(hr)) return Fail("Present", hr);
258 return hr; // DXGI_STATUS_OCCLUDED is retained for the host's idle loop.
259 }
260
262 {
263 if (!swapChain) return E_UNEXPECTED;
264 const HRESULT hr = swapChain->SetFullscreenState(fullscreen, nullptr);
265 return FAILED(hr) ? Fail("fullscreen transition", hr) : hr;
266 }
267
269 {
270 return device ? device->GetDeviceRemovedReason() : E_UNEXPECTED;
271 }
272
274 {
275 if (swapChain) swapChain->SetFullscreenState(FALSE, nullptr);
276 if (context) { context->ClearState(); context->Flush(); }
277 ReleaseTargets(); swapChain.Reset(); context.Reset(); device.Reset();
279 }
280}
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
UINT SelectSamples(UINT requested) const
Definition Device11.cpp:124
Microsoft::WRL::ComPtr< ID3D11RenderTargetView > sceneTarget
Definition Device11.h:86
HRESULT AttachWindow(HWND window, UINT width, UINT height, UINT requestedSamples)
Definition Device11.cpp:142
bool SupportsSamples(UINT count) const
Definition Device11.cpp:112
void UnbindShaderResources()
Definition Device11.cpp:163
HRESULT Fail(const char *stage, HRESULT hr)
Definition Device11.cpp:73
void BindSceneWithReadOnlyDepth()
Definition Device11.cpp:236
std::string status
Definition Device11.h:92
Microsoft::WRL::ComPtr< ID3D11Texture2D > sceneColor
Definition Device11.h:85
HRESULT CheckCloudFormats() const
Definition Device11.cpp:131
DXGI_ADAPTER_DESC1 adapterDescription
Definition Device11.h:88
Microsoft::WRL::ComPtr< IDXGISwapChain1 > swapChain
Definition Device11.h:84
HRESULT Present(UINT syncInterval=1)
Definition Device11.cpp:243
HRESULT SetFullscreen(bool fullscreen)
Definition Device11.cpp:261
Microsoft::WRL::ComPtr< ID3D11Texture2D > backBuffer
Definition Device11.h:85
HRESULT CreateTargets(UINT width, UINT height, UINT samples)
Definition Device11.cpp:186
D3D_FEATURE_LEVEL featureLevel
Definition Device11.h:89
Microsoft::WRL::ComPtr< ID3D11DeviceContext > context
Definition Device11.h:83
Microsoft::WRL::ComPtr< ID3D11Device > device
Definition Device11.h:82
HRESULT Resize(UINT width, UINT height, UINT requestedSamples)
Definition Device11.cpp:210
HRESULT Create(const DeviceOptions11 &options={})
Definition Device11.cpp:84
HRESULT RemovalReason() const
Definition Device11.cpp:268
SceneDepth11 depth
Definition Device11.h:87
static FrameProfiler11 & Get()
Microsoft::WRL::ComPtr< ID3D11ShaderResourceView > shaderView
Definition Device11.h:26
Microsoft::WRL::ComPtr< ID3D11DepthStencilView > writable
Definition Device11.h:25
D3D11_TEXTURE2D_DESC description
Definition Device11.h:27
Microsoft::WRL::ComPtr< ID3D11DepthStencilView > readOnly
Definition Device11.h:25
Microsoft::WRL::ComPtr< ID3D11Texture2D > texture
Definition Device11.h:24
HRESULT Create(ID3D11Device *device, UINT width, UINT height, DXGI_SAMPLE_DESC samples)
Definition Device11.cpp:20
ID3D11DepthStencilView * ReadView() const
Definition Device11.h:19
Microsoft::WRL::ComPtr< ID3D11ShaderResourceView > stencilView
Definition Device11.h:26
ID3D11DepthStencilView * WriteView() const
Definition Device11.h:18
D3D_DRIVER_TYPE driver
Definition Device11.h:32