1 //
2 // Copyright (c) 2012-2014 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6
7 // SwapChain11.cpp: Implements a back-end specific class for the D3D11 swap chain.
8
9 #include "libANGLE/renderer/d3d/d3d11/SwapChain11.h"
10
11 #include <EGL/eglext.h>
12
13 #include "libANGLE/features.h"
14 #include "libANGLE/renderer/d3d/d3d11/NativeWindow11.h"
15 #include "libANGLE/renderer/d3d/d3d11/Renderer11.h"
16 #include "libANGLE/renderer/d3d/d3d11/formatutils11.h"
17 #include "libANGLE/renderer/d3d/d3d11/renderer11_utils.h"
18 #include "libANGLE/renderer/d3d/d3d11/texture_format_table.h"
19 #include "third_party/trace_event/trace_event.h"
20
21 // Precompiled shaders
22 #include "libANGLE/renderer/d3d/d3d11/shaders/compiled/passthrough2d11vs.h"
23 #include "libANGLE/renderer/d3d/d3d11/shaders/compiled/passthroughrgba2d11ps.h"
24 #include "libANGLE/renderer/d3d/d3d11/shaders/compiled/passthroughrgba2dms11ps.h"
25
26 #ifdef ANGLE_ENABLE_KEYEDMUTEX
27 #define ANGLE_RESOURCE_SHARE_TYPE D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX
28 #else
29 #define ANGLE_RESOURCE_SHARE_TYPE D3D11_RESOURCE_MISC_SHARED
30 #endif
31
32 namespace rx
33 {
34
35 namespace
36 {
37 // To avoid overflow in QPC to Microseconds calculations, since we multiply
38 // by kMicrosecondsPerSecond, then the QPC value should not exceed
39 // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply.
40 static constexpr int64_t kQPCOverflowThreshold = 0x8637BD05AF7;
41 static constexpr int64_t kMicrosecondsPerSecond = 1000000;
42
NeedsOffscreenTexture(Renderer11 * renderer,NativeWindow11 * nativeWindow,EGLint orientation)43 bool NeedsOffscreenTexture(Renderer11 *renderer, NativeWindow11 *nativeWindow, EGLint orientation)
44 {
45 // We don't need an offscreen texture if either orientation = INVERT_Y,
46 // or present path fast is enabled and we're not rendering onto an offscreen surface.
47 return orientation != EGL_SURFACE_ORIENTATION_INVERT_Y_ANGLE &&
48 !(renderer->presentPathFastEnabled() && nativeWindow->getNativeWindow());
49 }
50 } // anonymous namespace
51
SwapChain11(Renderer11 * renderer,NativeWindow11 * nativeWindow,HANDLE shareHandle,IUnknown * d3dTexture,GLenum backBufferFormat,GLenum depthBufferFormat,EGLint orientation,EGLint samples)52 SwapChain11::SwapChain11(Renderer11 *renderer,
53 NativeWindow11 *nativeWindow,
54 HANDLE shareHandle,
55 IUnknown *d3dTexture,
56 GLenum backBufferFormat,
57 GLenum depthBufferFormat,
58 EGLint orientation,
59 EGLint samples)
60 : SwapChainD3D(shareHandle, d3dTexture, backBufferFormat, depthBufferFormat),
61 mRenderer(renderer),
62 mWidth(-1),
63 mHeight(-1),
64 mOrientation(orientation),
65 mAppCreatedShareHandle(mShareHandle != nullptr),
66 mSwapInterval(0),
67 mPassThroughResourcesInit(false),
68 mNativeWindow(nativeWindow),
69 mFirstSwap(true),
70 mSwapChain(nullptr),
71 mSwapChain1(nullptr),
72 mKeyedMutex(nullptr),
73 mBackBufferTexture(),
74 mBackBufferRTView(),
75 mBackBufferSRView(),
76 mNeedsOffscreenTexture(NeedsOffscreenTexture(renderer, nativeWindow, orientation)),
77 mOffscreenTexture(),
78 mOffscreenRTView(),
79 mOffscreenSRView(),
80 mNeedsOffscreenTextureCopy(false),
81 mOffscreenTextureCopyForSRV(),
82 mDepthStencilTexture(),
83 mDepthStencilDSView(),
84 mDepthStencilSRView(),
85 mQuadVB(),
86 mPassThroughSampler(),
87 mPassThroughIL(),
88 mPassThroughVS(),
89 mPassThroughPS(),
90 mPassThroughRS(),
91 mColorRenderTarget(this, renderer, false),
92 mDepthStencilRenderTarget(this, renderer, true),
93 mEGLSamples(samples)
94 {
95 // Sanity check that if present path fast is active then we're using the default orientation
96 ASSERT(!mRenderer->presentPathFastEnabled() || orientation == 0);
97
98 // Get the performance counter
99 LARGE_INTEGER counterFreqency = {};
100 BOOL success = QueryPerformanceFrequency(&counterFreqency);
101 ASSERT(success);
102
103 mQPCFrequency = counterFreqency.QuadPart;
104 }
105
~SwapChain11()106 SwapChain11::~SwapChain11()
107 {
108 release();
109 }
110
release()111 void SwapChain11::release()
112 {
113 // TODO(jmadill): Should probably signal that the RenderTarget is dirty.
114
115 SafeRelease(mSwapChain1);
116 SafeRelease(mSwapChain);
117 SafeRelease(mKeyedMutex);
118 mBackBufferTexture.reset();
119 mBackBufferRTView.reset();
120 mBackBufferSRView.reset();
121 mOffscreenTexture.reset();
122 mOffscreenRTView.reset();
123 mOffscreenSRView.reset();
124 mDepthStencilTexture.reset();
125 mDepthStencilDSView.reset();
126 mDepthStencilSRView.reset();
127 mQuadVB.reset();
128 mPassThroughSampler.reset();
129 mPassThroughIL.reset();
130 mPassThroughVS.reset();
131 mPassThroughPS.reset();
132 mPassThroughRS.reset();
133
134 if (!mAppCreatedShareHandle)
135 {
136 mShareHandle = nullptr;
137 }
138 }
139
releaseOffscreenColorBuffer()140 void SwapChain11::releaseOffscreenColorBuffer()
141 {
142 mOffscreenTexture.reset();
143 mOffscreenRTView.reset();
144 mOffscreenSRView.reset();
145 mNeedsOffscreenTextureCopy = false;
146 mOffscreenTextureCopyForSRV.reset();
147 }
148
releaseOffscreenDepthBuffer()149 void SwapChain11::releaseOffscreenDepthBuffer()
150 {
151 mDepthStencilTexture.reset();
152 mDepthStencilDSView.reset();
153 mDepthStencilSRView.reset();
154 }
155
resetOffscreenBuffers(const gl::Context * context,int backbufferWidth,int backbufferHeight)156 EGLint SwapChain11::resetOffscreenBuffers(const gl::Context *context,
157 int backbufferWidth,
158 int backbufferHeight)
159 {
160 if (mNeedsOffscreenTexture)
161 {
162 EGLint result = resetOffscreenColorBuffer(context, backbufferWidth, backbufferHeight);
163 if (result != EGL_SUCCESS)
164 {
165 return result;
166 }
167 }
168
169 EGLint result = resetOffscreenDepthBuffer(backbufferWidth, backbufferHeight);
170 if (result != EGL_SUCCESS)
171 {
172 return result;
173 }
174
175 mWidth = backbufferWidth;
176 mHeight = backbufferHeight;
177
178 return EGL_SUCCESS;
179 }
180
resetOffscreenColorBuffer(const gl::Context * context,int backbufferWidth,int backbufferHeight)181 EGLint SwapChain11::resetOffscreenColorBuffer(const gl::Context *context,
182 int backbufferWidth,
183 int backbufferHeight)
184 {
185 ASSERT(mNeedsOffscreenTexture);
186
187 TRACE_EVENT0("gpu.angle", "SwapChain11::resetOffscreenTexture");
188 ID3D11Device *device = mRenderer->getDevice();
189
190 ASSERT(device != nullptr);
191
192 // D3D11 does not allow zero size textures
193 ASSERT(backbufferWidth >= 1);
194 ASSERT(backbufferHeight >= 1);
195
196 // Preserve the render target content
197 TextureHelper11 previousOffscreenTexture(std::move(mOffscreenTexture));
198 const int previousWidth = mWidth;
199 const int previousHeight = mHeight;
200
201 releaseOffscreenColorBuffer();
202
203 const d3d11::Format &backbufferFormatInfo =
204 d3d11::Format::Get(mOffscreenRenderTargetFormat, mRenderer->getRenderer11DeviceCaps());
205 D3D11_TEXTURE2D_DESC offscreenTextureDesc = {0};
206
207 // If the app passed in a share handle or D3D texture, open the resource
208 // See EGL_ANGLE_d3d_share_handle_client_buffer and EGL_ANGLE_d3d_texture_client_buffer
209 if (mAppCreatedShareHandle || mD3DTexture != nullptr)
210 {
211 if (mAppCreatedShareHandle)
212 {
213 ID3D11Resource *tempResource11;
214 HRESULT result = device->OpenSharedResource(mShareHandle, __uuidof(ID3D11Resource),
215 (void **)&tempResource11);
216 ASSERT(SUCCEEDED(result));
217
218 mOffscreenTexture.set(d3d11::DynamicCastComObject<ID3D11Texture2D>(tempResource11),
219 backbufferFormatInfo);
220 SafeRelease(tempResource11);
221 }
222 else if (mD3DTexture != nullptr)
223 {
224 mOffscreenTexture.set(d3d11::DynamicCastComObject<ID3D11Texture2D>(mD3DTexture),
225 backbufferFormatInfo);
226 }
227 else
228 {
229 UNREACHABLE();
230 }
231 ASSERT(mOffscreenTexture.valid());
232 mOffscreenTexture.getDesc(&offscreenTextureDesc);
233
234 // Fail if the offscreen texture is not renderable.
235 if ((offscreenTextureDesc.BindFlags & D3D11_BIND_RENDER_TARGET) == 0)
236 {
237 ERR() << "Could not use provided offscreen texture, texture not renderable.";
238 release();
239 return EGL_BAD_SURFACE;
240 }
241 }
242 else
243 {
244 const bool useSharedResource =
245 !mNativeWindow->getNativeWindow() && mRenderer->getShareHandleSupport();
246
247 offscreenTextureDesc.Width = backbufferWidth;
248 offscreenTextureDesc.Height = backbufferHeight;
249 offscreenTextureDesc.Format = backbufferFormatInfo.texFormat;
250 offscreenTextureDesc.MipLevels = 1;
251 offscreenTextureDesc.ArraySize = 1;
252 offscreenTextureDesc.SampleDesc.Count = getD3DSamples();
253 offscreenTextureDesc.SampleDesc.Quality = 0;
254 offscreenTextureDesc.Usage = D3D11_USAGE_DEFAULT;
255 offscreenTextureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
256 offscreenTextureDesc.CPUAccessFlags = 0;
257 offscreenTextureDesc.MiscFlags = useSharedResource ? ANGLE_RESOURCE_SHARE_TYPE : 0;
258
259 gl::Error err = mRenderer->allocateTexture(offscreenTextureDesc, backbufferFormatInfo,
260 &mOffscreenTexture);
261 if (err.isError())
262 {
263 ERR() << "Could not create offscreen texture, " << err;
264 release();
265 return EGL_BAD_ALLOC;
266 }
267
268 mOffscreenTexture.setDebugName("Offscreen back buffer texture");
269
270 // EGL_ANGLE_surface_d3d_texture_2d_share_handle requires that we store a share handle for the client
271 if (useSharedResource)
272 {
273 IDXGIResource *offscreenTextureResource = nullptr;
274 HRESULT result = mOffscreenTexture.get()->QueryInterface(
275 __uuidof(IDXGIResource), (void **)&offscreenTextureResource);
276
277 // Fall back to no share handle on failure
278 if (FAILED(result))
279 {
280 ERR() << "Could not query offscreen texture resource, " << gl::FmtHR(result);
281 }
282 else
283 {
284 result = offscreenTextureResource->GetSharedHandle(&mShareHandle);
285 SafeRelease(offscreenTextureResource);
286
287 if (FAILED(result))
288 {
289 mShareHandle = nullptr;
290 ERR() << "Could not get offscreen texture shared handle, " << gl::FmtHR(result);
291 }
292 }
293 }
294 }
295
296 // This may return null if the original texture was created without a keyed mutex.
297 mKeyedMutex = d3d11::DynamicCastComObject<IDXGIKeyedMutex>(mOffscreenTexture.get());
298
299 D3D11_RENDER_TARGET_VIEW_DESC offscreenRTVDesc;
300 offscreenRTVDesc.Format = backbufferFormatInfo.rtvFormat;
301 offscreenRTVDesc.ViewDimension =
302 (mEGLSamples <= 1) ? D3D11_RTV_DIMENSION_TEXTURE2D : D3D11_RTV_DIMENSION_TEXTURE2DMS;
303 offscreenRTVDesc.Texture2D.MipSlice = 0;
304
305 gl::Error err =
306 mRenderer->allocateResource(offscreenRTVDesc, mOffscreenTexture.get(), &mOffscreenRTView);
307 ASSERT(!err.isError());
308 mOffscreenRTView.setDebugName("Offscreen back buffer render target");
309
310 D3D11_SHADER_RESOURCE_VIEW_DESC offscreenSRVDesc;
311 offscreenSRVDesc.Format = backbufferFormatInfo.srvFormat;
312 offscreenSRVDesc.ViewDimension =
313 (mEGLSamples <= 1) ? D3D11_SRV_DIMENSION_TEXTURE2D : D3D11_SRV_DIMENSION_TEXTURE2DMS;
314 offscreenSRVDesc.Texture2D.MostDetailedMip = 0;
315 offscreenSRVDesc.Texture2D.MipLevels = static_cast<UINT>(-1);
316
317 if (offscreenTextureDesc.BindFlags & D3D11_BIND_SHADER_RESOURCE)
318 {
319 err = mRenderer->allocateResource(offscreenSRVDesc, mOffscreenTexture.get(),
320 &mOffscreenSRView);
321 ASSERT(!err.isError());
322 mOffscreenSRView.setDebugName("Offscreen back buffer shader resource");
323 }
324 else
325 {
326 // Special case for external textures that cannot support sampling. Since internally we
327 // assume our SwapChain is always readable, we make a copy texture that is compatible.
328 mNeedsOffscreenTextureCopy = true;
329 }
330
331 if (previousOffscreenTexture.valid())
332 {
333 D3D11_BOX sourceBox = {0};
334 sourceBox.left = 0;
335 sourceBox.right = std::min(previousWidth, backbufferWidth);
336 sourceBox.top = std::max(previousHeight - backbufferHeight, 0);
337 sourceBox.bottom = previousHeight;
338 sourceBox.front = 0;
339 sourceBox.back = 1;
340
341 ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
342 const int yoffset = std::max(backbufferHeight - previousHeight, 0);
343 deviceContext->CopySubresourceRegion(mOffscreenTexture.get(), 0, 0, yoffset, 0,
344 previousOffscreenTexture.get(), 0, &sourceBox);
345
346 if (mSwapChain)
347 {
348 swapRect(context, 0, 0, backbufferWidth, backbufferHeight);
349 }
350 }
351
352 return EGL_SUCCESS;
353 }
354
resetOffscreenDepthBuffer(int backbufferWidth,int backbufferHeight)355 EGLint SwapChain11::resetOffscreenDepthBuffer(int backbufferWidth, int backbufferHeight)
356 {
357 releaseOffscreenDepthBuffer();
358
359 if (mDepthBufferFormat != GL_NONE)
360 {
361 const d3d11::Format &depthBufferFormatInfo =
362 d3d11::Format::Get(mDepthBufferFormat, mRenderer->getRenderer11DeviceCaps());
363
364 D3D11_TEXTURE2D_DESC depthStencilTextureDesc;
365 depthStencilTextureDesc.Width = backbufferWidth;
366 depthStencilTextureDesc.Height = backbufferHeight;
367 depthStencilTextureDesc.Format = depthBufferFormatInfo.texFormat;
368 depthStencilTextureDesc.MipLevels = 1;
369 depthStencilTextureDesc.ArraySize = 1;
370 depthStencilTextureDesc.SampleDesc.Count = getD3DSamples();
371 depthStencilTextureDesc.Usage = D3D11_USAGE_DEFAULT;
372 depthStencilTextureDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
373
374 // If there is a multisampled offscreen color texture, the offscreen depth-stencil texture
375 // must also have the same quality value.
376 if (mOffscreenTexture.valid() && getD3DSamples() > 1)
377 {
378 D3D11_TEXTURE2D_DESC offscreenTextureDesc = {0};
379 mOffscreenTexture.getDesc(&offscreenTextureDesc);
380 depthStencilTextureDesc.SampleDesc.Quality = offscreenTextureDesc.SampleDesc.Quality;
381 }
382 else
383 {
384 depthStencilTextureDesc.SampleDesc.Quality = 0;
385 }
386
387 // Only create an SRV if it is supported
388 bool depthStencilSRV =
389 depthBufferFormatInfo.srvFormat != DXGI_FORMAT_UNKNOWN &&
390 (mRenderer->getRenderer11DeviceCaps().supportsMultisampledDepthStencilSRVs ||
391 depthStencilTextureDesc.SampleDesc.Count <= 1);
392 if (depthStencilSRV)
393 {
394 depthStencilTextureDesc.BindFlags |= D3D11_BIND_SHADER_RESOURCE;
395 }
396
397 depthStencilTextureDesc.CPUAccessFlags = 0;
398 depthStencilTextureDesc.MiscFlags = 0;
399
400 gl::Error err = mRenderer->allocateTexture(depthStencilTextureDesc, depthBufferFormatInfo,
401 &mDepthStencilTexture);
402 if (err.isError())
403 {
404 ERR() << "Could not create depthstencil surface for new swap chain, " << err;
405 release();
406 return EGL_BAD_ALLOC;
407 }
408 mDepthStencilTexture.setDebugName("Offscreen depth stencil texture");
409
410 D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilDesc;
411 depthStencilDesc.Format = depthBufferFormatInfo.dsvFormat;
412 depthStencilDesc.ViewDimension =
413 (mEGLSamples <= 1) ? D3D11_DSV_DIMENSION_TEXTURE2D : D3D11_DSV_DIMENSION_TEXTURE2DMS;
414 depthStencilDesc.Flags = 0;
415 depthStencilDesc.Texture2D.MipSlice = 0;
416
417 err = mRenderer->allocateResource(depthStencilDesc, mDepthStencilTexture.get(),
418 &mDepthStencilDSView);
419 ASSERT(!err.isError());
420 mDepthStencilDSView.setDebugName("Offscreen depth stencil view");
421
422 if (depthStencilSRV)
423 {
424 D3D11_SHADER_RESOURCE_VIEW_DESC depthStencilSRVDesc;
425 depthStencilSRVDesc.Format = depthBufferFormatInfo.srvFormat;
426 depthStencilSRVDesc.ViewDimension = (mEGLSamples <= 1)
427 ? D3D11_SRV_DIMENSION_TEXTURE2D
428 : D3D11_SRV_DIMENSION_TEXTURE2DMS;
429 depthStencilSRVDesc.Texture2D.MostDetailedMip = 0;
430 depthStencilSRVDesc.Texture2D.MipLevels = static_cast<UINT>(-1);
431
432 err = mRenderer->allocateResource(depthStencilSRVDesc, mDepthStencilTexture.get(),
433 &mDepthStencilSRView);
434 ASSERT(!err.isError());
435 mDepthStencilSRView.setDebugName("Offscreen depth stencil shader resource");
436 }
437 }
438
439 return EGL_SUCCESS;
440 }
441
resize(const gl::Context * context,EGLint backbufferWidth,EGLint backbufferHeight)442 EGLint SwapChain11::resize(const gl::Context *context,
443 EGLint backbufferWidth,
444 EGLint backbufferHeight)
445 {
446 TRACE_EVENT0("gpu.angle", "SwapChain11::resize");
447 ID3D11Device *device = mRenderer->getDevice();
448
449 if (device == nullptr)
450 {
451 return EGL_BAD_ACCESS;
452 }
453
454 // EGL allows creating a surface with 0x0 dimension, however, DXGI does not like 0x0 swapchains
455 if (backbufferWidth < 1 || backbufferHeight < 1)
456 {
457 return EGL_SUCCESS;
458 }
459
460 // Don't resize unnecessarily
461 if (mWidth == backbufferWidth && mHeight == backbufferHeight)
462 {
463 return EGL_SUCCESS;
464 }
465
466 // Can only call resize if we have already created our swap buffer and resources
467 ASSERT(mSwapChain && mBackBufferTexture.valid() && mBackBufferRTView.valid() &&
468 mBackBufferSRView.valid());
469
470 mBackBufferTexture.reset();
471 mBackBufferRTView.reset();
472 mBackBufferSRView.reset();
473
474 // Resize swap chain
475 DXGI_SWAP_CHAIN_DESC desc;
476 HRESULT result = mSwapChain->GetDesc(&desc);
477 if (FAILED(result))
478 {
479 ERR() << "Error reading swap chain description, " << gl::FmtHR(result);
480 release();
481 return EGL_BAD_ALLOC;
482 }
483
484 result = mSwapChain->ResizeBuffers(desc.BufferCount, backbufferWidth, backbufferHeight, getSwapChainNativeFormat(), 0);
485
486 if (FAILED(result))
487 {
488 ERR() << "Error resizing swap chain buffers, " << gl::FmtHR(result);
489 release();
490
491 if (d3d11::isDeviceLostError(result))
492 {
493 return EGL_CONTEXT_LOST;
494 }
495 else
496 {
497 return EGL_BAD_ALLOC;
498 }
499 }
500
501 ID3D11Texture2D *backbufferTexture = nullptr;
502 result = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D),
503 reinterpret_cast<void **>(&backbufferTexture));
504 ASSERT(SUCCEEDED(result));
505 if (SUCCEEDED(result))
506 {
507 #ifndef ANGLE_ENABLE_WINDOWS_STORE
508 if (mNativeWindow->getNativeWindow())
509 InvalidateRect(mNativeWindow->getNativeWindow(), nullptr, FALSE);
510 #endif
511 const auto &format =
512 d3d11::Format::Get(mOffscreenRenderTargetFormat, mRenderer->getRenderer11DeviceCaps());
513 mBackBufferTexture.set(backbufferTexture, format);
514 mBackBufferTexture.setDebugName("Back buffer texture");
515
516 gl::Error err =
517 mRenderer->allocateResourceNoDesc(mBackBufferTexture.get(), &mBackBufferRTView);
518 ASSERT(!err.isError());
519 mBackBufferRTView.setDebugName("Back buffer render target");
520
521 err = mRenderer->allocateResourceNoDesc(mBackBufferTexture.get(), &mBackBufferSRView);
522 ASSERT(!err.isError());
523 mBackBufferSRView.setDebugName("Back buffer shader resource");
524 }
525
526 mFirstSwap = true;
527
528 return resetOffscreenBuffers(context, backbufferWidth, backbufferHeight);
529 }
530
getSwapChainNativeFormat() const531 DXGI_FORMAT SwapChain11::getSwapChainNativeFormat() const
532 {
533 // Return a render target format for offscreen rendering is supported by IDXGISwapChain.
534 // MSDN https://msdn.microsoft.com/en-us/library/windows/desktop/bb173064(v=vs.85).aspx
535 switch (mOffscreenRenderTargetFormat)
536 {
537 case GL_RGBA8:
538 case GL_RGBA4:
539 case GL_RGB5_A1:
540 case GL_RGB8:
541 case GL_RGB565:
542 return DXGI_FORMAT_R8G8B8A8_UNORM;
543
544 case GL_BGRA8_EXT:
545 return DXGI_FORMAT_B8G8R8A8_UNORM;
546
547 case GL_RGB10_A2:
548 return DXGI_FORMAT_R10G10B10A2_UNORM;
549
550 case GL_RGBA16F:
551 return DXGI_FORMAT_R16G16B16A16_FLOAT;
552
553 default:
554 UNREACHABLE();
555 return DXGI_FORMAT_UNKNOWN;
556 }
557 }
558
reset(const gl::Context * context,EGLint backbufferWidth,EGLint backbufferHeight,EGLint swapInterval)559 EGLint SwapChain11::reset(const gl::Context *context,
560 EGLint backbufferWidth,
561 EGLint backbufferHeight,
562 EGLint swapInterval)
563 {
564 mSwapInterval = static_cast<unsigned int>(swapInterval);
565 if (mSwapInterval > 4)
566 {
567 // IDXGISwapChain::Present documentation states that valid sync intervals are in the [0,4]
568 // range
569 return EGL_BAD_PARAMETER;
570 }
571
572 // If the swap chain already exists, just resize
573 if (mSwapChain != nullptr)
574 {
575 return resize(context, backbufferWidth, backbufferHeight);
576 }
577
578 TRACE_EVENT0("gpu.angle", "SwapChain11::reset");
579 ID3D11Device *device = mRenderer->getDevice();
580
581 if (device == nullptr)
582 {
583 return EGL_BAD_ACCESS;
584 }
585
586 // Release specific resources to free up memory for the new render target, while the
587 // old render target still exists for the purpose of preserving its contents.
588 SafeRelease(mSwapChain1);
589 SafeRelease(mSwapChain);
590 mBackBufferTexture.reset();
591 mBackBufferRTView.reset();
592
593 // EGL allows creating a surface with 0x0 dimension, however, DXGI does not like 0x0 swapchains
594 if (backbufferWidth < 1 || backbufferHeight < 1)
595 {
596 releaseOffscreenColorBuffer();
597 return EGL_SUCCESS;
598 }
599
600 if (mNativeWindow->getNativeWindow())
601 {
602 HRESULT result = mNativeWindow->createSwapChain(
603 device, mRenderer->getDxgiFactory(), getSwapChainNativeFormat(), backbufferWidth,
604 backbufferHeight, getD3DSamples(), &mSwapChain);
605
606 if (FAILED(result))
607 {
608 ERR() << "Could not create additional swap chains or offscreen surfaces, "
609 << gl::FmtHR(result);
610 release();
611
612 if (d3d11::isDeviceLostError(result))
613 {
614 return EGL_CONTEXT_LOST;
615 }
616 else
617 {
618 return EGL_BAD_ALLOC;
619 }
620 }
621
622 if (mRenderer->getRenderer11DeviceCaps().supportsDXGI1_2)
623 {
624 mSwapChain1 = d3d11::DynamicCastComObject<IDXGISwapChain1>(mSwapChain);
625 }
626
627 ID3D11Texture2D *backbufferTex = nullptr;
628 result = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D),
629 reinterpret_cast<LPVOID *>(&backbufferTex));
630 ASSERT(SUCCEEDED(result));
631 const auto &format =
632 d3d11::Format::Get(mOffscreenRenderTargetFormat, mRenderer->getRenderer11DeviceCaps());
633 mBackBufferTexture.set(backbufferTex, format);
634 mBackBufferTexture.setDebugName("Back buffer texture");
635
636 gl::Error err =
637 mRenderer->allocateResourceNoDesc(mBackBufferTexture.get(), &mBackBufferRTView);
638 ASSERT(!err.isError());
639 mBackBufferRTView.setDebugName("Back buffer render target");
640
641 err = mRenderer->allocateResourceNoDesc(mBackBufferTexture.get(), &mBackBufferSRView);
642 ASSERT(!err.isError());
643 mBackBufferSRView.setDebugName("Back buffer shader resource view");
644 }
645
646 mFirstSwap = true;
647
648 return resetOffscreenBuffers(context, backbufferWidth, backbufferHeight);
649 }
650
initPassThroughResources()651 void SwapChain11::initPassThroughResources()
652 {
653 if (mPassThroughResourcesInit)
654 {
655 return;
656 }
657
658 TRACE_EVENT0("gpu.angle", "SwapChain11::initPassThroughResources");
659 ID3D11Device *device = mRenderer->getDevice();
660
661 ASSERT(device != nullptr);
662
663 // Make sure our resources are all not allocated, when we create
664 ASSERT(!mQuadVB.valid() && !mPassThroughSampler.valid());
665 ASSERT(!mPassThroughIL.valid() && !mPassThroughVS.valid() && !mPassThroughPS.valid());
666
667 D3D11_BUFFER_DESC vbDesc;
668 vbDesc.ByteWidth = sizeof(d3d11::PositionTexCoordVertex) * 4;
669 vbDesc.Usage = D3D11_USAGE_DYNAMIC;
670 vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
671 vbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
672 vbDesc.MiscFlags = 0;
673 vbDesc.StructureByteStride = 0;
674
675 gl::Error err = mRenderer->allocateResource(vbDesc, &mQuadVB);
676 ASSERT(!err.isError());
677 mQuadVB.setDebugName("Swap chain quad vertex buffer");
678
679 D3D11_SAMPLER_DESC samplerDesc;
680 samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
681 samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
682 samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
683 samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
684 samplerDesc.MipLODBias = 0.0f;
685 samplerDesc.MaxAnisotropy = 0;
686 samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
687 samplerDesc.BorderColor[0] = 0.0f;
688 samplerDesc.BorderColor[1] = 0.0f;
689 samplerDesc.BorderColor[2] = 0.0f;
690 samplerDesc.BorderColor[3] = 0.0f;
691 samplerDesc.MinLOD = 0;
692 samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
693
694 err = mRenderer->allocateResource(samplerDesc, &mPassThroughSampler);
695 ASSERT(!err.isError());
696 mPassThroughSampler.setDebugName("Swap chain pass through sampler");
697
698 D3D11_INPUT_ELEMENT_DESC quadLayout[] =
699 {
700 { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
701 { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D11_INPUT_PER_VERTEX_DATA, 0 },
702 };
703
704 InputElementArray quadElements(quadLayout);
705 ShaderData vertexShaderData(g_VS_Passthrough2D);
706
707 err = mRenderer->allocateResource(quadElements, &vertexShaderData, &mPassThroughIL);
708 ASSERT(!err.isError());
709 mPassThroughIL.setDebugName("Swap chain pass through layout");
710
711 err = mRenderer->allocateResource(vertexShaderData, &mPassThroughVS);
712 ASSERT(!err.isError());
713 mPassThroughVS.setDebugName("Swap chain pass through vertex shader");
714
715 if (mEGLSamples <= 1)
716 {
717 ShaderData pixelShaderData(g_PS_PassthroughRGBA2D);
718 err = mRenderer->allocateResource(pixelShaderData, &mPassThroughPS);
719 }
720 else
721 {
722 ShaderData pixelShaderData(g_PS_PassthroughRGBA2DMS);
723 err = mRenderer->allocateResource(pixelShaderData, &mPassThroughPS);
724 }
725
726 ASSERT(!err.isError());
727 mPassThroughPS.setDebugName("Swap chain pass through pixel shader");
728
729 // Use the default rasterizer state but without culling
730 D3D11_RASTERIZER_DESC rasterizerDesc;
731 rasterizerDesc.FillMode = D3D11_FILL_SOLID;
732 rasterizerDesc.CullMode = D3D11_CULL_NONE;
733 rasterizerDesc.FrontCounterClockwise = FALSE;
734 rasterizerDesc.DepthBias = 0;
735 rasterizerDesc.SlopeScaledDepthBias = 0.0f;
736 rasterizerDesc.DepthBiasClamp = 0.0f;
737 rasterizerDesc.DepthClipEnable = TRUE;
738 rasterizerDesc.ScissorEnable = FALSE;
739 rasterizerDesc.MultisampleEnable = FALSE;
740 rasterizerDesc.AntialiasedLineEnable = FALSE;
741
742 err = mRenderer->allocateResource(rasterizerDesc, &mPassThroughRS);
743 ASSERT(!err.isError());
744 mPassThroughRS.setDebugName("Swap chain pass through rasterizer state");
745
746 mPassThroughResourcesInit = true;
747 }
748
749 // parameters should be validated/clamped by caller
swapRect(const gl::Context * context,EGLint x,EGLint y,EGLint width,EGLint height)750 EGLint SwapChain11::swapRect(const gl::Context *context,
751 EGLint x,
752 EGLint y,
753 EGLint width,
754 EGLint height)
755 {
756 if (mNeedsOffscreenTexture)
757 {
758 EGLint result = copyOffscreenToBackbuffer(context, x, y, width, height);
759 if (result != EGL_SUCCESS)
760 {
761 return result;
762 }
763 }
764
765 EGLint result = present(context, x, y, width, height);
766 if (result != EGL_SUCCESS)
767 {
768 return result;
769 }
770
771 mRenderer->onSwap();
772
773 return EGL_SUCCESS;
774 }
775
copyOffscreenToBackbuffer(const gl::Context * context,EGLint x,EGLint y,EGLint width,EGLint height)776 EGLint SwapChain11::copyOffscreenToBackbuffer(const gl::Context *context,
777 EGLint x,
778 EGLint y,
779 EGLint width,
780 EGLint height)
781 {
782 if (!mSwapChain)
783 {
784 return EGL_SUCCESS;
785 }
786
787 initPassThroughResources();
788
789 ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
790
791 // Set vertices
792 D3D11_MAPPED_SUBRESOURCE mappedResource;
793 HRESULT result =
794 deviceContext->Map(mQuadVB.get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
795 if (FAILED(result))
796 {
797 return EGL_BAD_ACCESS;
798 }
799
800 d3d11::PositionTexCoordVertex *vertices = static_cast<d3d11::PositionTexCoordVertex*>(mappedResource.pData);
801
802 // Create a quad in homogeneous coordinates
803 float x1 = (x / float(width)) * 2.0f - 1.0f;
804 float y1 = (y / float(height)) * 2.0f - 1.0f;
805 float x2 = ((x + width) / float(width)) * 2.0f - 1.0f;
806 float y2 = ((y + height) / float(height)) * 2.0f - 1.0f;
807
808 float u1 = x / float(width);
809 float v1 = y / float(height);
810 float u2 = (x + width) / float(width);
811 float v2 = (y + height) / float(height);
812 // Invert the quad vertices depending on the surface orientation.
813 if ((mOrientation & EGL_SURFACE_ORIENTATION_INVERT_X_ANGLE) != 0)
814 {
815 std::swap(x1, x2);
816 }
817 if ((mOrientation & EGL_SURFACE_ORIENTATION_INVERT_Y_ANGLE) != 0)
818 {
819 std::swap(y1, y2);
820 }
821
822 d3d11::SetPositionTexCoordVertex(&vertices[0], x1, y1, u1, v1);
823 d3d11::SetPositionTexCoordVertex(&vertices[1], x1, y2, u1, v2);
824 d3d11::SetPositionTexCoordVertex(&vertices[2], x2, y1, u2, v1);
825 d3d11::SetPositionTexCoordVertex(&vertices[3], x2, y2, u2, v2);
826
827 deviceContext->Unmap(mQuadVB.get(), 0);
828
829 StateManager11 *stateManager = mRenderer->getStateManager();
830
831 constexpr UINT stride = sizeof(d3d11::PositionTexCoordVertex);
832 stateManager->setSingleVertexBuffer(&mQuadVB, stride, 0);
833
834 // Apply state
835 stateManager->setDepthStencilState(nullptr, 0xFFFFFFFF);
836 stateManager->setSimpleBlendState(nullptr);
837 stateManager->setRasterizerState(&mPassThroughRS);
838
839 // Apply shaders
840 stateManager->setInputLayout(&mPassThroughIL);
841 stateManager->setPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
842 stateManager->setDrawShaders(&mPassThroughVS, nullptr, &mPassThroughPS);
843
844 // Apply render targets. Use the proxy context in display.
845 stateManager->setRenderTarget(mBackBufferRTView.get(), nullptr);
846
847 // Set the viewport
848 stateManager->setSimpleViewport(width, height);
849
850 // Apply textures
851 stateManager->setSimplePixelTextureAndSampler(mOffscreenSRView, mPassThroughSampler);
852
853 // Draw
854 deviceContext->Draw(4, 0);
855
856 return EGL_SUCCESS;
857 }
858
present(const gl::Context * context,EGLint x,EGLint y,EGLint width,EGLint height)859 EGLint SwapChain11::present(const gl::Context *context,
860 EGLint x,
861 EGLint y,
862 EGLint width,
863 EGLint height)
864 {
865 if (!mSwapChain)
866 {
867 return EGL_SUCCESS;
868 }
869
870 UINT swapInterval = mSwapInterval;
871 #if ANGLE_VSYNC == ANGLE_DISABLED
872 swapInterval = 0;
873 #endif
874
875 HRESULT result = S_OK;
876
877 // Use IDXGISwapChain1::Present1 with a dirty rect if DXGI 1.2 is available.
878 // Dirty rect present is not supported with a multisampled swapchain.
879 if (mSwapChain1 != nullptr && mEGLSamples <= 1)
880 {
881 if (mFirstSwap)
882 {
883 // Can't swap with a dirty rect if this swap chain has never swapped before
884 DXGI_PRESENT_PARAMETERS params = {0, nullptr, nullptr, nullptr};
885 result = mSwapChain1->Present1(swapInterval, 0, ¶ms);
886 }
887 else
888 {
889 RECT rect = {static_cast<LONG>(x), static_cast<LONG>(mHeight - y - height),
890 static_cast<LONG>(x + width), static_cast<LONG>(mHeight - y)};
891 DXGI_PRESENT_PARAMETERS params = {1, &rect, nullptr, nullptr};
892 result = mSwapChain1->Present1(swapInterval, 0, ¶ms);
893 }
894 }
895 else
896 {
897 result = mSwapChain->Present(swapInterval, 0);
898 }
899
900 mFirstSwap = false;
901
902 // Some swapping mechanisms such as DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL unbind the current render
903 // target. Mark it dirty. Use the proxy context in display since there is none available.
904 mRenderer->getStateManager()->invalidateRenderTarget();
905
906 if (result == DXGI_ERROR_DEVICE_REMOVED)
907 {
908 ERR() << "Present failed: the D3D11 device was removed, "
909 << gl::FmtHR(mRenderer->getDevice()->GetDeviceRemovedReason());
910 return EGL_CONTEXT_LOST;
911 }
912 else if (result == DXGI_ERROR_DEVICE_RESET)
913 {
914 ERR() << "Present failed: the D3D11 device was reset from a bad command.";
915 return EGL_CONTEXT_LOST;
916 }
917 else if (FAILED(result))
918 {
919 ERR() << "Present failed with " << gl::FmtHR(result);
920 }
921
922 mNativeWindow->commitChange();
923
924 return EGL_SUCCESS;
925 }
926
getOffscreenTexture()927 const TextureHelper11 &SwapChain11::getOffscreenTexture()
928 {
929 return mNeedsOffscreenTexture ? mOffscreenTexture : mBackBufferTexture;
930 }
931
getRenderTarget()932 const d3d11::RenderTargetView &SwapChain11::getRenderTarget()
933 {
934 return mNeedsOffscreenTexture ? mOffscreenRTView : mBackBufferRTView;
935 }
936
getRenderTargetShaderResource()937 const d3d11::SharedSRV &SwapChain11::getRenderTargetShaderResource()
938 {
939 if (!mNeedsOffscreenTexture)
940 {
941 ASSERT(mBackBufferSRView.valid());
942 return mBackBufferSRView;
943 }
944
945 if (!mNeedsOffscreenTextureCopy)
946 {
947 ASSERT(mOffscreenSRView.valid());
948 return mOffscreenSRView;
949 }
950
951 if (!mOffscreenTextureCopyForSRV.valid())
952 {
953 const d3d11::Format &backbufferFormatInfo =
954 d3d11::Format::Get(mOffscreenRenderTargetFormat, mRenderer->getRenderer11DeviceCaps());
955
956 D3D11_TEXTURE2D_DESC offscreenCopyDesc;
957 mOffscreenTexture.getDesc(&offscreenCopyDesc);
958
959 offscreenCopyDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
960 offscreenCopyDesc.MiscFlags = 0;
961 offscreenCopyDesc.CPUAccessFlags = 0;
962 gl::Error err = mRenderer->allocateTexture(offscreenCopyDesc, backbufferFormatInfo,
963 &mOffscreenTextureCopyForSRV);
964 ASSERT(!err.isError());
965 mOffscreenTextureCopyForSRV.setDebugName("Offscreen back buffer copy for SRV");
966
967 D3D11_SHADER_RESOURCE_VIEW_DESC offscreenSRVDesc;
968 offscreenSRVDesc.Format = backbufferFormatInfo.srvFormat;
969 offscreenSRVDesc.ViewDimension =
970 (mEGLSamples <= 1) ? D3D11_SRV_DIMENSION_TEXTURE2D : D3D11_SRV_DIMENSION_TEXTURE2DMS;
971 offscreenSRVDesc.Texture2D.MostDetailedMip = 0;
972 offscreenSRVDesc.Texture2D.MipLevels = static_cast<UINT>(-1);
973
974 err = mRenderer->allocateResource(offscreenSRVDesc, mOffscreenTextureCopyForSRV.get(),
975 &mOffscreenSRView);
976 ASSERT(!err.isError());
977 mOffscreenSRView.setDebugName("Offscreen back buffer shader resource");
978 }
979
980 // Need to copy the offscreen texture into the shader-readable copy, since it's external and
981 // we don't know if the copy is up-to-date. This works around the problem we have when the app
982 // passes in a texture that isn't shader-readable.
983 mRenderer->getDeviceContext()->CopyResource(mOffscreenTextureCopyForSRV.get(),
984 mOffscreenTexture.get());
985 return mOffscreenSRView;
986 }
987
getDepthStencil()988 const d3d11::DepthStencilView &SwapChain11::getDepthStencil()
989 {
990 return mDepthStencilDSView;
991 }
992
getDepthStencilShaderResource()993 const d3d11::SharedSRV &SwapChain11::getDepthStencilShaderResource()
994 {
995 return mDepthStencilSRView;
996 }
997
getDepthStencilTexture()998 const TextureHelper11 &SwapChain11::getDepthStencilTexture()
999 {
1000 return mDepthStencilTexture;
1001 }
1002
getKeyedMutex()1003 void *SwapChain11::getKeyedMutex()
1004 {
1005 return mKeyedMutex;
1006 }
1007
recreate()1008 void SwapChain11::recreate()
1009 {
1010 // possibly should use this method instead of reset
1011 }
1012
getDevice()1013 void *rx::SwapChain11::getDevice()
1014 {
1015 return mRenderer->getDevice();
1016 }
1017
getColorRenderTarget()1018 RenderTargetD3D *SwapChain11::getColorRenderTarget()
1019 {
1020 return &mColorRenderTarget;
1021 }
1022
getDepthStencilRenderTarget()1023 RenderTargetD3D *SwapChain11::getDepthStencilRenderTarget()
1024 {
1025 return &mDepthStencilRenderTarget;
1026 }
1027
getSyncValues(EGLuint64KHR * ust,EGLuint64KHR * msc,EGLuint64KHR * sbc)1028 egl::Error SwapChain11::getSyncValues(EGLuint64KHR *ust, EGLuint64KHR *msc, EGLuint64KHR *sbc)
1029 {
1030 if (!mSwapChain)
1031 {
1032 return egl::EglNotInitialized() << "Swap chain uninitialized";
1033 }
1034
1035 DXGI_FRAME_STATISTICS stats = {};
1036 HRESULT result = mSwapChain->GetFrameStatistics(&stats);
1037
1038 if (FAILED(result))
1039 {
1040 return egl::EglBadAlloc() << "Failed to get frame statistics, " << gl::FmtHR(result);
1041 }
1042
1043 // Conversion from DXGI_FRAME_STATISTICS to the output values:
1044 // stats.SyncRefreshCount -> msc
1045 // stats.PresentCount -> sbc
1046 // stats.SyncQPCTime -> ust with conversion to microseconds via QueryPerformanceFrequency
1047 *msc = stats.SyncRefreshCount;
1048 *sbc = stats.PresentCount;
1049
1050 LONGLONG syncQPCValue = stats.SyncQPCTime.QuadPart;
1051 // If the QPC Value is below the overflow threshold, we proceed with
1052 // simple multiply and divide.
1053 if (syncQPCValue < kQPCOverflowThreshold)
1054 {
1055 *ust = syncQPCValue * kMicrosecondsPerSecond / mQPCFrequency;
1056 }
1057 else
1058 {
1059 // Otherwise, calculate microseconds in a round about manner to avoid
1060 // overflow and precision issues.
1061 int64_t wholeSeconds = syncQPCValue / mQPCFrequency;
1062 int64_t leftoverTicks = syncQPCValue - (wholeSeconds * mQPCFrequency);
1063 *ust = wholeSeconds * kMicrosecondsPerSecond +
1064 leftoverTicks * kMicrosecondsPerSecond / mQPCFrequency;
1065 }
1066
1067 return egl::NoError();
1068 }
1069
getD3DSamples() const1070 UINT SwapChain11::getD3DSamples() const
1071 {
1072 return (mEGLSamples == 0) ? 1 : mEGLSamples;
1073 }
1074
1075 } // namespace rx
1076