• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright 2012 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 // renderer11_utils.cpp: Conversion functions and other utility routines
8 // specific to the D3D11 renderer.
9 
10 #include "libANGLE/renderer/d3d/d3d11/renderer11_utils.h"
11 
12 #include <algorithm>
13 
14 #include "common/debug.h"
15 #include "libANGLE/Buffer.h"
16 #include "libANGLE/Context.h"
17 #include "libANGLE/Framebuffer.h"
18 #include "libANGLE/Program.h"
19 #include "libANGLE/State.h"
20 #include "libANGLE/VertexArray.h"
21 #include "libANGLE/formatutils.h"
22 #include "libANGLE/renderer/d3d/BufferD3D.h"
23 #include "libANGLE/renderer/d3d/FramebufferD3D.h"
24 #include "libANGLE/renderer/d3d/d3d11/Context11.h"
25 #include "libANGLE/renderer/d3d/d3d11/RenderTarget11.h"
26 #include "libANGLE/renderer/d3d/d3d11/Renderer11.h"
27 #include "libANGLE/renderer/d3d/d3d11/formatutils11.h"
28 #include "libANGLE/renderer/d3d/d3d11/texture_format_table.h"
29 #include "libANGLE/renderer/driver_utils.h"
30 #include "libANGLE/renderer/dxgi_support_table.h"
31 #include "platform/PlatformMethods.h"
32 #include "platform/autogen/FeaturesD3D_autogen.h"
33 
34 namespace rx
35 {
36 
37 namespace d3d11_gl
38 {
39 namespace
40 {
41 // TODO(xinghua.cao@intel.com): Get a more accurate limit.
42 static D3D_FEATURE_LEVEL kMinimumFeatureLevelForES31 = D3D_FEATURE_LEVEL_11_0;
43 
44 // Helper functor for querying DXGI support. Saves passing the parameters repeatedly.
45 class DXGISupportHelper : angle::NonCopyable
46 {
47   public:
DXGISupportHelper(ID3D11Device * device,D3D_FEATURE_LEVEL featureLevel)48     DXGISupportHelper(ID3D11Device *device, D3D_FEATURE_LEVEL featureLevel)
49         : mDevice(device), mFeatureLevel(featureLevel)
50     {}
51 
query(DXGI_FORMAT dxgiFormat,UINT supportMask)52     bool query(DXGI_FORMAT dxgiFormat, UINT supportMask)
53     {
54         if (dxgiFormat == DXGI_FORMAT_UNKNOWN)
55             return false;
56 
57         auto dxgiSupport = d3d11::GetDXGISupport(dxgiFormat, mFeatureLevel);
58 
59         UINT supportedBits = dxgiSupport.alwaysSupportedFlags;
60 
61         if ((dxgiSupport.optionallySupportedFlags & supportMask) != 0)
62         {
63             UINT formatSupport;
64             if (SUCCEEDED(mDevice->CheckFormatSupport(dxgiFormat, &formatSupport)))
65             {
66                 supportedBits |= (formatSupport & supportMask);
67             }
68             else
69             {
70                 // TODO(jmadill): find out why we fail this call sometimes in FL9_3
71                 // ERR() << "Error checking format support for format 0x" << std::hex << dxgiFormat;
72             }
73         }
74 
75         return ((supportedBits & supportMask) == supportMask);
76     }
77 
78   private:
79     ID3D11Device *mDevice;
80     D3D_FEATURE_LEVEL mFeatureLevel;
81 };
82 
GenerateTextureFormatCaps(gl::Version maxClientVersion,GLenum internalFormat,ID3D11Device * device,const Renderer11DeviceCaps & renderer11DeviceCaps)83 gl::TextureCaps GenerateTextureFormatCaps(gl::Version maxClientVersion,
84                                           GLenum internalFormat,
85                                           ID3D11Device *device,
86                                           const Renderer11DeviceCaps &renderer11DeviceCaps)
87 {
88     gl::TextureCaps textureCaps;
89 
90     DXGISupportHelper support(device, renderer11DeviceCaps.featureLevel);
91     const d3d11::Format &formatInfo = d3d11::Format::Get(internalFormat, renderer11DeviceCaps);
92 
93     const gl::InternalFormat &internalFormatInfo = gl::GetSizedInternalFormatInfo(internalFormat);
94 
95     UINT texSupportMask = D3D11_FORMAT_SUPPORT_TEXTURE2D;
96     if (internalFormatInfo.depthBits == 0 && internalFormatInfo.stencilBits == 0)
97     {
98         texSupportMask |= D3D11_FORMAT_SUPPORT_TEXTURECUBE;
99         if (maxClientVersion.major > 2)
100         {
101             texSupportMask |= D3D11_FORMAT_SUPPORT_TEXTURE3D;
102         }
103     }
104 
105     textureCaps.texturable = support.query(formatInfo.texFormat, texSupportMask);
106     textureCaps.filterable =
107         support.query(formatInfo.srvFormat, D3D11_FORMAT_SUPPORT_SHADER_SAMPLE);
108     textureCaps.textureAttachment =
109         (support.query(formatInfo.rtvFormat, D3D11_FORMAT_SUPPORT_RENDER_TARGET)) ||
110         (support.query(formatInfo.dsvFormat, D3D11_FORMAT_SUPPORT_DEPTH_STENCIL));
111     textureCaps.renderbuffer = textureCaps.textureAttachment;
112     textureCaps.blendable    = textureCaps.renderbuffer;
113 
114     DXGI_FORMAT renderFormat = DXGI_FORMAT_UNKNOWN;
115     if (formatInfo.dsvFormat != DXGI_FORMAT_UNKNOWN)
116     {
117         renderFormat = formatInfo.dsvFormat;
118     }
119     else if (formatInfo.rtvFormat != DXGI_FORMAT_UNKNOWN)
120     {
121         renderFormat = formatInfo.rtvFormat;
122     }
123     if (renderFormat != DXGI_FORMAT_UNKNOWN &&
124         support.query(renderFormat, D3D11_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET))
125     {
126         // Assume 1x
127         textureCaps.sampleCounts.insert(1);
128 
129         for (unsigned int sampleCount = 2; sampleCount <= D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT;
130              sampleCount *= 2)
131         {
132             UINT qualityCount = 0;
133             if (SUCCEEDED(device->CheckMultisampleQualityLevels(renderFormat, sampleCount,
134                                                                 &qualityCount)))
135             {
136                 // Assume we always support lower sample counts
137                 if (qualityCount == 0)
138                 {
139                     break;
140                 }
141                 textureCaps.sampleCounts.insert(sampleCount);
142             }
143         }
144     }
145 
146     return textureCaps;
147 }
148 
GetNPOTTextureSupport(D3D_FEATURE_LEVEL featureLevel)149 bool GetNPOTTextureSupport(D3D_FEATURE_LEVEL featureLevel)
150 {
151     switch (featureLevel)
152     {
153         case D3D_FEATURE_LEVEL_11_1:
154         case D3D_FEATURE_LEVEL_11_0:
155         case D3D_FEATURE_LEVEL_10_1:
156         case D3D_FEATURE_LEVEL_10_0:
157             return true;
158 
159         // From http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876.aspx
160         case D3D_FEATURE_LEVEL_9_3:
161         case D3D_FEATURE_LEVEL_9_2:
162         case D3D_FEATURE_LEVEL_9_1:
163             return false;
164 
165         default:
166             UNREACHABLE();
167             return false;
168     }
169 }
170 
GetMaximumAnisotropy(D3D_FEATURE_LEVEL featureLevel)171 float GetMaximumAnisotropy(D3D_FEATURE_LEVEL featureLevel)
172 {
173     switch (featureLevel)
174     {
175         case D3D_FEATURE_LEVEL_11_1:
176         case D3D_FEATURE_LEVEL_11_0:
177             return D3D11_MAX_MAXANISOTROPY;
178 
179         case D3D_FEATURE_LEVEL_10_1:
180         case D3D_FEATURE_LEVEL_10_0:
181             return D3D10_MAX_MAXANISOTROPY;
182 
183         // From http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876.aspx
184         case D3D_FEATURE_LEVEL_9_3:
185         case D3D_FEATURE_LEVEL_9_2:
186             return 16;
187 
188         case D3D_FEATURE_LEVEL_9_1:
189             return D3D_FL9_1_DEFAULT_MAX_ANISOTROPY;
190 
191         default:
192             UNREACHABLE();
193             return 0;
194     }
195 }
196 
GetOcclusionQuerySupport(D3D_FEATURE_LEVEL featureLevel)197 bool GetOcclusionQuerySupport(D3D_FEATURE_LEVEL featureLevel)
198 {
199     switch (featureLevel)
200     {
201         case D3D_FEATURE_LEVEL_11_1:
202         case D3D_FEATURE_LEVEL_11_0:
203         case D3D_FEATURE_LEVEL_10_1:
204         case D3D_FEATURE_LEVEL_10_0:
205             return true;
206 
207         // From http://msdn.microsoft.com/en-us/library/windows/desktop/ff476150.aspx
208         // ID3D11Device::CreateQuery
209         case D3D_FEATURE_LEVEL_9_3:
210         case D3D_FEATURE_LEVEL_9_2:
211             return true;
212         case D3D_FEATURE_LEVEL_9_1:
213             return false;
214 
215         default:
216             UNREACHABLE();
217             return false;
218     }
219 }
220 
GetEventQuerySupport(D3D_FEATURE_LEVEL featureLevel)221 bool GetEventQuerySupport(D3D_FEATURE_LEVEL featureLevel)
222 {
223     // From http://msdn.microsoft.com/en-us/library/windows/desktop/ff476150.aspx
224     // ID3D11Device::CreateQuery
225 
226     switch (featureLevel)
227     {
228         case D3D_FEATURE_LEVEL_11_1:
229         case D3D_FEATURE_LEVEL_11_0:
230         case D3D_FEATURE_LEVEL_10_1:
231         case D3D_FEATURE_LEVEL_10_0:
232         case D3D_FEATURE_LEVEL_9_3:
233         case D3D_FEATURE_LEVEL_9_2:
234         case D3D_FEATURE_LEVEL_9_1:
235             return true;
236 
237         default:
238             UNREACHABLE();
239             return false;
240     }
241 }
242 
GetInstancingSupport(D3D_FEATURE_LEVEL featureLevel)243 bool GetInstancingSupport(D3D_FEATURE_LEVEL featureLevel)
244 {
245     // From http://msdn.microsoft.com/en-us/library/windows/desktop/ff476150.aspx
246     // ID3D11Device::CreateInputLayout
247 
248     switch (featureLevel)
249     {
250         case D3D_FEATURE_LEVEL_11_1:
251         case D3D_FEATURE_LEVEL_11_0:
252         case D3D_FEATURE_LEVEL_10_1:
253         case D3D_FEATURE_LEVEL_10_0:
254             return true;
255 
256         // Feature Level 9_3 supports instancing, but slot 0 in the input layout must not be
257         // instanced.
258         // D3D9 has a similar restriction, where stream 0 must not be instanced.
259         // This restriction can be worked around by remapping any non-instanced slot to slot
260         // 0.
261         // This works because HLSL uses shader semantics to match the vertex inputs to the
262         // elements in the input layout, rather than the slots.
263         // Note that we only support instancing via ANGLE_instanced_array on 9_3, since 9_3
264         // doesn't support OpenGL ES 3.0
265         case D3D_FEATURE_LEVEL_9_3:
266             return true;
267 
268         case D3D_FEATURE_LEVEL_9_2:
269         case D3D_FEATURE_LEVEL_9_1:
270             return false;
271 
272         default:
273             UNREACHABLE();
274             return false;
275     }
276 }
277 
GetFramebufferMultisampleSupport(D3D_FEATURE_LEVEL featureLevel)278 bool GetFramebufferMultisampleSupport(D3D_FEATURE_LEVEL featureLevel)
279 {
280     switch (featureLevel)
281     {
282         case D3D_FEATURE_LEVEL_11_1:
283         case D3D_FEATURE_LEVEL_11_0:
284         case D3D_FEATURE_LEVEL_10_1:
285         case D3D_FEATURE_LEVEL_10_0:
286             return true;
287 
288         case D3D_FEATURE_LEVEL_9_3:
289         case D3D_FEATURE_LEVEL_9_2:
290         case D3D_FEATURE_LEVEL_9_1:
291             return false;
292 
293         default:
294             UNREACHABLE();
295             return false;
296     }
297 }
298 
GetFramebufferBlitSupport(D3D_FEATURE_LEVEL featureLevel)299 bool GetFramebufferBlitSupport(D3D_FEATURE_LEVEL featureLevel)
300 {
301     switch (featureLevel)
302     {
303         case D3D_FEATURE_LEVEL_11_1:
304         case D3D_FEATURE_LEVEL_11_0:
305         case D3D_FEATURE_LEVEL_10_1:
306         case D3D_FEATURE_LEVEL_10_0:
307             return true;
308 
309         case D3D_FEATURE_LEVEL_9_3:
310         case D3D_FEATURE_LEVEL_9_2:
311         case D3D_FEATURE_LEVEL_9_1:
312             return false;
313 
314         default:
315             UNREACHABLE();
316             return false;
317     }
318 }
319 
GetDerivativeInstructionSupport(D3D_FEATURE_LEVEL featureLevel)320 bool GetDerivativeInstructionSupport(D3D_FEATURE_LEVEL featureLevel)
321 {
322     // http://msdn.microsoft.com/en-us/library/windows/desktop/bb509588.aspx states that
323     // shader model
324     // ps_2_x is required for the ddx (and other derivative functions).
325 
326     // http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876.aspx states that
327     // feature level
328     // 9.3 supports shader model ps_2_x.
329 
330     switch (featureLevel)
331     {
332         case D3D_FEATURE_LEVEL_11_1:
333         case D3D_FEATURE_LEVEL_11_0:
334         case D3D_FEATURE_LEVEL_10_1:
335         case D3D_FEATURE_LEVEL_10_0:
336         case D3D_FEATURE_LEVEL_9_3:
337             return true;
338         case D3D_FEATURE_LEVEL_9_2:
339         case D3D_FEATURE_LEVEL_9_1:
340             return false;
341 
342         default:
343             UNREACHABLE();
344             return false;
345     }
346 }
347 
GetShaderTextureLODSupport(D3D_FEATURE_LEVEL featureLevel)348 bool GetShaderTextureLODSupport(D3D_FEATURE_LEVEL featureLevel)
349 {
350     switch (featureLevel)
351     {
352         case D3D_FEATURE_LEVEL_11_1:
353         case D3D_FEATURE_LEVEL_11_0:
354         case D3D_FEATURE_LEVEL_10_1:
355         case D3D_FEATURE_LEVEL_10_0:
356             return true;
357 
358         case D3D_FEATURE_LEVEL_9_3:
359         case D3D_FEATURE_LEVEL_9_2:
360         case D3D_FEATURE_LEVEL_9_1:
361             return false;
362 
363         default:
364             UNREACHABLE();
365             return false;
366     }
367 }
368 
GetMaximumSimultaneousRenderTargets(D3D_FEATURE_LEVEL featureLevel)369 int GetMaximumSimultaneousRenderTargets(D3D_FEATURE_LEVEL featureLevel)
370 {
371     // From http://msdn.microsoft.com/en-us/library/windows/desktop/ff476150.aspx
372     // ID3D11Device::CreateInputLayout
373 
374     switch (featureLevel)
375     {
376         case D3D_FEATURE_LEVEL_11_1:
377         case D3D_FEATURE_LEVEL_11_0:
378             return D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT;
379 
380         case D3D_FEATURE_LEVEL_10_1:
381         case D3D_FEATURE_LEVEL_10_0:
382             return D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT;
383 
384         case D3D_FEATURE_LEVEL_9_3:
385             return D3D_FL9_3_SIMULTANEOUS_RENDER_TARGET_COUNT;
386         case D3D_FEATURE_LEVEL_9_2:
387         case D3D_FEATURE_LEVEL_9_1:
388             return D3D_FL9_1_SIMULTANEOUS_RENDER_TARGET_COUNT;
389 
390         default:
391             UNREACHABLE();
392             return 0;
393     }
394 }
395 
GetMaximum2DTextureSize(D3D_FEATURE_LEVEL featureLevel)396 int GetMaximum2DTextureSize(D3D_FEATURE_LEVEL featureLevel)
397 {
398     switch (featureLevel)
399     {
400         case D3D_FEATURE_LEVEL_11_1:
401         case D3D_FEATURE_LEVEL_11_0:
402             return D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION;
403 
404         case D3D_FEATURE_LEVEL_10_1:
405         case D3D_FEATURE_LEVEL_10_0:
406             return D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION;
407 
408         case D3D_FEATURE_LEVEL_9_3:
409             return D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION;
410         case D3D_FEATURE_LEVEL_9_2:
411         case D3D_FEATURE_LEVEL_9_1:
412             return D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION;
413 
414         default:
415             UNREACHABLE();
416             return 0;
417     }
418 }
419 
GetMaximumCubeMapTextureSize(D3D_FEATURE_LEVEL featureLevel)420 int GetMaximumCubeMapTextureSize(D3D_FEATURE_LEVEL featureLevel)
421 {
422     switch (featureLevel)
423     {
424         case D3D_FEATURE_LEVEL_11_1:
425         case D3D_FEATURE_LEVEL_11_0:
426             return D3D11_REQ_TEXTURECUBE_DIMENSION;
427 
428         case D3D_FEATURE_LEVEL_10_1:
429         case D3D_FEATURE_LEVEL_10_0:
430             return D3D10_REQ_TEXTURECUBE_DIMENSION;
431 
432         case D3D_FEATURE_LEVEL_9_3:
433             return D3D_FL9_3_REQ_TEXTURECUBE_DIMENSION;
434         case D3D_FEATURE_LEVEL_9_2:
435         case D3D_FEATURE_LEVEL_9_1:
436             return D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION;
437 
438         default:
439             UNREACHABLE();
440             return 0;
441     }
442 }
443 
GetMaximum2DTextureArraySize(D3D_FEATURE_LEVEL featureLevel)444 int GetMaximum2DTextureArraySize(D3D_FEATURE_LEVEL featureLevel)
445 {
446     switch (featureLevel)
447     {
448         case D3D_FEATURE_LEVEL_11_1:
449         case D3D_FEATURE_LEVEL_11_0:
450             return D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION;
451 
452         case D3D_FEATURE_LEVEL_10_1:
453         case D3D_FEATURE_LEVEL_10_0:
454             return D3D10_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION;
455 
456         case D3D_FEATURE_LEVEL_9_3:
457         case D3D_FEATURE_LEVEL_9_2:
458         case D3D_FEATURE_LEVEL_9_1:
459             return 0;
460 
461         default:
462             UNREACHABLE();
463             return 0;
464     }
465 }
466 
GetMaximum3DTextureSize(D3D_FEATURE_LEVEL featureLevel)467 int GetMaximum3DTextureSize(D3D_FEATURE_LEVEL featureLevel)
468 {
469     switch (featureLevel)
470     {
471         case D3D_FEATURE_LEVEL_11_1:
472         case D3D_FEATURE_LEVEL_11_0:
473             return D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION;
474 
475         case D3D_FEATURE_LEVEL_10_1:
476         case D3D_FEATURE_LEVEL_10_0:
477             return D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION;
478 
479         case D3D_FEATURE_LEVEL_9_3:
480         case D3D_FEATURE_LEVEL_9_2:
481         case D3D_FEATURE_LEVEL_9_1:
482             return D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION;
483 
484         default:
485             UNREACHABLE();
486             return 0;
487     }
488 }
489 
GetMaximumViewportSize(D3D_FEATURE_LEVEL featureLevel)490 int GetMaximumViewportSize(D3D_FEATURE_LEVEL featureLevel)
491 {
492     switch (featureLevel)
493     {
494         case D3D_FEATURE_LEVEL_11_1:
495         case D3D_FEATURE_LEVEL_11_0:
496             return D3D11_VIEWPORT_BOUNDS_MAX;
497 
498         case D3D_FEATURE_LEVEL_10_1:
499         case D3D_FEATURE_LEVEL_10_0:
500             return D3D10_VIEWPORT_BOUNDS_MAX;
501 
502         // No constants for D3D11 Feature Level 9 viewport size limits, use the maximum
503         // texture sizes
504         case D3D_FEATURE_LEVEL_9_3:
505             return D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION;
506         case D3D_FEATURE_LEVEL_9_2:
507         case D3D_FEATURE_LEVEL_9_1:
508             return D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION;
509 
510         default:
511             UNREACHABLE();
512             return 0;
513     }
514 }
515 
GetMaximumDrawIndexedIndexCount(D3D_FEATURE_LEVEL featureLevel)516 int GetMaximumDrawIndexedIndexCount(D3D_FEATURE_LEVEL featureLevel)
517 {
518     // D3D11 allows up to 2^32 elements, but we report max signed int for convenience since
519     // that's what's
520     // returned from glGetInteger
521     static_assert(D3D11_REQ_DRAWINDEXED_INDEX_COUNT_2_TO_EXP == 32,
522                   "Unexpected D3D11 constant value.");
523     static_assert(D3D10_REQ_DRAWINDEXED_INDEX_COUNT_2_TO_EXP == 32,
524                   "Unexpected D3D11 constant value.");
525 
526     switch (featureLevel)
527     {
528         case D3D_FEATURE_LEVEL_11_1:
529         case D3D_FEATURE_LEVEL_11_0:
530         case D3D_FEATURE_LEVEL_10_1:
531         case D3D_FEATURE_LEVEL_10_0:
532             return std::numeric_limits<GLint>::max();
533 
534         case D3D_FEATURE_LEVEL_9_3:
535         case D3D_FEATURE_LEVEL_9_2:
536             return D3D_FL9_2_IA_PRIMITIVE_MAX_COUNT;
537         case D3D_FEATURE_LEVEL_9_1:
538             return D3D_FL9_1_IA_PRIMITIVE_MAX_COUNT;
539 
540         default:
541             UNREACHABLE();
542             return 0;
543     }
544 }
545 
GetMaximumDrawVertexCount(D3D_FEATURE_LEVEL featureLevel)546 int GetMaximumDrawVertexCount(D3D_FEATURE_LEVEL featureLevel)
547 {
548     // D3D11 allows up to 2^32 elements, but we report max signed int for convenience since
549     // that's what's
550     // returned from glGetInteger
551     static_assert(D3D11_REQ_DRAW_VERTEX_COUNT_2_TO_EXP == 32, "Unexpected D3D11 constant value.");
552     static_assert(D3D10_REQ_DRAW_VERTEX_COUNT_2_TO_EXP == 32, "Unexpected D3D11 constant value.");
553 
554     switch (featureLevel)
555     {
556         case D3D_FEATURE_LEVEL_11_1:
557         case D3D_FEATURE_LEVEL_11_0:
558         case D3D_FEATURE_LEVEL_10_1:
559         case D3D_FEATURE_LEVEL_10_0:
560             return std::numeric_limits<GLint>::max();
561 
562         case D3D_FEATURE_LEVEL_9_3:
563         case D3D_FEATURE_LEVEL_9_2:
564             return D3D_FL9_2_IA_PRIMITIVE_MAX_COUNT;
565         case D3D_FEATURE_LEVEL_9_1:
566             return D3D_FL9_1_IA_PRIMITIVE_MAX_COUNT;
567 
568         default:
569             UNREACHABLE();
570             return 0;
571     }
572 }
573 
GetMaximumVertexInputSlots(D3D_FEATURE_LEVEL featureLevel)574 int GetMaximumVertexInputSlots(D3D_FEATURE_LEVEL featureLevel)
575 {
576     switch (featureLevel)
577     {
578         case D3D_FEATURE_LEVEL_11_1:
579         case D3D_FEATURE_LEVEL_11_0:
580             return D3D11_STANDARD_VERTEX_ELEMENT_COUNT;
581 
582         case D3D_FEATURE_LEVEL_10_1:
583             return D3D10_1_STANDARD_VERTEX_ELEMENT_COUNT;
584         case D3D_FEATURE_LEVEL_10_0:
585             return D3D10_STANDARD_VERTEX_ELEMENT_COUNT;
586 
587         // From http://http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876.aspx
588         // "Max Input Slots"
589         case D3D_FEATURE_LEVEL_9_3:
590         case D3D_FEATURE_LEVEL_9_2:
591         case D3D_FEATURE_LEVEL_9_1:
592             return 16;
593 
594         default:
595             UNREACHABLE();
596             return 0;
597     }
598 }
599 
GetMaximumVertexUniformVectors(D3D_FEATURE_LEVEL featureLevel)600 int GetMaximumVertexUniformVectors(D3D_FEATURE_LEVEL featureLevel)
601 {
602     switch (featureLevel)
603     {
604         case D3D_FEATURE_LEVEL_11_1:
605         case D3D_FEATURE_LEVEL_11_0:
606             return D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT;
607 
608         case D3D_FEATURE_LEVEL_10_1:
609         case D3D_FEATURE_LEVEL_10_0:
610             return D3D10_REQ_CONSTANT_BUFFER_ELEMENT_COUNT;
611 
612         // From http://msdn.microsoft.com/en-us/library/windows/desktop/ff476149.aspx
613         // ID3D11DeviceContext::VSSetConstantBuffers
614         case D3D_FEATURE_LEVEL_9_3:
615         case D3D_FEATURE_LEVEL_9_2:
616         case D3D_FEATURE_LEVEL_9_1:
617             return 255 - d3d11_gl::GetReservedVertexUniformVectors(featureLevel);
618 
619         default:
620             UNREACHABLE();
621             return 0;
622     }
623 }
624 
GetMaximumVertexUniformBlocks(D3D_FEATURE_LEVEL featureLevel)625 int GetMaximumVertexUniformBlocks(D3D_FEATURE_LEVEL featureLevel)
626 {
627     switch (featureLevel)
628     {
629         case D3D_FEATURE_LEVEL_11_1:
630         case D3D_FEATURE_LEVEL_11_0:
631             return D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT -
632                    d3d11::RESERVED_CONSTANT_BUFFER_SLOT_COUNT;
633 
634         case D3D_FEATURE_LEVEL_10_1:
635         case D3D_FEATURE_LEVEL_10_0:
636             return D3D10_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT -
637                    d3d11::RESERVED_CONSTANT_BUFFER_SLOT_COUNT;
638 
639         // Uniform blocks not supported on D3D11 Feature Level 9
640         case D3D_FEATURE_LEVEL_9_3:
641         case D3D_FEATURE_LEVEL_9_2:
642         case D3D_FEATURE_LEVEL_9_1:
643             return 0;
644 
645         default:
646             UNREACHABLE();
647             return 0;
648     }
649 }
650 
GetReservedVertexOutputVectors(D3D_FEATURE_LEVEL featureLevel)651 int GetReservedVertexOutputVectors(D3D_FEATURE_LEVEL featureLevel)
652 {
653     // According to The OpenGL ES Shading Language specifications
654     // (Language Version 1.00 section 10.16, Language Version 3.10 section 12.21)
655     // built-in special variables (e.g. gl_FragCoord, or gl_PointCoord)
656     // which are statically used in the shader should be included in the variable packing
657     // algorithm.
658     // Therefore, we should not reserve output vectors for them.
659 
660     switch (featureLevel)
661     {
662         // We must reserve one output vector for dx_Position.
663         // We also reserve one for gl_Position, which we unconditionally output on Feature
664         // Levels 10_0+,
665         // even if it's unused in the shader (e.g. for transform feedback). TODO: This could
666         // be improved.
667         case D3D_FEATURE_LEVEL_11_1:
668         case D3D_FEATURE_LEVEL_11_0:
669         case D3D_FEATURE_LEVEL_10_1:
670         case D3D_FEATURE_LEVEL_10_0:
671             return 2;
672 
673         // Just reserve dx_Position on Feature Level 9, since we don't ever need to output
674         // gl_Position.
675         case D3D_FEATURE_LEVEL_9_3:
676         case D3D_FEATURE_LEVEL_9_2:
677         case D3D_FEATURE_LEVEL_9_1:
678             return 1;
679 
680         default:
681             UNREACHABLE();
682             return 0;
683     }
684 }
685 
GetMaximumVertexOutputVectors(D3D_FEATURE_LEVEL featureLevel)686 int GetMaximumVertexOutputVectors(D3D_FEATURE_LEVEL featureLevel)
687 {
688     static_assert(gl::IMPLEMENTATION_MAX_VARYING_VECTORS == D3D11_VS_OUTPUT_REGISTER_COUNT,
689                   "Unexpected D3D11 constant value.");
690 
691     switch (featureLevel)
692     {
693         case D3D_FEATURE_LEVEL_11_1:
694         case D3D_FEATURE_LEVEL_11_0:
695             return D3D11_VS_OUTPUT_REGISTER_COUNT - GetReservedVertexOutputVectors(featureLevel);
696 
697         case D3D_FEATURE_LEVEL_10_1:
698             return D3D10_1_VS_OUTPUT_REGISTER_COUNT - GetReservedVertexOutputVectors(featureLevel);
699         case D3D_FEATURE_LEVEL_10_0:
700             return D3D10_VS_OUTPUT_REGISTER_COUNT - GetReservedVertexOutputVectors(featureLevel);
701 
702         // Use Shader Model 2.X limits
703         case D3D_FEATURE_LEVEL_9_3:
704         case D3D_FEATURE_LEVEL_9_2:
705         case D3D_FEATURE_LEVEL_9_1:
706             return 8 - GetReservedVertexOutputVectors(featureLevel);
707 
708         default:
709             UNREACHABLE();
710             return 0;
711     }
712 }
713 
GetMaximumVertexTextureUnits(D3D_FEATURE_LEVEL featureLevel)714 int GetMaximumVertexTextureUnits(D3D_FEATURE_LEVEL featureLevel)
715 {
716     switch (featureLevel)
717     {
718         case D3D_FEATURE_LEVEL_11_1:
719         case D3D_FEATURE_LEVEL_11_0:
720             return D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT;
721 
722         case D3D_FEATURE_LEVEL_10_1:
723         case D3D_FEATURE_LEVEL_10_0:
724             return D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT;
725 
726         // Vertex textures not supported on D3D11 Feature Level 9 according to
727         // http://msdn.microsoft.com/en-us/library/windows/desktop/ff476149.aspx
728         // ID3D11DeviceContext::VSSetSamplers and ID3D11DeviceContext::VSSetShaderResources
729         case D3D_FEATURE_LEVEL_9_3:
730         case D3D_FEATURE_LEVEL_9_2:
731         case D3D_FEATURE_LEVEL_9_1:
732             return 0;
733 
734         default:
735             UNREACHABLE();
736             return 0;
737     }
738 }
739 
GetMaximumPixelUniformVectors(D3D_FEATURE_LEVEL featureLevel)740 int GetMaximumPixelUniformVectors(D3D_FEATURE_LEVEL featureLevel)
741 {
742     // TODO(geofflang): Remove hard-coded limit once the gl-uniform-arrays test can pass
743     switch (featureLevel)
744     {
745         case D3D_FEATURE_LEVEL_11_1:
746         case D3D_FEATURE_LEVEL_11_0:
747             return 1024;  // D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT;
748 
749         case D3D_FEATURE_LEVEL_10_1:
750         case D3D_FEATURE_LEVEL_10_0:
751             return 1024;  // D3D10_REQ_CONSTANT_BUFFER_ELEMENT_COUNT;
752 
753         // From http://msdn.microsoft.com/en-us/library/windows/desktop/ff476149.aspx
754         // ID3D11DeviceContext::PSSetConstantBuffers
755         case D3D_FEATURE_LEVEL_9_3:
756         case D3D_FEATURE_LEVEL_9_2:
757         case D3D_FEATURE_LEVEL_9_1:
758             return 32 - d3d11_gl::GetReservedFragmentUniformVectors(featureLevel);
759 
760         default:
761             UNREACHABLE();
762             return 0;
763     }
764 }
765 
GetMaximumPixelUniformBlocks(D3D_FEATURE_LEVEL featureLevel)766 int GetMaximumPixelUniformBlocks(D3D_FEATURE_LEVEL featureLevel)
767 {
768     switch (featureLevel)
769     {
770         case D3D_FEATURE_LEVEL_11_1:
771         case D3D_FEATURE_LEVEL_11_0:
772             return D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT -
773                    d3d11::RESERVED_CONSTANT_BUFFER_SLOT_COUNT;
774 
775         case D3D_FEATURE_LEVEL_10_1:
776         case D3D_FEATURE_LEVEL_10_0:
777             return D3D10_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT -
778                    d3d11::RESERVED_CONSTANT_BUFFER_SLOT_COUNT;
779 
780         // Uniform blocks not supported on D3D11 Feature Level 9
781         case D3D_FEATURE_LEVEL_9_3:
782         case D3D_FEATURE_LEVEL_9_2:
783         case D3D_FEATURE_LEVEL_9_1:
784             return 0;
785 
786         default:
787             UNREACHABLE();
788             return 0;
789     }
790 }
791 
GetMaximumPixelInputVectors(D3D_FEATURE_LEVEL featureLevel)792 int GetMaximumPixelInputVectors(D3D_FEATURE_LEVEL featureLevel)
793 {
794     switch (featureLevel)
795     {
796         case D3D_FEATURE_LEVEL_11_1:
797         case D3D_FEATURE_LEVEL_11_0:
798             return D3D11_PS_INPUT_REGISTER_COUNT - GetReservedVertexOutputVectors(featureLevel);
799 
800         case D3D_FEATURE_LEVEL_10_1:
801         case D3D_FEATURE_LEVEL_10_0:
802             return D3D10_PS_INPUT_REGISTER_COUNT - GetReservedVertexOutputVectors(featureLevel);
803 
804         // Use Shader Model 2.X limits
805         case D3D_FEATURE_LEVEL_9_3:
806             return 8 - GetReservedVertexOutputVectors(featureLevel);
807         case D3D_FEATURE_LEVEL_9_2:
808         case D3D_FEATURE_LEVEL_9_1:
809             return 8 - GetReservedVertexOutputVectors(featureLevel);
810 
811         default:
812             UNREACHABLE();
813             return 0;
814     }
815 }
816 
GetMaximumPixelTextureUnits(D3D_FEATURE_LEVEL featureLevel)817 int GetMaximumPixelTextureUnits(D3D_FEATURE_LEVEL featureLevel)
818 {
819     switch (featureLevel)
820     {
821         case D3D_FEATURE_LEVEL_11_1:
822         case D3D_FEATURE_LEVEL_11_0:
823             return D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT;
824 
825         case D3D_FEATURE_LEVEL_10_1:
826         case D3D_FEATURE_LEVEL_10_0:
827             return D3D10_COMMONSHADER_SAMPLER_SLOT_COUNT;
828 
829         // http://msdn.microsoft.com/en-us/library/windows/desktop/ff476149.aspx
830         // ID3D11DeviceContext::PSSetShaderResources
831         case D3D_FEATURE_LEVEL_9_3:
832         case D3D_FEATURE_LEVEL_9_2:
833         case D3D_FEATURE_LEVEL_9_1:
834             return 16;
835 
836         default:
837             UNREACHABLE();
838             return 0;
839     }
840 }
841 
GetMaxComputeWorkGroupCount(D3D_FEATURE_LEVEL featureLevel)842 std::array<GLint, 3> GetMaxComputeWorkGroupCount(D3D_FEATURE_LEVEL featureLevel)
843 {
844     switch (featureLevel)
845     {
846         case D3D_FEATURE_LEVEL_11_1:
847         case D3D_FEATURE_LEVEL_11_0:
848             return {{D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION,
849                      D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION,
850                      D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION}};
851         default:
852             return {{0, 0, 0}};
853     }
854 }
855 
GetMaxComputeWorkGroupSize(D3D_FEATURE_LEVEL featureLevel)856 std::array<GLint, 3> GetMaxComputeWorkGroupSize(D3D_FEATURE_LEVEL featureLevel)
857 {
858     switch (featureLevel)
859     {
860         case D3D_FEATURE_LEVEL_11_1:
861         case D3D_FEATURE_LEVEL_11_0:
862             return {{D3D11_CS_THREAD_GROUP_MAX_X, D3D11_CS_THREAD_GROUP_MAX_Y,
863                      D3D11_CS_THREAD_GROUP_MAX_Z}};
864         default:
865             return {{0, 0, 0}};
866     }
867 }
868 
GetMaxComputeWorkGroupInvocations(D3D_FEATURE_LEVEL featureLevel)869 int GetMaxComputeWorkGroupInvocations(D3D_FEATURE_LEVEL featureLevel)
870 {
871     switch (featureLevel)
872     {
873         case D3D_FEATURE_LEVEL_11_1:
874         case D3D_FEATURE_LEVEL_11_0:
875             return D3D11_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP;
876         default:
877             return 0;
878     }
879 }
880 
GetMaxComputeSharedMemorySize(D3D_FEATURE_LEVEL featureLevel)881 int GetMaxComputeSharedMemorySize(D3D_FEATURE_LEVEL featureLevel)
882 {
883     switch (featureLevel)
884     {
885         // In D3D11 the maximum total size of all variables with the groupshared storage class is
886         // 32kb.
887         // https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl/dx-graphics-hlsl-variable-syntax
888         case D3D_FEATURE_LEVEL_11_1:
889         case D3D_FEATURE_LEVEL_11_0:
890             return 32768;
891         default:
892             return 0;
893     }
894 }
895 
GetMaximumComputeUniformVectors(D3D_FEATURE_LEVEL featureLevel)896 int GetMaximumComputeUniformVectors(D3D_FEATURE_LEVEL featureLevel)
897 {
898     switch (featureLevel)
899     {
900         case D3D_FEATURE_LEVEL_11_1:
901         case D3D_FEATURE_LEVEL_11_0:
902             return D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT;
903         default:
904             return 0;
905     }
906 }
907 
GetMaximumComputeUniformBlocks(D3D_FEATURE_LEVEL featureLevel)908 int GetMaximumComputeUniformBlocks(D3D_FEATURE_LEVEL featureLevel)
909 {
910     switch (featureLevel)
911     {
912         case D3D_FEATURE_LEVEL_11_1:
913         case D3D_FEATURE_LEVEL_11_0:
914             return D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT -
915                    d3d11::RESERVED_CONSTANT_BUFFER_SLOT_COUNT;
916         default:
917             return 0;
918     }
919 }
920 
GetMaximumComputeTextureUnits(D3D_FEATURE_LEVEL featureLevel)921 int GetMaximumComputeTextureUnits(D3D_FEATURE_LEVEL featureLevel)
922 {
923     switch (featureLevel)
924     {
925         case D3D_FEATURE_LEVEL_11_1:
926         case D3D_FEATURE_LEVEL_11_0:
927             return D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT;
928         default:
929             return 0;
930     }
931 }
932 
SetUAVRelatedResourceLimits(D3D_FEATURE_LEVEL featureLevel,gl::Caps * caps)933 void SetUAVRelatedResourceLimits(D3D_FEATURE_LEVEL featureLevel, gl::Caps *caps)
934 {
935     ASSERT(caps);
936 
937     GLuint reservedUAVsForAtomicCounterBuffers = 0u;
938 
939     // For pixel shaders, the render targets and unordered access views share the same resource
940     // slots when being written out.
941     // https://msdn.microsoft.com/en-us/library/windows/desktop/ff476465(v=vs.85).aspx
942     GLuint maxNumRTVsAndUAVs = 0u;
943 
944     switch (featureLevel)
945     {
946         case D3D_FEATURE_LEVEL_11_1:
947             // Currently we allocate 4 UAV slots for atomic counter buffers on feature level 11_1.
948             reservedUAVsForAtomicCounterBuffers = 4u;
949             maxNumRTVsAndUAVs                   = D3D11_1_UAV_SLOT_COUNT;
950             break;
951         case D3D_FEATURE_LEVEL_11_0:
952             // Currently we allocate 1 UAV slot for atomic counter buffers on feature level 11_0.
953             reservedUAVsForAtomicCounterBuffers = 1u;
954             maxNumRTVsAndUAVs                   = D3D11_PS_CS_UAV_REGISTER_COUNT;
955             break;
956         default:
957             return;
958     }
959 
960     // Set limits on atomic counter buffers in fragment shaders and compute shaders.
961     caps->maxCombinedAtomicCounterBuffers = reservedUAVsForAtomicCounterBuffers;
962     caps->maxShaderAtomicCounterBuffers[gl::ShaderType::Compute] =
963         reservedUAVsForAtomicCounterBuffers;
964     caps->maxShaderAtomicCounterBuffers[gl::ShaderType::Fragment] =
965         reservedUAVsForAtomicCounterBuffers;
966     caps->maxAtomicCounterBufferBindings = reservedUAVsForAtomicCounterBuffers;
967 
968     // Setting MAX_COMPUTE_ATOMIC_COUNTERS to a conservative number of 1024 * the number of UAV
969     // reserved for atomic counters. It could theoretically be set to max buffer size / 4 but that
970     // number could cause problems.
971     caps->maxCombinedAtomicCounters = reservedUAVsForAtomicCounterBuffers * 1024;
972     caps->maxShaderAtomicCounters[gl::ShaderType::Compute] = caps->maxCombinedAtomicCounters;
973 
974     // See
975     // https://docs.microsoft.com/en-us/windows/desktop/direct3d11/overviews-direct3d-11-resources-limits
976     // Resource size (in MB) for any of the preceding resources is min(max(128,0.25f * (amount of
977     // dedicated VRAM)), 2048) MB. So we set it to 128MB to keep same with GL backend.
978     caps->maxShaderStorageBlockSize =
979         D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM * 1024 * 1024;
980 
981     // Allocate the remaining slots for images and shader storage blocks.
982     // The maximum number of fragment shader outputs depends on the current context version, so we
983     // will not set it here. See comments in Context11::initialize().
984     caps->maxCombinedShaderOutputResources =
985         maxNumRTVsAndUAVs - reservedUAVsForAtomicCounterBuffers;
986 
987     // Set limits on images and shader storage blocks in fragment shaders and compute shaders.
988     caps->maxCombinedShaderStorageBlocks                   = caps->maxCombinedShaderOutputResources;
989     caps->maxShaderStorageBlocks[gl::ShaderType::Compute]  = caps->maxCombinedShaderOutputResources;
990     caps->maxShaderStorageBlocks[gl::ShaderType::Fragment] = caps->maxCombinedShaderOutputResources;
991     caps->maxShaderStorageBufferBindings                   = caps->maxCombinedShaderOutputResources;
992 
993     caps->maxImageUnits                                    = caps->maxCombinedShaderOutputResources;
994     caps->maxCombinedImageUniforms                         = caps->maxCombinedShaderOutputResources;
995     caps->maxShaderImageUniforms[gl::ShaderType::Compute]  = caps->maxCombinedShaderOutputResources;
996     caps->maxShaderImageUniforms[gl::ShaderType::Fragment] = caps->maxCombinedShaderOutputResources;
997 
998     // On feature level 11_1, UAVs are also available in vertex shaders and geometry shaders.
999     if (featureLevel == D3D_FEATURE_LEVEL_11_1)
1000     {
1001         caps->maxShaderAtomicCounterBuffers[gl::ShaderType::Vertex] =
1002             caps->maxCombinedAtomicCounterBuffers;
1003         caps->maxShaderAtomicCounterBuffers[gl::ShaderType::Geometry] =
1004             caps->maxCombinedAtomicCounterBuffers;
1005 
1006         caps->maxShaderImageUniforms[gl::ShaderType::Vertex] =
1007             caps->maxCombinedShaderOutputResources;
1008         caps->maxShaderStorageBlocks[gl::ShaderType::Vertex] =
1009             caps->maxCombinedShaderOutputResources;
1010         caps->maxShaderImageUniforms[gl::ShaderType::Geometry] =
1011             caps->maxCombinedShaderOutputResources;
1012         caps->maxShaderStorageBlocks[gl::ShaderType::Geometry] =
1013             caps->maxCombinedShaderOutputResources;
1014     }
1015 }
1016 
GetMinimumTexelOffset(D3D_FEATURE_LEVEL featureLevel)1017 int GetMinimumTexelOffset(D3D_FEATURE_LEVEL featureLevel)
1018 {
1019     switch (featureLevel)
1020     {
1021         case D3D_FEATURE_LEVEL_11_1:
1022         case D3D_FEATURE_LEVEL_11_0:
1023             return D3D11_COMMONSHADER_TEXEL_OFFSET_MAX_NEGATIVE;
1024 
1025         case D3D_FEATURE_LEVEL_10_1:
1026         case D3D_FEATURE_LEVEL_10_0:
1027             return D3D10_COMMONSHADER_TEXEL_OFFSET_MAX_NEGATIVE;
1028 
1029         // Sampling functions with offsets are not available below shader model 4.0.
1030         case D3D_FEATURE_LEVEL_9_3:
1031         case D3D_FEATURE_LEVEL_9_2:
1032         case D3D_FEATURE_LEVEL_9_1:
1033             return 0;
1034 
1035         default:
1036             UNREACHABLE();
1037             return 0;
1038     }
1039 }
1040 
GetMaximumTexelOffset(D3D_FEATURE_LEVEL featureLevel)1041 int GetMaximumTexelOffset(D3D_FEATURE_LEVEL featureLevel)
1042 {
1043     switch (featureLevel)
1044     {
1045         case D3D_FEATURE_LEVEL_11_1:
1046         case D3D_FEATURE_LEVEL_11_0:
1047             return D3D11_COMMONSHADER_TEXEL_OFFSET_MAX_POSITIVE;
1048         case D3D_FEATURE_LEVEL_10_1:
1049         case D3D_FEATURE_LEVEL_10_0:
1050             return D3D11_COMMONSHADER_TEXEL_OFFSET_MAX_POSITIVE;
1051 
1052         // Sampling functions with offsets are not available below shader model 4.0.
1053         case D3D_FEATURE_LEVEL_9_3:
1054         case D3D_FEATURE_LEVEL_9_2:
1055         case D3D_FEATURE_LEVEL_9_1:
1056             return 0;
1057 
1058         default:
1059             UNREACHABLE();
1060             return 0;
1061     }
1062 }
1063 
GetMinimumTextureGatherOffset(D3D_FEATURE_LEVEL featureLevel)1064 int GetMinimumTextureGatherOffset(D3D_FEATURE_LEVEL featureLevel)
1065 {
1066     switch (featureLevel)
1067     {
1068         // https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl/gather4-po--sm5---asm-
1069         case D3D_FEATURE_LEVEL_11_1:
1070         case D3D_FEATURE_LEVEL_11_0:
1071             return -32;
1072 
1073         case D3D_FEATURE_LEVEL_10_1:
1074         case D3D_FEATURE_LEVEL_10_0:
1075         case D3D_FEATURE_LEVEL_9_3:
1076         case D3D_FEATURE_LEVEL_9_2:
1077         case D3D_FEATURE_LEVEL_9_1:
1078             return 0;
1079 
1080         default:
1081             UNREACHABLE();
1082             return 0;
1083     }
1084 }
1085 
GetMaximumTextureGatherOffset(D3D_FEATURE_LEVEL featureLevel)1086 int GetMaximumTextureGatherOffset(D3D_FEATURE_LEVEL featureLevel)
1087 {
1088     switch (featureLevel)
1089     {
1090         // https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl/gather4-po--sm5---asm-
1091         case D3D_FEATURE_LEVEL_11_1:
1092         case D3D_FEATURE_LEVEL_11_0:
1093             return 31;
1094 
1095         case D3D_FEATURE_LEVEL_10_1:
1096         case D3D_FEATURE_LEVEL_10_0:
1097         case D3D_FEATURE_LEVEL_9_3:
1098         case D3D_FEATURE_LEVEL_9_2:
1099         case D3D_FEATURE_LEVEL_9_1:
1100             return 0;
1101 
1102         default:
1103             UNREACHABLE();
1104             return 0;
1105     }
1106 }
1107 
GetMaximumConstantBufferSize(D3D_FEATURE_LEVEL featureLevel)1108 size_t GetMaximumConstantBufferSize(D3D_FEATURE_LEVEL featureLevel)
1109 {
1110     // Returns a size_t despite the limit being a GLuint64 because size_t is the maximum
1111     // size of
1112     // any buffer that could be allocated.
1113 
1114     const size_t bytesPerComponent = 4 * sizeof(float);
1115 
1116     switch (featureLevel)
1117     {
1118         case D3D_FEATURE_LEVEL_11_1:
1119         case D3D_FEATURE_LEVEL_11_0:
1120             return D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT * bytesPerComponent;
1121 
1122         case D3D_FEATURE_LEVEL_10_1:
1123         case D3D_FEATURE_LEVEL_10_0:
1124             return D3D10_REQ_CONSTANT_BUFFER_ELEMENT_COUNT * bytesPerComponent;
1125 
1126         // Limits from http://msdn.microsoft.com/en-us/library/windows/desktop/ff476501.aspx
1127         // remarks section
1128         case D3D_FEATURE_LEVEL_9_3:
1129         case D3D_FEATURE_LEVEL_9_2:
1130         case D3D_FEATURE_LEVEL_9_1:
1131             return 4096 * bytesPerComponent;
1132 
1133         default:
1134             UNREACHABLE();
1135             return 0;
1136     }
1137 }
1138 
GetMaximumStreamOutputBuffers(D3D_FEATURE_LEVEL featureLevel)1139 int GetMaximumStreamOutputBuffers(D3D_FEATURE_LEVEL featureLevel)
1140 {
1141     switch (featureLevel)
1142     {
1143         case D3D_FEATURE_LEVEL_11_1:
1144         case D3D_FEATURE_LEVEL_11_0:
1145             return D3D11_SO_BUFFER_SLOT_COUNT;
1146 
1147         case D3D_FEATURE_LEVEL_10_1:
1148             return D3D10_1_SO_BUFFER_SLOT_COUNT;
1149         case D3D_FEATURE_LEVEL_10_0:
1150             return D3D10_SO_BUFFER_SLOT_COUNT;
1151 
1152         case D3D_FEATURE_LEVEL_9_3:
1153         case D3D_FEATURE_LEVEL_9_2:
1154         case D3D_FEATURE_LEVEL_9_1:
1155             return 0;
1156 
1157         default:
1158             UNREACHABLE();
1159             return 0;
1160     }
1161 }
1162 
GetMaximumStreamOutputInterleavedComponents(D3D_FEATURE_LEVEL featureLevel)1163 int GetMaximumStreamOutputInterleavedComponents(D3D_FEATURE_LEVEL featureLevel)
1164 {
1165     switch (featureLevel)
1166     {
1167         case D3D_FEATURE_LEVEL_11_1:
1168         case D3D_FEATURE_LEVEL_11_0:
1169 
1170         case D3D_FEATURE_LEVEL_10_1:
1171         case D3D_FEATURE_LEVEL_10_0:
1172             return GetMaximumVertexOutputVectors(featureLevel) * 4;
1173 
1174         case D3D_FEATURE_LEVEL_9_3:
1175         case D3D_FEATURE_LEVEL_9_2:
1176         case D3D_FEATURE_LEVEL_9_1:
1177             return 0;
1178 
1179         default:
1180             UNREACHABLE();
1181             return 0;
1182     }
1183 }
1184 
GetMaximumStreamOutputSeparateComponents(D3D_FEATURE_LEVEL featureLevel)1185 int GetMaximumStreamOutputSeparateComponents(D3D_FEATURE_LEVEL featureLevel)
1186 {
1187     switch (featureLevel)
1188     {
1189         case D3D_FEATURE_LEVEL_11_1:
1190         case D3D_FEATURE_LEVEL_11_0:
1191             return GetMaximumStreamOutputInterleavedComponents(featureLevel) /
1192                    GetMaximumStreamOutputBuffers(featureLevel);
1193 
1194         // D3D 10 and 10.1 only allow one output per output slot if an output slot other
1195         // than zero is used.
1196         case D3D_FEATURE_LEVEL_10_1:
1197         case D3D_FEATURE_LEVEL_10_0:
1198             return 4;
1199 
1200         case D3D_FEATURE_LEVEL_9_3:
1201         case D3D_FEATURE_LEVEL_9_2:
1202         case D3D_FEATURE_LEVEL_9_1:
1203             return 0;
1204 
1205         default:
1206             UNREACHABLE();
1207             return 0;
1208     }
1209 }
1210 
GetMaximumRenderToBufferWindowSize(D3D_FEATURE_LEVEL featureLevel)1211 int GetMaximumRenderToBufferWindowSize(D3D_FEATURE_LEVEL featureLevel)
1212 {
1213     switch (featureLevel)
1214     {
1215         case D3D_FEATURE_LEVEL_11_1:
1216         case D3D_FEATURE_LEVEL_11_0:
1217             return D3D11_REQ_RENDER_TO_BUFFER_WINDOW_WIDTH;
1218         case D3D_FEATURE_LEVEL_10_1:
1219         case D3D_FEATURE_LEVEL_10_0:
1220             return D3D10_REQ_RENDER_TO_BUFFER_WINDOW_WIDTH;
1221 
1222         // REQ_RENDER_TO_BUFFER_WINDOW_WIDTH not supported on D3D11 Feature Level 9,
1223         // use the maximum texture sizes
1224         case D3D_FEATURE_LEVEL_9_3:
1225             return D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION;
1226         case D3D_FEATURE_LEVEL_9_2:
1227         case D3D_FEATURE_LEVEL_9_1:
1228             return D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION;
1229 
1230         default:
1231             UNREACHABLE();
1232             return 0;
1233     }
1234 }
1235 
GetIntelDriverVersion(const Optional<LARGE_INTEGER> driverVersion)1236 IntelDriverVersion GetIntelDriverVersion(const Optional<LARGE_INTEGER> driverVersion)
1237 {
1238     if (!driverVersion.valid())
1239         return IntelDriverVersion(0);
1240 
1241     DWORD lowPart = driverVersion.value().LowPart;
1242     return IntelDriverVersion(HIWORD(lowPart) * 10000 + LOWORD(lowPart));
1243 }
1244 
1245 }  // anonymous namespace
1246 
GetReservedVertexUniformVectors(D3D_FEATURE_LEVEL featureLevel)1247 unsigned int GetReservedVertexUniformVectors(D3D_FEATURE_LEVEL featureLevel)
1248 {
1249     switch (featureLevel)
1250     {
1251         case D3D_FEATURE_LEVEL_11_1:
1252         case D3D_FEATURE_LEVEL_11_0:
1253         case D3D_FEATURE_LEVEL_10_1:
1254         case D3D_FEATURE_LEVEL_10_0:
1255             return 0;
1256 
1257         case D3D_FEATURE_LEVEL_9_3:
1258         case D3D_FEATURE_LEVEL_9_2:
1259         case D3D_FEATURE_LEVEL_9_1:
1260             return 3;  // dx_ViewAdjust, dx_ViewCoords and dx_ViewScale
1261 
1262         default:
1263             UNREACHABLE();
1264             return 0;
1265     }
1266 }
1267 
GetReservedFragmentUniformVectors(D3D_FEATURE_LEVEL featureLevel)1268 unsigned int GetReservedFragmentUniformVectors(D3D_FEATURE_LEVEL featureLevel)
1269 {
1270     switch (featureLevel)
1271     {
1272         case D3D_FEATURE_LEVEL_11_1:
1273         case D3D_FEATURE_LEVEL_11_0:
1274         case D3D_FEATURE_LEVEL_10_1:
1275         case D3D_FEATURE_LEVEL_10_0:
1276             return 0;
1277 
1278         case D3D_FEATURE_LEVEL_9_3:
1279         case D3D_FEATURE_LEVEL_9_2:
1280         case D3D_FEATURE_LEVEL_9_1:
1281             return 4;  // dx_ViewCoords, dx_DepthFront, dx_DepthRange, dx_FragCoordOffset
1282 
1283         default:
1284             UNREACHABLE();
1285             return 0;
1286     }
1287 }
1288 
GetMaximumClientVersion(const Renderer11DeviceCaps & caps)1289 gl::Version GetMaximumClientVersion(const Renderer11DeviceCaps &caps)
1290 {
1291     switch (caps.featureLevel)
1292     {
1293         case D3D_FEATURE_LEVEL_11_1:
1294         case D3D_FEATURE_LEVEL_11_0:
1295             return gl::Version(3, 1);
1296         case D3D_FEATURE_LEVEL_10_1:
1297             return gl::Version(3, 0);
1298 
1299         case D3D_FEATURE_LEVEL_10_0:
1300             if (caps.allowES3OnFL10_0)
1301             {
1302                 return gl::Version(3, 0);
1303             }
1304             else
1305             {
1306                 return gl::Version(2, 0);
1307             }
1308         case D3D_FEATURE_LEVEL_9_3:
1309         case D3D_FEATURE_LEVEL_9_2:
1310         case D3D_FEATURE_LEVEL_9_1:
1311             return gl::Version(2, 0);
1312 
1313         default:
1314             UNREACHABLE();
1315             return gl::Version(0, 0);
1316     }
1317 }
1318 
GetMinimumFeatureLevelForES31()1319 D3D_FEATURE_LEVEL GetMinimumFeatureLevelForES31()
1320 {
1321     return kMinimumFeatureLevelForES31;
1322 }
1323 
GetMaxViewportAndScissorRectanglesPerPipeline(D3D_FEATURE_LEVEL featureLevel)1324 unsigned int GetMaxViewportAndScissorRectanglesPerPipeline(D3D_FEATURE_LEVEL featureLevel)
1325 {
1326     switch (featureLevel)
1327     {
1328         case D3D_FEATURE_LEVEL_11_1:
1329         case D3D_FEATURE_LEVEL_11_0:
1330             return D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
1331         case D3D_FEATURE_LEVEL_10_1:
1332         case D3D_FEATURE_LEVEL_10_0:
1333         case D3D_FEATURE_LEVEL_9_3:
1334         case D3D_FEATURE_LEVEL_9_2:
1335         case D3D_FEATURE_LEVEL_9_1:
1336             return 1;
1337         default:
1338             UNREACHABLE();
1339             return 0;
1340     }
1341 }
1342 
IsMultiviewSupported(D3D_FEATURE_LEVEL featureLevel)1343 bool IsMultiviewSupported(D3D_FEATURE_LEVEL featureLevel)
1344 {
1345     // The multiview extensions can always be supported in D3D11 through geometry shaders.
1346     switch (featureLevel)
1347     {
1348         case D3D_FEATURE_LEVEL_11_1:
1349         case D3D_FEATURE_LEVEL_11_0:
1350             return true;
1351         default:
1352             return false;
1353     }
1354 }
1355 
GetMaxSampleMaskWords(D3D_FEATURE_LEVEL featureLevel)1356 int GetMaxSampleMaskWords(D3D_FEATURE_LEVEL featureLevel)
1357 {
1358     switch (featureLevel)
1359     {
1360         // D3D10+ only allows 1 sample mask.
1361         case D3D_FEATURE_LEVEL_11_1:
1362         case D3D_FEATURE_LEVEL_11_0:
1363         case D3D_FEATURE_LEVEL_10_1:
1364         case D3D_FEATURE_LEVEL_10_0:
1365             return 1;
1366         case D3D_FEATURE_LEVEL_9_3:
1367         case D3D_FEATURE_LEVEL_9_2:
1368         case D3D_FEATURE_LEVEL_9_1:
1369             return 0;
1370         default:
1371             UNREACHABLE();
1372             return 0;
1373     }
1374 }
1375 
HasTextureBufferSupport(ID3D11Device * device,const Renderer11DeviceCaps & renderer11DeviceCaps)1376 bool HasTextureBufferSupport(ID3D11Device *device, const Renderer11DeviceCaps &renderer11DeviceCaps)
1377 {
1378     if (renderer11DeviceCaps.featureLevel < D3D_FEATURE_LEVEL_11_0)
1379         return false;
1380 
1381     if (!renderer11DeviceCaps.supportsTypedUAVLoadAdditionalFormats)
1382         return false;
1383 
1384     // https://docs.microsoft.com/en-us/windows/win32/direct3d12/typed-unordered-access-view-loads
1385     // we don't need to check the typed store. from the spec,
1386     // https://microsoft.github.io/DirectX-Specs/d3d/archive/D3D11_3_FunctionalSpec.htm#FormatList
1387     // all the following format support typed stored.
1388     // According to spec,
1389     // https://www.khronos.org/registry/OpenGL-Refpages/es3/html/glBindImageTexture.xhtml the
1390     // required image unit format are GL_RGBA32F, GL_RGBA32UI, GL_RGBA32I, GL_RGBA16F, GL_RGBA16UI,
1391     // GL_RGBA16I, GL_RGBA8, GL_RGBAUI, GL_RGBA8I, GL_RGBA8_SNORM, GL_R32F, GL_R32UI, GL_R32I,
1392     const std::array<DXGI_FORMAT, 2> &optionalFormats = {
1393         DXGI_FORMAT_R32G32B32A32_FLOAT,  // test for GL_RGBA32(UIF), GL_RGBA16(UIF),
1394                                          // GL_RGBA8(UIUnorm)
1395         DXGI_FORMAT_R8G8B8A8_SNORM,      // test for GL_RGBA8_SNORM,
1396     };
1397 
1398     for (DXGI_FORMAT dxgiFormat : optionalFormats)
1399     {
1400         D3D11_FEATURE_DATA_FORMAT_SUPPORT FormatSupport = {dxgiFormat, 0};
1401         if (!SUCCEEDED(device->CheckFeatureSupport(D3D11_FEATURE_FORMAT_SUPPORT, &FormatSupport,
1402                                                    sizeof(FormatSupport))))
1403         {
1404             WARN() << "Error checking typed load support for format 0x" << std::hex << dxgiFormat;
1405             return false;
1406         }
1407         if ((FormatSupport.OutFormatSupport & D3D11_FORMAT_SUPPORT2_UAV_TYPED_LOAD) == 0)
1408             return false;
1409     }
1410     return true;
1411 }
1412 
GenerateCaps(ID3D11Device * device,ID3D11DeviceContext * deviceContext,const Renderer11DeviceCaps & renderer11DeviceCaps,const angle::FeaturesD3D & features,const char * description,gl::Caps * caps,gl::TextureCapsMap * textureCapsMap,gl::Extensions * extensions,gl::Limitations * limitations,ShPixelLocalStorageOptions * plsOptions)1413 void GenerateCaps(ID3D11Device *device,
1414                   ID3D11DeviceContext *deviceContext,
1415                   const Renderer11DeviceCaps &renderer11DeviceCaps,
1416                   const angle::FeaturesD3D &features,
1417                   const char *description,
1418                   gl::Caps *caps,
1419                   gl::TextureCapsMap *textureCapsMap,
1420                   gl::Extensions *extensions,
1421                   gl::Limitations *limitations,
1422                   ShPixelLocalStorageOptions *plsOptions)
1423 {
1424     const D3D_FEATURE_LEVEL featureLevel = renderer11DeviceCaps.featureLevel;
1425     const gl::FormatSet &allFormats      = gl::GetAllSizedInternalFormats();
1426     for (GLenum internalFormat : allFormats)
1427     {
1428         gl::TextureCaps textureCaps =
1429             GenerateTextureFormatCaps(GetMaximumClientVersion(renderer11DeviceCaps), internalFormat,
1430                                       device, renderer11DeviceCaps);
1431         textureCapsMap->insert(internalFormat, textureCaps);
1432     }
1433 
1434     // GL core feature limits
1435     // Reserve MAX_UINT for D3D11's primitive restart.
1436     caps->maxElementIndex  = static_cast<GLint64>(std::numeric_limits<unsigned int>::max() - 1);
1437     caps->max3DTextureSize = GetMaximum3DTextureSize(featureLevel);
1438     caps->max2DTextureSize = GetMaximum2DTextureSize(featureLevel);
1439     caps->maxCubeMapTextureSize = GetMaximumCubeMapTextureSize(featureLevel);
1440     caps->maxArrayTextureLayers = GetMaximum2DTextureArraySize(featureLevel);
1441 
1442     // Unimplemented, set to minimum required
1443     caps->maxLODBias = 2.0f;
1444 
1445     // No specific limits on render target size, maximum 2D texture size is equivalent
1446     caps->maxRenderbufferSize = caps->max2DTextureSize;
1447 
1448     // Maximum draw buffers and color attachments are the same, max color attachments could
1449     // eventually be increased to 16
1450     caps->maxDrawBuffers      = GetMaximumSimultaneousRenderTargets(featureLevel);
1451     caps->maxColorAttachments = GetMaximumSimultaneousRenderTargets(featureLevel);
1452 
1453     // D3D11 has the same limit for viewport width and height
1454     caps->maxViewportWidth  = GetMaximumViewportSize(featureLevel);
1455     caps->maxViewportHeight = caps->maxViewportWidth;
1456 
1457     // Choose a reasonable maximum, enforced in the shader.
1458     caps->minAliasedPointSize = 1.0f;
1459     caps->maxAliasedPointSize = 1024.0f;
1460 
1461     // Wide lines not supported
1462     caps->minAliasedLineWidth = 1.0f;
1463     caps->maxAliasedLineWidth = 1.0f;
1464 
1465     // Primitive count limits
1466     caps->maxElementsIndices  = GetMaximumDrawIndexedIndexCount(featureLevel);
1467     caps->maxElementsVertices = GetMaximumDrawVertexCount(featureLevel);
1468 
1469     // Program and shader binary formats (no supported shader binary formats)
1470     caps->programBinaryFormats.push_back(GL_PROGRAM_BINARY_ANGLE);
1471 
1472     caps->vertexHighpFloat.setIEEEFloat();
1473     caps->vertexMediumpFloat.setIEEEFloat();
1474     caps->vertexLowpFloat.setIEEEFloat();
1475     caps->fragmentHighpFloat.setIEEEFloat();
1476     caps->fragmentMediumpFloat.setIEEEFloat();
1477     caps->fragmentLowpFloat.setIEEEFloat();
1478 
1479     // 32-bit integers are natively supported
1480     caps->vertexHighpInt.setTwosComplementInt(32);
1481     caps->vertexMediumpInt.setTwosComplementInt(32);
1482     caps->vertexLowpInt.setTwosComplementInt(32);
1483     caps->fragmentHighpInt.setTwosComplementInt(32);
1484     caps->fragmentMediumpInt.setTwosComplementInt(32);
1485     caps->fragmentLowpInt.setTwosComplementInt(32);
1486 
1487     // We do not wait for server fence objects internally, so report a max timeout of zero.
1488     caps->maxServerWaitTimeout = 0;
1489 
1490     // Vertex shader limits
1491     caps->maxVertexAttributes     = GetMaximumVertexInputSlots(featureLevel);
1492     caps->maxVertexUniformVectors = GetMaximumVertexUniformVectors(featureLevel);
1493     if (features.skipVSConstantRegisterZero.enabled)
1494     {
1495         caps->maxVertexUniformVectors -= 1;
1496     }
1497     caps->maxShaderUniformComponents[gl::ShaderType::Vertex] = caps->maxVertexUniformVectors * 4;
1498     caps->maxShaderUniformBlocks[gl::ShaderType::Vertex] =
1499         GetMaximumVertexUniformBlocks(featureLevel);
1500     caps->maxVertexOutputComponents = GetMaximumVertexOutputVectors(featureLevel) * 4;
1501     caps->maxShaderTextureImageUnits[gl::ShaderType::Vertex] =
1502         GetMaximumVertexTextureUnits(featureLevel);
1503 
1504     // Vertex Attribute Bindings are emulated on D3D11.
1505     caps->maxVertexAttribBindings = caps->maxVertexAttributes;
1506     // Experimental testing confirmed there is no explicit limit on maximum buffer offset in D3D11.
1507     caps->maxVertexAttribRelativeOffset = std::numeric_limits<GLint>::max();
1508     // Experimental testing confirmed 2048 is the maximum stride that D3D11 can support on all
1509     // platforms.
1510     caps->maxVertexAttribStride = 2048;
1511 
1512     // Fragment shader limits
1513     caps->maxFragmentUniformVectors = GetMaximumPixelUniformVectors(featureLevel);
1514     caps->maxShaderUniformComponents[gl::ShaderType::Fragment] =
1515         caps->maxFragmentUniformVectors * 4;
1516     caps->maxShaderUniformBlocks[gl::ShaderType::Fragment] =
1517         GetMaximumPixelUniformBlocks(featureLevel);
1518     caps->maxFragmentInputComponents = GetMaximumPixelInputVectors(featureLevel) * 4;
1519     caps->maxShaderTextureImageUnits[gl::ShaderType::Fragment] =
1520         GetMaximumPixelTextureUnits(featureLevel);
1521     caps->minProgramTexelOffset = GetMinimumTexelOffset(featureLevel);
1522     caps->maxProgramTexelOffset = GetMaximumTexelOffset(featureLevel);
1523 
1524     // Compute shader limits
1525     caps->maxComputeWorkGroupCount       = GetMaxComputeWorkGroupCount(featureLevel);
1526     caps->maxComputeWorkGroupSize        = GetMaxComputeWorkGroupSize(featureLevel);
1527     caps->maxComputeWorkGroupInvocations = GetMaxComputeWorkGroupInvocations(featureLevel);
1528     caps->maxComputeSharedMemorySize     = GetMaxComputeSharedMemorySize(featureLevel);
1529     caps->maxShaderUniformComponents[gl::ShaderType::Compute] =
1530         GetMaximumComputeUniformVectors(featureLevel) * 4;
1531     caps->maxShaderUniformBlocks[gl::ShaderType::Compute] =
1532         GetMaximumComputeUniformBlocks(featureLevel);
1533     caps->maxShaderTextureImageUnits[gl::ShaderType::Compute] =
1534         GetMaximumComputeTextureUnits(featureLevel);
1535 
1536     SetUAVRelatedResourceLimits(featureLevel, caps);
1537 
1538     // Aggregate shader limits
1539     caps->maxUniformBufferBindings = caps->maxShaderUniformBlocks[gl::ShaderType::Vertex] +
1540                                      caps->maxShaderUniformBlocks[gl::ShaderType::Fragment];
1541     caps->maxUniformBlockSize = static_cast<GLuint64>(GetMaximumConstantBufferSize(featureLevel));
1542 
1543     // TODO(oetuaho): Get a more accurate limit. For now using the minimum requirement for GLES 3.1.
1544     caps->maxUniformLocations = 1024;
1545 
1546     // With DirectX 11.1, constant buffer offset and size must be a multiple of 16 constants of 16
1547     // bytes each.
1548     // https://msdn.microsoft.com/en-us/library/windows/desktop/hh404649%28v=vs.85%29.aspx
1549     // With DirectX 11.0, we emulate UBO offsets using copies of ranges of the UBO however
1550     // we still keep the same alignment as 11.1 for consistency.
1551     caps->uniformBufferOffsetAlignment = 256;
1552 
1553     caps->maxCombinedUniformBlocks = caps->maxShaderUniformBlocks[gl::ShaderType::Vertex] +
1554                                      caps->maxShaderUniformBlocks[gl::ShaderType::Fragment];
1555 
1556     // A shader storage block will be translated to a structure in HLSL. So We reference the HLSL
1557     // structure packing rules
1558     // https://msdn.microsoft.com/en-us/library/windows/desktop/bb509632(v=vs.85).aspx. The
1559     // resulting size of any structure will always be evenly divisible by sizeof(four-component
1560     // vector).
1561     caps->shaderStorageBufferOffsetAlignment = 16;
1562 
1563     for (gl::ShaderType shaderType : gl::AllShaderTypes())
1564     {
1565         caps->maxCombinedShaderUniformComponents[shaderType] =
1566             static_cast<GLint64>(caps->maxShaderUniformBlocks[shaderType]) *
1567                 static_cast<GLint64>(caps->maxUniformBlockSize / 4) +
1568             static_cast<GLint64>(caps->maxShaderUniformComponents[shaderType]);
1569     }
1570 
1571     caps->maxVaryingComponents         = GetMaximumVertexOutputVectors(featureLevel) * 4;
1572     caps->maxVaryingVectors            = GetMaximumVertexOutputVectors(featureLevel);
1573     caps->maxCombinedTextureImageUnits = caps->maxShaderTextureImageUnits[gl::ShaderType::Vertex] +
1574                                          caps->maxShaderTextureImageUnits[gl::ShaderType::Fragment];
1575 
1576     // Transform feedback limits
1577     caps->maxTransformFeedbackInterleavedComponents =
1578         GetMaximumStreamOutputInterleavedComponents(featureLevel);
1579     caps->maxTransformFeedbackSeparateAttributes = GetMaximumStreamOutputBuffers(featureLevel);
1580     caps->maxTransformFeedbackSeparateComponents =
1581         GetMaximumStreamOutputSeparateComponents(featureLevel);
1582 
1583     // Defer the computation of multisample limits to Context::updateCaps() where max*Samples values
1584     // are determined according to available sample counts for each individual format.
1585     caps->maxSamples             = std::numeric_limits<GLint>::max();
1586     caps->maxColorTextureSamples = std::numeric_limits<GLint>::max();
1587     caps->maxDepthTextureSamples = std::numeric_limits<GLint>::max();
1588     caps->maxIntegerSamples      = std::numeric_limits<GLint>::max();
1589 
1590     // Sample mask words limits
1591     caps->maxSampleMaskWords = GetMaxSampleMaskWords(featureLevel);
1592 
1593     // Framebuffer limits
1594     caps->maxFramebufferSamples = std::numeric_limits<GLint>::max();
1595     caps->maxFramebufferWidth   = GetMaximumRenderToBufferWindowSize(featureLevel);
1596     caps->maxFramebufferHeight  = caps->maxFramebufferWidth;
1597 
1598     // Texture gather offset limits
1599     caps->minProgramTextureGatherOffset = GetMinimumTextureGatherOffset(featureLevel);
1600     caps->maxProgramTextureGatherOffset = GetMaximumTextureGatherOffset(featureLevel);
1601 
1602     caps->maxTextureAnisotropy        = GetMaximumAnisotropy(featureLevel);
1603     caps->queryCounterBitsTimeElapsed = 64;
1604 
1605     caps->queryCounterBitsTimestamp = features.enableTimestampQueries.enabled ? 64 : 0;
1606 
1607     caps->maxDualSourceDrawBuffers = 1;
1608 
1609     // GL extension support
1610     extensions->setTextureExtensionSupport(*textureCapsMap);
1611 
1612     // Explicitly disable GL_OES_compressed_ETC1_RGB8_texture because it's emulated and never
1613     // becomes core. WebGL doesn't want to expose it unless there is native support.
1614     extensions->compressedETC1RGB8TextureOES    = false;
1615     extensions->compressedETC1RGB8SubTextureEXT = false;
1616 
1617     extensions->elementIndexUintOES         = true;
1618     extensions->getProgramBinaryOES         = true;
1619     extensions->rgb8Rgba8OES                = true;
1620     extensions->readFormatBgraEXT           = true;
1621     extensions->pixelBufferObjectNV         = true;
1622     extensions->mapbufferOES                = true;
1623     extensions->mapBufferRangeEXT           = true;
1624     extensions->textureNpotOES              = GetNPOTTextureSupport(featureLevel);
1625     extensions->drawBuffersEXT              = GetMaximumSimultaneousRenderTargets(featureLevel) > 1;
1626     extensions->drawBuffersIndexedEXT       = (featureLevel >= D3D_FEATURE_LEVEL_10_1);
1627     extensions->drawBuffersIndexedOES       = extensions->drawBuffersIndexedEXT;
1628     extensions->textureStorageEXT           = true;
1629     extensions->textureFilterAnisotropicEXT = true;
1630     extensions->occlusionQueryBooleanEXT    = GetOcclusionQuerySupport(featureLevel);
1631     extensions->fenceNV                     = GetEventQuerySupport(featureLevel);
1632     extensions->disjointTimerQueryEXT       = true;
1633     extensions->robustnessEXT               = true;
1634     extensions->robustnessKHR               = true;
1635     // Direct3D guarantees to return zero for any resource that is accessed out of bounds.
1636     // See https://msdn.microsoft.com/en-us/library/windows/desktop/ff476332(v=vs.85).aspx
1637     // and https://msdn.microsoft.com/en-us/library/windows/desktop/ff476900(v=vs.85).aspx
1638     extensions->robustBufferAccessBehaviorKHR = true;
1639     extensions->blendMinmaxEXT                = true;
1640     // https://docs.microsoft.com/en-us/windows/desktop/direct3ddxgi/format-support-for-direct3d-11-0-feature-level-hardware
1641     extensions->floatBlendEXT               = true;
1642     extensions->framebufferBlitANGLE        = GetFramebufferBlitSupport(featureLevel);
1643     extensions->framebufferBlitNV           = extensions->framebufferBlitANGLE;
1644     extensions->framebufferMultisampleANGLE = GetFramebufferMultisampleSupport(featureLevel);
1645     extensions->instancedArraysANGLE        = GetInstancingSupport(featureLevel);
1646     extensions->instancedArraysEXT          = GetInstancingSupport(featureLevel);
1647     extensions->packReverseRowOrderANGLE    = true;
1648     extensions->standardDerivativesOES      = GetDerivativeInstructionSupport(featureLevel);
1649     extensions->shaderTextureLodEXT         = GetShaderTextureLODSupport(featureLevel);
1650     extensions->fragDepthEXT                = true;
1651     extensions->conservativeDepthEXT        = (featureLevel >= D3D_FEATURE_LEVEL_11_0);
1652     extensions->polygonModeANGLE            = true;
1653     extensions->polygonOffsetClampEXT       = (featureLevel >= D3D_FEATURE_LEVEL_10_0);
1654     extensions->depthClampEXT               = true;
1655     extensions->stencilTexturingANGLE       = (featureLevel >= D3D_FEATURE_LEVEL_10_1);
1656     extensions->multiviewOVR                = IsMultiviewSupported(featureLevel);
1657     extensions->multiview2OVR               = IsMultiviewSupported(featureLevel);
1658     if (extensions->multiviewOVR || extensions->multiview2OVR)
1659     {
1660         caps->maxViews = std::min(static_cast<GLuint>(GetMaximum2DTextureArraySize(featureLevel)),
1661                                   GetMaxViewportAndScissorRectanglesPerPipeline(featureLevel));
1662     }
1663     extensions->textureUsageANGLE = true;  // This could be false since it has no effect in D3D11
1664     extensions->discardFramebufferEXT               = true;
1665     extensions->translatedShaderSourceANGLE         = true;
1666     extensions->fboRenderMipmapOES                  = true;
1667     extensions->debugMarkerEXT                      = true;
1668     extensions->EGLImageOES                         = true;
1669     extensions->EGLImageExternalOES                 = true;
1670     extensions->EGLImageExternalWrapModesEXT        = true;
1671     extensions->EGLImageExternalEssl3OES            = true;
1672     extensions->EGLStreamConsumerExternalNV         = true;
1673     extensions->unpackSubimageEXT                   = true;
1674     extensions->packSubimageNV                      = true;
1675     extensions->lossyEtcDecodeANGLE                 = true;
1676     extensions->syncQueryCHROMIUM                   = GetEventQuerySupport(featureLevel);
1677     extensions->copyTextureCHROMIUM                 = true;
1678     extensions->copyCompressedTextureCHROMIUM       = true;
1679     extensions->textureStorageMultisample2dArrayOES = true;
1680     extensions->textureMirrorClampToEdgeEXT         = true;
1681     extensions->shaderNoperspectiveInterpolationNV  = (featureLevel >= D3D_FEATURE_LEVEL_10_0);
1682     extensions->sampleVariablesOES                  = (featureLevel >= D3D_FEATURE_LEVEL_11_0);
1683     extensions->shaderMultisampleInterpolationOES   = (featureLevel >= D3D_FEATURE_LEVEL_11_0);
1684     if (extensions->shaderMultisampleInterpolationOES)
1685     {
1686         caps->subPixelInterpolationOffsetBits = 4;
1687         caps->minInterpolationOffset          = -0.5f;
1688         caps->maxInterpolationOffset          = +0.4375f;  // +0.5 - (2 ^ -4)
1689     }
1690     extensions->multiviewMultisampleANGLE =
1691         ((extensions->multiviewOVR || extensions->multiview2OVR) &&
1692          extensions->textureStorageMultisample2dArrayOES);
1693     extensions->copyTexture3dANGLE      = true;
1694     extensions->textureBorderClampEXT   = true;
1695     extensions->textureBorderClampOES   = true;
1696     extensions->multiDrawIndirectEXT    = true;
1697     extensions->textureMultisampleANGLE = true;
1698     extensions->provokingVertexANGLE    = true;
1699     extensions->blendFuncExtendedEXT    = true;
1700     // http://anglebug.com/4926
1701     extensions->texture3DOES                             = false;
1702     extensions->baseInstanceEXT                          = true;
1703     extensions->baseVertexBaseInstanceANGLE              = true;
1704     extensions->baseVertexBaseInstanceShaderBuiltinANGLE = true;
1705     extensions->drawElementsBaseVertexOES                = true;
1706     extensions->drawElementsBaseVertexEXT                = true;
1707     if (!strstr(description, "Adreno"))
1708     {
1709         extensions->multisampledRenderToTextureEXT = true;
1710     }
1711     extensions->videoTextureWEBGL = true;
1712 
1713     // D3D11 cannot support reading depth texture as a luminance texture.
1714     // It treats it as a red-channel-only texture.
1715     extensions->depthTextureOES = false;
1716 
1717     // readPixels on depth & stencil not working with D3D11 backend.
1718     extensions->readDepthNV         = false;
1719     extensions->readStencilNV       = false;
1720     extensions->depthBufferFloat2NV = false;
1721 
1722     // GL_EXT_clip_control
1723     extensions->clipControlEXT = (featureLevel >= D3D_FEATURE_LEVEL_9_3);
1724 
1725     // GL_APPLE_clip_distance / GL_EXT_clip_cull_distance / GL_ANGLE_clip_cull_distance
1726     extensions->clipDistanceAPPLE         = true;
1727     extensions->clipCullDistanceEXT       = true;
1728     extensions->clipCullDistanceANGLE     = true;
1729     caps->maxClipDistances                = D3D11_CLIP_OR_CULL_DISTANCE_COUNT;
1730     caps->maxCullDistances                = D3D11_CLIP_OR_CULL_DISTANCE_COUNT;
1731     caps->maxCombinedClipAndCullDistances = D3D11_CLIP_OR_CULL_DISTANCE_COUNT;
1732 
1733     // GL_KHR_parallel_shader_compile
1734     extensions->parallelShaderCompileKHR = true;
1735 
1736     // GL_EXT_texture_buffer
1737     extensions->textureBufferEXT = HasTextureBufferSupport(device, renderer11DeviceCaps);
1738 
1739     // GL_OES_texture_buffer
1740     extensions->textureBufferOES = extensions->textureBufferEXT;
1741 
1742     // ANGLE_shader_pixel_local_storage -- fragment shader UAVs appear in D3D 11.0.
1743     if (featureLevel >= D3D_FEATURE_LEVEL_11_0)
1744     {
1745         extensions->shaderPixelLocalStorageANGLE = true;
1746         plsOptions->type                         = ShPixelLocalStorageType::ImageLoadStore;
1747         if (renderer11DeviceCaps.supportsRasterizerOrderViews)
1748         {
1749             extensions->shaderPixelLocalStorageCoherentANGLE = true;
1750             plsOptions->fragmentSyncType = ShFragmentSynchronizationType::RasterizerOrderViews_D3D;
1751         }
1752         // TODO(anglebug.com/7279): If we add RG* support to pixel local storage, these are *NOT*
1753         // in the set of common formats, so we need to query support for each individualy:
1754         // https://learn.microsoft.com/en-us/windows/win32/direct3d11/typed-unordered-access-view-loads
1755         plsOptions->supportsNativeRGBA8ImageFormats =
1756             renderer11DeviceCaps.supportsUAVLoadStoreCommonFormats;
1757     }
1758 
1759     // D3D11 Feature Level 10_0+ uses SV_IsFrontFace in HLSL to emulate gl_FrontFacing.
1760     // D3D11 Feature Level 9_3 doesn't support SV_IsFrontFace, and has no equivalent, so can't
1761     // support gl_FrontFacing.
1762     limitations->noFrontFacingSupport = (featureLevel <= D3D_FEATURE_LEVEL_9_3);
1763 
1764     // D3D11 Feature Level 9_3 doesn't support alpha-to-coverage
1765     limitations->noSampleAlphaToCoverageSupport = (featureLevel <= D3D_FEATURE_LEVEL_9_3);
1766 
1767     // D3D11 has no concept of separate masks and refs for front and back faces in the depth stencil
1768     // state.
1769     limitations->noSeparateStencilRefsAndMasks = true;
1770 
1771     // D3D11 cannot support constant color and alpha blend funcs together
1772     limitations->noSimultaneousConstantColorAndAlphaBlendFunc = true;
1773 
1774     // D3D11 does not support multiple transform feedback outputs writing to the same buffer.
1775     limitations->noDoubleBoundTransformFeedbackBuffers = true;
1776 
1777     // D3D11 does not support vertex attribute aliasing
1778     limitations->noVertexAttributeAliasing = true;
1779 
1780     // D3D11 does not support compressed textures where the base mip level is not a multiple of 4
1781     limitations->compressedBaseMipLevelMultipleOfFour = true;
1782 
1783     if (extensions->textureBufferAny())
1784     {
1785         caps->maxTextureBufferSize = 1 << D3D11_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP;
1786         // this maybe touble for RGB32 format.
1787         caps->textureBufferOffsetAlignment = 16;
1788     }
1789 
1790 #ifdef ANGLE_ENABLE_WINDOWS_UWP
1791     // Setting a non-zero divisor on attribute zero doesn't work on certain Windows Phone 8-era
1792     // devices. We should prevent developers from doing this on ALL Windows Store devices. This will
1793     // maintain consistency across all Windows devices. We allow non-zero divisors on attribute zero
1794     // if the Client Version >= 3, since devices affected by this issue don't support ES3+.
1795     limitations->attributeZeroRequiresZeroDivisorInEXT = true;
1796 #endif
1797 }
1798 
1799 }  // namespace d3d11_gl
1800 
1801 namespace gl_d3d11
1802 {
1803 
ConvertBlendFunc(gl::BlendFactorType glBlend,bool isAlpha)1804 D3D11_BLEND ConvertBlendFunc(gl::BlendFactorType glBlend, bool isAlpha)
1805 {
1806     D3D11_BLEND d3dBlend = D3D11_BLEND_ZERO;
1807 
1808     switch (glBlend)
1809     {
1810         case gl::BlendFactorType::Zero:
1811             d3dBlend = D3D11_BLEND_ZERO;
1812             break;
1813         case gl::BlendFactorType::One:
1814             d3dBlend = D3D11_BLEND_ONE;
1815             break;
1816         case gl::BlendFactorType::SrcColor:
1817             d3dBlend = (isAlpha ? D3D11_BLEND_SRC_ALPHA : D3D11_BLEND_SRC_COLOR);
1818             break;
1819         case gl::BlendFactorType::OneMinusSrcColor:
1820             d3dBlend = (isAlpha ? D3D11_BLEND_INV_SRC_ALPHA : D3D11_BLEND_INV_SRC_COLOR);
1821             break;
1822         case gl::BlendFactorType::DstColor:
1823             d3dBlend = (isAlpha ? D3D11_BLEND_DEST_ALPHA : D3D11_BLEND_DEST_COLOR);
1824             break;
1825         case gl::BlendFactorType::OneMinusDstColor:
1826             d3dBlend = (isAlpha ? D3D11_BLEND_INV_DEST_ALPHA : D3D11_BLEND_INV_DEST_COLOR);
1827             break;
1828         case gl::BlendFactorType::SrcAlpha:
1829             d3dBlend = D3D11_BLEND_SRC_ALPHA;
1830             break;
1831         case gl::BlendFactorType::OneMinusSrcAlpha:
1832             d3dBlend = D3D11_BLEND_INV_SRC_ALPHA;
1833             break;
1834         case gl::BlendFactorType::DstAlpha:
1835             d3dBlend = D3D11_BLEND_DEST_ALPHA;
1836             break;
1837         case gl::BlendFactorType::OneMinusDstAlpha:
1838             d3dBlend = D3D11_BLEND_INV_DEST_ALPHA;
1839             break;
1840         case gl::BlendFactorType::ConstantColor:
1841             d3dBlend = D3D11_BLEND_BLEND_FACTOR;
1842             break;
1843         case gl::BlendFactorType::OneMinusConstantColor:
1844             d3dBlend = D3D11_BLEND_INV_BLEND_FACTOR;
1845             break;
1846         case gl::BlendFactorType::ConstantAlpha:
1847             d3dBlend = D3D11_BLEND_BLEND_FACTOR;
1848             break;
1849         case gl::BlendFactorType::OneMinusConstantAlpha:
1850             d3dBlend = D3D11_BLEND_INV_BLEND_FACTOR;
1851             break;
1852         case gl::BlendFactorType::SrcAlphaSaturate:
1853             d3dBlend = D3D11_BLEND_SRC_ALPHA_SAT;
1854             break;
1855         case gl::BlendFactorType::Src1Color:
1856             d3dBlend = (isAlpha ? D3D11_BLEND_SRC1_ALPHA : D3D11_BLEND_SRC1_COLOR);
1857             break;
1858         case gl::BlendFactorType::Src1Alpha:
1859             d3dBlend = D3D11_BLEND_SRC1_ALPHA;
1860             break;
1861         case gl::BlendFactorType::OneMinusSrc1Color:
1862             d3dBlend = (isAlpha ? D3D11_BLEND_INV_SRC1_ALPHA : D3D11_BLEND_INV_SRC1_COLOR);
1863             break;
1864         case gl::BlendFactorType::OneMinusSrc1Alpha:
1865             d3dBlend = D3D11_BLEND_INV_SRC1_ALPHA;
1866             break;
1867         default:
1868             UNREACHABLE();
1869     }
1870 
1871     return d3dBlend;
1872 }
1873 
ConvertBlendOp(gl::BlendEquationType glBlendOp)1874 D3D11_BLEND_OP ConvertBlendOp(gl::BlendEquationType glBlendOp)
1875 {
1876     D3D11_BLEND_OP d3dBlendOp = D3D11_BLEND_OP_ADD;
1877 
1878     switch (glBlendOp)
1879     {
1880         case gl::BlendEquationType::Add:
1881             d3dBlendOp = D3D11_BLEND_OP_ADD;
1882             break;
1883         case gl::BlendEquationType::Subtract:
1884             d3dBlendOp = D3D11_BLEND_OP_SUBTRACT;
1885             break;
1886         case gl::BlendEquationType::ReverseSubtract:
1887             d3dBlendOp = D3D11_BLEND_OP_REV_SUBTRACT;
1888             break;
1889         case gl::BlendEquationType::Min:
1890             d3dBlendOp = D3D11_BLEND_OP_MIN;
1891             break;
1892         case gl::BlendEquationType::Max:
1893             d3dBlendOp = D3D11_BLEND_OP_MAX;
1894             break;
1895         default:
1896             UNREACHABLE();
1897     }
1898 
1899     return d3dBlendOp;
1900 }
1901 
ConvertColorMask(bool red,bool green,bool blue,bool alpha)1902 UINT8 ConvertColorMask(bool red, bool green, bool blue, bool alpha)
1903 {
1904     UINT8 mask = 0;
1905     if (red)
1906     {
1907         mask |= D3D11_COLOR_WRITE_ENABLE_RED;
1908     }
1909     if (green)
1910     {
1911         mask |= D3D11_COLOR_WRITE_ENABLE_GREEN;
1912     }
1913     if (blue)
1914     {
1915         mask |= D3D11_COLOR_WRITE_ENABLE_BLUE;
1916     }
1917     if (alpha)
1918     {
1919         mask |= D3D11_COLOR_WRITE_ENABLE_ALPHA;
1920     }
1921     return mask;
1922 }
1923 
ConvertCullMode(bool cullEnabled,gl::CullFaceMode cullMode)1924 D3D11_CULL_MODE ConvertCullMode(bool cullEnabled, gl::CullFaceMode cullMode)
1925 {
1926     D3D11_CULL_MODE cull = D3D11_CULL_NONE;
1927 
1928     if (cullEnabled)
1929     {
1930         switch (cullMode)
1931         {
1932             case gl::CullFaceMode::Front:
1933                 cull = D3D11_CULL_FRONT;
1934                 break;
1935             case gl::CullFaceMode::Back:
1936                 cull = D3D11_CULL_BACK;
1937                 break;
1938             case gl::CullFaceMode::FrontAndBack:
1939                 cull = D3D11_CULL_NONE;
1940                 break;
1941             default:
1942                 UNREACHABLE();
1943         }
1944     }
1945     else
1946     {
1947         cull = D3D11_CULL_NONE;
1948     }
1949 
1950     return cull;
1951 }
1952 
ConvertComparison(GLenum comparison)1953 D3D11_COMPARISON_FUNC ConvertComparison(GLenum comparison)
1954 {
1955     D3D11_COMPARISON_FUNC d3dComp = D3D11_COMPARISON_NEVER;
1956     switch (comparison)
1957     {
1958         case GL_NEVER:
1959             d3dComp = D3D11_COMPARISON_NEVER;
1960             break;
1961         case GL_ALWAYS:
1962             d3dComp = D3D11_COMPARISON_ALWAYS;
1963             break;
1964         case GL_LESS:
1965             d3dComp = D3D11_COMPARISON_LESS;
1966             break;
1967         case GL_LEQUAL:
1968             d3dComp = D3D11_COMPARISON_LESS_EQUAL;
1969             break;
1970         case GL_EQUAL:
1971             d3dComp = D3D11_COMPARISON_EQUAL;
1972             break;
1973         case GL_GREATER:
1974             d3dComp = D3D11_COMPARISON_GREATER;
1975             break;
1976         case GL_GEQUAL:
1977             d3dComp = D3D11_COMPARISON_GREATER_EQUAL;
1978             break;
1979         case GL_NOTEQUAL:
1980             d3dComp = D3D11_COMPARISON_NOT_EQUAL;
1981             break;
1982         default:
1983             UNREACHABLE();
1984     }
1985 
1986     return d3dComp;
1987 }
1988 
ConvertDepthMask(bool depthWriteEnabled)1989 D3D11_DEPTH_WRITE_MASK ConvertDepthMask(bool depthWriteEnabled)
1990 {
1991     return depthWriteEnabled ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
1992 }
1993 
ConvertStencilMask(GLuint stencilmask)1994 UINT8 ConvertStencilMask(GLuint stencilmask)
1995 {
1996     return static_cast<UINT8>(stencilmask);
1997 }
1998 
ConvertStencilOp(GLenum stencilOp)1999 D3D11_STENCIL_OP ConvertStencilOp(GLenum stencilOp)
2000 {
2001     D3D11_STENCIL_OP d3dStencilOp = D3D11_STENCIL_OP_KEEP;
2002 
2003     switch (stencilOp)
2004     {
2005         case GL_ZERO:
2006             d3dStencilOp = D3D11_STENCIL_OP_ZERO;
2007             break;
2008         case GL_KEEP:
2009             d3dStencilOp = D3D11_STENCIL_OP_KEEP;
2010             break;
2011         case GL_REPLACE:
2012             d3dStencilOp = D3D11_STENCIL_OP_REPLACE;
2013             break;
2014         case GL_INCR:
2015             d3dStencilOp = D3D11_STENCIL_OP_INCR_SAT;
2016             break;
2017         case GL_DECR:
2018             d3dStencilOp = D3D11_STENCIL_OP_DECR_SAT;
2019             break;
2020         case GL_INVERT:
2021             d3dStencilOp = D3D11_STENCIL_OP_INVERT;
2022             break;
2023         case GL_INCR_WRAP:
2024             d3dStencilOp = D3D11_STENCIL_OP_INCR;
2025             break;
2026         case GL_DECR_WRAP:
2027             d3dStencilOp = D3D11_STENCIL_OP_DECR;
2028             break;
2029         default:
2030             UNREACHABLE();
2031     }
2032 
2033     return d3dStencilOp;
2034 }
2035 
ConvertFilter(GLenum minFilter,GLenum magFilter,float maxAnisotropy,GLenum comparisonMode)2036 D3D11_FILTER ConvertFilter(GLenum minFilter,
2037                            GLenum magFilter,
2038                            float maxAnisotropy,
2039                            GLenum comparisonMode)
2040 {
2041     bool comparison = comparisonMode != GL_NONE;
2042 
2043     if (maxAnisotropy > 1.0f)
2044     {
2045         return D3D11_ENCODE_ANISOTROPIC_FILTER(static_cast<D3D11_COMPARISON_FUNC>(comparison));
2046     }
2047     else
2048     {
2049         D3D11_FILTER_TYPE dxMin = D3D11_FILTER_TYPE_POINT;
2050         D3D11_FILTER_TYPE dxMip = D3D11_FILTER_TYPE_POINT;
2051         switch (minFilter)
2052         {
2053             case GL_NEAREST:
2054                 dxMin = D3D11_FILTER_TYPE_POINT;
2055                 dxMip = D3D11_FILTER_TYPE_POINT;
2056                 break;
2057             case GL_LINEAR:
2058                 dxMin = D3D11_FILTER_TYPE_LINEAR;
2059                 dxMip = D3D11_FILTER_TYPE_POINT;
2060                 break;
2061             case GL_NEAREST_MIPMAP_NEAREST:
2062                 dxMin = D3D11_FILTER_TYPE_POINT;
2063                 dxMip = D3D11_FILTER_TYPE_POINT;
2064                 break;
2065             case GL_LINEAR_MIPMAP_NEAREST:
2066                 dxMin = D3D11_FILTER_TYPE_LINEAR;
2067                 dxMip = D3D11_FILTER_TYPE_POINT;
2068                 break;
2069             case GL_NEAREST_MIPMAP_LINEAR:
2070                 dxMin = D3D11_FILTER_TYPE_POINT;
2071                 dxMip = D3D11_FILTER_TYPE_LINEAR;
2072                 break;
2073             case GL_LINEAR_MIPMAP_LINEAR:
2074                 dxMin = D3D11_FILTER_TYPE_LINEAR;
2075                 dxMip = D3D11_FILTER_TYPE_LINEAR;
2076                 break;
2077             default:
2078                 UNREACHABLE();
2079         }
2080 
2081         D3D11_FILTER_TYPE dxMag = D3D11_FILTER_TYPE_POINT;
2082         switch (magFilter)
2083         {
2084             case GL_NEAREST:
2085                 dxMag = D3D11_FILTER_TYPE_POINT;
2086                 break;
2087             case GL_LINEAR:
2088                 dxMag = D3D11_FILTER_TYPE_LINEAR;
2089                 break;
2090             default:
2091                 UNREACHABLE();
2092         }
2093 
2094         return D3D11_ENCODE_BASIC_FILTER(dxMin, dxMag, dxMip,
2095                                          static_cast<D3D11_COMPARISON_FUNC>(comparison));
2096     }
2097 }
2098 
ConvertTextureWrap(GLenum wrap)2099 D3D11_TEXTURE_ADDRESS_MODE ConvertTextureWrap(GLenum wrap)
2100 {
2101     switch (wrap)
2102     {
2103         case GL_REPEAT:
2104             return D3D11_TEXTURE_ADDRESS_WRAP;
2105         case GL_MIRRORED_REPEAT:
2106             return D3D11_TEXTURE_ADDRESS_MIRROR;
2107         case GL_CLAMP_TO_EDGE:
2108             return D3D11_TEXTURE_ADDRESS_CLAMP;
2109         case GL_CLAMP_TO_BORDER:
2110             return D3D11_TEXTURE_ADDRESS_BORDER;
2111         case GL_MIRROR_CLAMP_TO_EDGE_EXT:
2112             return D3D11_TEXTURE_ADDRESS_MIRROR_ONCE;
2113         default:
2114             UNREACHABLE();
2115     }
2116 
2117     return D3D11_TEXTURE_ADDRESS_WRAP;
2118 }
2119 
ConvertMaxAnisotropy(float maxAnisotropy,D3D_FEATURE_LEVEL featureLevel)2120 UINT ConvertMaxAnisotropy(float maxAnisotropy, D3D_FEATURE_LEVEL featureLevel)
2121 {
2122     return static_cast<UINT>(std::min(maxAnisotropy, d3d11_gl::GetMaximumAnisotropy(featureLevel)));
2123 }
2124 
ConvertQueryType(gl::QueryType type)2125 D3D11_QUERY ConvertQueryType(gl::QueryType type)
2126 {
2127     switch (type)
2128     {
2129         case gl::QueryType::AnySamples:
2130         case gl::QueryType::AnySamplesConservative:
2131             return D3D11_QUERY_OCCLUSION;
2132         case gl::QueryType::TransformFeedbackPrimitivesWritten:
2133             return D3D11_QUERY_SO_STATISTICS;
2134         case gl::QueryType::TimeElapsed:
2135             // Two internal queries are also created for begin/end timestamps
2136             return D3D11_QUERY_TIMESTAMP_DISJOINT;
2137         case gl::QueryType::Timestamp:
2138             // A disjoint query is also created for timestamp
2139             return D3D11_QUERY_TIMESTAMP_DISJOINT;
2140         case gl::QueryType::CommandsCompleted:
2141             return D3D11_QUERY_EVENT;
2142         default:
2143             UNREACHABLE();
2144             return D3D11_QUERY_EVENT;
2145     }
2146 }
2147 
2148 // Get the D3D11 write mask covering all color channels of a given format
GetColorMask(const gl::InternalFormat & format)2149 UINT8 GetColorMask(const gl::InternalFormat &format)
2150 {
2151     return ConvertColorMask(format.redBits > 0, format.greenBits > 0, format.blueBits > 0,
2152                             format.alphaBits > 0);
2153 }
2154 
2155 }  // namespace gl_d3d11
2156 
2157 namespace d3d11
2158 {
2159 
GetDeviceType(ID3D11Device * device)2160 ANGLED3D11DeviceType GetDeviceType(ID3D11Device *device)
2161 {
2162     // Note that this function returns an ANGLED3D11DeviceType rather than a D3D_DRIVER_TYPE value,
2163     // since it is difficult to tell Software and Reference devices apart
2164 
2165     IDXGIDevice *dxgiDevice     = nullptr;
2166     IDXGIAdapter *dxgiAdapter   = nullptr;
2167     IDXGIAdapter2 *dxgiAdapter2 = nullptr;
2168 
2169     ANGLED3D11DeviceType retDeviceType = ANGLE_D3D11_DEVICE_TYPE_UNKNOWN;
2170 
2171     HRESULT hr = device->QueryInterface(__uuidof(IDXGIDevice), (void **)&dxgiDevice);
2172     if (SUCCEEDED(hr))
2173     {
2174         hr = dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void **)&dxgiAdapter);
2175         if (SUCCEEDED(hr))
2176         {
2177             std::wstring adapterString;
2178             HRESULT adapter2hr =
2179                 dxgiAdapter->QueryInterface(__uuidof(dxgiAdapter2), (void **)&dxgiAdapter2);
2180             if (SUCCEEDED(adapter2hr))
2181             {
2182                 // On D3D_FEATURE_LEVEL_9_*, IDXGIAdapter::GetDesc returns "Software Adapter"
2183                 // for the description string. Try to use IDXGIAdapter2::GetDesc2 to get the
2184                 // actual hardware values if possible.
2185                 DXGI_ADAPTER_DESC2 adapterDesc2;
2186                 dxgiAdapter2->GetDesc2(&adapterDesc2);
2187                 adapterString = std::wstring(adapterDesc2.Description);
2188             }
2189             else
2190             {
2191                 DXGI_ADAPTER_DESC adapterDesc;
2192                 dxgiAdapter->GetDesc(&adapterDesc);
2193                 adapterString = std::wstring(adapterDesc.Description);
2194             }
2195 
2196             // Both Reference and Software adapters will be 'Software Adapter'
2197             const bool isSoftwareDevice =
2198                 (adapterString.find(std::wstring(L"Software Adapter")) != std::string::npos);
2199             const bool isNullDevice = (adapterString == L"");
2200             const bool isWARPDevice =
2201                 (adapterString.find(std::wstring(L"Basic Render")) != std::string::npos);
2202 
2203             if (isSoftwareDevice || isNullDevice)
2204             {
2205                 ASSERT(!isWARPDevice);
2206                 retDeviceType = ANGLE_D3D11_DEVICE_TYPE_SOFTWARE_REF_OR_NULL;
2207             }
2208             else if (isWARPDevice)
2209             {
2210                 retDeviceType = ANGLE_D3D11_DEVICE_TYPE_WARP;
2211             }
2212             else
2213             {
2214                 retDeviceType = ANGLE_D3D11_DEVICE_TYPE_HARDWARE;
2215             }
2216         }
2217     }
2218 
2219     SafeRelease(dxgiDevice);
2220     SafeRelease(dxgiAdapter);
2221     SafeRelease(dxgiAdapter2);
2222 
2223     return retDeviceType;
2224 }
2225 
MakeValidSize(bool isImage,DXGI_FORMAT format,GLsizei * requestWidth,GLsizei * requestHeight,int * levelOffset)2226 void MakeValidSize(bool isImage,
2227                    DXGI_FORMAT format,
2228                    GLsizei *requestWidth,
2229                    GLsizei *requestHeight,
2230                    int *levelOffset)
2231 {
2232     const DXGIFormatSize &dxgiFormatInfo = d3d11::GetDXGIFormatSizeInfo(format);
2233     bool validFormat                     = format != DXGI_FORMAT_UNKNOWN;
2234     bool validImage                      = isImage && validFormat;
2235 
2236     int upsampleCount = 0;
2237     // Don't expand the size of full textures that are at least (blockWidth x blockHeight) already.
2238     if (validImage || *requestWidth < static_cast<GLsizei>(dxgiFormatInfo.blockWidth) ||
2239         *requestHeight < static_cast<GLsizei>(dxgiFormatInfo.blockHeight))
2240     {
2241         while (*requestWidth % dxgiFormatInfo.blockWidth != 0 ||
2242                *requestHeight % dxgiFormatInfo.blockHeight != 0)
2243         {
2244             *requestWidth <<= 1;
2245             *requestHeight <<= 1;
2246             upsampleCount++;
2247         }
2248     }
2249     else if (validFormat)
2250     {
2251         if (*requestWidth % dxgiFormatInfo.blockWidth != 0)
2252         {
2253             *requestWidth = roundUp(*requestWidth, static_cast<GLsizei>(dxgiFormatInfo.blockWidth));
2254         }
2255 
2256         if (*requestHeight % dxgiFormatInfo.blockHeight != 0)
2257         {
2258             *requestHeight =
2259                 roundUp(*requestHeight, static_cast<GLsizei>(dxgiFormatInfo.blockHeight));
2260         }
2261     }
2262 
2263     if (levelOffset)
2264     {
2265         *levelOffset = upsampleCount;
2266     }
2267 }
2268 
GenerateInitialTextureData(const gl::Context * context,GLint internalFormat,const Renderer11DeviceCaps & renderer11DeviceCaps,GLuint width,GLuint height,GLuint depth,GLuint mipLevels,gl::TexLevelArray<D3D11_SUBRESOURCE_DATA> * outSubresourceData)2269 angle::Result GenerateInitialTextureData(
2270     const gl::Context *context,
2271     GLint internalFormat,
2272     const Renderer11DeviceCaps &renderer11DeviceCaps,
2273     GLuint width,
2274     GLuint height,
2275     GLuint depth,
2276     GLuint mipLevels,
2277     gl::TexLevelArray<D3D11_SUBRESOURCE_DATA> *outSubresourceData)
2278 {
2279     const d3d11::Format &d3dFormatInfo = d3d11::Format::Get(internalFormat, renderer11DeviceCaps);
2280     ASSERT(d3dFormatInfo.dataInitializerFunction != nullptr);
2281 
2282     const d3d11::DXGIFormatSize &dxgiFormatInfo =
2283         d3d11::GetDXGIFormatSizeInfo(d3dFormatInfo.texFormat);
2284 
2285     using CheckedSize        = angle::CheckedNumeric<size_t>;
2286     CheckedSize rowPitch     = CheckedSize(dxgiFormatInfo.pixelBytes) * CheckedSize(width);
2287     CheckedSize depthPitch   = rowPitch * CheckedSize(height);
2288     CheckedSize maxImageSize = depthPitch * CheckedSize(depth);
2289 
2290     Context11 *context11 = GetImplAs<Context11>(context);
2291     ANGLE_CHECK_GL_ALLOC(context11, maxImageSize.IsValid());
2292 
2293     angle::MemoryBuffer *scratchBuffer = nullptr;
2294     ANGLE_CHECK_GL_ALLOC(context11,
2295                          context->getScratchBuffer(maxImageSize.ValueOrDie(), &scratchBuffer));
2296 
2297     d3dFormatInfo.dataInitializerFunction(width, height, depth, scratchBuffer->data(),
2298                                           rowPitch.ValueOrDie(), depthPitch.ValueOrDie());
2299 
2300     for (unsigned int i = 0; i < mipLevels; i++)
2301     {
2302         unsigned int mipWidth  = std::max(width >> i, 1U);
2303         unsigned int mipHeight = std::max(height >> i, 1U);
2304 
2305         using CheckedUINT         = angle::CheckedNumeric<UINT>;
2306         CheckedUINT mipRowPitch   = CheckedUINT(dxgiFormatInfo.pixelBytes) * CheckedUINT(mipWidth);
2307         CheckedUINT mipDepthPitch = mipRowPitch * CheckedUINT(mipHeight);
2308 
2309         ANGLE_CHECK_GL_ALLOC(context11, mipRowPitch.IsValid() && mipDepthPitch.IsValid());
2310 
2311         outSubresourceData->at(i).pSysMem          = scratchBuffer->data();
2312         outSubresourceData->at(i).SysMemPitch      = mipRowPitch.ValueOrDie();
2313         outSubresourceData->at(i).SysMemSlicePitch = mipDepthPitch.ValueOrDie();
2314     }
2315 
2316     return angle::Result::Continue;
2317 }
2318 
GetPrimitiveRestartIndex()2319 UINT GetPrimitiveRestartIndex()
2320 {
2321     return std::numeric_limits<UINT>::max();
2322 }
2323 
SetPositionTexCoordVertex(PositionTexCoordVertex * vertex,float x,float y,float u,float v)2324 void SetPositionTexCoordVertex(PositionTexCoordVertex *vertex, float x, float y, float u, float v)
2325 {
2326     vertex->x = x;
2327     vertex->y = y;
2328     vertex->u = u;
2329     vertex->v = v;
2330 }
2331 
SetPositionLayerTexCoord3DVertex(PositionLayerTexCoord3DVertex * vertex,float x,float y,unsigned int layer,float u,float v,float s)2332 void SetPositionLayerTexCoord3DVertex(PositionLayerTexCoord3DVertex *vertex,
2333                                       float x,
2334                                       float y,
2335                                       unsigned int layer,
2336                                       float u,
2337                                       float v,
2338                                       float s)
2339 {
2340     vertex->x = x;
2341     vertex->y = y;
2342     vertex->l = layer;
2343     vertex->u = u;
2344     vertex->v = v;
2345     vertex->s = s;
2346 }
2347 
BlendStateKey()2348 BlendStateKey::BlendStateKey()
2349 {
2350     memset(this, 0, sizeof(BlendStateKey));
2351     blendStateExt = gl::BlendStateExt();
2352 }
2353 
BlendStateKey(const BlendStateKey & other)2354 BlendStateKey::BlendStateKey(const BlendStateKey &other)
2355 {
2356     memcpy(this, &other, sizeof(BlendStateKey));
2357 }
2358 
operator ==(const BlendStateKey & a,const BlendStateKey & b)2359 bool operator==(const BlendStateKey &a, const BlendStateKey &b)
2360 {
2361     return memcmp(&a, &b, sizeof(BlendStateKey)) == 0;
2362 }
2363 
operator !=(const BlendStateKey & a,const BlendStateKey & b)2364 bool operator!=(const BlendStateKey &a, const BlendStateKey &b)
2365 {
2366     return !(a == b);
2367 }
2368 
RasterizerStateKey()2369 RasterizerStateKey::RasterizerStateKey()
2370 {
2371     memset(this, 0, sizeof(RasterizerStateKey));
2372 }
2373 
operator ==(const RasterizerStateKey & a,const RasterizerStateKey & b)2374 bool operator==(const RasterizerStateKey &a, const RasterizerStateKey &b)
2375 {
2376     return memcmp(&a, &b, sizeof(RasterizerStateKey)) == 0;
2377 }
2378 
operator !=(const RasterizerStateKey & a,const RasterizerStateKey & b)2379 bool operator!=(const RasterizerStateKey &a, const RasterizerStateKey &b)
2380 {
2381     return !(a == b);
2382 }
2383 
SetDebugName(ID3D11DeviceChild * resource,const char * internalName,const std::string * khrDebugName)2384 HRESULT SetDebugName(ID3D11DeviceChild *resource,
2385                      const char *internalName,
2386                      const std::string *khrDebugName)
2387 {
2388     // Prepend ANGLE to separate names from other components in the same process.
2389     std::string d3dName = "ANGLE";
2390     bool sendNameToD3D  = false;
2391     if (internalName && internalName[0] != '\0')
2392     {
2393         d3dName += std::string("_") + internalName;
2394         sendNameToD3D = true;
2395     }
2396     if (khrDebugName && !khrDebugName->empty())
2397     {
2398         d3dName += std::string("_") + *khrDebugName;
2399         sendNameToD3D = true;
2400     }
2401     // If both internalName and khrDebugName are empty, avoid sending the string to d3d.
2402     if (sendNameToD3D)
2403     {
2404         return resource->SetPrivateData(WKPDID_D3DDebugObjectName,
2405                                         static_cast<UINT>(d3dName.size()), d3dName.c_str());
2406     }
2407     return S_OK;
2408 }
2409 
2410 // Keep this in cpp file where it has visibility of Renderer11.h, otherwise calling
2411 // allocateResource is only compatible with Clang and MSVS, which support calling a
2412 // method on a forward declared class in a template.
2413 template <ResourceType ResourceT>
resolveImpl(d3d::Context * context,Renderer11 * renderer,const GetDescType<ResourceT> & desc,GetInitDataType<ResourceT> * initData,const char * name)2414 angle::Result LazyResource<ResourceT>::resolveImpl(d3d::Context *context,
2415                                                    Renderer11 *renderer,
2416                                                    const GetDescType<ResourceT> &desc,
2417                                                    GetInitDataType<ResourceT> *initData,
2418                                                    const char *name)
2419 {
2420     if (!mResource.valid())
2421     {
2422         ANGLE_TRY(renderer->allocateResource(context, desc, initData, &mResource));
2423         mResource.setInternalName(name);
2424     }
2425     return angle::Result::Continue;
2426 }
2427 
2428 template angle::Result LazyResource<ResourceType::BlendState>::resolveImpl(
2429     d3d::Context *context,
2430     Renderer11 *renderer,
2431     const D3D11_BLEND_DESC &desc,
2432     void *initData,
2433     const char *name);
2434 template angle::Result LazyResource<ResourceType::ComputeShader>::resolveImpl(
2435     d3d::Context *context,
2436     Renderer11 *renderer,
2437     const ShaderData &desc,
2438     void *initData,
2439     const char *name);
2440 template angle::Result LazyResource<ResourceType::GeometryShader>::resolveImpl(
2441     d3d::Context *context,
2442     Renderer11 *renderer,
2443     const ShaderData &desc,
2444     const std::vector<D3D11_SO_DECLARATION_ENTRY> *initData,
2445     const char *name);
2446 template angle::Result LazyResource<ResourceType::InputLayout>::resolveImpl(
2447     d3d::Context *context,
2448     Renderer11 *renderer,
2449     const InputElementArray &desc,
2450     const ShaderData *initData,
2451     const char *name);
2452 template angle::Result LazyResource<ResourceType::PixelShader>::resolveImpl(d3d::Context *context,
2453                                                                             Renderer11 *renderer,
2454                                                                             const ShaderData &desc,
2455                                                                             void *initData,
2456                                                                             const char *name);
2457 template angle::Result LazyResource<ResourceType::VertexShader>::resolveImpl(d3d::Context *context,
2458                                                                              Renderer11 *renderer,
2459                                                                              const ShaderData &desc,
2460                                                                              void *initData,
2461                                                                              const char *name);
2462 
LazyInputLayout(const D3D11_INPUT_ELEMENT_DESC * inputDesc,size_t inputDescLen,const BYTE * byteCode,size_t byteCodeLen,const char * debugName)2463 LazyInputLayout::LazyInputLayout(const D3D11_INPUT_ELEMENT_DESC *inputDesc,
2464                                  size_t inputDescLen,
2465                                  const BYTE *byteCode,
2466                                  size_t byteCodeLen,
2467                                  const char *debugName)
2468     : mInputDesc(inputDesc, inputDescLen), mByteCode(byteCode, byteCodeLen), mDebugName(debugName)
2469 {}
2470 
~LazyInputLayout()2471 LazyInputLayout::~LazyInputLayout() {}
2472 
resolve(d3d::Context * context,Renderer11 * renderer)2473 angle::Result LazyInputLayout::resolve(d3d::Context *context, Renderer11 *renderer)
2474 {
2475     return resolveImpl(context, renderer, mInputDesc, &mByteCode, mDebugName);
2476 }
2477 
LazyBlendState(const D3D11_BLEND_DESC & desc,const char * debugName)2478 LazyBlendState::LazyBlendState(const D3D11_BLEND_DESC &desc, const char *debugName)
2479     : mDesc(desc), mDebugName(debugName)
2480 {}
2481 
resolve(d3d::Context * context,Renderer11 * renderer)2482 angle::Result LazyBlendState::resolve(d3d::Context *context, Renderer11 *renderer)
2483 {
2484     return resolveImpl(context, renderer, mDesc, nullptr, mDebugName);
2485 }
2486 
InitializeFeatures(const Renderer11DeviceCaps & deviceCaps,const DXGI_ADAPTER_DESC & adapterDesc,angle::FeaturesD3D * features)2487 void InitializeFeatures(const Renderer11DeviceCaps &deviceCaps,
2488                         const DXGI_ADAPTER_DESC &adapterDesc,
2489                         angle::FeaturesD3D *features)
2490 {
2491     bool isNvidia          = IsNvidia(adapterDesc.VendorId);
2492     bool isIntel           = IsIntel(adapterDesc.VendorId);
2493     bool isSkylake         = false;
2494     bool isBroadwell       = false;
2495     bool isHaswell         = false;
2496     bool isIvyBridge       = false;
2497     bool isAMD             = IsAMD(adapterDesc.VendorId);
2498     bool isFeatureLevel9_3 = deviceCaps.featureLevel <= D3D_FEATURE_LEVEL_9_3;
2499 
2500     IntelDriverVersion capsVersion = IntelDriverVersion(0);
2501     if (isIntel)
2502     {
2503         capsVersion = d3d11_gl::GetIntelDriverVersion(deviceCaps.driverVersion);
2504 
2505         isSkylake   = IsSkylake(adapterDesc.DeviceId);
2506         isBroadwell = IsBroadwell(adapterDesc.DeviceId);
2507         isHaswell   = IsHaswell(adapterDesc.DeviceId);
2508         isIvyBridge = IsIvyBridge(adapterDesc.DeviceId);
2509     }
2510 
2511     if (isNvidia)
2512     {
2513         // TODO(jmadill): Narrow problematic driver range.
2514         bool driverVersionValid = deviceCaps.driverVersion.valid();
2515         if (driverVersionValid)
2516         {
2517             WORD part1 = HIWORD(deviceCaps.driverVersion.value().LowPart);
2518             WORD part2 = LOWORD(deviceCaps.driverVersion.value().LowPart);
2519 
2520             // Disable the workaround to fix a second driver bug on newer NVIDIA.
2521             ANGLE_FEATURE_CONDITION(
2522                 features, depthStencilBlitExtraCopy,
2523                 (part1 <= 13u && part2 < 6881) && isNvidia && driverVersionValid);
2524         }
2525         else
2526         {
2527             ANGLE_FEATURE_CONDITION(features, depthStencilBlitExtraCopy,
2528                                     isNvidia && !driverVersionValid);
2529         }
2530     }
2531 
2532     ANGLE_FEATURE_CONDITION(features, mrtPerfWorkaround, true);
2533     ANGLE_FEATURE_CONDITION(features, zeroMaxLodWorkaround, isFeatureLevel9_3);
2534     ANGLE_FEATURE_CONDITION(features, useInstancedPointSpriteEmulation, isFeatureLevel9_3);
2535     ANGLE_FEATURE_CONDITION(features, allowES3OnFL100, false);
2536 
2537     // TODO(jmadill): Disable workaround when we have a fixed compiler DLL.
2538     ANGLE_FEATURE_CONDITION(features, expandIntegerPowExpressions, true);
2539 
2540     ANGLE_FEATURE_CONDITION(features, flushAfterEndingTransformFeedback, isNvidia);
2541     ANGLE_FEATURE_CONDITION(features, getDimensionsIgnoresBaseLevel, isNvidia);
2542     ANGLE_FEATURE_CONDITION(features, skipVSConstantRegisterZero, isNvidia);
2543     ANGLE_FEATURE_CONDITION(features, forceAtomicValueResolution, isNvidia);
2544 
2545     ANGLE_FEATURE_CONDITION(features, preAddTexelFetchOffsets, isIntel);
2546     ANGLE_FEATURE_CONDITION(features, useSystemMemoryForConstantBuffers, isIntel);
2547 
2548     ANGLE_FEATURE_CONDITION(features, callClearTwice,
2549                             isIntel && isSkylake && capsVersion >= IntelDriverVersion(160000) &&
2550                                 capsVersion < IntelDriverVersion(164771));
2551     ANGLE_FEATURE_CONDITION(features, emulateIsnanFloat,
2552                             isIntel && isSkylake && capsVersion >= IntelDriverVersion(160000) &&
2553                                 capsVersion < IntelDriverVersion(164542));
2554     ANGLE_FEATURE_CONDITION(features, rewriteUnaryMinusOperator,
2555                             isIntel && (isBroadwell || isHaswell) &&
2556                                 capsVersion >= IntelDriverVersion(150000) &&
2557                                 capsVersion < IntelDriverVersion(154624));
2558 
2559     ANGLE_FEATURE_CONDITION(features, addMockTextureNoRenderTarget,
2560                             isIntel && capsVersion >= IntelDriverVersion(160000) &&
2561                                 capsVersion < IntelDriverVersion(164815));
2562 
2563     // Haswell/Ivybridge drivers occasionally corrupt (small?) (vertex?) texture data uploads.
2564     ANGLE_FEATURE_CONDITION(features, setDataFasterThanImageUpload,
2565                             !(isIvyBridge || isBroadwell || isHaswell));
2566 
2567     ANGLE_FEATURE_CONDITION(features, disableB5G6R5Support,
2568                             (isIntel && capsVersion >= IntelDriverVersion(150000) &&
2569                              capsVersion < IntelDriverVersion(154539)) ||
2570                                 isAMD);
2571 
2572     // TODO(jmadill): Disable when we have a fixed driver version.
2573     // The tiny stencil texture workaround involves using CopySubresource or UpdateSubresource on a
2574     // depth stencil texture.  This is not allowed until feature level 10.1 but since it is not
2575     // possible to support ES3 on these devices, there is no need for the workaround to begin with
2576     // (anglebug.com/1572).
2577     ANGLE_FEATURE_CONDITION(features, emulateTinyStencilTextures,
2578                             isAMD && !(deviceCaps.featureLevel < D3D_FEATURE_LEVEL_10_1));
2579 
2580     // If the VPAndRTArrayIndexFromAnyShaderFeedingRasterizer feature is not available, we have to
2581     // select the viewport / RT array index in the geometry shader.
2582     ANGLE_FEATURE_CONDITION(features, selectViewInGeometryShader,
2583                             !deviceCaps.supportsVpRtIndexWriteFromVertexShader);
2584 
2585     // NVidia drivers have no trouble clearing textures without showing corruption.
2586     // Intel and AMD drivers that have trouble have been blocklisted by Chromium. In the case of
2587     // Intel, they've been blocklisted to the DX9 runtime.
2588     ANGLE_FEATURE_CONDITION(features, allowClearForRobustResourceInit, true);
2589 
2590     // Allow translating uniform block to StructuredBuffer on Windows 10. This is targeted
2591     // to work around a slow fxc compile performance issue with dynamic uniform indexing.
2592     ANGLE_FEATURE_CONDITION(features, allowTranslateUniformBlockToStructuredBuffer,
2593                             IsWindows10OrLater());
2594 
2595     // D3D11 Feature Levels 9_3 and below do not support non-constant loop indexing and require
2596     // additional
2597     // pre-validation of the shader at compile time to produce a better error message.
2598     ANGLE_FEATURE_CONDITION(features, supportsNonConstantLoopIndexing, !isFeatureLevel9_3);
2599 }
2600 
InitializeFrontendFeatures(const DXGI_ADAPTER_DESC & adapterDesc,angle::FrontendFeatures * features)2601 void InitializeFrontendFeatures(const DXGI_ADAPTER_DESC &adapterDesc,
2602                                 angle::FrontendFeatures *features)
2603 {
2604     bool isAMD = IsAMD(adapterDesc.VendorId);
2605 
2606     ANGLE_FEATURE_CONDITION(features, forceDepthAttachmentInitOnClear, isAMD);
2607 
2608     // The D3D backend's handling of compile and link is thread-safe
2609     ANGLE_FEATURE_CONDITION(features, compileJobIsThreadSafe, true);
2610     ANGLE_FEATURE_CONDITION(features, linkJobIsThreadSafe, true);
2611 }
2612 
InitConstantBufferDesc(D3D11_BUFFER_DESC * constantBufferDescription,size_t byteWidth)2613 void InitConstantBufferDesc(D3D11_BUFFER_DESC *constantBufferDescription, size_t byteWidth)
2614 {
2615     constantBufferDescription->ByteWidth           = static_cast<UINT>(byteWidth);
2616     constantBufferDescription->Usage               = D3D11_USAGE_DYNAMIC;
2617     constantBufferDescription->BindFlags           = D3D11_BIND_CONSTANT_BUFFER;
2618     constantBufferDescription->CPUAccessFlags      = D3D11_CPU_ACCESS_WRITE;
2619     constantBufferDescription->MiscFlags           = 0;
2620     constantBufferDescription->StructureByteStride = 0;
2621 }
2622 
2623 }  // namespace d3d11
2624 
2625 // TextureHelper11 implementation.
TextureHelper11()2626 TextureHelper11::TextureHelper11() : mFormatSet(nullptr), mSampleCount(0) {}
2627 
TextureHelper11(TextureHelper11 && toCopy)2628 TextureHelper11::TextureHelper11(TextureHelper11 &&toCopy) : TextureHelper11()
2629 {
2630     *this = std::move(toCopy);
2631 }
2632 
TextureHelper11(const TextureHelper11 & other)2633 TextureHelper11::TextureHelper11(const TextureHelper11 &other)
2634     : mFormatSet(other.mFormatSet), mExtents(other.mExtents), mSampleCount(other.mSampleCount)
2635 {
2636     mData = other.mData;
2637 }
2638 
~TextureHelper11()2639 TextureHelper11::~TextureHelper11() {}
2640 
getDesc(D3D11_TEXTURE2D_DESC * desc) const2641 void TextureHelper11::getDesc(D3D11_TEXTURE2D_DESC *desc) const
2642 {
2643     static_cast<ID3D11Texture2D *>(mData->object)->GetDesc(desc);
2644 }
2645 
getDesc(D3D11_TEXTURE3D_DESC * desc) const2646 void TextureHelper11::getDesc(D3D11_TEXTURE3D_DESC *desc) const
2647 {
2648     static_cast<ID3D11Texture3D *>(mData->object)->GetDesc(desc);
2649 }
2650 
getDesc(D3D11_BUFFER_DESC * desc) const2651 void TextureHelper11::getDesc(D3D11_BUFFER_DESC *desc) const
2652 {
2653     static_cast<ID3D11Buffer *>(mData->object)->GetDesc(desc);
2654 }
2655 
initDesc(const D3D11_TEXTURE2D_DESC & desc2D)2656 void TextureHelper11::initDesc(const D3D11_TEXTURE2D_DESC &desc2D)
2657 {
2658     mData->resourceType = ResourceType::Texture2D;
2659     mExtents.width      = static_cast<int>(desc2D.Width);
2660     mExtents.height     = static_cast<int>(desc2D.Height);
2661     mExtents.depth      = 1;
2662     mSampleCount        = desc2D.SampleDesc.Count;
2663 }
2664 
initDesc(const D3D11_TEXTURE3D_DESC & desc3D)2665 void TextureHelper11::initDesc(const D3D11_TEXTURE3D_DESC &desc3D)
2666 {
2667     mData->resourceType = ResourceType::Texture3D;
2668     mExtents.width      = static_cast<int>(desc3D.Width);
2669     mExtents.height     = static_cast<int>(desc3D.Height);
2670     mExtents.depth      = static_cast<int>(desc3D.Depth);
2671     mSampleCount        = 1;
2672 }
2673 
initDesc(const D3D11_BUFFER_DESC & descBuffer)2674 void TextureHelper11::initDesc(const D3D11_BUFFER_DESC &descBuffer)
2675 {
2676     mData->resourceType = ResourceType::Buffer;
2677     mExtents.width      = static_cast<int>(descBuffer.ByteWidth);
2678     mExtents.height     = 1;
2679     mExtents.depth      = 1;
2680     mSampleCount        = 1;
2681 }
2682 
operator =(TextureHelper11 && other)2683 TextureHelper11 &TextureHelper11::operator=(TextureHelper11 &&other)
2684 {
2685     std::swap(mData, other.mData);
2686     std::swap(mExtents, other.mExtents);
2687     std::swap(mFormatSet, other.mFormatSet);
2688     std::swap(mSampleCount, other.mSampleCount);
2689     return *this;
2690 }
2691 
operator =(const TextureHelper11 & other)2692 TextureHelper11 &TextureHelper11::operator=(const TextureHelper11 &other)
2693 {
2694     mData        = other.mData;
2695     mExtents     = other.mExtents;
2696     mFormatSet   = other.mFormatSet;
2697     mSampleCount = other.mSampleCount;
2698     return *this;
2699 }
2700 
operator ==(const TextureHelper11 & other) const2701 bool TextureHelper11::operator==(const TextureHelper11 &other) const
2702 {
2703     return mData->object == other.mData->object;
2704 }
2705 
operator !=(const TextureHelper11 & other) const2706 bool TextureHelper11::operator!=(const TextureHelper11 &other) const
2707 {
2708     return mData->object != other.mData->object;
2709 }
2710 
UsePresentPathFast(const Renderer11 * renderer,const gl::FramebufferAttachment * framebufferAttachment)2711 bool UsePresentPathFast(const Renderer11 *renderer,
2712                         const gl::FramebufferAttachment *framebufferAttachment)
2713 {
2714     if (framebufferAttachment == nullptr)
2715     {
2716         return false;
2717     }
2718 
2719     return (framebufferAttachment->type() == GL_FRAMEBUFFER_DEFAULT &&
2720             renderer->presentPathFastEnabled());
2721 }
2722 
UsePrimitiveRestartWorkaround(bool primitiveRestartFixedIndexEnabled,gl::DrawElementsType type)2723 bool UsePrimitiveRestartWorkaround(bool primitiveRestartFixedIndexEnabled,
2724                                    gl::DrawElementsType type)
2725 {
2726     // We should never have to deal with primitive restart workaround issue with GL_UNSIGNED_INT
2727     // indices, since we restrict it via MAX_ELEMENT_INDEX.
2728     return (!primitiveRestartFixedIndexEnabled && type == gl::DrawElementsType::UnsignedShort);
2729 }
2730 
ClassifyIndexStorage(const gl::State & glState,const gl::Buffer * elementArrayBuffer,gl::DrawElementsType elementType,gl::DrawElementsType destElementType,unsigned int offset)2731 IndexStorageType ClassifyIndexStorage(const gl::State &glState,
2732                                       const gl::Buffer *elementArrayBuffer,
2733                                       gl::DrawElementsType elementType,
2734                                       gl::DrawElementsType destElementType,
2735                                       unsigned int offset)
2736 {
2737     // No buffer bound means we are streaming from a client pointer.
2738     if (!elementArrayBuffer || !IsOffsetAligned(elementType, offset))
2739     {
2740         return IndexStorageType::Dynamic;
2741     }
2742 
2743     // The buffer can be used directly if the storage supports it and no translation needed.
2744     BufferD3D *bufferD3D = GetImplAs<BufferD3D>(elementArrayBuffer);
2745     if (bufferD3D->supportsDirectBinding() && destElementType == elementType)
2746     {
2747         return IndexStorageType::Direct;
2748     }
2749 
2750     // Use a static copy when available.
2751     StaticIndexBufferInterface *staticBuffer = bufferD3D->getStaticIndexBuffer();
2752     if (staticBuffer != nullptr)
2753     {
2754         return IndexStorageType::Static;
2755     }
2756 
2757     // Static buffer not available, fall back to streaming.
2758     return IndexStorageType::Dynamic;
2759 }
2760 
SwizzleRequired(const gl::TextureState & textureState)2761 bool SwizzleRequired(const gl::TextureState &textureState)
2762 {
2763     // When sampling stencil, a swizzle is needed to move the stencil channel from G to R.
2764     return textureState.swizzleRequired() || textureState.isStencilMode();
2765 }
2766 
GetEffectiveSwizzle(const gl::TextureState & textureState)2767 gl::SwizzleState GetEffectiveSwizzle(const gl::TextureState &textureState)
2768 {
2769     const gl::SwizzleState &swizzle = textureState.getSwizzleState();
2770     if (textureState.isStencilMode())
2771     {
2772         // Per GL semantics, the stencil value should be in the red channel, while D3D11 formats
2773         // leave stencil in the green channel. So copy the stencil value from green to all
2774         // components requesting red. Green and blue become zero; alpha becomes one.
2775         std::unordered_map<GLenum, GLenum> map = {{GL_RED, GL_GREEN}, {GL_GREEN, GL_ZERO},
2776                                                   {GL_BLUE, GL_ZERO}, {GL_ALPHA, GL_ONE},
2777                                                   {GL_ZERO, GL_ZERO}, {GL_ONE, GL_ONE}};
2778 
2779         return gl::SwizzleState(map[swizzle.swizzleRed], map[swizzle.swizzleGreen],
2780                                 map[swizzle.swizzleBlue], map[swizzle.swizzleAlpha]);
2781     }
2782     return swizzle;
2783 }
2784 
2785 }  // namespace rx
2786