1 //
2 // Copyright 2014 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 // DynamicHLSL.cpp: Implementation for link and run-time HLSL generation
7 //
8
9 #include "libANGLE/renderer/d3d/DynamicHLSL.h"
10
11 #include "common/string_utils.h"
12 #include "common/utilities.h"
13 #include "compiler/translator/blocklayoutHLSL.h"
14 #include "libANGLE/Context.h"
15 #include "libANGLE/Program.h"
16 #include "libANGLE/Shader.h"
17 #include "libANGLE/VaryingPacking.h"
18 #include "libANGLE/formatutils.h"
19 #include "libANGLE/renderer/d3d/ProgramD3D.h"
20 #include "libANGLE/renderer/d3d/RendererD3D.h"
21 #include "libANGLE/renderer/d3d/ShaderD3D.h"
22
23 using namespace gl;
24
25 namespace rx
26 {
27
28 namespace
29 {
30
HLSLComponentTypeString(GLenum componentType)31 const char *HLSLComponentTypeString(GLenum componentType)
32 {
33 switch (componentType)
34 {
35 case GL_UNSIGNED_INT:
36 return "uint";
37 case GL_INT:
38 return "int";
39 case GL_UNSIGNED_NORMALIZED:
40 case GL_SIGNED_NORMALIZED:
41 case GL_FLOAT:
42 return "float";
43 default:
44 UNREACHABLE();
45 return "not-component-type";
46 }
47 }
48
HLSLComponentTypeString(std::ostringstream & ostream,GLenum componentType,int componentCount)49 void HLSLComponentTypeString(std::ostringstream &ostream, GLenum componentType, int componentCount)
50 {
51 ostream << HLSLComponentTypeString(componentType);
52 if (componentCount > 1)
53 {
54 ostream << componentCount;
55 }
56 }
57
HLSLMatrixTypeString(GLenum type)58 const char *HLSLMatrixTypeString(GLenum type)
59 {
60 switch (type)
61 {
62 case GL_FLOAT_MAT2:
63 return "float2x2";
64 case GL_FLOAT_MAT3:
65 return "float3x3";
66 case GL_FLOAT_MAT4:
67 return "float4x4";
68 case GL_FLOAT_MAT2x3:
69 return "float2x3";
70 case GL_FLOAT_MAT3x2:
71 return "float3x2";
72 case GL_FLOAT_MAT2x4:
73 return "float2x4";
74 case GL_FLOAT_MAT4x2:
75 return "float4x2";
76 case GL_FLOAT_MAT3x4:
77 return "float3x4";
78 case GL_FLOAT_MAT4x3:
79 return "float4x3";
80 default:
81 UNREACHABLE();
82 return "not-matrix-type";
83 }
84 }
85
HLSLTypeString(std::ostringstream & ostream,GLenum type)86 void HLSLTypeString(std::ostringstream &ostream, GLenum type)
87 {
88 if (gl::IsMatrixType(type))
89 {
90 ostream << HLSLMatrixTypeString(type);
91 return;
92 }
93
94 HLSLComponentTypeString(ostream, gl::VariableComponentType(type),
95 gl::VariableComponentCount(type));
96 }
97
FindOutputAtLocation(const std::vector<PixelShaderOutputVariable> & outputVariables,unsigned int location,size_t index=0)98 const PixelShaderOutputVariable *FindOutputAtLocation(
99 const std::vector<PixelShaderOutputVariable> &outputVariables,
100 unsigned int location,
101 size_t index = 0)
102 {
103 for (auto &outputVar : outputVariables)
104 {
105 if (outputVar.outputLocation == location && outputVar.outputIndex == index)
106 {
107 return &outputVar;
108 }
109 }
110
111 return nullptr;
112 }
113
WriteArrayString(std::ostringstream & strstr,unsigned int i)114 void WriteArrayString(std::ostringstream &strstr, unsigned int i)
115 {
116 static_assert(GL_INVALID_INDEX == UINT_MAX,
117 "GL_INVALID_INDEX must be equal to the max unsigned int.");
118 if (i == UINT_MAX)
119 {
120 return;
121 }
122
123 strstr << "[";
124 strstr << i;
125 strstr << "]";
126 }
127
128 constexpr const char *VERTEX_ATTRIBUTE_STUB_STRING = "@@ VERTEX ATTRIBUTES @@";
129 constexpr const char *VERTEX_OUTPUT_STUB_STRING = "@@ VERTEX OUTPUT @@";
130 constexpr const char *PIXEL_OUTPUT_STUB_STRING = "@@ PIXEL OUTPUT @@";
131 constexpr const char *PIXEL_MAIN_PARAMETERS_STUB_STRING = "@@ PIXEL MAIN PARAMETERS @@";
132 constexpr const char *MAIN_PROLOGUE_STUB_STRING = "@@ MAIN PROLOGUE @@";
133 } // anonymous namespace
134
135 // BuiltinInfo implementation
136
137 BuiltinInfo::BuiltinInfo() = default;
138 BuiltinInfo::~BuiltinInfo() = default;
139
140 // DynamicHLSL implementation
141
DynamicHLSL(RendererD3D * const renderer)142 DynamicHLSL::DynamicHLSL(RendererD3D *const renderer) : mRenderer(renderer) {}
143
generateVertexShaderForInputLayout(const std::string & sourceShader,const InputLayout & inputLayout,const std::vector<sh::ShaderVariable> & shaderAttributes) const144 std::string DynamicHLSL::generateVertexShaderForInputLayout(
145 const std::string &sourceShader,
146 const InputLayout &inputLayout,
147 const std::vector<sh::ShaderVariable> &shaderAttributes) const
148 {
149 std::ostringstream structStream;
150 std::ostringstream initStream;
151
152 structStream << "struct VS_INPUT\n"
153 << "{\n";
154
155 int semanticIndex = 0;
156 unsigned int inputIndex = 0;
157
158 // If gl_PointSize is used in the shader then pointsprites rendering is expected.
159 // If the renderer does not support Geometry shaders then Instanced PointSprite emulation
160 // must be used.
161 bool usesPointSize = sourceShader.find("GL_USES_POINT_SIZE") != std::string::npos;
162 bool useInstancedPointSpriteEmulation =
163 usesPointSize && mRenderer->getFeatures().useInstancedPointSpriteEmulation.enabled;
164
165 // Instanced PointSprite emulation requires additional entries in the
166 // VS_INPUT structure to support the vertices that make up the quad vertices.
167 // These values must be in sync with the cooresponding values added during inputlayout creation
168 // in InputLayoutCache::applyVertexBuffers().
169 //
170 // The additional entries must appear first in the VS_INPUT layout because
171 // Windows Phone 8 era devices require per vertex data to physically come
172 // before per instance data in the shader.
173 if (useInstancedPointSpriteEmulation)
174 {
175 structStream << " float3 spriteVertexPos : SPRITEPOSITION0;\n"
176 << " float2 spriteTexCoord : SPRITETEXCOORD0;\n";
177 }
178
179 for (size_t attributeIndex = 0; attributeIndex < shaderAttributes.size(); ++attributeIndex)
180 {
181 const sh::ShaderVariable &shaderAttribute = shaderAttributes[attributeIndex];
182 if (!shaderAttribute.name.empty())
183 {
184 ASSERT(inputIndex < MAX_VERTEX_ATTRIBS);
185 angle::FormatID vertexFormatID =
186 inputIndex < inputLayout.size() ? inputLayout[inputIndex] : angle::FormatID::NONE;
187
188 // HLSL code for input structure
189 if (IsMatrixType(shaderAttribute.type))
190 {
191 // Matrix types are always transposed
192 structStream << " "
193 << HLSLMatrixTypeString(TransposeMatrixType(shaderAttribute.type));
194 }
195 else
196 {
197 if (shaderAttribute.name == "gl_InstanceID" ||
198 shaderAttribute.name == "gl_VertexID")
199 {
200 // The input types of the instance ID and vertex ID in HLSL (uint) differs from
201 // the ones in ESSL (int).
202 structStream << " uint";
203 }
204 else
205 {
206 GLenum componentType = mRenderer->getVertexComponentType(vertexFormatID);
207
208 structStream << " ";
209 HLSLComponentTypeString(structStream, componentType,
210 VariableComponentCount(shaderAttribute.type));
211 }
212 }
213
214 structStream << " " << DecorateVariable(shaderAttribute.name) << " : ";
215
216 if (shaderAttribute.name == "gl_InstanceID")
217 {
218 structStream << "SV_InstanceID";
219 }
220 else if (shaderAttribute.name == "gl_VertexID")
221 {
222 structStream << "SV_VertexID";
223 }
224 else
225 {
226 structStream << "TEXCOORD" << semanticIndex;
227 semanticIndex += VariableRegisterCount(shaderAttribute.type);
228 }
229
230 structStream << ";\n";
231
232 // HLSL code for initialization
233 initStream << " " << DecorateVariable(shaderAttribute.name) << " = ";
234
235 // Mismatched vertex attribute to vertex input may result in an undefined
236 // data reinterpretation (eg for pure integer->float, float->pure integer)
237 // TODO: issue warning with gl debug info extension, when supported
238 if (IsMatrixType(shaderAttribute.type) ||
239 (mRenderer->getVertexConversionType(vertexFormatID) & VERTEX_CONVERT_GPU) != 0)
240 {
241 GenerateAttributeConversionHLSL(vertexFormatID, shaderAttribute, initStream);
242 }
243 else
244 {
245 initStream << "input." << DecorateVariable(shaderAttribute.name);
246 }
247
248 if (shaderAttribute.name == "gl_VertexID")
249 {
250 // dx_VertexID contains the firstVertex offset
251 initStream << " + dx_VertexID";
252 }
253
254 initStream << ";\n";
255
256 inputIndex += VariableRowCount(TransposeMatrixType(shaderAttribute.type));
257 }
258 }
259
260 structStream << "};\n"
261 "\n"
262 "void initAttributes(VS_INPUT input)\n"
263 "{\n"
264 << initStream.str() << "}\n";
265
266 std::string vertexHLSL(sourceShader);
267
268 bool success =
269 angle::ReplaceSubstring(&vertexHLSL, VERTEX_ATTRIBUTE_STUB_STRING, structStream.str());
270 ASSERT(success);
271
272 return vertexHLSL;
273 }
274
generatePixelShaderForOutputSignature(const std::string & sourceShader,const std::vector<PixelShaderOutputVariable> & outputVariables,bool usesFragDepth,const std::vector<GLenum> & outputLayout) const275 std::string DynamicHLSL::generatePixelShaderForOutputSignature(
276 const std::string &sourceShader,
277 const std::vector<PixelShaderOutputVariable> &outputVariables,
278 bool usesFragDepth,
279 const std::vector<GLenum> &outputLayout) const
280 {
281 const int shaderModel = mRenderer->getMajorShaderModel();
282 std::string targetSemantic = (shaderModel >= 4) ? "SV_TARGET" : "COLOR";
283 std::string depthSemantic = (shaderModel >= 4) ? "SV_Depth" : "DEPTH";
284
285 std::ostringstream declarationStream;
286 std::ostringstream copyStream;
287
288 declarationStream << "struct PS_OUTPUT\n"
289 "{\n";
290
291 size_t numOutputs = outputLayout.size();
292
293 // Workaround for HLSL 3.x: We can't do a depth/stencil only render, the runtime will complain.
294 if (numOutputs == 0 && (shaderModel == 3 || !mRenderer->getShaderModelSuffix().empty()))
295 {
296 numOutputs = 1u;
297 }
298 const PixelShaderOutputVariable defaultOutput(GL_FLOAT_VEC4, "dummy", "float4(0, 0, 0, 1)", 0,
299 0);
300 size_t outputIndex = 0;
301
302 for (size_t layoutIndex = 0; layoutIndex < numOutputs; ++layoutIndex)
303 {
304 GLenum binding = outputLayout.empty() ? GL_COLOR_ATTACHMENT0 : outputLayout[layoutIndex];
305
306 if (binding != GL_NONE)
307 {
308 unsigned int location = (binding - GL_COLOR_ATTACHMENT0);
309 outputIndex =
310 layoutIndex > 0 && binding == outputLayout[layoutIndex - 1] ? outputIndex + 1 : 0;
311
312 const PixelShaderOutputVariable *outputVariable =
313 outputLayout.empty() ? &defaultOutput
314 : FindOutputAtLocation(outputVariables, location, outputIndex);
315
316 // OpenGL ES 3.0 spec $4.2.1
317 // If [...] not all user-defined output variables are written, the values of fragment
318 // colors corresponding to unwritten variables are similarly undefined.
319 if (outputVariable)
320 {
321 declarationStream << " ";
322 HLSLTypeString(declarationStream, outputVariable->type);
323 declarationStream << " " << outputVariable->name << " : " << targetSemantic
324 << static_cast<int>(layoutIndex) << ";\n";
325
326 copyStream << " output." << outputVariable->name << " = "
327 << outputVariable->source << ";\n";
328 }
329 }
330 }
331
332 if (usesFragDepth)
333 {
334 declarationStream << " float gl_Depth : " << depthSemantic << ";\n";
335 copyStream << " output.gl_Depth = gl_Depth; \n";
336 }
337
338 declarationStream << "};\n"
339 "\n"
340 "PS_OUTPUT generateOutput()\n"
341 "{\n"
342 " PS_OUTPUT output;\n"
343 << copyStream.str()
344 << " return output;\n"
345 "}\n";
346
347 std::string pixelHLSL(sourceShader);
348
349 bool success =
350 angle::ReplaceSubstring(&pixelHLSL, PIXEL_OUTPUT_STUB_STRING, declarationStream.str());
351 ASSERT(success);
352
353 return pixelHLSL;
354 }
355
generateComputeShaderForImage2DBindSignature(const d3d::Context * context,ProgramD3D & programD3D,const gl::ProgramState & programData,std::vector<sh::ShaderVariable> & image2DUniforms,const gl::ImageUnitTextureTypeMap & image2DBindLayout) const356 std::string DynamicHLSL::generateComputeShaderForImage2DBindSignature(
357 const d3d::Context *context,
358 ProgramD3D &programD3D,
359 const gl::ProgramState &programData,
360 std::vector<sh::ShaderVariable> &image2DUniforms,
361 const gl::ImageUnitTextureTypeMap &image2DBindLayout) const
362 {
363 std::string computeHLSL(
364 programData.getAttachedShader(ShaderType::Compute)->getTranslatedSource());
365
366 if (image2DUniforms.empty())
367 {
368 return computeHLSL;
369 }
370
371 return GenerateComputeShaderForImage2DBindSignature(context, programD3D, programData,
372 image2DUniforms, image2DBindLayout);
373 }
374
generateVaryingLinkHLSL(const VaryingPacking & varyingPacking,const BuiltinInfo & builtins,bool programUsesPointSize,std::ostringstream & hlslStream) const375 void DynamicHLSL::generateVaryingLinkHLSL(const VaryingPacking &varyingPacking,
376 const BuiltinInfo &builtins,
377 bool programUsesPointSize,
378 std::ostringstream &hlslStream) const
379 {
380 ASSERT(builtins.dxPosition.enabled);
381 hlslStream << "{\n"
382 << " float4 dx_Position : " << builtins.dxPosition.str() << ";\n";
383
384 if (builtins.glPosition.enabled)
385 {
386 hlslStream << " float4 gl_Position : " << builtins.glPosition.str() << ";\n";
387 }
388
389 if (builtins.glFragCoord.enabled)
390 {
391 hlslStream << " float4 gl_FragCoord : " << builtins.glFragCoord.str() << ";\n";
392 }
393
394 if (builtins.glPointCoord.enabled)
395 {
396 hlslStream << " float2 gl_PointCoord : " << builtins.glPointCoord.str() << ";\n";
397 }
398
399 if (builtins.glPointSize.enabled)
400 {
401 hlslStream << " float gl_PointSize : " << builtins.glPointSize.str() << ";\n";
402 }
403
404 if (builtins.glViewIDOVR.enabled)
405 {
406 hlslStream << " nointerpolation uint gl_ViewID_OVR : " << builtins.glViewIDOVR.str()
407 << ";\n";
408 }
409
410 std::string varyingSemantic =
411 GetVaryingSemantic(mRenderer->getMajorShaderModel(), programUsesPointSize);
412
413 const auto ®isterInfos = varyingPacking.getRegisterList();
414 for (GLuint registerIndex = 0u; registerIndex < registerInfos.size(); ++registerIndex)
415 {
416 const PackedVaryingRegister ®isterInfo = registerInfos[registerIndex];
417 const auto &varying = registerInfo.packedVarying->varying();
418 ASSERT(!varying.isStruct());
419
420 // TODO: Add checks to ensure D3D interpolation modifiers don't result in too many
421 // registers being used.
422 // For example, if there are N registers, and we have N vec3 varyings and 1 float
423 // varying, then D3D will pack them into N registers.
424 // If the float varying has the 'nointerpolation' modifier on it then we would need
425 // N + 1 registers, and D3D compilation will fail.
426
427 switch (registerInfo.packedVarying->interpolation)
428 {
429 case sh::INTERPOLATION_SMOOTH:
430 hlslStream << " ";
431 break;
432 case sh::INTERPOLATION_FLAT:
433 hlslStream << " nointerpolation ";
434 break;
435 case sh::INTERPOLATION_CENTROID:
436 hlslStream << " centroid ";
437 break;
438 default:
439 UNREACHABLE();
440 }
441
442 GLenum transposedType = gl::TransposeMatrixType(varying.type);
443 GLenum componentType = gl::VariableComponentType(transposedType);
444 int columnCount = gl::VariableColumnCount(transposedType);
445 HLSLComponentTypeString(hlslStream, componentType, columnCount);
446 hlslStream << " v" << registerIndex << " : " << varyingSemantic << registerIndex << ";\n";
447 }
448
449 // Note that the following outputs need to be declared after the others. They are not included
450 // in pixel shader inputs even when they are in vertex/geometry shader outputs, and the pixel
451 // shader input struct must be a prefix of the vertex/geometry shader output struct.
452
453 if (builtins.glViewportIndex.enabled)
454 {
455 hlslStream << " nointerpolation uint gl_ViewportIndex : "
456 << builtins.glViewportIndex.str() << ";\n";
457 }
458
459 if (builtins.glLayer.enabled)
460 {
461 hlslStream << " nointerpolation uint gl_Layer : " << builtins.glLayer.str() << ";\n";
462 }
463
464 hlslStream << "};\n";
465 }
466
generateShaderLinkHLSL(const gl::Caps & caps,const gl::ProgramState & programData,const ProgramD3DMetadata & programMetadata,const VaryingPacking & varyingPacking,const BuiltinVaryingsD3D & builtinsD3D,gl::ShaderMap<std::string> * shaderHLSL) const467 void DynamicHLSL::generateShaderLinkHLSL(const gl::Caps &caps,
468 const gl::ProgramState &programData,
469 const ProgramD3DMetadata &programMetadata,
470 const VaryingPacking &varyingPacking,
471 const BuiltinVaryingsD3D &builtinsD3D,
472 gl::ShaderMap<std::string> *shaderHLSL) const
473 {
474 ASSERT(shaderHLSL);
475 ASSERT((*shaderHLSL)[gl::ShaderType::Vertex].empty() &&
476 (*shaderHLSL)[gl::ShaderType::Fragment].empty());
477
478 gl::Shader *vertexShaderGL = programData.getAttachedShader(ShaderType::Vertex);
479 gl::Shader *fragmentShaderGL = programData.getAttachedShader(ShaderType::Fragment);
480 const int shaderModel = mRenderer->getMajorShaderModel();
481
482 const ShaderD3D *fragmentShader = nullptr;
483 if (fragmentShaderGL)
484 {
485 fragmentShader = GetImplAs<ShaderD3D>(fragmentShaderGL);
486 }
487
488 // usesViewScale() isn't supported in the D3D9 renderer
489 ASSERT(shaderModel >= 4 || !programMetadata.usesViewScale());
490
491 bool useInstancedPointSpriteEmulation =
492 programMetadata.usesPointSize() &&
493 mRenderer->getFeatures().useInstancedPointSpriteEmulation.enabled;
494
495 // Validation done in the compiler
496 ASSERT(!fragmentShader || !fragmentShader->usesFragColor() || !fragmentShader->usesFragData());
497
498 std::ostringstream vertexStream;
499 vertexStream << "struct VS_OUTPUT\n";
500 const auto &vertexBuiltins = builtinsD3D[gl::ShaderType::Vertex];
501 generateVaryingLinkHLSL(varyingPacking, vertexBuiltins, builtinsD3D.usesPointSize(),
502 vertexStream);
503
504 // Instanced PointSprite emulation requires additional entries originally generated in the
505 // GeometryShader HLSL. These include pointsize clamp values.
506 if (useInstancedPointSpriteEmulation)
507 {
508 vertexStream << "static float minPointSize = " << static_cast<int>(caps.minAliasedPointSize)
509 << ".0f;\n"
510 << "static float maxPointSize = " << static_cast<int>(caps.maxAliasedPointSize)
511 << ".0f;\n";
512 }
513
514 std::ostringstream vertexGenerateOutput;
515 vertexGenerateOutput << "VS_OUTPUT generateOutput(VS_INPUT input)\n"
516 << "{\n"
517 << " VS_OUTPUT output;\n";
518
519 if (vertexBuiltins.glPosition.enabled)
520 {
521 vertexGenerateOutput << " output.gl_Position = gl_Position;\n";
522 }
523
524 if (vertexBuiltins.glViewIDOVR.enabled)
525 {
526 vertexGenerateOutput << " output.gl_ViewID_OVR = ViewID_OVR;\n";
527 }
528 if (programMetadata.hasANGLEMultiviewEnabled() && programMetadata.canSelectViewInVertexShader())
529 {
530 ASSERT(vertexBuiltins.glViewportIndex.enabled && vertexBuiltins.glLayer.enabled);
531 vertexGenerateOutput << " if (multiviewSelectViewportIndex)\n"
532 << " {\n"
533 << " output.gl_ViewportIndex = ViewID_OVR;\n"
534 << " } else {\n"
535 << " output.gl_ViewportIndex = 0;\n"
536 << " output.gl_Layer = ViewID_OVR;\n"
537 << " }\n";
538 }
539
540 // On D3D9 or D3D11 Feature Level 9, we need to emulate large viewports using dx_ViewAdjust.
541 if (shaderModel >= 4 && mRenderer->getShaderModelSuffix() == "")
542 {
543 vertexGenerateOutput << " output.dx_Position.x = gl_Position.x;\n";
544
545 if (programMetadata.usesViewScale())
546 {
547 // This code assumes that dx_ViewScale.y = -1.0f when rendering to texture, and +1.0f
548 // when rendering to the default framebuffer. No other values are valid.
549 vertexGenerateOutput << " output.dx_Position.y = dx_ViewScale.y * gl_Position.y;\n";
550 }
551 else
552 {
553 vertexGenerateOutput << " output.dx_Position.y = - gl_Position.y;\n";
554 }
555
556 vertexGenerateOutput
557 << " output.dx_Position.z = (gl_Position.z + gl_Position.w) * 0.5;\n"
558 << " output.dx_Position.w = gl_Position.w;\n";
559 }
560 else
561 {
562 vertexGenerateOutput << " output.dx_Position.x = gl_Position.x * dx_ViewAdjust.z + "
563 "dx_ViewAdjust.x * gl_Position.w;\n";
564
565 // If usesViewScale() is true and we're using the D3D11 renderer via Feature Level 9_*,
566 // then we need to multiply the gl_Position.y by the viewScale.
567 // usesViewScale() isn't supported when using the D3D9 renderer.
568 if (programMetadata.usesViewScale() &&
569 (shaderModel >= 4 && mRenderer->getShaderModelSuffix() != ""))
570 {
571 vertexGenerateOutput << " output.dx_Position.y = dx_ViewScale.y * (gl_Position.y * "
572 "dx_ViewAdjust.w + dx_ViewAdjust.y * gl_Position.w);\n";
573 }
574 else
575 {
576 vertexGenerateOutput
577 << " output.dx_Position.y = -(gl_Position.y * dx_ViewAdjust.w + "
578 "dx_ViewAdjust.y * gl_Position.w);\n";
579 }
580
581 vertexGenerateOutput
582 << " output.dx_Position.z = (gl_Position.z + gl_Position.w) * 0.5;\n"
583 << " output.dx_Position.w = gl_Position.w;\n";
584 }
585
586 // We don't need to output gl_PointSize if we use are emulating point sprites via instancing.
587 if (vertexBuiltins.glPointSize.enabled)
588 {
589 vertexGenerateOutput << " output.gl_PointSize = gl_PointSize;\n";
590 }
591
592 if (vertexBuiltins.glFragCoord.enabled)
593 {
594 vertexGenerateOutput << " output.gl_FragCoord = gl_Position;\n";
595 }
596
597 const auto ®isterInfos = varyingPacking.getRegisterList();
598 for (GLuint registerIndex = 0u; registerIndex < registerInfos.size(); ++registerIndex)
599 {
600 const PackedVaryingRegister ®isterInfo = registerInfos[registerIndex];
601 const auto &packedVarying = *registerInfo.packedVarying;
602 const auto &varying = *packedVarying.frontVarying.varying;
603 ASSERT(!varying.isStruct());
604
605 vertexGenerateOutput << " output.v" << registerIndex << " = ";
606
607 if (packedVarying.isStructField())
608 {
609 vertexGenerateOutput << DecorateVariable(packedVarying.frontVarying.parentStructName)
610 << ".";
611 }
612
613 vertexGenerateOutput << DecorateVariable(varying.name);
614
615 if (varying.isArray())
616 {
617 WriteArrayString(vertexGenerateOutput, registerInfo.varyingArrayIndex);
618 }
619
620 if (VariableRowCount(varying.type) > 1)
621 {
622 WriteArrayString(vertexGenerateOutput, registerInfo.varyingRowIndex);
623 }
624
625 vertexGenerateOutput << ";\n";
626 }
627
628 // Instanced PointSprite emulation requires additional entries to calculate
629 // the final output vertex positions of the quad that represents each sprite.
630 if (useInstancedPointSpriteEmulation)
631 {
632 vertexGenerateOutput
633 << "\n"
634 << " gl_PointSize = clamp(gl_PointSize, minPointSize, maxPointSize);\n";
635
636 vertexGenerateOutput
637 << " output.dx_Position.x += (input.spriteVertexPos.x * gl_PointSize / "
638 "(dx_ViewCoords.x*2)) * output.dx_Position.w;";
639
640 if (programMetadata.usesViewScale())
641 {
642 // Multiply by ViewScale to invert the rendering when appropriate
643 vertexGenerateOutput
644 << " output.dx_Position.y += (-dx_ViewScale.y * "
645 "input.spriteVertexPos.y * gl_PointSize / (dx_ViewCoords.y*2)) * "
646 "output.dx_Position.w;";
647 }
648 else
649 {
650 vertexGenerateOutput
651 << " output.dx_Position.y += (input.spriteVertexPos.y * gl_PointSize / "
652 "(dx_ViewCoords.y*2)) * output.dx_Position.w;";
653 }
654
655 vertexGenerateOutput
656 << " output.dx_Position.z += input.spriteVertexPos.z * output.dx_Position.w;\n";
657
658 if (programMetadata.usesPointCoord())
659 {
660 vertexGenerateOutput << "\n"
661 << " output.gl_PointCoord = input.spriteTexCoord;\n";
662 }
663 }
664
665 // Renderers that enable instanced pointsprite emulation require the vertex shader output member
666 // gl_PointCoord to be set to a default value if used without gl_PointSize. 0.5,0.5 is the same
667 // default value used in the generated pixel shader.
668 if (programMetadata.usesInsertedPointCoordValue())
669 {
670 ASSERT(!useInstancedPointSpriteEmulation);
671 vertexGenerateOutput << "\n"
672 << " output.gl_PointCoord = float2(0.5, 0.5);\n";
673 }
674
675 vertexGenerateOutput << "\n"
676 << " return output;\n"
677 << "}";
678
679 if (vertexShaderGL)
680 {
681 std::string vertexSource = vertexShaderGL->getTranslatedSource();
682 angle::ReplaceSubstring(&vertexSource, std::string(MAIN_PROLOGUE_STUB_STRING),
683 " initAttributes(input);\n");
684 angle::ReplaceSubstring(&vertexSource, std::string(VERTEX_OUTPUT_STUB_STRING),
685 vertexGenerateOutput.str());
686 vertexStream << vertexSource;
687 }
688
689 const auto &pixelBuiltins = builtinsD3D[gl::ShaderType::Fragment];
690
691 std::ostringstream pixelStream;
692 pixelStream << "struct PS_INPUT\n";
693 generateVaryingLinkHLSL(varyingPacking, pixelBuiltins, builtinsD3D.usesPointSize(),
694 pixelStream);
695 pixelStream << "\n";
696
697 std::ostringstream pixelPrologue;
698 if (fragmentShader && fragmentShader->usesViewID())
699 {
700 ASSERT(pixelBuiltins.glViewIDOVR.enabled);
701 pixelPrologue << " ViewID_OVR = input.gl_ViewID_OVR;\n";
702 }
703
704 if (pixelBuiltins.glFragCoord.enabled)
705 {
706 pixelPrologue << " float rhw = 1.0 / input.gl_FragCoord.w;\n";
707
708 // Certain Shader Models (4_0+ and 3_0) allow reading from dx_Position in the pixel shader.
709 // Other Shader Models (4_0_level_9_3 and 2_x) don't support this, so we emulate it using
710 // dx_ViewCoords.
711 if (shaderModel >= 4 && mRenderer->getShaderModelSuffix() == "")
712 {
713 pixelPrologue << " gl_FragCoord.x = input.dx_Position.x;\n"
714 << " gl_FragCoord.y = input.dx_Position.y;\n";
715 }
716 else if (shaderModel == 3)
717 {
718 pixelPrologue << " gl_FragCoord.x = input.dx_Position.x + 0.5;\n"
719 << " gl_FragCoord.y = input.dx_Position.y + 0.5;\n";
720 }
721 else
722 {
723 // dx_ViewCoords contains the viewport width/2, height/2, center.x and center.y. See
724 // Renderer::setViewport()
725 pixelPrologue
726 << " gl_FragCoord.x = (input.gl_FragCoord.x * rhw) * dx_ViewCoords.x + "
727 "dx_ViewCoords.z;\n"
728 << " gl_FragCoord.y = (input.gl_FragCoord.y * rhw) * dx_ViewCoords.y + "
729 "dx_ViewCoords.w;\n";
730 }
731
732 if (programMetadata.usesViewScale())
733 {
734 // For Feature Level 9_3 and below, we need to correct gl_FragCoord.y to account
735 // for dx_ViewScale. On Feature Level 10_0+, gl_FragCoord.y is calculated above using
736 // dx_ViewCoords and is always correct irrespective of dx_ViewScale's value.
737 // NOTE: usesViewScale() can only be true on D3D11 (i.e. Shader Model 4.0+).
738 if (shaderModel >= 4 && mRenderer->getShaderModelSuffix() == "")
739 {
740 // Some assumptions:
741 // - dx_ViewScale.y = -1.0f when rendering to texture
742 // - dx_ViewScale.y = +1.0f when rendering to the default framebuffer
743 // - gl_FragCoord.y has been set correctly above.
744 //
745 // When rendering to the backbuffer, the code inverts gl_FragCoord's y coordinate.
746 // This involves subtracting the y coordinate from the height of the area being
747 // rendered to.
748 //
749 // First we calculate the height of the area being rendered to:
750 // render_area_height = (2.0f / (1.0f - input.gl_FragCoord.y * rhw)) *
751 // gl_FragCoord.y
752 //
753 // Note that when we're rendering to default FB, we want our output to be
754 // equivalent to:
755 // "gl_FragCoord.y = render_area_height - gl_FragCoord.y"
756 //
757 // When we're rendering to a texture, we want our output to be equivalent to:
758 // "gl_FragCoord.y = gl_FragCoord.y;"
759 //
760 // If we set scale_factor = ((1.0f + dx_ViewScale.y) / 2.0f), then notice that
761 // - When rendering to default FB: scale_factor = 1.0f
762 // - When rendering to texture: scale_factor = 0.0f
763 //
764 // Therefore, we can get our desired output by setting:
765 // "gl_FragCoord.y = scale_factor * render_area_height - dx_ViewScale.y *
766 // gl_FragCoord.y"
767 //
768 // Simplifying, this becomes:
769 pixelPrologue
770 << " gl_FragCoord.y = (1.0f + dx_ViewScale.y) * gl_FragCoord.y /"
771 "(1.0f - input.gl_FragCoord.y * rhw) - dx_ViewScale.y * gl_FragCoord.y;\n";
772 }
773 }
774
775 pixelPrologue << " gl_FragCoord.z = (input.gl_FragCoord.z * rhw) * dx_DepthFront.x + "
776 "dx_DepthFront.y;\n"
777 << " gl_FragCoord.w = rhw;\n";
778 }
779
780 if (pixelBuiltins.glPointCoord.enabled && shaderModel >= 3)
781 {
782 pixelPrologue << " gl_PointCoord.x = input.gl_PointCoord.x;\n"
783 << " gl_PointCoord.y = 1.0 - input.gl_PointCoord.y;\n";
784 }
785
786 if (fragmentShader && fragmentShader->usesFrontFacing())
787 {
788 if (shaderModel <= 3)
789 {
790 pixelPrologue << " gl_FrontFacing = (vFace * dx_DepthFront.z >= 0.0);\n";
791 }
792 else
793 {
794 pixelPrologue << " gl_FrontFacing = isFrontFace;\n";
795 }
796 }
797
798 for (GLuint registerIndex = 0u; registerIndex < registerInfos.size(); ++registerIndex)
799 {
800 const PackedVaryingRegister ®isterInfo = registerInfos[registerIndex];
801 const auto &packedVarying = *registerInfo.packedVarying;
802
803 // Don't reference VS-only transform feedback varyings in the PS.
804 if (packedVarying.vertexOnly())
805 {
806 continue;
807 }
808
809 const auto &varying = *packedVarying.backVarying.varying;
810 ASSERT(!varying.isBuiltIn() && !varying.isStruct());
811
812 // Note that we're relying on that the active flag is set according to usage in the fragment
813 // shader.
814 if (!varying.active)
815 {
816 continue;
817 }
818
819 pixelPrologue << " ";
820
821 if (packedVarying.isStructField())
822 {
823 pixelPrologue << DecorateVariable(packedVarying.backVarying.parentStructName) << ".";
824 }
825
826 pixelPrologue << DecorateVariable(varying.name);
827
828 if (varying.isArray())
829 {
830 WriteArrayString(pixelPrologue, registerInfo.varyingArrayIndex);
831 }
832
833 GLenum transposedType = TransposeMatrixType(varying.type);
834 if (VariableRowCount(transposedType) > 1)
835 {
836 WriteArrayString(pixelPrologue, registerInfo.varyingRowIndex);
837 }
838
839 pixelPrologue << " = input.v" << registerIndex;
840
841 switch (VariableColumnCount(transposedType))
842 {
843 case 1:
844 pixelPrologue << ".x";
845 break;
846 case 2:
847 pixelPrologue << ".xy";
848 break;
849 case 3:
850 pixelPrologue << ".xyz";
851 break;
852 case 4:
853 break;
854 default:
855 UNREACHABLE();
856 }
857 pixelPrologue << ";\n";
858 }
859
860 if (fragmentShaderGL)
861 {
862 std::string pixelSource = fragmentShaderGL->getTranslatedSource();
863
864 if (fragmentShader->usesFrontFacing())
865 {
866 if (shaderModel >= 4)
867 {
868 angle::ReplaceSubstring(&pixelSource,
869 std::string(PIXEL_MAIN_PARAMETERS_STUB_STRING),
870 "PS_INPUT input, bool isFrontFace : SV_IsFrontFace");
871 }
872 else
873 {
874 angle::ReplaceSubstring(&pixelSource,
875 std::string(PIXEL_MAIN_PARAMETERS_STUB_STRING),
876 "PS_INPUT input, float vFace : VFACE");
877 }
878 }
879 else
880 {
881 angle::ReplaceSubstring(&pixelSource, std::string(PIXEL_MAIN_PARAMETERS_STUB_STRING),
882 "PS_INPUT input");
883 }
884
885 angle::ReplaceSubstring(&pixelSource, std::string(MAIN_PROLOGUE_STUB_STRING),
886 pixelPrologue.str());
887 pixelStream << pixelSource;
888 }
889
890 (*shaderHLSL)[gl::ShaderType::Vertex] = vertexStream.str();
891 (*shaderHLSL)[gl::ShaderType::Fragment] = pixelStream.str();
892 }
893
generateGeometryShaderPreamble(const VaryingPacking & varyingPacking,const BuiltinVaryingsD3D & builtinsD3D,const bool hasANGLEMultiviewEnabled,const bool selectViewInVS) const894 std::string DynamicHLSL::generateGeometryShaderPreamble(const VaryingPacking &varyingPacking,
895 const BuiltinVaryingsD3D &builtinsD3D,
896 const bool hasANGLEMultiviewEnabled,
897 const bool selectViewInVS) const
898 {
899 ASSERT(mRenderer->getMajorShaderModel() >= 4);
900
901 std::ostringstream preambleStream;
902
903 const auto &vertexBuiltins = builtinsD3D[gl::ShaderType::Vertex];
904
905 preambleStream << "struct GS_INPUT\n";
906 generateVaryingLinkHLSL(varyingPacking, vertexBuiltins, builtinsD3D.usesPointSize(),
907 preambleStream);
908 preambleStream << "\n"
909 << "struct GS_OUTPUT\n";
910 generateVaryingLinkHLSL(varyingPacking, builtinsD3D[gl::ShaderType::Geometry],
911 builtinsD3D.usesPointSize(), preambleStream);
912 preambleStream
913 << "\n"
914 << "void copyVertex(inout GS_OUTPUT output, GS_INPUT input, GS_INPUT flatinput)\n"
915 << "{\n"
916 << " output.gl_Position = input.gl_Position;\n";
917
918 if (vertexBuiltins.glPointSize.enabled)
919 {
920 preambleStream << " output.gl_PointSize = input.gl_PointSize;\n";
921 }
922
923 if (hasANGLEMultiviewEnabled)
924 {
925 preambleStream << " output.gl_ViewID_OVR = input.gl_ViewID_OVR;\n";
926 if (selectViewInVS)
927 {
928 ASSERT(builtinsD3D[gl::ShaderType::Geometry].glViewportIndex.enabled &&
929 builtinsD3D[gl::ShaderType::Geometry].glLayer.enabled);
930
931 // If the view is already selected in the VS, then we just pass the gl_ViewportIndex and
932 // gl_Layer to the output.
933 preambleStream << " output.gl_ViewportIndex = input.gl_ViewportIndex;\n"
934 << " output.gl_Layer = input.gl_Layer;\n";
935 }
936 }
937
938 const auto ®isterInfos = varyingPacking.getRegisterList();
939 for (GLuint registerIndex = 0u; registerIndex < registerInfos.size(); ++registerIndex)
940 {
941 const PackedVaryingRegister &varyingRegister = registerInfos[registerIndex];
942 preambleStream << " output.v" << registerIndex << " = ";
943 if (varyingRegister.packedVarying->interpolation == sh::INTERPOLATION_FLAT)
944 {
945 preambleStream << "flat";
946 }
947 preambleStream << "input.v" << registerIndex << "; \n";
948 }
949
950 if (vertexBuiltins.glFragCoord.enabled)
951 {
952 preambleStream << " output.gl_FragCoord = input.gl_FragCoord;\n";
953 }
954
955 // Only write the dx_Position if we aren't using point sprites
956 preambleStream << "#ifndef ANGLE_POINT_SPRITE_SHADER\n"
957 << " output.dx_Position = input.dx_Position;\n"
958 << "#endif // ANGLE_POINT_SPRITE_SHADER\n"
959 << "}\n";
960
961 if (hasANGLEMultiviewEnabled && !selectViewInVS)
962 {
963 ASSERT(builtinsD3D[gl::ShaderType::Geometry].glViewportIndex.enabled &&
964 builtinsD3D[gl::ShaderType::Geometry].glLayer.enabled);
965
966 // According to the HLSL reference, using SV_RenderTargetArrayIndex is only valid if the
967 // render target is an array resource. Because of this we do not write to gl_Layer if we are
968 // taking the side-by-side code path. We still select the viewport index in the layered code
969 // path as that is always valid. See:
970 // https://msdn.microsoft.com/en-us/library/windows/desktop/bb509647(v=vs.85).aspx
971 preambleStream << "\n"
972 << "void selectView(inout GS_OUTPUT output, GS_INPUT input)\n"
973 << "{\n"
974 << " if (multiviewSelectViewportIndex)\n"
975 << " {\n"
976 << " output.gl_ViewportIndex = input.gl_ViewID_OVR;\n"
977 << " } else {\n"
978 << " output.gl_ViewportIndex = 0;\n"
979 << " output.gl_Layer = input.gl_ViewID_OVR;\n"
980 << " }\n"
981 << "}\n";
982 }
983
984 return preambleStream.str();
985 }
986
generateGeometryShaderHLSL(const gl::Caps & caps,gl::PrimitiveMode primitiveType,const gl::ProgramState & programData,const bool useViewScale,const bool hasANGLEMultiviewEnabled,const bool selectViewInVS,const bool pointSpriteEmulation,const std::string & preambleString) const987 std::string DynamicHLSL::generateGeometryShaderHLSL(const gl::Caps &caps,
988 gl::PrimitiveMode primitiveType,
989 const gl::ProgramState &programData,
990 const bool useViewScale,
991 const bool hasANGLEMultiviewEnabled,
992 const bool selectViewInVS,
993 const bool pointSpriteEmulation,
994 const std::string &preambleString) const
995 {
996 ASSERT(mRenderer->getMajorShaderModel() >= 4);
997
998 std::stringstream shaderStream;
999
1000 const bool pointSprites = (primitiveType == gl::PrimitiveMode::Points) && pointSpriteEmulation;
1001 const bool usesPointCoord = preambleString.find("gl_PointCoord") != std::string::npos;
1002
1003 const char *inputPT = nullptr;
1004 const char *outputPT = nullptr;
1005 int inputSize = 0;
1006 int maxVertexOutput = 0;
1007
1008 switch (primitiveType)
1009 {
1010 case gl::PrimitiveMode::Points:
1011 inputPT = "point";
1012 inputSize = 1;
1013
1014 if (pointSprites)
1015 {
1016 outputPT = "Triangle";
1017 maxVertexOutput = 4;
1018 }
1019 else
1020 {
1021 outputPT = "Point";
1022 maxVertexOutput = 1;
1023 }
1024
1025 break;
1026
1027 case gl::PrimitiveMode::Lines:
1028 case gl::PrimitiveMode::LineStrip:
1029 case gl::PrimitiveMode::LineLoop:
1030 inputPT = "line";
1031 outputPT = "Line";
1032 inputSize = 2;
1033 maxVertexOutput = 2;
1034 break;
1035
1036 case gl::PrimitiveMode::Triangles:
1037 case gl::PrimitiveMode::TriangleStrip:
1038 case gl::PrimitiveMode::TriangleFan:
1039 inputPT = "triangle";
1040 outputPT = "Triangle";
1041 inputSize = 3;
1042 maxVertexOutput = 3;
1043 break;
1044
1045 default:
1046 UNREACHABLE();
1047 break;
1048 }
1049
1050 if (pointSprites || hasANGLEMultiviewEnabled)
1051 {
1052 shaderStream << "cbuffer DriverConstants : register(b0)\n"
1053 "{\n";
1054
1055 if (pointSprites)
1056 {
1057 shaderStream << " float4 dx_ViewCoords : packoffset(c1);\n";
1058 if (useViewScale)
1059 {
1060 shaderStream << " float2 dx_ViewScale : packoffset(c3);\n";
1061 }
1062 }
1063
1064 if (hasANGLEMultiviewEnabled)
1065 {
1066 // We have to add a value which we can use to keep track of which multi-view code path
1067 // is to be selected in the GS.
1068 shaderStream << " float multiviewSelectViewportIndex : packoffset(c3.z);\n";
1069 }
1070
1071 shaderStream << "};\n\n";
1072 }
1073
1074 if (pointSprites)
1075 {
1076 shaderStream << "#define ANGLE_POINT_SPRITE_SHADER\n"
1077 "\n"
1078 "static float2 pointSpriteCorners[] = \n"
1079 "{\n"
1080 " float2( 0.5f, -0.5f),\n"
1081 " float2( 0.5f, 0.5f),\n"
1082 " float2(-0.5f, -0.5f),\n"
1083 " float2(-0.5f, 0.5f)\n"
1084 "};\n"
1085 "\n"
1086 "static float2 pointSpriteTexcoords[] = \n"
1087 "{\n"
1088 " float2(1.0f, 1.0f),\n"
1089 " float2(1.0f, 0.0f),\n"
1090 " float2(0.0f, 1.0f),\n"
1091 " float2(0.0f, 0.0f)\n"
1092 "};\n"
1093 "\n"
1094 "static float minPointSize = "
1095 << static_cast<int>(caps.minAliasedPointSize)
1096 << ".0f;\n"
1097 "static float maxPointSize = "
1098 << static_cast<int>(caps.maxAliasedPointSize) << ".0f;\n"
1099 << "\n";
1100 }
1101
1102 shaderStream << preambleString << "\n"
1103 << "[maxvertexcount(" << maxVertexOutput << ")]\n"
1104 << "void main(" << inputPT << " GS_INPUT input[" << inputSize << "], ";
1105
1106 if (primitiveType == gl::PrimitiveMode::TriangleStrip)
1107 {
1108 shaderStream << "uint primitiveID : SV_PrimitiveID, ";
1109 }
1110
1111 shaderStream << " inout " << outputPT << "Stream<GS_OUTPUT> outStream)\n"
1112 << "{\n"
1113 << " GS_OUTPUT output = (GS_OUTPUT)0;\n";
1114
1115 if (primitiveType == gl::PrimitiveMode::TriangleStrip)
1116 {
1117 shaderStream << " uint lastVertexIndex = (primitiveID % 2 == 0 ? 2 : 1);\n";
1118 }
1119 else
1120 {
1121 shaderStream << " uint lastVertexIndex = " << (inputSize - 1) << ";\n";
1122 }
1123
1124 for (int vertexIndex = 0; vertexIndex < inputSize; ++vertexIndex)
1125 {
1126 shaderStream << " copyVertex(output, input[" << vertexIndex
1127 << "], input[lastVertexIndex]);\n";
1128 if (hasANGLEMultiviewEnabled && !selectViewInVS)
1129 {
1130 shaderStream << " selectView(output, input[" << vertexIndex << "]);\n";
1131 }
1132 if (!pointSprites)
1133 {
1134 ASSERT(inputSize == maxVertexOutput);
1135 shaderStream << " outStream.Append(output);\n";
1136 }
1137 }
1138
1139 if (pointSprites)
1140 {
1141 shaderStream << "\n"
1142 " float4 dx_Position = input[0].dx_Position;\n"
1143 " float gl_PointSize = clamp(input[0].gl_PointSize, minPointSize, "
1144 "maxPointSize);\n"
1145 " float2 viewportScale = float2(1.0f / dx_ViewCoords.x, 1.0f / "
1146 "dx_ViewCoords.y) * dx_Position.w;\n";
1147
1148 for (int corner = 0; corner < 4; corner++)
1149 {
1150 if (useViewScale)
1151 {
1152 shaderStream << " \n"
1153 " output.dx_Position = dx_Position + float4(1.0f, "
1154 "-dx_ViewScale.y, 1.0f, 1.0f)"
1155 " * float4(pointSpriteCorners["
1156 << corner << "] * viewportScale * gl_PointSize, 0.0f, 0.0f);\n";
1157 }
1158 else
1159 {
1160 shaderStream << "\n"
1161 " output.dx_Position = dx_Position + float4(pointSpriteCorners["
1162 << corner << "] * viewportScale * gl_PointSize, 0.0f, 0.0f);\n";
1163 }
1164
1165 if (usesPointCoord)
1166 {
1167 shaderStream << " output.gl_PointCoord = pointSpriteTexcoords[" << corner
1168 << "];\n";
1169 }
1170
1171 shaderStream << " outStream.Append(output);\n";
1172 }
1173 }
1174
1175 shaderStream << " \n"
1176 " outStream.RestartStrip();\n"
1177 "}\n";
1178
1179 return shaderStream.str();
1180 }
1181
1182 // static
GenerateAttributeConversionHLSL(angle::FormatID vertexFormatID,const sh::ShaderVariable & shaderAttrib,std::ostringstream & outStream)1183 void DynamicHLSL::GenerateAttributeConversionHLSL(angle::FormatID vertexFormatID,
1184 const sh::ShaderVariable &shaderAttrib,
1185 std::ostringstream &outStream)
1186 {
1187 // Matrix
1188 if (IsMatrixType(shaderAttrib.type))
1189 {
1190 outStream << "transpose(input." << DecorateVariable(shaderAttrib.name) << ")";
1191 return;
1192 }
1193
1194 GLenum shaderComponentType = VariableComponentType(shaderAttrib.type);
1195 int shaderComponentCount = VariableComponentCount(shaderAttrib.type);
1196 const gl::VertexFormat &vertexFormat = gl::GetVertexFormatFromID(vertexFormatID);
1197
1198 // Perform integer to float conversion (if necessary)
1199 if (shaderComponentType == GL_FLOAT && vertexFormat.type != GL_FLOAT)
1200 {
1201 // TODO: normalization for 32-bit integer formats
1202 ASSERT(!vertexFormat.normalized && !vertexFormat.pureInteger);
1203 outStream << "float" << shaderComponentCount << "(input."
1204 << DecorateVariable(shaderAttrib.name) << ")";
1205 return;
1206 }
1207
1208 // No conversion necessary
1209 outStream << "input." << DecorateVariable(shaderAttrib.name);
1210 }
1211
getPixelShaderOutputKey(const gl::State & data,const gl::ProgramState & programData,const ProgramD3DMetadata & metadata,std::vector<PixelShaderOutputVariable> * outPixelShaderKey)1212 void DynamicHLSL::getPixelShaderOutputKey(const gl::State &data,
1213 const gl::ProgramState &programData,
1214 const ProgramD3DMetadata &metadata,
1215 std::vector<PixelShaderOutputVariable> *outPixelShaderKey)
1216 {
1217 // Two cases when writing to gl_FragColor and using ESSL 1.0:
1218 // - with a 3.0 context, the output color is copied to channel 0
1219 // - with a 2.0 context, the output color is broadcast to all channels
1220 bool broadcast = metadata.usesBroadcast(data);
1221 const unsigned int numRenderTargets =
1222 (broadcast || metadata.usesMultipleFragmentOuts()
1223 ? static_cast<unsigned int>(data.getCaps().maxDrawBuffers)
1224 : 1);
1225
1226 if (!metadata.usesCustomOutVars())
1227 {
1228 for (unsigned int renderTargetIndex = 0; renderTargetIndex < numRenderTargets;
1229 renderTargetIndex++)
1230 {
1231 PixelShaderOutputVariable outputKeyVariable;
1232 outputKeyVariable.type = GL_FLOAT_VEC4;
1233 outputKeyVariable.name = "gl_Color" + Str(renderTargetIndex);
1234 outputKeyVariable.source =
1235 broadcast ? "gl_Color[0]" : "gl_Color[" + Str(renderTargetIndex) + "]";
1236 outputKeyVariable.outputLocation = renderTargetIndex;
1237
1238 outPixelShaderKey->push_back(outputKeyVariable);
1239 }
1240
1241 if (metadata.usesSecondaryColor())
1242 {
1243 for (unsigned int secondaryIndex = 0;
1244 secondaryIndex < data.getExtensions().maxDualSourceDrawBuffers; secondaryIndex++)
1245 {
1246 PixelShaderOutputVariable outputKeyVariable;
1247 outputKeyVariable.type = GL_FLOAT_VEC4;
1248 outputKeyVariable.name = "gl_SecondaryColor" + Str(secondaryIndex);
1249 outputKeyVariable.source = "gl_SecondaryColor[" + Str(secondaryIndex) + "]";
1250 outputKeyVariable.outputLocation = secondaryIndex;
1251 outputKeyVariable.outputIndex = 1;
1252
1253 outPixelShaderKey->push_back(outputKeyVariable);
1254 }
1255 }
1256 }
1257 else
1258 {
1259 const ShaderD3D *fragmentShader = metadata.getFragmentShader();
1260
1261 if (!fragmentShader)
1262 {
1263 return;
1264 }
1265
1266 const auto &shaderOutputVars = fragmentShader->getData().getActiveOutputVariables();
1267
1268 for (size_t outputLocationIndex = 0u;
1269 outputLocationIndex < programData.getOutputLocations().size(); ++outputLocationIndex)
1270 {
1271 const VariableLocation &outputLocation =
1272 programData.getOutputLocations().at(outputLocationIndex);
1273 if (!outputLocation.used())
1274 {
1275 continue;
1276 }
1277 const sh::ShaderVariable &outputVariable = shaderOutputVars[outputLocation.index];
1278 const std::string &variableName = "out_" + outputVariable.name;
1279
1280 // Fragment outputs can't be arrays of arrays. ESSL 3.10 section 4.3.6.
1281 const std::string &elementString =
1282 (outputVariable.isArray() ? Str(outputLocation.arrayIndex) : "");
1283
1284 ASSERT(outputVariable.active);
1285
1286 PixelShaderOutputVariable outputKeyVariable;
1287 outputKeyVariable.type = outputVariable.type;
1288 outputKeyVariable.name = variableName + elementString;
1289 outputKeyVariable.source =
1290 variableName +
1291 (outputVariable.isArray() ? ArrayString(outputLocation.arrayIndex) : "");
1292 outputKeyVariable.outputLocation = outputLocationIndex;
1293
1294 outPixelShaderKey->push_back(outputKeyVariable);
1295 }
1296
1297 // Now generate any secondary outputs...
1298 for (size_t outputLocationIndex = 0u;
1299 outputLocationIndex < programData.getSecondaryOutputLocations().size();
1300 ++outputLocationIndex)
1301 {
1302 const VariableLocation &outputLocation =
1303 programData.getSecondaryOutputLocations().at(outputLocationIndex);
1304 if (!outputLocation.used())
1305 {
1306 continue;
1307 }
1308 const sh::ShaderVariable &outputVariable = shaderOutputVars[outputLocation.index];
1309 const std::string &variableName = "out_" + outputVariable.name;
1310
1311 // Fragment outputs can't be arrays of arrays. ESSL 3.10 section 4.3.6.
1312 const std::string &elementString =
1313 (outputVariable.isArray() ? Str(outputLocation.arrayIndex) : "");
1314
1315 ASSERT(outputVariable.active);
1316
1317 PixelShaderOutputVariable outputKeyVariable;
1318 outputKeyVariable.type = outputVariable.type;
1319 outputKeyVariable.name = variableName + elementString;
1320 outputKeyVariable.source =
1321 variableName +
1322 (outputVariable.isArray() ? ArrayString(outputLocation.arrayIndex) : "");
1323 outputKeyVariable.outputLocation = outputLocationIndex;
1324 outputKeyVariable.outputIndex = 1;
1325
1326 outPixelShaderKey->push_back(outputKeyVariable);
1327 }
1328 }
1329 }
1330
1331 // BuiltinVarying Implementation.
BuiltinVarying()1332 BuiltinVarying::BuiltinVarying() : enabled(false), index(0), systemValue(false) {}
1333
str() const1334 std::string BuiltinVarying::str() const
1335 {
1336 return (systemValue ? semantic : (semantic + Str(index)));
1337 }
1338
enableSystem(const std::string & systemValueSemantic)1339 void BuiltinVarying::enableSystem(const std::string &systemValueSemantic)
1340 {
1341 enabled = true;
1342 semantic = systemValueSemantic;
1343 systemValue = true;
1344 }
1345
enable(const std::string & semanticVal,unsigned int indexVal)1346 void BuiltinVarying::enable(const std::string &semanticVal, unsigned int indexVal)
1347 {
1348 enabled = true;
1349 semantic = semanticVal;
1350 index = indexVal;
1351 }
1352
1353 // BuiltinVaryingsD3D Implementation.
BuiltinVaryingsD3D(const ProgramD3DMetadata & metadata,const VaryingPacking & packing)1354 BuiltinVaryingsD3D::BuiltinVaryingsD3D(const ProgramD3DMetadata &metadata,
1355 const VaryingPacking &packing)
1356 {
1357 updateBuiltins(gl::ShaderType::Vertex, metadata, packing);
1358 updateBuiltins(gl::ShaderType::Fragment, metadata, packing);
1359 int shaderModel = metadata.getRendererMajorShaderModel();
1360 if (shaderModel >= 4)
1361 {
1362 updateBuiltins(gl::ShaderType::Geometry, metadata, packing);
1363 }
1364 // In shader model >= 4, some builtins need to be the same in vertex and pixel shaders - input
1365 // struct needs to be a prefix of output struct.
1366 ASSERT(shaderModel < 4 || mBuiltinInfo[gl::ShaderType::Vertex].glPosition.enabled ==
1367 mBuiltinInfo[gl::ShaderType::Fragment].glPosition.enabled);
1368 ASSERT(shaderModel < 4 || mBuiltinInfo[gl::ShaderType::Vertex].glFragCoord.enabled ==
1369 mBuiltinInfo[gl::ShaderType::Fragment].glFragCoord.enabled);
1370 ASSERT(shaderModel < 4 || mBuiltinInfo[gl::ShaderType::Vertex].glPointCoord.enabled ==
1371 mBuiltinInfo[gl::ShaderType::Fragment].glPointCoord.enabled);
1372 ASSERT(shaderModel < 4 || mBuiltinInfo[gl::ShaderType::Vertex].glPointSize.enabled ==
1373 mBuiltinInfo[gl::ShaderType::Fragment].glPointSize.enabled);
1374 ASSERT(shaderModel < 4 || mBuiltinInfo[gl::ShaderType::Vertex].glViewIDOVR.enabled ==
1375 mBuiltinInfo[gl::ShaderType::Fragment].glViewIDOVR.enabled);
1376 }
1377
1378 BuiltinVaryingsD3D::~BuiltinVaryingsD3D() = default;
1379
updateBuiltins(gl::ShaderType shaderType,const ProgramD3DMetadata & metadata,const VaryingPacking & packing)1380 void BuiltinVaryingsD3D::updateBuiltins(gl::ShaderType shaderType,
1381 const ProgramD3DMetadata &metadata,
1382 const VaryingPacking &packing)
1383 {
1384 const std::string &userSemantic = GetVaryingSemantic(metadata.getRendererMajorShaderModel(),
1385 metadata.usesSystemValuePointSize());
1386
1387 // Note that when enabling builtins only for specific shader stages in shader model >= 4, the
1388 // code needs to ensure that the input struct of the shader stage is a prefix of the output
1389 // struct of the previous stage.
1390
1391 unsigned int reservedSemanticIndex = packing.getMaxSemanticIndex();
1392
1393 BuiltinInfo *builtins = &mBuiltinInfo[shaderType];
1394
1395 if (metadata.getRendererMajorShaderModel() >= 4)
1396 {
1397 builtins->dxPosition.enableSystem("SV_Position");
1398 }
1399 else if (shaderType == gl::ShaderType::Fragment)
1400 {
1401 builtins->dxPosition.enableSystem("VPOS");
1402 }
1403 else
1404 {
1405 builtins->dxPosition.enableSystem("POSITION");
1406 }
1407
1408 if (metadata.usesTransformFeedbackGLPosition())
1409 {
1410 builtins->glPosition.enable(userSemantic, reservedSemanticIndex++);
1411 }
1412
1413 if (metadata.usesFragCoord())
1414 {
1415 builtins->glFragCoord.enable(userSemantic, reservedSemanticIndex++);
1416 }
1417
1418 if (shaderType == gl::ShaderType::Vertex ? metadata.addsPointCoordToVertexShader()
1419 : metadata.usesPointCoord())
1420 {
1421 // SM3 reserves the TEXCOORD semantic for point sprite texcoords (gl_PointCoord)
1422 // In D3D11 we manually compute gl_PointCoord in the GS.
1423 if (metadata.getRendererMajorShaderModel() >= 4)
1424 {
1425 builtins->glPointCoord.enable(userSemantic, reservedSemanticIndex++);
1426 }
1427 else
1428 {
1429 builtins->glPointCoord.enable("TEXCOORD", 0);
1430 }
1431 }
1432
1433 if (metadata.hasANGLEMultiviewEnabled())
1434 {
1435 // Although it is possible to compute gl_ViewID_OVR from the value of
1436 // SV_ViewportArrayIndex or SV_RenderTargetArrayIndex and the multi-view state in the
1437 // driver constant buffer, it is easier and cleaner to always pass it as a varying.
1438 builtins->glViewIDOVR.enable(userSemantic, reservedSemanticIndex++);
1439
1440 if (shaderType == gl::ShaderType::Vertex)
1441 {
1442 if (metadata.canSelectViewInVertexShader())
1443 {
1444 builtins->glViewportIndex.enableSystem("SV_ViewportArrayIndex");
1445 builtins->glLayer.enableSystem("SV_RenderTargetArrayIndex");
1446 }
1447 }
1448
1449 if (shaderType == gl::ShaderType::Geometry)
1450 {
1451 // gl_Layer and gl_ViewportIndex are necessary so that we can write to either based on
1452 // the multiview state in the driver constant buffer.
1453 builtins->glViewportIndex.enableSystem("SV_ViewportArrayIndex");
1454 builtins->glLayer.enableSystem("SV_RenderTargetArrayIndex");
1455 }
1456 }
1457
1458 // Special case: do not include PSIZE semantic in HLSL 3 pixel shaders
1459 if (metadata.usesSystemValuePointSize() &&
1460 (shaderType != gl::ShaderType::Fragment || metadata.getRendererMajorShaderModel() >= 4))
1461 {
1462 builtins->glPointSize.enableSystem("PSIZE");
1463 }
1464 }
1465
1466 } // namespace rx
1467