2 // Copyright (c) 2002-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.
7 #include "compiler/translator/OutputHLSL.h"
9 #include "common/angleutils.h"
10 #include "common/utilities.h"
11 #include "common/blocklayout.h"
12 #include "compiler/translator/compilerdebug.h"
13 #include "compiler/translator/InfoSink.h"
14 #include "compiler/translator/DetectDiscontinuity.h"
15 #include "compiler/translator/SearchSymbol.h"
16 #include "compiler/translator/UnfoldShortCircuit.h"
17 #include "compiler/translator/FlagStd140Structs.h"
18 #include "compiler/translator/NodeSearch.h"
19 #include "compiler/translator/RewriteElseBlocks.h"
28 TString OutputHLSL::TextureFunction::name() const
30 TString name = "gl_texture";
32 if (IsSampler2D(sampler))
36 else if (IsSampler3D(sampler))
40 else if (IsSamplerCube(sampler))
59 case BIAS: break; // Extra parameter makes the signature unique
60 case LOD: name += "Lod"; break;
61 case LOD0: name += "Lod0"; break;
62 case LOD0BIAS: name += "Lod0"; break; // Extra parameter makes the signature unique
63 case SIZE: name += "Size"; break;
64 case FETCH: name += "Fetch"; break;
65 case GRAD: name += "Grad"; break;
66 default: UNREACHABLE();
72 const char *RegisterPrefix(const TType &type)
74 if (IsSampler(type.getBasicType()))
84 bool OutputHLSL::TextureFunction::operator<(const TextureFunction &rhs) const
86 if (sampler < rhs.sampler) return true;
87 if (sampler > rhs.sampler) return false;
89 if (coords < rhs.coords) return true;
90 if (coords > rhs.coords) return false;
92 if (!proj && rhs.proj) return true;
93 if (proj && !rhs.proj) return false;
95 if (!offset && rhs.offset) return true;
96 if (offset && !rhs.offset) return false;
98 if (method < rhs.method) return true;
99 if (method > rhs.method) return false;
104 OutputHLSL::OutputHLSL(TParseContext &context, const ShBuiltInResources& resources, ShShaderOutput outputType)
105 : TIntermTraverser(true, true, true), mContext(context), mOutputType(outputType)
107 mUnfoldShortCircuit = new UnfoldShortCircuit(context, this);
108 mInsideFunction = false;
110 mUsesFragColor = false;
111 mUsesFragData = false;
112 mUsesDepthRange = false;
113 mUsesFragCoord = false;
114 mUsesPointCoord = false;
115 mUsesFrontFacing = false;
116 mUsesPointSize = false;
117 mUsesFragDepth = false;
126 mUsesFaceforward1 = false;
127 mUsesFaceforward2 = false;
128 mUsesFaceforward3 = false;
129 mUsesFaceforward4 = false;
130 mUsesAtan2_1 = false;
131 mUsesAtan2_2 = false;
132 mUsesAtan2_3 = false;
133 mUsesAtan2_4 = false;
134 mUsesDiscardRewriting = false;
135 mUsesNestedBreak = false;
137 mNumRenderTargets = resources.EXT_draw_buffers ? resources.MaxDrawBuffers : 1;
141 mContainsLoopDiscontinuity = false;
142 mOutputLod0Function = false;
143 mInsideDiscontinuousLoop = false;
144 mNestedLoopDepth = 0;
146 mExcessiveLoopIndex = NULL;
148 if (mOutputType == SH_HLSL9_OUTPUT)
150 if (mContext.shaderType == SH_FRAGMENT_SHADER)
152 mUniformRegister = 3; // Reserve registers for dx_DepthRange, dx_ViewCoords and dx_DepthFront
156 mUniformRegister = 2; // Reserve registers for dx_DepthRange and dx_ViewAdjust
161 mUniformRegister = 0;
164 mSamplerRegister = 0;
165 mInterfaceBlockRegister = 2; // Reserve registers for the default uniform block and driver constants
169 OutputHLSL::~OutputHLSL()
171 delete mUnfoldShortCircuit;
174 void OutputHLSL::output()
176 mContainsLoopDiscontinuity = mContext.shaderType == SH_FRAGMENT_SHADER && containsLoopDiscontinuity(mContext.treeRoot);
177 const std::vector<TIntermTyped*> &flaggedStructs = FlagStd140ValueStructs(mContext.treeRoot);
178 makeFlaggedStructMaps(flaggedStructs);
180 // Work around D3D9 bug that would manifest in vertex shaders with selection blocks which
181 // use a vertex attribute as a condition, and some related computation in the else block.
182 if (mOutputType == SH_HLSL9_OUTPUT && mContext.shaderType == SH_VERTEX_SHADER)
184 RewriteElseBlocks(mContext.treeRoot);
187 mContext.treeRoot->traverse(this); // Output the body first to determine what has to go in the header
190 mContext.infoSink().obj << mHeader.c_str();
191 mContext.infoSink().obj << mBody.c_str();
194 void OutputHLSL::makeFlaggedStructMaps(const std::vector<TIntermTyped *> &flaggedStructs)
196 for (unsigned int structIndex = 0; structIndex < flaggedStructs.size(); structIndex++)
198 TIntermTyped *flaggedNode = flaggedStructs[structIndex];
200 // This will mark the necessary block elements as referenced
201 flaggedNode->traverse(this);
202 TString structName(mBody.c_str());
205 mFlaggedStructOriginalNames[flaggedNode] = structName;
207 for (size_t pos = structName.find('.'); pos != std::string::npos; pos = structName.find('.'))
209 structName.erase(pos, 1);
212 mFlaggedStructMappedNames[flaggedNode] = "map" + structName;
216 TInfoSinkBase &OutputHLSL::getBodyStream()
221 const std::vector<gl::Uniform> &OutputHLSL::getUniforms()
223 return mActiveUniforms;
226 const std::vector<gl::InterfaceBlock> &OutputHLSL::getInterfaceBlocks() const
228 return mActiveInterfaceBlocks;
231 const std::vector<gl::Attribute> &OutputHLSL::getOutputVariables() const
233 return mActiveOutputVariables;
236 const std::vector<gl::Attribute> &OutputHLSL::getAttributes() const
238 return mActiveAttributes;
241 const std::vector<gl::Varying> &OutputHLSL::getVaryings() const
243 return mActiveVaryings;
246 int OutputHLSL::vectorSize(const TType &type) const
248 int elementSize = type.isMatrix() ? type.getCols() : 1;
249 int arraySize = type.isArray() ? type.getArraySize() : 1;
251 return elementSize * arraySize;
254 TString OutputHLSL::interfaceBlockFieldString(const TInterfaceBlock &interfaceBlock, const TField &field)
256 if (interfaceBlock.hasInstanceName())
258 return interfaceBlock.name() + "." + field.name();
266 TString OutputHLSL::decoratePrivate(const TString &privateText)
268 return "dx_" + privateText;
271 TString OutputHLSL::interfaceBlockStructNameString(const TInterfaceBlock &interfaceBlock)
273 return decoratePrivate(interfaceBlock.name()) + "_type";
276 TString OutputHLSL::interfaceBlockInstanceString(const TInterfaceBlock& interfaceBlock, unsigned int arrayIndex)
278 if (!interfaceBlock.hasInstanceName())
282 else if (interfaceBlock.isArray())
284 return decoratePrivate(interfaceBlock.instanceName()) + "_" + str(arrayIndex);
288 return decorate(interfaceBlock.instanceName());
292 TString OutputHLSL::interfaceBlockFieldTypeString(const TField &field, TLayoutBlockStorage blockStorage)
294 const TType &fieldType = *field.type();
295 const TLayoutMatrixPacking matrixPacking = fieldType.getLayoutQualifier().matrixPacking;
296 ASSERT(matrixPacking != EmpUnspecified);
298 if (fieldType.isMatrix())
300 // Use HLSL row-major packing for GLSL column-major matrices
301 const TString &matrixPackString = (matrixPacking == EmpRowMajor ? "column_major" : "row_major");
302 return matrixPackString + " " + typeString(fieldType);
304 else if (fieldType.getStruct())
306 // Use HLSL row-major packing for GLSL column-major matrices
307 return structureTypeName(*fieldType.getStruct(), matrixPacking == EmpColumnMajor, blockStorage == EbsStd140);
311 return typeString(fieldType);
315 TString OutputHLSL::interfaceBlockFieldString(const TInterfaceBlock &interfaceBlock, TLayoutBlockStorage blockStorage)
319 int elementIndex = 0;
321 for (unsigned int typeIndex = 0; typeIndex < interfaceBlock.fields().size(); typeIndex++)
323 const TField &field = *interfaceBlock.fields()[typeIndex];
324 const TType &fieldType = *field.type();
326 if (blockStorage == EbsStd140)
328 // 2 and 3 component vector types in some cases need pre-padding
329 hlsl += std140PrePaddingString(fieldType, &elementIndex);
332 hlsl += " " + interfaceBlockFieldTypeString(field, blockStorage) +
333 " " + decorate(field.name()) + arrayString(fieldType) + ";\n";
335 // must pad out after matrices and arrays, where HLSL usually allows itself room to pack stuff
336 if (blockStorage == EbsStd140)
338 const bool useHLSLRowMajorPacking = (fieldType.getLayoutQualifier().matrixPacking == EmpColumnMajor);
339 hlsl += std140PostPaddingString(fieldType, useHLSLRowMajorPacking);
346 TString OutputHLSL::interfaceBlockStructString(const TInterfaceBlock &interfaceBlock)
348 const TLayoutBlockStorage blockStorage = interfaceBlock.blockStorage();
350 return "struct " + interfaceBlockStructNameString(interfaceBlock) + "\n"
352 interfaceBlockFieldString(interfaceBlock, blockStorage) +
356 TString OutputHLSL::interfaceBlockString(const TInterfaceBlock &interfaceBlock, unsigned int registerIndex, unsigned int arrayIndex)
358 const TString &arrayIndexString = (arrayIndex != GL_INVALID_INDEX ? decorate(str(arrayIndex)) : "");
359 const TString &blockName = interfaceBlock.name() + arrayIndexString;
362 hlsl += "cbuffer " + blockName + " : register(b" + str(registerIndex) + ")\n"
365 if (interfaceBlock.hasInstanceName())
367 hlsl += " " + interfaceBlockStructNameString(interfaceBlock) + " " + interfaceBlockInstanceString(interfaceBlock, arrayIndex) + ";\n";
371 const TLayoutBlockStorage blockStorage = interfaceBlock.blockStorage();
372 hlsl += interfaceBlockFieldString(interfaceBlock, blockStorage);
380 TString OutputHLSL::std140PrePaddingString(const TType &type, int *elementIndex)
382 if (type.getBasicType() == EbtStruct || type.isMatrix() || type.isArray())
384 // no padding needed, HLSL will align the field to a new register
389 const GLenum glType = glVariableType(type);
390 const int numComponents = gl::UniformComponentCount(glType);
392 if (numComponents >= 4)
394 // no padding needed, HLSL will align the field to a new register
399 if (*elementIndex + numComponents > 4)
401 // no padding needed, HLSL will align the field to a new register
402 *elementIndex = numComponents;
408 const int alignment = numComponents == 3 ? 4 : numComponents;
409 const int paddingOffset = (*elementIndex % alignment);
411 if (paddingOffset != 0)
413 // padding is neccessary
414 for (int paddingIndex = paddingOffset; paddingIndex < alignment; paddingIndex++)
416 padding += " float pad_" + str(mPaddingCounter++) + ";\n";
419 *elementIndex += (alignment - paddingOffset);
422 *elementIndex += numComponents;
428 TString OutputHLSL::std140PostPaddingString(const TType &type, bool useHLSLRowMajorPacking)
430 if (!type.isMatrix() && !type.isArray() && type.getBasicType() != EbtStruct)
435 int numComponents = 0;
439 // This method can also be called from structureString, which does not use layout qualifiers.
440 // Thus, use the method parameter for determining the matrix packing.
442 // Note HLSL row major packing corresponds to GL API column-major, and vice-versa, since we
443 // wish to always transpose GL matrices to play well with HLSL's matrix array indexing.
445 const bool isRowMajorMatrix = !useHLSLRowMajorPacking;
446 const GLenum glType = glVariableType(type);
447 numComponents = gl::MatrixComponentCount(glType, isRowMajorMatrix);
449 else if (type.getStruct())
451 const TString &structName = structureTypeName(*type.getStruct(), useHLSLRowMajorPacking, true);
452 numComponents = mStd140StructElementIndexes[structName];
454 if (numComponents == 0)
461 const GLenum glType = glVariableType(type);
462 numComponents = gl::UniformComponentCount(glType);
466 for (int paddingOffset = numComponents; paddingOffset < 4; paddingOffset++)
468 padding += " float pad_" + str(mPaddingCounter++) + ";\n";
473 // Use the same layout for packed and shared
474 void setBlockLayout(gl::InterfaceBlock *interfaceBlock, gl::BlockLayoutType newLayout)
476 interfaceBlock->layout = newLayout;
477 interfaceBlock->blockInfo.clear();
481 case gl::BLOCKLAYOUT_SHARED:
482 case gl::BLOCKLAYOUT_PACKED:
484 gl::HLSLBlockEncoder hlslEncoder(&interfaceBlock->blockInfo, gl::HLSLBlockEncoder::ENCODE_PACKED);
485 hlslEncoder.encodeInterfaceBlockFields(interfaceBlock->fields);
486 interfaceBlock->dataSize = hlslEncoder.getBlockSize();
490 case gl::BLOCKLAYOUT_STANDARD:
492 gl::Std140BlockEncoder stdEncoder(&interfaceBlock->blockInfo);
493 stdEncoder.encodeInterfaceBlockFields(interfaceBlock->fields);
494 interfaceBlock->dataSize = stdEncoder.getBlockSize();
504 gl::BlockLayoutType convertBlockLayoutType(TLayoutBlockStorage blockStorage)
506 switch (blockStorage)
508 case EbsPacked: return gl::BLOCKLAYOUT_PACKED;
509 case EbsShared: return gl::BLOCKLAYOUT_SHARED;
510 case EbsStd140: return gl::BLOCKLAYOUT_STANDARD;
511 default: UNREACHABLE(); return gl::BLOCKLAYOUT_SHARED;
515 TString OutputHLSL::structInitializerString(int indent, const TStructure &structure, const TString &rhsStructName)
519 TString preIndentString;
520 TString fullIndentString;
522 for (int spaces = 0; spaces < (indent * 4); spaces++)
524 preIndentString += ' ';
527 for (int spaces = 0; spaces < ((indent+1) * 4); spaces++)
529 fullIndentString += ' ';
532 init += preIndentString + "{\n";
534 const TFieldList &fields = structure.fields();
535 for (unsigned int fieldIndex = 0; fieldIndex < fields.size(); fieldIndex++)
537 const TField &field = *fields[fieldIndex];
538 const TString &fieldName = rhsStructName + "." + decorate(field.name());
539 const TType &fieldType = *field.type();
541 if (fieldType.getStruct())
543 init += structInitializerString(indent + 1, *fieldType.getStruct(), fieldName);
547 init += fullIndentString + fieldName + ",\n";
551 init += preIndentString + "}" + (indent == 0 ? ";" : ",") + "\n";
556 void OutputHLSL::header()
558 TInfoSinkBase &out = mHeader;
561 TString interfaceBlocks;
564 TString flaggedStructs;
566 for (ReferencedSymbols::const_iterator uniformIt = mReferencedUniforms.begin(); uniformIt != mReferencedUniforms.end(); uniformIt++)
568 const TIntermSymbol &uniform = *uniformIt->second;
569 const TType &type = uniform.getType();
570 const TString &name = uniform.getSymbol();
572 int registerIndex = declareUniformAndAssignRegister(type, name);
574 if (mOutputType == SH_HLSL11_OUTPUT && IsSampler(type.getBasicType())) // Also declare the texture
576 uniforms += "uniform " + samplerString(type) + " sampler_" + decorateUniform(name, type) + arrayString(type) +
577 " : register(s" + str(registerIndex) + ");\n";
579 uniforms += "uniform " + textureString(type) + " texture_" + decorateUniform(name, type) + arrayString(type) +
580 " : register(t" + str(registerIndex) + ");\n";
584 const TStructure *structure = type.getStruct();
585 const TString &typeName = (structure ? structureTypeName(*structure, false, false) : typeString(type));
587 const TString ®isterString = TString("register(") + RegisterPrefix(type) + str(registerIndex) + ")";
589 uniforms += "uniform " + typeName + " " + decorateUniform(name, type) + arrayString(type) + " : " + registerString + ";\n";
593 for (ReferencedSymbols::const_iterator interfaceBlockIt = mReferencedInterfaceBlocks.begin(); interfaceBlockIt != mReferencedInterfaceBlocks.end(); interfaceBlockIt++)
595 const TType &nodeType = interfaceBlockIt->second->getType();
596 const TInterfaceBlock &interfaceBlock = *nodeType.getInterfaceBlock();
597 const TFieldList &fieldList = interfaceBlock.fields();
599 unsigned int arraySize = static_cast<unsigned int>(interfaceBlock.arraySize());
600 gl::InterfaceBlock activeBlock(interfaceBlock.name().c_str(), arraySize, mInterfaceBlockRegister);
601 for (unsigned int typeIndex = 0; typeIndex < fieldList.size(); typeIndex++)
603 const TField &field = *fieldList[typeIndex];
604 const TString &fullUniformName = interfaceBlockFieldString(interfaceBlock, field);
605 declareInterfaceBlockField(*field.type(), fullUniformName, activeBlock.fields);
608 mInterfaceBlockRegister += std::max(1u, arraySize);
610 gl::BlockLayoutType blockLayoutType = convertBlockLayoutType(interfaceBlock.blockStorage());
611 setBlockLayout(&activeBlock, blockLayoutType);
613 if (interfaceBlock.matrixPacking() == EmpRowMajor)
615 activeBlock.isRowMajorLayout = true;
618 mActiveInterfaceBlocks.push_back(activeBlock);
620 if (interfaceBlock.hasInstanceName())
622 interfaceBlocks += interfaceBlockStructString(interfaceBlock);
627 for (unsigned int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++)
629 interfaceBlocks += interfaceBlockString(interfaceBlock, activeBlock.registerIndex + arrayIndex, arrayIndex);
634 interfaceBlocks += interfaceBlockString(interfaceBlock, activeBlock.registerIndex, GL_INVALID_INDEX);
638 for (std::map<TIntermTyped*, TString>::const_iterator flaggedStructIt = mFlaggedStructMappedNames.begin(); flaggedStructIt != mFlaggedStructMappedNames.end(); flaggedStructIt++)
640 TIntermTyped *structNode = flaggedStructIt->first;
641 const TString &mappedName = flaggedStructIt->second;
642 const TStructure &structure = *structNode->getType().getStruct();
643 const TString &originalName = mFlaggedStructOriginalNames[structNode];
645 flaggedStructs += "static " + decorate(structure.name()) + " " + mappedName + " =\n";
646 flaggedStructs += structInitializerString(0, structure, originalName);
647 flaggedStructs += "\n";
650 for (ReferencedSymbols::const_iterator varying = mReferencedVaryings.begin(); varying != mReferencedVaryings.end(); varying++)
652 const TType &type = varying->second->getType();
653 const TString &name = varying->second->getSymbol();
655 // Program linking depends on this exact format
656 varyings += "static " + interpolationString(type.getQualifier()) + " " + typeString(type) + " " +
657 decorate(name) + arrayString(type) + " = " + initializer(type) + ";\n";
659 declareVaryingToList(type, type.getQualifier(), name, mActiveVaryings);
662 for (ReferencedSymbols::const_iterator attribute = mReferencedAttributes.begin(); attribute != mReferencedAttributes.end(); attribute++)
664 const TType &type = attribute->second->getType();
665 const TString &name = attribute->second->getSymbol();
667 attributes += "static " + typeString(type) + " " + decorate(name) + arrayString(type) + " = " + initializer(type) + ";\n";
669 gl::Attribute attributeVar(glVariableType(type), glVariablePrecision(type), name.c_str(),
670 (unsigned int)type.getArraySize(), type.getLayoutQualifier().location);
671 mActiveAttributes.push_back(attributeVar);
674 for (StructDeclarations::iterator structDeclaration = mStructDeclarations.begin(); structDeclaration != mStructDeclarations.end(); structDeclaration++)
676 out << *structDeclaration;
679 for (Constructors::iterator constructor = mConstructors.begin(); constructor != mConstructors.end(); constructor++)
684 if (mUsesDiscardRewriting)
686 out << "#define ANGLE_USES_DISCARD_REWRITING" << "\n";
689 if (mUsesNestedBreak)
691 out << "#define ANGLE_USES_NESTED_BREAK" << "\n";
694 if (mContext.shaderType == SH_FRAGMENT_SHADER)
696 TExtensionBehavior::const_iterator iter = mContext.extensionBehavior().find("GL_EXT_draw_buffers");
697 const bool usingMRTExtension = (iter != mContext.extensionBehavior().end() && (iter->second == EBhEnable || iter->second == EBhRequire));
699 out << "// Varyings\n";
703 if (mContext.getShaderVersion() >= 300)
705 for (ReferencedSymbols::const_iterator outputVariableIt = mReferencedOutputVariables.begin(); outputVariableIt != mReferencedOutputVariables.end(); outputVariableIt++)
707 const TString &variableName = outputVariableIt->first;
708 const TType &variableType = outputVariableIt->second->getType();
709 const TLayoutQualifier &layoutQualifier = variableType.getLayoutQualifier();
711 out << "static " + typeString(variableType) + " out_" + variableName + arrayString(variableType) +
712 " = " + initializer(variableType) + ";\n";
714 gl::Attribute outputVar(glVariableType(variableType), glVariablePrecision(variableType), variableName.c_str(),
715 (unsigned int)variableType.getArraySize(), layoutQualifier.location);
716 mActiveOutputVariables.push_back(outputVar);
721 const unsigned int numColorValues = usingMRTExtension ? mNumRenderTargets : 1;
723 out << "static float4 gl_Color[" << numColorValues << "] =\n"
725 for (unsigned int i = 0; i < numColorValues; i++)
727 out << " float4(0, 0, 0, 0)";
728 if (i + 1 != numColorValues)
740 out << "static float gl_Depth = 0.0;\n";
745 out << "static float4 gl_FragCoord = float4(0, 0, 0, 0);\n";
750 out << "static float2 gl_PointCoord = float2(0.5, 0.5);\n";
753 if (mUsesFrontFacing)
755 out << "static bool gl_FrontFacing = false;\n";
762 out << "struct gl_DepthRangeParameters\n"
771 if (mOutputType == SH_HLSL11_OUTPUT)
773 out << "cbuffer DriverConstants : register(b1)\n"
778 out << " float3 dx_DepthRange : packoffset(c0);\n";
783 out << " float4 dx_ViewCoords : packoffset(c1);\n";
786 if (mUsesFragCoord || mUsesFrontFacing)
788 out << " float3 dx_DepthFront : packoffset(c2);\n";
797 out << "uniform float3 dx_DepthRange : register(c0);";
802 out << "uniform float4 dx_ViewCoords : register(c1);\n";
805 if (mUsesFragCoord || mUsesFrontFacing)
807 out << "uniform float3 dx_DepthFront : register(c2);\n";
815 out << "static gl_DepthRangeParameters gl_DepthRange = {dx_DepthRange.x, dx_DepthRange.y, dx_DepthRange.z};\n"
822 if (!interfaceBlocks.empty())
824 out << interfaceBlocks;
827 if (!flaggedStructs.empty())
829 out << "// Std140 Structures accessed by value\n";
831 out << flaggedStructs;
836 if (usingMRTExtension && mNumRenderTargets > 1)
838 out << "#define GL_USES_MRT\n";
843 out << "#define GL_USES_FRAG_COLOR\n";
848 out << "#define GL_USES_FRAG_DATA\n";
851 else // Vertex shader
853 out << "// Attributes\n";
856 "static float4 gl_Position = float4(0, 0, 0, 0);\n";
860 out << "static float gl_PointSize = float(1);\n";
870 out << "struct gl_DepthRangeParameters\n"
879 if (mOutputType == SH_HLSL11_OUTPUT)
883 out << "cbuffer DriverConstants : register(b1)\n"
885 " float3 dx_DepthRange : packoffset(c0);\n"
894 out << "uniform float3 dx_DepthRange : register(c0);\n";
897 out << "uniform float4 dx_ViewAdjust : register(c1);\n"
903 out << "static gl_DepthRangeParameters gl_DepthRange = {dx_DepthRange.x, dx_DepthRange.y, dx_DepthRange.z};\n"
910 if (!interfaceBlocks.empty())
912 out << interfaceBlocks;
915 if (!flaggedStructs.empty())
917 out << "// Std140 Structures accessed by value\n";
919 out << flaggedStructs;
925 for (TextureFunctionSet::const_iterator textureFunction = mUsesTexture.begin(); textureFunction != mUsesTexture.end(); textureFunction++)
928 if (textureFunction->method == TextureFunction::SIZE)
930 switch(textureFunction->sampler)
932 case EbtSampler2D: out << "int2 "; break;
933 case EbtSampler3D: out << "int3 "; break;
934 case EbtSamplerCube: out << "int2 "; break;
935 case EbtSampler2DArray: out << "int3 "; break;
936 case EbtISampler2D: out << "int2 "; break;
937 case EbtISampler3D: out << "int3 "; break;
938 case EbtISamplerCube: out << "int2 "; break;
939 case EbtISampler2DArray: out << "int3 "; break;
940 case EbtUSampler2D: out << "int2 "; break;
941 case EbtUSampler3D: out << "int3 "; break;
942 case EbtUSamplerCube: out << "int2 "; break;
943 case EbtUSampler2DArray: out << "int3 "; break;
944 case EbtSampler2DShadow: out << "int2 "; break;
945 case EbtSamplerCubeShadow: out << "int2 "; break;
946 case EbtSampler2DArrayShadow: out << "int3 "; break;
947 default: UNREACHABLE();
950 else // Sampling function
952 switch(textureFunction->sampler)
954 case EbtSampler2D: out << "float4 "; break;
955 case EbtSampler3D: out << "float4 "; break;
956 case EbtSamplerCube: out << "float4 "; break;
957 case EbtSampler2DArray: out << "float4 "; break;
958 case EbtISampler2D: out << "int4 "; break;
959 case EbtISampler3D: out << "int4 "; break;
960 case EbtISamplerCube: out << "int4 "; break;
961 case EbtISampler2DArray: out << "int4 "; break;
962 case EbtUSampler2D: out << "uint4 "; break;
963 case EbtUSampler3D: out << "uint4 "; break;
964 case EbtUSamplerCube: out << "uint4 "; break;
965 case EbtUSampler2DArray: out << "uint4 "; break;
966 case EbtSampler2DShadow: out << "float "; break;
967 case EbtSamplerCubeShadow: out << "float "; break;
968 case EbtSampler2DArrayShadow: out << "float "; break;
969 default: UNREACHABLE();
974 out << textureFunction->name();
979 if (mOutputType == SH_HLSL9_OUTPUT)
981 switch(textureFunction->sampler)
983 case EbtSampler2D: out << "sampler2D s"; hlslCoords = 2; break;
984 case EbtSamplerCube: out << "samplerCUBE s"; hlslCoords = 3; break;
985 default: UNREACHABLE();
988 switch(textureFunction->method)
990 case TextureFunction::IMPLICIT: break;
991 case TextureFunction::BIAS: hlslCoords = 4; break;
992 case TextureFunction::LOD: hlslCoords = 4; break;
993 case TextureFunction::LOD0: hlslCoords = 4; break;
994 case TextureFunction::LOD0BIAS: hlslCoords = 4; break;
995 default: UNREACHABLE();
998 else if (mOutputType == SH_HLSL11_OUTPUT)
1000 switch(textureFunction->sampler)
1002 case EbtSampler2D: out << "Texture2D x, SamplerState s"; hlslCoords = 2; break;
1003 case EbtSampler3D: out << "Texture3D x, SamplerState s"; hlslCoords = 3; break;
1004 case EbtSamplerCube: out << "TextureCube x, SamplerState s"; hlslCoords = 3; break;
1005 case EbtSampler2DArray: out << "Texture2DArray x, SamplerState s"; hlslCoords = 3; break;
1006 case EbtISampler2D: out << "Texture2D<int4> x, SamplerState s"; hlslCoords = 2; break;
1007 case EbtISampler3D: out << "Texture3D<int4> x, SamplerState s"; hlslCoords = 3; break;
1008 case EbtISamplerCube: out << "Texture2DArray<int4> x, SamplerState s"; hlslCoords = 3; break;
1009 case EbtISampler2DArray: out << "Texture2DArray<int4> x, SamplerState s"; hlslCoords = 3; break;
1010 case EbtUSampler2D: out << "Texture2D<uint4> x, SamplerState s"; hlslCoords = 2; break;
1011 case EbtUSampler3D: out << "Texture3D<uint4> x, SamplerState s"; hlslCoords = 3; break;
1012 case EbtUSamplerCube: out << "Texture2DArray<uint4> x, SamplerState s"; hlslCoords = 3; break;
1013 case EbtUSampler2DArray: out << "Texture2DArray<uint4> x, SamplerState s"; hlslCoords = 3; break;
1014 case EbtSampler2DShadow: out << "Texture2D x, SamplerComparisonState s"; hlslCoords = 2; break;
1015 case EbtSamplerCubeShadow: out << "TextureCube x, SamplerComparisonState s"; hlslCoords = 3; break;
1016 case EbtSampler2DArrayShadow: out << "Texture2DArray x, SamplerComparisonState s"; hlslCoords = 3; break;
1017 default: UNREACHABLE();
1022 if (textureFunction->method == TextureFunction::FETCH) // Integer coordinates
1024 switch(textureFunction->coords)
1026 case 2: out << ", int2 t"; break;
1027 case 3: out << ", int3 t"; break;
1028 default: UNREACHABLE();
1031 else // Floating-point coordinates (except textureSize)
1033 switch(textureFunction->coords)
1035 case 1: out << ", int lod"; break; // textureSize()
1036 case 2: out << ", float2 t"; break;
1037 case 3: out << ", float3 t"; break;
1038 case 4: out << ", float4 t"; break;
1039 default: UNREACHABLE();
1043 if (textureFunction->method == TextureFunction::GRAD)
1045 switch(textureFunction->sampler)
1050 case EbtSampler2DArray:
1051 case EbtISampler2DArray:
1052 case EbtUSampler2DArray:
1053 case EbtSampler2DShadow:
1054 case EbtSampler2DArrayShadow:
1055 out << ", float2 ddx, float2 ddy";
1060 case EbtSamplerCube:
1061 case EbtISamplerCube:
1062 case EbtUSamplerCube:
1063 case EbtSamplerCubeShadow:
1064 out << ", float3 ddx, float3 ddy";
1066 default: UNREACHABLE();
1070 switch(textureFunction->method)
1072 case TextureFunction::IMPLICIT: break;
1073 case TextureFunction::BIAS: break; // Comes after the offset parameter
1074 case TextureFunction::LOD: out << ", float lod"; break;
1075 case TextureFunction::LOD0: break;
1076 case TextureFunction::LOD0BIAS: break; // Comes after the offset parameter
1077 case TextureFunction::SIZE: break;
1078 case TextureFunction::FETCH: out << ", int mip"; break;
1079 case TextureFunction::GRAD: break;
1080 default: UNREACHABLE();
1083 if (textureFunction->offset)
1085 switch(textureFunction->sampler)
1087 case EbtSampler2D: out << ", int2 offset"; break;
1088 case EbtSampler3D: out << ", int3 offset"; break;
1089 case EbtSampler2DArray: out << ", int2 offset"; break;
1090 case EbtISampler2D: out << ", int2 offset"; break;
1091 case EbtISampler3D: out << ", int3 offset"; break;
1092 case EbtISampler2DArray: out << ", int2 offset"; break;
1093 case EbtUSampler2D: out << ", int2 offset"; break;
1094 case EbtUSampler3D: out << ", int3 offset"; break;
1095 case EbtUSampler2DArray: out << ", int2 offset"; break;
1096 case EbtSampler2DShadow: out << ", int2 offset"; break;
1097 case EbtSampler2DArrayShadow: out << ", int2 offset"; break;
1098 default: UNREACHABLE();
1102 if (textureFunction->method == TextureFunction::BIAS ||
1103 textureFunction->method == TextureFunction::LOD0BIAS)
1105 out << ", float bias";
1111 if (textureFunction->method == TextureFunction::SIZE)
1113 if (IsSampler2D(textureFunction->sampler) || IsSamplerCube(textureFunction->sampler))
1115 if (IsSamplerArray(textureFunction->sampler))
1117 out << " uint width; uint height; uint layers; uint numberOfLevels;\n"
1118 " x.GetDimensions(lod, width, height, layers, numberOfLevels);\n";
1122 out << " uint width; uint height; uint numberOfLevels;\n"
1123 " x.GetDimensions(lod, width, height, numberOfLevels);\n";
1126 else if (IsSampler3D(textureFunction->sampler))
1128 out << " uint width; uint height; uint depth; uint numberOfLevels;\n"
1129 " x.GetDimensions(lod, width, height, depth, numberOfLevels);\n";
1133 switch(textureFunction->sampler)
1135 case EbtSampler2D: out << " return int2(width, height);"; break;
1136 case EbtSampler3D: out << " return int3(width, height, depth);"; break;
1137 case EbtSamplerCube: out << " return int2(width, height);"; break;
1138 case EbtSampler2DArray: out << " return int3(width, height, layers);"; break;
1139 case EbtISampler2D: out << " return int2(width, height);"; break;
1140 case EbtISampler3D: out << " return int3(width, height, depth);"; break;
1141 case EbtISamplerCube: out << " return int2(width, height);"; break;
1142 case EbtISampler2DArray: out << " return int3(width, height, layers);"; break;
1143 case EbtUSampler2D: out << " return int2(width, height);"; break;
1144 case EbtUSampler3D: out << " return int3(width, height, depth);"; break;
1145 case EbtUSamplerCube: out << " return int2(width, height);"; break;
1146 case EbtUSampler2DArray: out << " return int3(width, height, layers);"; break;
1147 case EbtSampler2DShadow: out << " return int2(width, height);"; break;
1148 case EbtSamplerCubeShadow: out << " return int2(width, height);"; break;
1149 case EbtSampler2DArrayShadow: out << " return int3(width, height, layers);"; break;
1150 default: UNREACHABLE();
1155 if (IsIntegerSampler(textureFunction->sampler) && IsSamplerCube(textureFunction->sampler))
1157 out << " float width; float height; float layers; float levels;\n";
1159 out << " uint mip = 0;\n";
1161 out << " x.GetDimensions(mip, width, height, layers, levels);\n";
1163 out << " bool xMajor = abs(t.x) > abs(t.y) && abs(t.x) > abs(t.z);\n";
1164 out << " bool yMajor = abs(t.y) > abs(t.z) && abs(t.y) > abs(t.x);\n";
1165 out << " bool zMajor = abs(t.z) > abs(t.x) && abs(t.z) > abs(t.y);\n";
1166 out << " bool negative = (xMajor && t.x < 0.0f) || (yMajor && t.y < 0.0f) || (zMajor && t.z < 0.0f);\n";
1168 // FACE_POSITIVE_X = 000b
1169 // FACE_NEGATIVE_X = 001b
1170 // FACE_POSITIVE_Y = 010b
1171 // FACE_NEGATIVE_Y = 011b
1172 // FACE_POSITIVE_Z = 100b
1173 // FACE_NEGATIVE_Z = 101b
1174 out << " int face = (int)negative + (int)yMajor * 2 + (int)zMajor * 4;\n";
1176 out << " float u = xMajor ? -t.z : (yMajor && t.y < 0.0f ? -t.x : t.x);\n";
1177 out << " float v = yMajor ? t.z : (negative ? t.y : -t.y);\n";
1178 out << " float m = xMajor ? t.x : (yMajor ? t.y : t.z);\n";
1180 out << " t.x = (u * 0.5f / m) + 0.5f;\n";
1181 out << " t.y = (v * 0.5f / m) + 0.5f;\n";
1183 else if (IsIntegerSampler(textureFunction->sampler) &&
1184 textureFunction->method != TextureFunction::FETCH)
1186 if (IsSampler2D(textureFunction->sampler))
1188 if (IsSamplerArray(textureFunction->sampler))
1190 out << " float width; float height; float layers; float levels;\n";
1192 if (textureFunction->method == TextureFunction::LOD0)
1194 out << " uint mip = 0;\n";
1196 else if (textureFunction->method == TextureFunction::LOD0BIAS)
1198 out << " uint mip = bias;\n";
1202 if (textureFunction->method == TextureFunction::IMPLICIT ||
1203 textureFunction->method == TextureFunction::BIAS)
1205 out << " x.GetDimensions(0, width, height, layers, levels);\n"
1206 " float2 tSized = float2(t.x * width, t.y * height);\n"
1207 " float dx = length(ddx(tSized));\n"
1208 " float dy = length(ddy(tSized));\n"
1209 " float lod = log2(max(dx, dy));\n";
1211 if (textureFunction->method == TextureFunction::BIAS)
1213 out << " lod += bias;\n";
1216 else if (textureFunction->method == TextureFunction::GRAD)
1218 out << " x.GetDimensions(0, width, height, layers, levels);\n"
1219 " float lod = log2(max(length(ddx), length(ddy)));\n";
1222 out << " uint mip = uint(min(max(round(lod), 0), levels - 1));\n";
1225 out << " x.GetDimensions(mip, width, height, layers, levels);\n";
1229 out << " float width; float height; float levels;\n";
1231 if (textureFunction->method == TextureFunction::LOD0)
1233 out << " uint mip = 0;\n";
1235 else if (textureFunction->method == TextureFunction::LOD0BIAS)
1237 out << " uint mip = bias;\n";
1241 if (textureFunction->method == TextureFunction::IMPLICIT ||
1242 textureFunction->method == TextureFunction::BIAS)
1244 out << " x.GetDimensions(0, width, height, levels);\n"
1245 " float2 tSized = float2(t.x * width, t.y * height);\n"
1246 " float dx = length(ddx(tSized));\n"
1247 " float dy = length(ddy(tSized));\n"
1248 " float lod = log2(max(dx, dy));\n";
1250 if (textureFunction->method == TextureFunction::BIAS)
1252 out << " lod += bias;\n";
1255 else if (textureFunction->method == TextureFunction::LOD)
1257 out << " x.GetDimensions(0, width, height, levels);\n";
1259 else if (textureFunction->method == TextureFunction::GRAD)
1261 out << " x.GetDimensions(0, width, height, levels);\n"
1262 " float lod = log2(max(length(ddx), length(ddy)));\n";
1265 out << " uint mip = uint(min(max(round(lod), 0), levels - 1));\n";
1268 out << " x.GetDimensions(mip, width, height, levels);\n";
1271 else if (IsSampler3D(textureFunction->sampler))
1273 out << " float width; float height; float depth; float levels;\n";
1275 if (textureFunction->method == TextureFunction::LOD0)
1277 out << " uint mip = 0;\n";
1279 else if (textureFunction->method == TextureFunction::LOD0BIAS)
1281 out << " uint mip = bias;\n";
1285 if (textureFunction->method == TextureFunction::IMPLICIT ||
1286 textureFunction->method == TextureFunction::BIAS)
1288 out << " x.GetDimensions(0, width, height, depth, levels);\n"
1289 " float3 tSized = float3(t.x * width, t.y * height, t.z * depth);\n"
1290 " float dx = length(ddx(tSized));\n"
1291 " float dy = length(ddy(tSized));\n"
1292 " float lod = log2(max(dx, dy));\n";
1294 if (textureFunction->method == TextureFunction::BIAS)
1296 out << " lod += bias;\n";
1299 else if (textureFunction->method == TextureFunction::GRAD)
1301 out << " x.GetDimensions(0, width, height, depth, levels);\n"
1302 " float lod = log2(max(length(ddx), length(ddy)));\n";
1305 out << " uint mip = uint(min(max(round(lod), 0), levels - 1));\n";
1308 out << " x.GetDimensions(mip, width, height, depth, levels);\n";
1316 if (mOutputType == SH_HLSL9_OUTPUT)
1318 switch(textureFunction->sampler)
1320 case EbtSampler2D: out << "tex2D"; break;
1321 case EbtSamplerCube: out << "texCUBE"; break;
1322 default: UNREACHABLE();
1325 switch(textureFunction->method)
1327 case TextureFunction::IMPLICIT: out << "(s, "; break;
1328 case TextureFunction::BIAS: out << "bias(s, "; break;
1329 case TextureFunction::LOD: out << "lod(s, "; break;
1330 case TextureFunction::LOD0: out << "lod(s, "; break;
1331 case TextureFunction::LOD0BIAS: out << "lod(s, "; break;
1332 default: UNREACHABLE();
1335 else if (mOutputType == SH_HLSL11_OUTPUT)
1337 if (textureFunction->method == TextureFunction::GRAD)
1339 if (IsIntegerSampler(textureFunction->sampler))
1343 else if (IsShadowSampler(textureFunction->sampler))
1345 out << "x.SampleCmpLevelZero(s, ";
1349 out << "x.SampleGrad(s, ";
1352 else if (IsIntegerSampler(textureFunction->sampler) ||
1353 textureFunction->method == TextureFunction::FETCH)
1357 else if (IsShadowSampler(textureFunction->sampler))
1359 out << "x.SampleCmp(s, ";
1363 switch(textureFunction->method)
1365 case TextureFunction::IMPLICIT: out << "x.Sample(s, "; break;
1366 case TextureFunction::BIAS: out << "x.SampleBias(s, "; break;
1367 case TextureFunction::LOD: out << "x.SampleLevel(s, "; break;
1368 case TextureFunction::LOD0: out << "x.SampleLevel(s, "; break;
1369 case TextureFunction::LOD0BIAS: out << "x.SampleLevel(s, "; break;
1370 default: UNREACHABLE();
1376 // Integer sampling requires integer addresses
1377 TString addressx = "";
1378 TString addressy = "";
1379 TString addressz = "";
1382 if (IsIntegerSampler(textureFunction->sampler) ||
1383 textureFunction->method == TextureFunction::FETCH)
1387 case 2: out << "int3("; break;
1388 case 3: out << "int4("; break;
1389 default: UNREACHABLE();
1392 // Convert from normalized floating-point to integer
1393 if (textureFunction->method != TextureFunction::FETCH)
1395 addressx = "int(floor(width * frac((";
1396 addressy = "int(floor(height * frac((";
1398 if (IsSamplerArray(textureFunction->sampler))
1400 addressz = "int(max(0, min(layers - 1, floor(0.5 + ";
1402 else if (IsSamplerCube(textureFunction->sampler))
1408 addressz = "int(floor(depth * frac((";
1418 case 2: out << "float2("; break;
1419 case 3: out << "float3("; break;
1420 case 4: out << "float4("; break;
1421 default: UNREACHABLE();
1425 TString proj = ""; // Only used for projected textures
1427 if (textureFunction->proj)
1429 switch(textureFunction->coords)
1431 case 3: proj = " / t.z"; break;
1432 case 4: proj = " / t.w"; break;
1433 default: UNREACHABLE();
1437 out << addressx + ("t.x" + proj) + close + ", " + addressy + ("t.y" + proj) + close;
1439 if (mOutputType == SH_HLSL9_OUTPUT)
1441 if (hlslCoords >= 3)
1443 if (textureFunction->coords < 3)
1449 out << ", t.z" + proj;
1453 if (hlslCoords == 4)
1455 switch(textureFunction->method)
1457 case TextureFunction::BIAS: out << ", bias"; break;
1458 case TextureFunction::LOD: out << ", lod"; break;
1459 case TextureFunction::LOD0: out << ", 0"; break;
1460 case TextureFunction::LOD0BIAS: out << ", bias"; break;
1461 default: UNREACHABLE();
1467 else if (mOutputType == SH_HLSL11_OUTPUT)
1469 if (hlslCoords >= 3)
1471 if (IsIntegerSampler(textureFunction->sampler) && IsSamplerCube(textureFunction->sampler))
1477 out << ", " + addressz + ("t.z" + proj) + close;
1481 if (textureFunction->method == TextureFunction::GRAD)
1483 if (IsIntegerSampler(textureFunction->sampler))
1487 else if (IsShadowSampler(textureFunction->sampler))
1490 switch(textureFunction->coords)
1492 case 3: out << "), t.z"; break;
1493 case 4: out << "), t.w"; break;
1494 default: UNREACHABLE();
1499 out << "), ddx, ddy";
1502 else if (IsIntegerSampler(textureFunction->sampler) ||
1503 textureFunction->method == TextureFunction::FETCH)
1507 else if (IsShadowSampler(textureFunction->sampler))
1510 switch(textureFunction->coords)
1512 case 3: out << "), t.z"; break;
1513 case 4: out << "), t.w"; break;
1514 default: UNREACHABLE();
1519 switch(textureFunction->method)
1521 case TextureFunction::IMPLICIT: out << ")"; break;
1522 case TextureFunction::BIAS: out << "), bias"; break;
1523 case TextureFunction::LOD: out << "), lod"; break;
1524 case TextureFunction::LOD0: out << "), 0"; break;
1525 case TextureFunction::LOD0BIAS: out << "), bias"; break;
1526 default: UNREACHABLE();
1530 if (textureFunction->offset)
1547 out << "#define GL_USES_FRAG_COORD\n";
1550 if (mUsesPointCoord)
1552 out << "#define GL_USES_POINT_COORD\n";
1555 if (mUsesFrontFacing)
1557 out << "#define GL_USES_FRONT_FACING\n";
1562 out << "#define GL_USES_POINT_SIZE\n";
1567 out << "#define GL_USES_FRAG_DEPTH\n";
1570 if (mUsesDepthRange)
1572 out << "#define GL_USES_DEPTH_RANGE\n";
1577 out << "bool xor(bool p, bool q)\n"
1579 " return (p || q) && !(p && q);\n"
1586 out << "float mod(float x, float y)\n"
1588 " return x - y * floor(x / y);\n"
1595 out << "float2 mod(float2 x, float2 y)\n"
1597 " return x - y * floor(x / y);\n"
1604 out << "float2 mod(float2 x, float y)\n"
1606 " return x - y * floor(x / y);\n"
1613 out << "float3 mod(float3 x, float3 y)\n"
1615 " return x - y * floor(x / y);\n"
1622 out << "float3 mod(float3 x, float y)\n"
1624 " return x - y * floor(x / y);\n"
1631 out << "float4 mod(float4 x, float4 y)\n"
1633 " return x - y * floor(x / y);\n"
1640 out << "float4 mod(float4 x, float y)\n"
1642 " return x - y * floor(x / y);\n"
1647 if (mUsesFaceforward1)
1649 out << "float faceforward(float N, float I, float Nref)\n"
1651 " if(dot(Nref, I) >= 0)\n"
1663 if (mUsesFaceforward2)
1665 out << "float2 faceforward(float2 N, float2 I, float2 Nref)\n"
1667 " if(dot(Nref, I) >= 0)\n"
1679 if (mUsesFaceforward3)
1681 out << "float3 faceforward(float3 N, float3 I, float3 Nref)\n"
1683 " if(dot(Nref, I) >= 0)\n"
1695 if (mUsesFaceforward4)
1697 out << "float4 faceforward(float4 N, float4 I, float4 Nref)\n"
1699 " if(dot(Nref, I) >= 0)\n"
1713 out << "float atanyx(float y, float x)\n"
1715 " if(x == 0 && y == 0) x = 1;\n" // Avoid producing a NaN
1716 " return atan2(y, x);\n"
1722 out << "float2 atanyx(float2 y, float2 x)\n"
1724 " if(x[0] == 0 && y[0] == 0) x[0] = 1;\n"
1725 " if(x[1] == 0 && y[1] == 0) x[1] = 1;\n"
1726 " return float2(atan2(y[0], x[0]), atan2(y[1], x[1]));\n"
1732 out << "float3 atanyx(float3 y, float3 x)\n"
1734 " if(x[0] == 0 && y[0] == 0) x[0] = 1;\n"
1735 " if(x[1] == 0 && y[1] == 0) x[1] = 1;\n"
1736 " if(x[2] == 0 && y[2] == 0) x[2] = 1;\n"
1737 " return float3(atan2(y[0], x[0]), atan2(y[1], x[1]), atan2(y[2], x[2]));\n"
1743 out << "float4 atanyx(float4 y, float4 x)\n"
1745 " if(x[0] == 0 && y[0] == 0) x[0] = 1;\n"
1746 " if(x[1] == 0 && y[1] == 0) x[1] = 1;\n"
1747 " if(x[2] == 0 && y[2] == 0) x[2] = 1;\n"
1748 " if(x[3] == 0 && y[3] == 0) x[3] = 1;\n"
1749 " return float4(atan2(y[0], x[0]), atan2(y[1], x[1]), atan2(y[2], x[2]), atan2(y[3], x[3]));\n"
1754 void OutputHLSL::visitSymbol(TIntermSymbol *node)
1756 TInfoSinkBase &out = mBody;
1758 // Handle accessing std140 structs by value
1759 if (mFlaggedStructMappedNames.count(node) > 0)
1761 out << mFlaggedStructMappedNames[node];
1765 TString name = node->getSymbol();
1767 if (name == "gl_DepthRange")
1769 mUsesDepthRange = true;
1774 TQualifier qualifier = node->getQualifier();
1776 if (qualifier == EvqUniform)
1778 const TType& nodeType = node->getType();
1779 const TInterfaceBlock* interfaceBlock = nodeType.getInterfaceBlock();
1783 mReferencedInterfaceBlocks[interfaceBlock->name()] = node;
1787 mReferencedUniforms[name] = node;
1790 out << decorateUniform(name, nodeType);
1792 else if (qualifier == EvqAttribute || qualifier == EvqVertexIn)
1794 mReferencedAttributes[name] = node;
1795 out << decorate(name);
1797 else if (isVarying(qualifier))
1799 mReferencedVaryings[name] = node;
1800 out << decorate(name);
1802 else if (qualifier == EvqFragmentOut)
1804 mReferencedOutputVariables[name] = node;
1805 out << "out_" << name;
1807 else if (qualifier == EvqFragColor)
1809 out << "gl_Color[0]";
1810 mUsesFragColor = true;
1812 else if (qualifier == EvqFragData)
1815 mUsesFragData = true;
1817 else if (qualifier == EvqFragCoord)
1819 mUsesFragCoord = true;
1822 else if (qualifier == EvqPointCoord)
1824 mUsesPointCoord = true;
1827 else if (qualifier == EvqFrontFacing)
1829 mUsesFrontFacing = true;
1832 else if (qualifier == EvqPointSize)
1834 mUsesPointSize = true;
1837 else if (name == "gl_FragDepthEXT")
1839 mUsesFragDepth = true;
1842 else if (qualifier == EvqInternal)
1848 out << decorate(name);
1853 void OutputHLSL::visitRaw(TIntermRaw *node)
1855 mBody << node->getRawText();
1858 bool OutputHLSL::visitBinary(Visit visit, TIntermBinary *node)
1860 TInfoSinkBase &out = mBody;
1862 // Handle accessing std140 structs by value
1863 if (mFlaggedStructMappedNames.count(node) > 0)
1865 out << mFlaggedStructMappedNames[node];
1869 switch (node->getOp())
1871 case EOpAssign: outputTriplet(visit, "(", " = ", ")"); break;
1873 if (visit == PreVisit)
1875 // GLSL allows to write things like "float x = x;" where a new variable x is defined
1876 // and the value of an existing variable x is assigned. HLSL uses C semantics (the
1877 // new variable is created before the assignment is evaluated), so we need to convert
1878 // this to "float t = x, x = t;".
1880 TIntermSymbol *symbolNode = node->getLeft()->getAsSymbolNode();
1881 TIntermTyped *expression = node->getRight();
1883 sh::SearchSymbol searchSymbol(symbolNode->getSymbol());
1884 expression->traverse(&searchSymbol);
1885 bool sameSymbol = searchSymbol.foundMatch();
1889 // Type already printed
1890 out << "t" + str(mUniqueIndex) + " = ";
1891 expression->traverse(this);
1893 symbolNode->traverse(this);
1894 out << " = t" + str(mUniqueIndex);
1900 else if (visit == InVisit)
1905 case EOpAddAssign: outputTriplet(visit, "(", " += ", ")"); break;
1906 case EOpSubAssign: outputTriplet(visit, "(", " -= ", ")"); break;
1907 case EOpMulAssign: outputTriplet(visit, "(", " *= ", ")"); break;
1908 case EOpVectorTimesScalarAssign: outputTriplet(visit, "(", " *= ", ")"); break;
1909 case EOpMatrixTimesScalarAssign: outputTriplet(visit, "(", " *= ", ")"); break;
1910 case EOpVectorTimesMatrixAssign:
1911 if (visit == PreVisit)
1915 else if (visit == InVisit)
1918 node->getLeft()->traverse(this);
1919 out << ", transpose(";
1926 case EOpMatrixTimesMatrixAssign:
1927 if (visit == PreVisit)
1931 else if (visit == InVisit)
1934 node->getLeft()->traverse(this);
1942 case EOpDivAssign: outputTriplet(visit, "(", " /= ", ")"); break;
1943 case EOpIndexDirect:
1945 const TType& leftType = node->getLeft()->getType();
1946 if (leftType.isInterfaceBlock())
1948 if (visit == PreVisit)
1950 TInterfaceBlock* interfaceBlock = leftType.getInterfaceBlock();
1951 const int arrayIndex = node->getRight()->getAsConstantUnion()->getIConst(0);
1953 mReferencedInterfaceBlocks[interfaceBlock->instanceName()] = node->getLeft()->getAsSymbolNode();
1954 out << interfaceBlockInstanceString(*interfaceBlock, arrayIndex);
1961 outputTriplet(visit, "", "[", "]");
1965 case EOpIndexIndirect:
1966 // We do not currently support indirect references to interface blocks
1967 ASSERT(node->getLeft()->getBasicType() != EbtInterfaceBlock);
1968 outputTriplet(visit, "", "[", "]");
1970 case EOpIndexDirectStruct:
1971 if (visit == InVisit)
1973 const TStructure* structure = node->getLeft()->getType().getStruct();
1974 const TIntermConstantUnion* index = node->getRight()->getAsConstantUnion();
1975 const TField* field = structure->fields()[index->getIConst(0)];
1976 out << "." + decorateField(field->name(), *structure);
1981 case EOpIndexDirectInterfaceBlock:
1982 if (visit == InVisit)
1984 const TInterfaceBlock* interfaceBlock = node->getLeft()->getType().getInterfaceBlock();
1985 const TIntermConstantUnion* index = node->getRight()->getAsConstantUnion();
1986 const TField* field = interfaceBlock->fields()[index->getIConst(0)];
1987 out << "." + decorate(field->name());
1992 case EOpVectorSwizzle:
1993 if (visit == InVisit)
1997 TIntermAggregate *swizzle = node->getRight()->getAsAggregate();
2001 TIntermSequence &sequence = swizzle->getSequence();
2003 for (TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++)
2005 TIntermConstantUnion *element = (*sit)->getAsConstantUnion();
2009 int i = element->getIConst(0);
2013 case 0: out << "x"; break;
2014 case 1: out << "y"; break;
2015 case 2: out << "z"; break;
2016 case 3: out << "w"; break;
2017 default: UNREACHABLE();
2025 return false; // Fully processed
2028 case EOpAdd: outputTriplet(visit, "(", " + ", ")"); break;
2029 case EOpSub: outputTriplet(visit, "(", " - ", ")"); break;
2030 case EOpMul: outputTriplet(visit, "(", " * ", ")"); break;
2031 case EOpDiv: outputTriplet(visit, "(", " / ", ")"); break;
2034 if (node->getLeft()->isScalar())
2036 if (node->getOp() == EOpEqual)
2038 outputTriplet(visit, "(", " == ", ")");
2042 outputTriplet(visit, "(", " != ", ")");
2045 else if (node->getLeft()->getBasicType() == EbtStruct)
2047 if (node->getOp() == EOpEqual)
2056 const TStructure &structure = *node->getLeft()->getType().getStruct();
2057 const TFieldList &fields = structure.fields();
2059 for (size_t i = 0; i < fields.size(); i++)
2061 const TField *field = fields[i];
2063 node->getLeft()->traverse(this);
2064 out << "." + decorateField(field->name(), structure) + " == ";
2065 node->getRight()->traverse(this);
2066 out << "." + decorateField(field->name(), structure);
2068 if (i < fields.size() - 1)
2080 ASSERT(node->getLeft()->isMatrix() || node->getLeft()->isVector());
2082 if (node->getOp() == EOpEqual)
2084 outputTriplet(visit, "all(", " == ", ")");
2088 outputTriplet(visit, "!all(", " == ", ")");
2092 case EOpLessThan: outputTriplet(visit, "(", " < ", ")"); break;
2093 case EOpGreaterThan: outputTriplet(visit, "(", " > ", ")"); break;
2094 case EOpLessThanEqual: outputTriplet(visit, "(", " <= ", ")"); break;
2095 case EOpGreaterThanEqual: outputTriplet(visit, "(", " >= ", ")"); break;
2096 case EOpVectorTimesScalar: outputTriplet(visit, "(", " * ", ")"); break;
2097 case EOpMatrixTimesScalar: outputTriplet(visit, "(", " * ", ")"); break;
2098 case EOpVectorTimesMatrix: outputTriplet(visit, "mul(", ", transpose(", "))"); break;
2099 case EOpMatrixTimesVector: outputTriplet(visit, "mul(transpose(", "), ", ")"); break;
2100 case EOpMatrixTimesMatrix: outputTriplet(visit, "transpose(mul(transpose(", "), transpose(", ")))"); break;
2102 if (node->getRight()->hasSideEffects())
2104 out << "s" << mUnfoldShortCircuit->getNextTemporaryIndex();
2109 outputTriplet(visit, "(", " || ", ")");
2114 outputTriplet(visit, "xor(", ", ", ")");
2117 if (node->getRight()->hasSideEffects())
2119 out << "s" << mUnfoldShortCircuit->getNextTemporaryIndex();
2124 outputTriplet(visit, "(", " && ", ")");
2127 default: UNREACHABLE();
2133 bool OutputHLSL::visitUnary(Visit visit, TIntermUnary *node)
2135 switch (node->getOp())
2137 case EOpNegative: outputTriplet(visit, "(-", "", ")"); break;
2138 case EOpVectorLogicalNot: outputTriplet(visit, "(!", "", ")"); break;
2139 case EOpLogicalNot: outputTriplet(visit, "(!", "", ")"); break;
2140 case EOpPostIncrement: outputTriplet(visit, "(", "", "++)"); break;
2141 case EOpPostDecrement: outputTriplet(visit, "(", "", "--)"); break;
2142 case EOpPreIncrement: outputTriplet(visit, "(++", "", ")"); break;
2143 case EOpPreDecrement: outputTriplet(visit, "(--", "", ")"); break;
2144 case EOpConvIntToBool:
2145 case EOpConvUIntToBool:
2146 case EOpConvFloatToBool:
2147 switch (node->getOperand()->getType().getNominalSize())
2149 case 1: outputTriplet(visit, "bool(", "", ")"); break;
2150 case 2: outputTriplet(visit, "bool2(", "", ")"); break;
2151 case 3: outputTriplet(visit, "bool3(", "", ")"); break;
2152 case 4: outputTriplet(visit, "bool4(", "", ")"); break;
2153 default: UNREACHABLE();
2156 case EOpConvBoolToFloat:
2157 case EOpConvIntToFloat:
2158 case EOpConvUIntToFloat:
2159 switch (node->getOperand()->getType().getNominalSize())
2161 case 1: outputTriplet(visit, "float(", "", ")"); break;
2162 case 2: outputTriplet(visit, "float2(", "", ")"); break;
2163 case 3: outputTriplet(visit, "float3(", "", ")"); break;
2164 case 4: outputTriplet(visit, "float4(", "", ")"); break;
2165 default: UNREACHABLE();
2168 case EOpConvFloatToInt:
2169 case EOpConvBoolToInt:
2170 case EOpConvUIntToInt:
2171 switch (node->getOperand()->getType().getNominalSize())
2173 case 1: outputTriplet(visit, "int(", "", ")"); break;
2174 case 2: outputTriplet(visit, "int2(", "", ")"); break;
2175 case 3: outputTriplet(visit, "int3(", "", ")"); break;
2176 case 4: outputTriplet(visit, "int4(", "", ")"); break;
2177 default: UNREACHABLE();
2180 case EOpConvFloatToUInt:
2181 case EOpConvBoolToUInt:
2182 case EOpConvIntToUInt:
2183 switch (node->getOperand()->getType().getNominalSize())
2185 case 1: outputTriplet(visit, "uint(", "", ")"); break;
2186 case 2: outputTriplet(visit, "uint2(", "", ")"); break;
2187 case 3: outputTriplet(visit, "uint3(", "", ")"); break;
2188 case 4: outputTriplet(visit, "uint4(", "", ")"); break;
2189 default: UNREACHABLE();
2192 case EOpRadians: outputTriplet(visit, "radians(", "", ")"); break;
2193 case EOpDegrees: outputTriplet(visit, "degrees(", "", ")"); break;
2194 case EOpSin: outputTriplet(visit, "sin(", "", ")"); break;
2195 case EOpCos: outputTriplet(visit, "cos(", "", ")"); break;
2196 case EOpTan: outputTriplet(visit, "tan(", "", ")"); break;
2197 case EOpAsin: outputTriplet(visit, "asin(", "", ")"); break;
2198 case EOpAcos: outputTriplet(visit, "acos(", "", ")"); break;
2199 case EOpAtan: outputTriplet(visit, "atan(", "", ")"); break;
2200 case EOpExp: outputTriplet(visit, "exp(", "", ")"); break;
2201 case EOpLog: outputTriplet(visit, "log(", "", ")"); break;
2202 case EOpExp2: outputTriplet(visit, "exp2(", "", ")"); break;
2203 case EOpLog2: outputTriplet(visit, "log2(", "", ")"); break;
2204 case EOpSqrt: outputTriplet(visit, "sqrt(", "", ")"); break;
2205 case EOpInverseSqrt: outputTriplet(visit, "rsqrt(", "", ")"); break;
2206 case EOpAbs: outputTriplet(visit, "abs(", "", ")"); break;
2207 case EOpSign: outputTriplet(visit, "sign(", "", ")"); break;
2208 case EOpFloor: outputTriplet(visit, "floor(", "", ")"); break;
2209 case EOpCeil: outputTriplet(visit, "ceil(", "", ")"); break;
2210 case EOpFract: outputTriplet(visit, "frac(", "", ")"); break;
2211 case EOpLength: outputTriplet(visit, "length(", "", ")"); break;
2212 case EOpNormalize: outputTriplet(visit, "normalize(", "", ")"); break;
2214 if(mInsideDiscontinuousLoop || mOutputLod0Function)
2216 outputTriplet(visit, "(", "", ", 0.0)");
2220 outputTriplet(visit, "ddx(", "", ")");
2224 if(mInsideDiscontinuousLoop || mOutputLod0Function)
2226 outputTriplet(visit, "(", "", ", 0.0)");
2230 outputTriplet(visit, "ddy(", "", ")");
2234 if(mInsideDiscontinuousLoop || mOutputLod0Function)
2236 outputTriplet(visit, "(", "", ", 0.0)");
2240 outputTriplet(visit, "fwidth(", "", ")");
2243 case EOpAny: outputTriplet(visit, "any(", "", ")"); break;
2244 case EOpAll: outputTriplet(visit, "all(", "", ")"); break;
2245 default: UNREACHABLE();
2251 bool OutputHLSL::visitAggregate(Visit visit, TIntermAggregate *node)
2253 TInfoSinkBase &out = mBody;
2255 switch (node->getOp())
2259 if (mInsideFunction)
2261 outputLineDirective(node->getLine().first_line);
2265 for (TIntermSequence::iterator sit = node->getSequence().begin(); sit != node->getSequence().end(); sit++)
2267 outputLineDirective((*sit)->getLine().first_line);
2269 traverseStatements(*sit);
2274 if (mInsideFunction)
2276 outputLineDirective(node->getLine().last_line);
2282 case EOpDeclaration:
2283 if (visit == PreVisit)
2285 TIntermSequence &sequence = node->getSequence();
2286 TIntermTyped *variable = sequence[0]->getAsTyped();
2288 if (variable && (variable->getQualifier() == EvqTemporary || variable->getQualifier() == EvqGlobal))
2290 if (variable->getType().getStruct())
2292 addConstructor(variable->getType(), structNameString(*variable->getType().getStruct()), NULL);
2295 if (!variable->getAsSymbolNode() || variable->getAsSymbolNode()->getSymbol() != "") // Variable declaration
2297 if (!mInsideFunction)
2302 out << typeString(variable->getType()) + " ";
2304 for (TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++)
2306 TIntermSymbol *symbol = (*sit)->getAsSymbolNode();
2310 symbol->traverse(this);
2311 out << arrayString(symbol->getType());
2312 out << " = " + initializer(symbol->getType());
2316 (*sit)->traverse(this);
2319 if (*sit != sequence.back())
2325 else if (variable->getAsSymbolNode() && variable->getAsSymbolNode()->getSymbol() == "") // Type (struct) declaration
2327 // Already added to constructor map
2331 else if (variable && isVaryingOut(variable->getQualifier()))
2333 for (TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++)
2335 TIntermSymbol *symbol = (*sit)->getAsSymbolNode();
2339 // Vertex (output) varyings which are declared but not written to should still be declared to allow successful linking
2340 mReferencedVaryings[symbol->getSymbol()] = symbol;
2344 (*sit)->traverse(this);
2351 else if (visit == InVisit)
2357 if (visit == PreVisit)
2359 out << typeString(node->getType()) << " " << decorate(node->getName()) << (mOutputLod0Function ? "Lod0(" : "(");
2361 TIntermSequence &arguments = node->getSequence();
2363 for (unsigned int i = 0; i < arguments.size(); i++)
2365 TIntermSymbol *symbol = arguments[i]->getAsSymbolNode();
2369 out << argumentString(symbol);
2371 if (i < arguments.size() - 1)
2381 // Also prototype the Lod0 variant if needed
2382 if (mContainsLoopDiscontinuity && !mOutputLod0Function)
2384 mOutputLod0Function = true;
2385 node->traverse(this);
2386 mOutputLod0Function = false;
2392 case EOpComma: outputTriplet(visit, "(", ", ", ")"); break;
2395 TString name = TFunction::unmangleName(node->getName());
2397 out << typeString(node->getType()) << " ";
2405 out << decorate(name) << (mOutputLod0Function ? "Lod0(" : "(");
2408 TIntermSequence &sequence = node->getSequence();
2409 TIntermSequence &arguments = sequence[0]->getAsAggregate()->getSequence();
2411 for (unsigned int i = 0; i < arguments.size(); i++)
2413 TIntermSymbol *symbol = arguments[i]->getAsSymbolNode();
2417 if (symbol->getType().getStruct())
2419 addConstructor(symbol->getType(), structNameString(*symbol->getType().getStruct()), NULL);
2422 out << argumentString(symbol);
2424 if (i < arguments.size() - 1)
2435 if (sequence.size() > 1)
2437 mInsideFunction = true;
2438 sequence[1]->traverse(this);
2439 mInsideFunction = false;
2444 if (mContainsLoopDiscontinuity && !mOutputLod0Function)
2448 mOutputLod0Function = true;
2449 node->traverse(this);
2450 mOutputLod0Function = false;
2457 case EOpFunctionCall:
2459 TString name = TFunction::unmangleName(node->getName());
2460 bool lod0 = mInsideDiscontinuousLoop || mOutputLod0Function;
2461 TIntermSequence &arguments = node->getSequence();
2463 if (node->isUserDefined())
2465 out << decorate(name) << (lod0 ? "Lod0(" : "(");
2469 TBasicType samplerType = arguments[0]->getAsTyped()->getType().getBasicType();
2471 TextureFunction textureFunction;
2472 textureFunction.sampler = samplerType;
2473 textureFunction.coords = arguments[1]->getAsTyped()->getNominalSize();
2474 textureFunction.method = TextureFunction::IMPLICIT;
2475 textureFunction.proj = false;
2476 textureFunction.offset = false;
2478 if (name == "texture2D" || name == "textureCube" || name == "texture")
2480 textureFunction.method = TextureFunction::IMPLICIT;
2482 else if (name == "texture2DProj" || name == "textureProj")
2484 textureFunction.method = TextureFunction::IMPLICIT;
2485 textureFunction.proj = true;
2487 else if (name == "texture2DLod" || name == "textureCubeLod" || name == "textureLod" ||
2488 name == "texture2DLodEXT" || name == "textureCubeLodEXT")
2490 textureFunction.method = TextureFunction::LOD;
2492 else if (name == "texture2DProjLod" || name == "textureProjLod" || name == "texture2DProjLodEXT")
2494 textureFunction.method = TextureFunction::LOD;
2495 textureFunction.proj = true;
2497 else if (name == "textureSize")
2499 textureFunction.method = TextureFunction::SIZE;
2501 else if (name == "textureOffset")
2503 textureFunction.method = TextureFunction::IMPLICIT;
2504 textureFunction.offset = true;
2506 else if (name == "textureProjOffset")
2508 textureFunction.method = TextureFunction::IMPLICIT;
2509 textureFunction.offset = true;
2510 textureFunction.proj = true;
2512 else if (name == "textureLodOffset")
2514 textureFunction.method = TextureFunction::LOD;
2515 textureFunction.offset = true;
2517 else if (name == "textureProjLodOffset")
2519 textureFunction.method = TextureFunction::LOD;
2520 textureFunction.proj = true;
2521 textureFunction.offset = true;
2523 else if (name == "texelFetch")
2525 textureFunction.method = TextureFunction::FETCH;
2527 else if (name == "texelFetchOffset")
2529 textureFunction.method = TextureFunction::FETCH;
2530 textureFunction.offset = true;
2532 else if (name == "textureGrad" || name == "texture2DGradEXT")
2534 textureFunction.method = TextureFunction::GRAD;
2536 else if (name == "textureGradOffset")
2538 textureFunction.method = TextureFunction::GRAD;
2539 textureFunction.offset = true;
2541 else if (name == "textureProjGrad" || name == "texture2DProjGradEXT" || name == "textureCubeGradEXT")
2543 textureFunction.method = TextureFunction::GRAD;
2544 textureFunction.proj = true;
2546 else if (name == "textureProjGradOffset")
2548 textureFunction.method = TextureFunction::GRAD;
2549 textureFunction.proj = true;
2550 textureFunction.offset = true;
2554 if (textureFunction.method == TextureFunction::IMPLICIT) // Could require lod 0 or have a bias argument
2556 unsigned int mandatoryArgumentCount = 2; // All functions have sampler and coordinate arguments
2558 if (textureFunction.offset)
2560 mandatoryArgumentCount++;
2563 bool bias = (arguments.size() > mandatoryArgumentCount); // Bias argument is optional
2565 if (lod0 || mContext.shaderType == SH_VERTEX_SHADER)
2569 textureFunction.method = TextureFunction::LOD0BIAS;
2573 textureFunction.method = TextureFunction::LOD0;
2578 textureFunction.method = TextureFunction::BIAS;
2582 mUsesTexture.insert(textureFunction);
2584 out << textureFunction.name();
2587 for (TIntermSequence::iterator arg = arguments.begin(); arg != arguments.end(); arg++)
2589 if (mOutputType == SH_HLSL11_OUTPUT && IsSampler((*arg)->getAsTyped()->getBasicType()))
2592 (*arg)->traverse(this);
2593 out << ", sampler_";
2596 (*arg)->traverse(this);
2598 if (arg < arguments.end() - 1)
2609 case EOpParameters: outputTriplet(visit, "(", ", ", ")\n{\n"); break;
2610 case EOpConstructFloat:
2611 addConstructor(node->getType(), "vec1", &node->getSequence());
2612 outputTriplet(visit, "vec1(", "", ")");
2614 case EOpConstructVec2:
2615 addConstructor(node->getType(), "vec2", &node->getSequence());
2616 outputTriplet(visit, "vec2(", ", ", ")");
2618 case EOpConstructVec3:
2619 addConstructor(node->getType(), "vec3", &node->getSequence());
2620 outputTriplet(visit, "vec3(", ", ", ")");
2622 case EOpConstructVec4:
2623 addConstructor(node->getType(), "vec4", &node->getSequence());
2624 outputTriplet(visit, "vec4(", ", ", ")");
2626 case EOpConstructBool:
2627 addConstructor(node->getType(), "bvec1", &node->getSequence());
2628 outputTriplet(visit, "bvec1(", "", ")");
2630 case EOpConstructBVec2:
2631 addConstructor(node->getType(), "bvec2", &node->getSequence());
2632 outputTriplet(visit, "bvec2(", ", ", ")");
2634 case EOpConstructBVec3:
2635 addConstructor(node->getType(), "bvec3", &node->getSequence());
2636 outputTriplet(visit, "bvec3(", ", ", ")");
2638 case EOpConstructBVec4:
2639 addConstructor(node->getType(), "bvec4", &node->getSequence());
2640 outputTriplet(visit, "bvec4(", ", ", ")");
2642 case EOpConstructInt:
2643 addConstructor(node->getType(), "ivec1", &node->getSequence());
2644 outputTriplet(visit, "ivec1(", "", ")");
2646 case EOpConstructIVec2:
2647 addConstructor(node->getType(), "ivec2", &node->getSequence());
2648 outputTriplet(visit, "ivec2(", ", ", ")");
2650 case EOpConstructIVec3:
2651 addConstructor(node->getType(), "ivec3", &node->getSequence());
2652 outputTriplet(visit, "ivec3(", ", ", ")");
2654 case EOpConstructIVec4:
2655 addConstructor(node->getType(), "ivec4", &node->getSequence());
2656 outputTriplet(visit, "ivec4(", ", ", ")");
2658 case EOpConstructUInt:
2659 addConstructor(node->getType(), "uvec1", &node->getSequence());
2660 outputTriplet(visit, "uvec1(", "", ")");
2662 case EOpConstructUVec2:
2663 addConstructor(node->getType(), "uvec2", &node->getSequence());
2664 outputTriplet(visit, "uvec2(", ", ", ")");
2666 case EOpConstructUVec3:
2667 addConstructor(node->getType(), "uvec3", &node->getSequence());
2668 outputTriplet(visit, "uvec3(", ", ", ")");
2670 case EOpConstructUVec4:
2671 addConstructor(node->getType(), "uvec4", &node->getSequence());
2672 outputTriplet(visit, "uvec4(", ", ", ")");
2674 case EOpConstructMat2:
2675 addConstructor(node->getType(), "mat2", &node->getSequence());
2676 outputTriplet(visit, "mat2(", ", ", ")");
2678 case EOpConstructMat3:
2679 addConstructor(node->getType(), "mat3", &node->getSequence());
2680 outputTriplet(visit, "mat3(", ", ", ")");
2682 case EOpConstructMat4:
2683 addConstructor(node->getType(), "mat4", &node->getSequence());
2684 outputTriplet(visit, "mat4(", ", ", ")");
2686 case EOpConstructStruct:
2688 const TString &structName = structNameString(*node->getType().getStruct());
2689 addConstructor(node->getType(), structName, &node->getSequence());
2690 outputTriplet(visit, structName + "_ctor(", ", ", ")");
2693 case EOpLessThan: outputTriplet(visit, "(", " < ", ")"); break;
2694 case EOpGreaterThan: outputTriplet(visit, "(", " > ", ")"); break;
2695 case EOpLessThanEqual: outputTriplet(visit, "(", " <= ", ")"); break;
2696 case EOpGreaterThanEqual: outputTriplet(visit, "(", " >= ", ")"); break;
2697 case EOpVectorEqual: outputTriplet(visit, "(", " == ", ")"); break;
2698 case EOpVectorNotEqual: outputTriplet(visit, "(", " != ", ")"); break;
2701 // We need to look at the number of components in both arguments
2702 const int modValue = node->getSequence()[0]->getAsTyped()->getNominalSize() * 10
2703 + node->getSequence()[1]->getAsTyped()->getNominalSize();
2706 case 11: mUsesMod1 = true; break;
2707 case 22: mUsesMod2v = true; break;
2708 case 21: mUsesMod2f = true; break;
2709 case 33: mUsesMod3v = true; break;
2710 case 31: mUsesMod3f = true; break;
2711 case 44: mUsesMod4v = true; break;
2712 case 41: mUsesMod4f = true; break;
2713 default: UNREACHABLE();
2716 outputTriplet(visit, "mod(", ", ", ")");
2719 case EOpPow: outputTriplet(visit, "pow(", ", ", ")"); break;
2721 ASSERT(node->getSequence().size() == 2); // atan(x) is a unary operator
2722 switch (node->getSequence()[0]->getAsTyped()->getNominalSize())
2724 case 1: mUsesAtan2_1 = true; break;
2725 case 2: mUsesAtan2_2 = true; break;
2726 case 3: mUsesAtan2_3 = true; break;
2727 case 4: mUsesAtan2_4 = true; break;
2728 default: UNREACHABLE();
2730 outputTriplet(visit, "atanyx(", ", ", ")");
2732 case EOpMin: outputTriplet(visit, "min(", ", ", ")"); break;
2733 case EOpMax: outputTriplet(visit, "max(", ", ", ")"); break;
2734 case EOpClamp: outputTriplet(visit, "clamp(", ", ", ")"); break;
2735 case EOpMix: outputTriplet(visit, "lerp(", ", ", ")"); break;
2736 case EOpStep: outputTriplet(visit, "step(", ", ", ")"); break;
2737 case EOpSmoothStep: outputTriplet(visit, "smoothstep(", ", ", ")"); break;
2738 case EOpDistance: outputTriplet(visit, "distance(", ", ", ")"); break;
2739 case EOpDot: outputTriplet(visit, "dot(", ", ", ")"); break;
2740 case EOpCross: outputTriplet(visit, "cross(", ", ", ")"); break;
2741 case EOpFaceForward:
2743 switch (node->getSequence()[0]->getAsTyped()->getNominalSize()) // Number of components in the first argument
2745 case 1: mUsesFaceforward1 = true; break;
2746 case 2: mUsesFaceforward2 = true; break;
2747 case 3: mUsesFaceforward3 = true; break;
2748 case 4: mUsesFaceforward4 = true; break;
2749 default: UNREACHABLE();
2752 outputTriplet(visit, "faceforward(", ", ", ")");
2755 case EOpReflect: outputTriplet(visit, "reflect(", ", ", ")"); break;
2756 case EOpRefract: outputTriplet(visit, "refract(", ", ", ")"); break;
2757 case EOpMul: outputTriplet(visit, "(", " * ", ")"); break;
2758 default: UNREACHABLE();
2764 bool OutputHLSL::visitSelection(Visit visit, TIntermSelection *node)
2766 TInfoSinkBase &out = mBody;
2768 if (node->usesTernaryOperator())
2770 out << "s" << mUnfoldShortCircuit->getNextTemporaryIndex();
2772 else // if/else statement
2774 mUnfoldShortCircuit->traverse(node->getCondition());
2778 node->getCondition()->traverse(this);
2782 outputLineDirective(node->getLine().first_line);
2785 bool discard = false;
2787 if (node->getTrueBlock())
2789 traverseStatements(node->getTrueBlock());
2791 // Detect true discard
2792 discard = (discard || FindDiscard::search(node->getTrueBlock()));
2795 outputLineDirective(node->getLine().first_line);
2798 if (node->getFalseBlock())
2802 outputLineDirective(node->getFalseBlock()->getLine().first_line);
2805 outputLineDirective(node->getFalseBlock()->getLine().first_line);
2806 traverseStatements(node->getFalseBlock());
2808 outputLineDirective(node->getFalseBlock()->getLine().first_line);
2811 // Detect false discard
2812 discard = (discard || FindDiscard::search(node->getFalseBlock()));
2815 // ANGLE issue 486: Detect problematic conditional discard
2816 if (discard && FindSideEffectRewriting::search(node))
2818 mUsesDiscardRewriting = true;
2825 void OutputHLSL::visitConstantUnion(TIntermConstantUnion *node)
2827 writeConstantUnion(node->getType(), node->getUnionArrayPointer());
2830 bool OutputHLSL::visitLoop(Visit visit, TIntermLoop *node)
2834 bool wasDiscontinuous = mInsideDiscontinuousLoop;
2836 if (mContainsLoopDiscontinuity && !mInsideDiscontinuousLoop)
2838 mInsideDiscontinuousLoop = containsLoopDiscontinuity(node);
2841 if (mOutputType == SH_HLSL9_OUTPUT)
2843 if (handleExcessiveLoop(node))
2845 mInsideDiscontinuousLoop = wasDiscontinuous;
2852 TInfoSinkBase &out = mBody;
2854 if (node->getType() == ELoopDoWhile)
2858 outputLineDirective(node->getLine().first_line);
2865 if (node->getInit())
2867 node->getInit()->traverse(this);
2872 if (node->getCondition())
2874 node->getCondition()->traverse(this);
2879 if (node->getExpression())
2881 node->getExpression()->traverse(this);
2886 outputLineDirective(node->getLine().first_line);
2890 if (node->getBody())
2892 traverseStatements(node->getBody());
2895 outputLineDirective(node->getLine().first_line);
2898 if (node->getType() == ELoopDoWhile)
2900 outputLineDirective(node->getCondition()->getLine().first_line);
2903 node->getCondition()->traverse(this);
2910 mInsideDiscontinuousLoop = wasDiscontinuous;
2916 bool OutputHLSL::visitBranch(Visit visit, TIntermBranch *node)
2918 TInfoSinkBase &out = mBody;
2920 switch (node->getFlowOp())
2923 outputTriplet(visit, "discard;\n", "", "");
2926 if (visit == PreVisit)
2928 if (mNestedLoopDepth > 1)
2930 mUsesNestedBreak = true;
2933 if (mExcessiveLoopIndex)
2936 mExcessiveLoopIndex->traverse(this);
2937 out << " = true; break;}\n";
2945 case EOpContinue: outputTriplet(visit, "continue;\n", "", ""); break;
2947 if (visit == PreVisit)
2949 if (node->getExpression())
2958 else if (visit == PostVisit)
2960 if (node->getExpression())
2966 default: UNREACHABLE();
2972 void OutputHLSL::traverseStatements(TIntermNode *node)
2974 if (isSingleStatement(node))
2976 mUnfoldShortCircuit->traverse(node);
2979 node->traverse(this);
2982 bool OutputHLSL::isSingleStatement(TIntermNode *node)
2984 TIntermAggregate *aggregate = node->getAsAggregate();
2988 if (aggregate->getOp() == EOpSequence)
2994 for (TIntermSequence::iterator sit = aggregate->getSequence().begin(); sit != aggregate->getSequence().end(); sit++)
2996 if (!isSingleStatement(*sit))
3009 // Handle loops with more than 254 iterations (unsupported by D3D9) by splitting them
3010 // (The D3D documentation says 255 iterations, but the compiler complains at anything more than 254).
3011 bool OutputHLSL::handleExcessiveLoop(TIntermLoop *node)
3013 const int MAX_LOOP_ITERATIONS = 254;
3014 TInfoSinkBase &out = mBody;
3016 // Parse loops of the form:
3017 // for(int index = initial; index [comparator] limit; index += increment)
3018 TIntermSymbol *index = NULL;
3019 TOperator comparator = EOpNull;
3024 // Parse index name and intial value
3025 if (node->getInit())
3027 TIntermAggregate *init = node->getInit()->getAsAggregate();
3031 TIntermSequence &sequence = init->getSequence();
3032 TIntermTyped *variable = sequence[0]->getAsTyped();
3034 if (variable && variable->getQualifier() == EvqTemporary)
3036 TIntermBinary *assign = variable->getAsBinaryNode();
3038 if (assign->getOp() == EOpInitialize)
3040 TIntermSymbol *symbol = assign->getLeft()->getAsSymbolNode();
3041 TIntermConstantUnion *constant = assign->getRight()->getAsConstantUnion();
3043 if (symbol && constant)
3045 if (constant->getBasicType() == EbtInt && constant->isScalar())
3048 initial = constant->getIConst(0);
3056 // Parse comparator and limit value
3057 if (index != NULL && node->getCondition())
3059 TIntermBinary *test = node->getCondition()->getAsBinaryNode();
3061 if (test && test->getLeft()->getAsSymbolNode()->getId() == index->getId())
3063 TIntermConstantUnion *constant = test->getRight()->getAsConstantUnion();
3067 if (constant->getBasicType() == EbtInt && constant->isScalar())
3069 comparator = test->getOp();
3070 limit = constant->getIConst(0);
3077 if (index != NULL && comparator != EOpNull && node->getExpression())
3079 TIntermBinary *binaryTerminal = node->getExpression()->getAsBinaryNode();
3080 TIntermUnary *unaryTerminal = node->getExpression()->getAsUnaryNode();
3084 TOperator op = binaryTerminal->getOp();
3085 TIntermConstantUnion *constant = binaryTerminal->getRight()->getAsConstantUnion();
3089 if (constant->getBasicType() == EbtInt && constant->isScalar())
3091 int value = constant->getIConst(0);
3095 case EOpAddAssign: increment = value; break;
3096 case EOpSubAssign: increment = -value; break;
3097 default: UNIMPLEMENTED();
3102 else if (unaryTerminal)
3104 TOperator op = unaryTerminal->getOp();
3108 case EOpPostIncrement: increment = 1; break;
3109 case EOpPostDecrement: increment = -1; break;
3110 case EOpPreIncrement: increment = 1; break;
3111 case EOpPreDecrement: increment = -1; break;
3112 default: UNIMPLEMENTED();
3117 if (index != NULL && comparator != EOpNull && increment != 0)
3119 if (comparator == EOpLessThanEqual)
3121 comparator = EOpLessThan;
3125 if (comparator == EOpLessThan)
3127 int iterations = (limit - initial) / increment;
3129 if (iterations <= MAX_LOOP_ITERATIONS)
3131 return false; // Not an excessive loop
3134 TIntermSymbol *restoreIndex = mExcessiveLoopIndex;
3135 mExcessiveLoopIndex = index;
3138 index->traverse(this);
3141 index->traverse(this);
3142 out << " = false;\n";
3144 bool firstLoopFragment = true;
3146 while (iterations > 0)
3148 int clampedLimit = initial + increment * std::min(MAX_LOOP_ITERATIONS, iterations);
3150 if (!firstLoopFragment)
3152 out << "if (!Break";
3153 index->traverse(this);
3157 if (iterations <= MAX_LOOP_ITERATIONS) // Last loop fragment
3159 mExcessiveLoopIndex = NULL; // Stops setting the Break flag
3162 // for(int index = initial; index < clampedLimit; index += increment)
3165 index->traverse(this);
3170 index->traverse(this);
3172 out << clampedLimit;
3175 index->traverse(this);
3180 outputLineDirective(node->getLine().first_line);
3183 if (node->getBody())
3185 node->getBody()->traverse(this);
3188 outputLineDirective(node->getLine().first_line);
3191 if (!firstLoopFragment)
3196 firstLoopFragment = false;
3198 initial += MAX_LOOP_ITERATIONS * increment;
3199 iterations -= MAX_LOOP_ITERATIONS;
3204 mExcessiveLoopIndex = restoreIndex;
3208 else UNIMPLEMENTED();
3211 return false; // Not handled as an excessive loop
3214 void OutputHLSL::outputTriplet(Visit visit, const TString &preString, const TString &inString, const TString &postString)
3216 TInfoSinkBase &out = mBody;
3218 if (visit == PreVisit)
3222 else if (visit == InVisit)
3226 else if (visit == PostVisit)
3232 void OutputHLSL::outputLineDirective(int line)
3234 if ((mContext.compileOptions & SH_LINE_DIRECTIVES) && (line > 0))
3237 mBody << "#line " << line;
3239 if (mContext.sourcePath)
3241 mBody << " \"" << mContext.sourcePath << "\"";
3248 TString OutputHLSL::argumentString(const TIntermSymbol *symbol)
3250 TQualifier qualifier = symbol->getQualifier();
3251 const TType &type = symbol->getType();
3252 TString name = symbol->getSymbol();
3254 if (name.empty()) // HLSL demands named arguments, also for prototypes
3256 name = "x" + str(mUniqueIndex++);
3260 name = decorate(name);
3263 if (mOutputType == SH_HLSL11_OUTPUT && IsSampler(type.getBasicType()))
3265 return qualifierString(qualifier) + " " + textureString(type) + " texture_" + name + arrayString(type) + ", " +
3266 qualifierString(qualifier) + " " + samplerString(type) + " sampler_" + name + arrayString(type);
3269 return qualifierString(qualifier) + " " + typeString(type) + " " + name + arrayString(type);
3272 TString OutputHLSL::interpolationString(TQualifier qualifier)
3276 case EvqVaryingIn: return "";
3277 case EvqFragmentIn: return "";
3278 case EvqInvariantVaryingIn: return "";
3279 case EvqSmoothIn: return "linear";
3280 case EvqFlatIn: return "nointerpolation";
3281 case EvqCentroidIn: return "centroid";
3282 case EvqVaryingOut: return "";
3283 case EvqVertexOut: return "";
3284 case EvqInvariantVaryingOut: return "";
3285 case EvqSmoothOut: return "linear";
3286 case EvqFlatOut: return "nointerpolation";
3287 case EvqCentroidOut: return "centroid";
3288 default: UNREACHABLE();
3294 TString OutputHLSL::qualifierString(TQualifier qualifier)
3298 case EvqIn: return "in";
3299 case EvqOut: return "inout"; // 'out' results in an HLSL error if not all fields are written, for GLSL it's undefined
3300 case EvqInOut: return "inout";
3301 case EvqConstReadOnly: return "const";
3302 default: UNREACHABLE();
3308 TString OutputHLSL::typeString(const TType &type)
3310 const TStructure* structure = type.getStruct();
3313 const TString& typeName = structure->name();
3316 return structNameString(*type.getStruct());
3318 else // Nameless structure, define in place
3320 return structureString(*structure, false, false);
3323 else if (type.isMatrix())
3325 int cols = type.getCols();
3326 int rows = type.getRows();
3327 return "float" + str(cols) + "x" + str(rows);
3331 switch (type.getBasicType())
3334 switch (type.getNominalSize())
3336 case 1: return "float";
3337 case 2: return "float2";
3338 case 3: return "float3";
3339 case 4: return "float4";
3342 switch (type.getNominalSize())
3344 case 1: return "int";
3345 case 2: return "int2";
3346 case 3: return "int3";
3347 case 4: return "int4";
3350 switch (type.getNominalSize())
3352 case 1: return "uint";
3353 case 2: return "uint2";
3354 case 3: return "uint3";
3355 case 4: return "uint4";
3358 switch (type.getNominalSize())
3360 case 1: return "bool";
3361 case 2: return "bool2";
3362 case 3: return "bool3";
3363 case 4: return "bool4";
3370 case EbtSampler2DArray:
3371 case EbtISampler2DArray:
3372 case EbtUSampler2DArray:
3374 case EbtSamplerCube:
3375 case EbtISamplerCube:
3376 case EbtUSamplerCube:
3377 return "samplerCUBE";
3378 case EbtSamplerExternalOES:
3386 return "<unknown type>";
3389 TString OutputHLSL::textureString(const TType &type)
3391 switch (type.getBasicType())
3393 case EbtSampler2D: return "Texture2D";
3394 case EbtSamplerCube: return "TextureCube";
3395 case EbtSamplerExternalOES: return "Texture2D";
3396 case EbtSampler2DArray: return "Texture2DArray";
3397 case EbtSampler3D: return "Texture3D";
3398 case EbtISampler2D: return "Texture2D<int4>";
3399 case EbtISampler3D: return "Texture3D<int4>";
3400 case EbtISamplerCube: return "Texture2DArray<int4>";
3401 case EbtISampler2DArray: return "Texture2DArray<int4>";
3402 case EbtUSampler2D: return "Texture2D<uint4>";
3403 case EbtUSampler3D: return "Texture3D<uint4>";
3404 case EbtUSamplerCube: return "Texture2DArray<uint4>";
3405 case EbtUSampler2DArray: return "Texture2DArray<uint4>";
3406 case EbtSampler2DShadow: return "Texture2D";
3407 case EbtSamplerCubeShadow: return "TextureCube";
3408 case EbtSampler2DArrayShadow: return "Texture2DArray";
3409 default: UNREACHABLE();
3412 return "<unknown texture type>";
3415 TString OutputHLSL::samplerString(const TType &type)
3417 if (IsShadowSampler(type.getBasicType()))
3419 return "SamplerComparisonState";
3423 return "SamplerState";
3427 TString OutputHLSL::arrayString(const TType &type)
3429 if (!type.isArray())
3434 return "[" + str(type.getArraySize()) + "]";
3437 TString OutputHLSL::initializer(const TType &type)
3441 size_t size = type.getObjectSize();
3442 for (size_t component = 0; component < size; component++)
3446 if (component + 1 < size)
3452 return "{" + string + "}";
3455 TString OutputHLSL::structureString(const TStructure &structure, bool useHLSLRowMajorPacking, bool useStd140Packing)
3457 const TFieldList &fields = structure.fields();
3458 const bool isNameless = (structure.name() == "");
3459 const TString &structName = structureTypeName(structure, useHLSLRowMajorPacking, useStd140Packing);
3460 const TString declareString = (isNameless ? "struct" : "struct " + structName);
3463 string += declareString + "\n"
3466 int elementIndex = 0;
3468 for (unsigned int i = 0; i < fields.size(); i++)
3470 const TField &field = *fields[i];
3471 const TType &fieldType = *field.type();
3472 const TStructure *fieldStruct = fieldType.getStruct();
3473 const TString &fieldTypeString = fieldStruct ? structureTypeName(*fieldStruct, useHLSLRowMajorPacking, useStd140Packing) : typeString(fieldType);
3475 if (useStd140Packing)
3477 string += std140PrePaddingString(*field.type(), &elementIndex);
3480 string += " " + fieldTypeString + " " + decorateField(field.name(), structure) + arrayString(fieldType) + ";\n";
3482 if (useStd140Packing)
3484 string += std140PostPaddingString(*field.type(), useHLSLRowMajorPacking);
3488 // Nameless structs do not finish with a semicolon and newline, to leave room for an instance variable
3489 string += (isNameless ? "} " : "};\n");
3491 // Add remaining element index to the global map, for use with nested structs in standard layouts
3492 if (useStd140Packing)
3494 mStd140StructElementIndexes[structName] = elementIndex;
3500 TString OutputHLSL::structureTypeName(const TStructure &structure, bool useHLSLRowMajorPacking, bool useStd140Packing)
3502 if (structure.name() == "")
3507 TString prefix = "";
3509 // Structs packed with row-major matrices in HLSL are prefixed with "rm"
3510 // GLSL column-major maps to HLSL row-major, and the converse is true
3512 if (useStd140Packing)
3517 if (useHLSLRowMajorPacking)
3519 if (prefix != "") prefix += "_";
3523 return prefix + structNameString(structure);
3526 void OutputHLSL::addConstructor(const TType &type, const TString &name, const TIntermSequence *parameters)
3530 return; // Nameless structures don't have constructors
3533 if (type.getStruct() && mStructNames.find(name) != mStructNames.end())
3535 return; // Already added
3538 TType ctorType = type;
3539 ctorType.clearArrayness();
3540 ctorType.setPrecision(EbpHigh);
3541 ctorType.setQualifier(EvqTemporary);
3543 typedef std::vector<TType> ParameterArray;
3544 ParameterArray ctorParameters;
3546 const TStructure* structure = type.getStruct();
3549 mStructNames.insert(name);
3551 const TString &structString = structureString(*structure, false, false);
3553 if (std::find(mStructDeclarations.begin(), mStructDeclarations.end(), structString) == mStructDeclarations.end())
3555 // Add row-major packed struct for interface blocks
3556 TString rowMajorString = "#pragma pack_matrix(row_major)\n" +
3557 structureString(*structure, true, false) +
3558 "#pragma pack_matrix(column_major)\n";
3560 TString std140String = structureString(*structure, false, true);
3561 TString std140RowMajorString = "#pragma pack_matrix(row_major)\n" +
3562 structureString(*structure, true, true) +
3563 "#pragma pack_matrix(column_major)\n";
3565 mStructDeclarations.push_back(structString);
3566 mStructDeclarations.push_back(rowMajorString);
3567 mStructDeclarations.push_back(std140String);
3568 mStructDeclarations.push_back(std140RowMajorString);
3571 const TFieldList &fields = structure->fields();
3572 for (unsigned int i = 0; i < fields.size(); i++)
3574 ctorParameters.push_back(*fields[i]->type());
3577 else if (parameters)
3579 for (TIntermSequence::const_iterator parameter = parameters->begin(); parameter != parameters->end(); parameter++)
3581 ctorParameters.push_back((*parameter)->getAsTyped()->getType());
3586 TString constructor;
3588 if (ctorType.getStruct())
3590 constructor += name + " " + name + "_ctor(";
3592 else // Built-in type
3594 constructor += typeString(ctorType) + " " + name + "(";
3597 for (unsigned int parameter = 0; parameter < ctorParameters.size(); parameter++)
3599 const TType &type = ctorParameters[parameter];
3601 constructor += typeString(type) + " x" + str(parameter) + arrayString(type);
3603 if (parameter < ctorParameters.size() - 1)
3605 constructor += ", ";
3609 constructor += ")\n"
3612 if (ctorType.getStruct())
3614 constructor += " " + name + " structure = {";
3618 constructor += " return " + typeString(ctorType) + "(";
3621 if (ctorType.isMatrix() && ctorParameters.size() == 1)
3623 int rows = ctorType.getRows();
3624 int cols = ctorType.getCols();
3625 const TType ¶meter = ctorParameters[0];
3627 if (parameter.isScalar())
3629 for (int row = 0; row < rows; row++)
3631 for (int col = 0; col < cols; col++)
3633 constructor += TString((row == col) ? "x0" : "0.0");
3635 if (row < rows - 1 || col < cols - 1)
3637 constructor += ", ";
3642 else if (parameter.isMatrix())
3644 for (int row = 0; row < rows; row++)
3646 for (int col = 0; col < cols; col++)
3648 if (row < parameter.getRows() && col < parameter.getCols())
3650 constructor += TString("x0") + "[" + str(row) + "]" + "[" + str(col) + "]";
3654 constructor += TString((row == col) ? "1.0" : "0.0");
3657 if (row < rows - 1 || col < cols - 1)
3659 constructor += ", ";
3668 size_t remainingComponents = ctorType.getObjectSize();
3669 size_t parameterIndex = 0;
3671 while (remainingComponents > 0)
3673 const TType ¶meter = ctorParameters[parameterIndex];
3674 const size_t parameterSize = parameter.getObjectSize();
3675 bool moreParameters = parameterIndex + 1 < ctorParameters.size();
3677 constructor += "x" + str(parameterIndex);
3679 if (parameter.isScalar())
3681 remainingComponents -= parameter.getObjectSize();
3683 else if (parameter.isVector())
3685 if (remainingComponents == parameterSize || moreParameters)
3687 ASSERT(parameterSize <= remainingComponents);
3688 remainingComponents -= parameterSize;
3690 else if (remainingComponents < static_cast<size_t>(parameter.getNominalSize()))
3692 switch (remainingComponents)
3694 case 1: constructor += ".x"; break;
3695 case 2: constructor += ".xy"; break;
3696 case 3: constructor += ".xyz"; break;
3697 case 4: constructor += ".xyzw"; break;
3698 default: UNREACHABLE();
3701 remainingComponents = 0;
3705 else if (parameter.isMatrix() || parameter.getStruct())
3707 ASSERT(remainingComponents == parameterSize || moreParameters);
3708 ASSERT(parameterSize <= remainingComponents);
3710 remainingComponents -= parameterSize;
3719 if (remainingComponents)
3721 constructor += ", ";
3726 if (ctorType.getStruct())
3728 constructor += "};\n"
3729 " return structure;\n"
3734 constructor += ");\n"
3738 mConstructors.insert(constructor);
3741 const ConstantUnion *OutputHLSL::writeConstantUnion(const TType &type, const ConstantUnion *constUnion)
3743 TInfoSinkBase &out = mBody;
3745 const TStructure* structure = type.getStruct();
3748 out << structNameString(*structure) + "_ctor(";
3750 const TFieldList& fields = structure->fields();
3752 for (size_t i = 0; i < fields.size(); i++)
3754 const TType *fieldType = fields[i]->type();
3756 constUnion = writeConstantUnion(*fieldType, constUnion);
3758 if (i != fields.size() - 1)
3768 size_t size = type.getObjectSize();
3769 bool writeType = size > 1;
3773 out << typeString(type) << "(";
3776 for (size_t i = 0; i < size; i++, constUnion++)
3778 switch (constUnion->getType())
3780 case EbtFloat: out << std::min(FLT_MAX, std::max(-FLT_MAX, constUnion->getFConst())); break;
3781 case EbtInt: out << constUnion->getIConst(); break;
3782 case EbtUInt: out << constUnion->getUConst(); break;
3783 case EbtBool: out << constUnion->getBConst(); break;
3784 default: UNREACHABLE();
3802 TString OutputHLSL::structNameString(const TStructure &structure)
3804 if (structure.name().empty())
3809 return "ss_" + str(structure.uniqueId()) + structure.name();
3812 TString OutputHLSL::decorate(const TString &string)
3814 if (string.compare(0, 3, "gl_") != 0 && string.compare(0, 3, "dx_") != 0)
3816 return "_" + string;
3822 TString OutputHLSL::decorateUniform(const TString &string, const TType &type)
3824 if (type.getBasicType() == EbtSamplerExternalOES)
3826 return "ex_" + string;
3829 return decorate(string);
3832 TString OutputHLSL::decorateField(const TString &string, const TStructure &structure)
3834 if (structure.name().compare(0, 3, "gl_") != 0)
3836 return decorate(string);
3842 void OutputHLSL::declareInterfaceBlockField(const TType &type, const TString &name, std::vector<gl::InterfaceBlockField>& output)
3844 const TStructure *structure = type.getStruct();
3848 const bool isRowMajorMatrix = (type.isMatrix() && type.getLayoutQualifier().matrixPacking == EmpRowMajor);
3849 gl::InterfaceBlockField field(glVariableType(type), glVariablePrecision(type), name.c_str(),
3850 (unsigned int)type.getArraySize(), isRowMajorMatrix);
3851 output.push_back(field);
3855 gl::InterfaceBlockField structField(GL_STRUCT_ANGLEX, GL_NONE, name.c_str(), (unsigned int)type.getArraySize(), false);
3857 const TFieldList &fields = structure->fields();
3859 for (size_t fieldIndex = 0; fieldIndex < fields.size(); fieldIndex++)
3861 TField *field = fields[fieldIndex];
3862 TType *fieldType = field->type();
3864 // make sure to copy matrix packing information
3865 fieldType->setLayoutQualifier(type.getLayoutQualifier());
3867 declareInterfaceBlockField(*fieldType, field->name(), structField.fields);
3870 output.push_back(structField);
3874 gl::Uniform OutputHLSL::declareUniformToList(const TType &type, const TString &name, int registerIndex, std::vector<gl::Uniform>& output)
3876 const TStructure *structure = type.getStruct();
3880 gl::Uniform uniform(glVariableType(type), glVariablePrecision(type), name.c_str(),
3881 (unsigned int)type.getArraySize(), (unsigned int)registerIndex, 0);
3882 output.push_back(uniform);
3888 gl::Uniform structUniform(GL_STRUCT_ANGLEX, GL_NONE, name.c_str(), (unsigned int)type.getArraySize(),
3889 (unsigned int)registerIndex, GL_INVALID_INDEX);
3891 const TFieldList &fields = structure->fields();
3893 for (size_t fieldIndex = 0; fieldIndex < fields.size(); fieldIndex++)
3895 TField *field = fields[fieldIndex];
3896 TType *fieldType = field->type();
3898 declareUniformToList(*fieldType, field->name(), GL_INVALID_INDEX, structUniform.fields);
3901 // assign register offset information -- this will override the information in any sub-structures.
3902 HLSLVariableGetRegisterInfo(registerIndex, &structUniform, mOutputType);
3904 output.push_back(structUniform);
3906 return structUniform;
3910 gl::InterpolationType getInterpolationType(TQualifier qualifier)
3916 return gl::INTERPOLATION_FLAT;
3924 return gl::INTERPOLATION_SMOOTH;
3927 case EvqCentroidOut:
3928 return gl::INTERPOLATION_CENTROID;
3930 default: UNREACHABLE();
3931 return gl::INTERPOLATION_SMOOTH;
3935 void OutputHLSL::declareVaryingToList(const TType &type, TQualifier baseTypeQualifier, const TString &name, std::vector<gl::Varying>& fieldsOut)
3937 const TStructure *structure = type.getStruct();
3939 gl::InterpolationType interpolation = getInterpolationType(baseTypeQualifier);
3942 gl::Varying varying(glVariableType(type), glVariablePrecision(type), name.c_str(), (unsigned int)type.getArraySize(), interpolation);
3943 fieldsOut.push_back(varying);
3947 gl::Varying structVarying(GL_STRUCT_ANGLEX, GL_NONE, name.c_str(), (unsigned int)type.getArraySize(), interpolation);
3948 const TFieldList &fields = structure->fields();
3950 structVarying.structName = structure->name().c_str();
3952 for (size_t fieldIndex = 0; fieldIndex < fields.size(); fieldIndex++)
3954 const TField &field = *fields[fieldIndex];
3955 declareVaryingToList(*field.type(), baseTypeQualifier, field.name(), structVarying.fields);
3958 fieldsOut.push_back(structVarying);
3962 int OutputHLSL::declareUniformAndAssignRegister(const TType &type, const TString &name)
3964 int registerIndex = (IsSampler(type.getBasicType()) ? mSamplerRegister : mUniformRegister);
3966 const gl::Uniform &uniform = declareUniformToList(type, name, registerIndex, mActiveUniforms);
3968 if (IsSampler(type.getBasicType()))
3970 mSamplerRegister += gl::HLSLVariableRegisterCount(uniform, mOutputType);
3974 mUniformRegister += gl::HLSLVariableRegisterCount(uniform, mOutputType);
3977 return registerIndex;
3980 GLenum OutputHLSL::glVariableType(const TType &type)
3982 if (type.getBasicType() == EbtFloat)
3984 if (type.isScalar())
3988 else if (type.isVector())
3990 switch(type.getNominalSize())
3992 case 2: return GL_FLOAT_VEC2;
3993 case 3: return GL_FLOAT_VEC3;
3994 case 4: return GL_FLOAT_VEC4;
3995 default: UNREACHABLE();
3998 else if (type.isMatrix())
4000 switch (type.getCols())
4003 switch(type.getRows())
4005 case 2: return GL_FLOAT_MAT2;
4006 case 3: return GL_FLOAT_MAT2x3;
4007 case 4: return GL_FLOAT_MAT2x4;
4008 default: UNREACHABLE();
4012 switch(type.getRows())
4014 case 2: return GL_FLOAT_MAT3x2;
4015 case 3: return GL_FLOAT_MAT3;
4016 case 4: return GL_FLOAT_MAT3x4;
4017 default: UNREACHABLE();
4021 switch(type.getRows())
4023 case 2: return GL_FLOAT_MAT4x2;
4024 case 3: return GL_FLOAT_MAT4x3;
4025 case 4: return GL_FLOAT_MAT4;
4026 default: UNREACHABLE();
4029 default: UNREACHABLE();
4034 else if (type.getBasicType() == EbtInt)
4036 if (type.isScalar())
4040 else if (type.isVector())
4042 switch(type.getNominalSize())
4044 case 2: return GL_INT_VEC2;
4045 case 3: return GL_INT_VEC3;
4046 case 4: return GL_INT_VEC4;
4047 default: UNREACHABLE();
4052 else if (type.getBasicType() == EbtUInt)
4054 if (type.isScalar())
4056 return GL_UNSIGNED_INT;
4058 else if (type.isVector())
4060 switch(type.getNominalSize())
4062 case 2: return GL_UNSIGNED_INT_VEC2;
4063 case 3: return GL_UNSIGNED_INT_VEC3;
4064 case 4: return GL_UNSIGNED_INT_VEC4;
4065 default: UNREACHABLE();
4070 else if (type.getBasicType() == EbtBool)
4072 if (type.isScalar())
4076 else if (type.isVector())
4078 switch(type.getNominalSize())
4080 case 2: return GL_BOOL_VEC2;
4081 case 3: return GL_BOOL_VEC3;
4082 case 4: return GL_BOOL_VEC4;
4083 default: UNREACHABLE();
4089 switch(type.getBasicType())
4091 case EbtSampler2D: return GL_SAMPLER_2D;
4092 case EbtSampler3D: return GL_SAMPLER_3D;
4093 case EbtSamplerCube: return GL_SAMPLER_CUBE;
4094 case EbtSampler2DArray: return GL_SAMPLER_2D_ARRAY;
4095 case EbtISampler2D: return GL_INT_SAMPLER_2D;
4096 case EbtISampler3D: return GL_INT_SAMPLER_3D;
4097 case EbtISamplerCube: return GL_INT_SAMPLER_CUBE;
4098 case EbtISampler2DArray: return GL_INT_SAMPLER_2D_ARRAY;
4099 case EbtUSampler2D: return GL_UNSIGNED_INT_SAMPLER_2D;
4100 case EbtUSampler3D: return GL_UNSIGNED_INT_SAMPLER_3D;
4101 case EbtUSamplerCube: return GL_UNSIGNED_INT_SAMPLER_CUBE;
4102 case EbtUSampler2DArray: return GL_UNSIGNED_INT_SAMPLER_2D_ARRAY;
4103 case EbtSampler2DShadow: return GL_SAMPLER_2D_SHADOW;
4104 case EbtSamplerCubeShadow: return GL_SAMPLER_CUBE_SHADOW;
4105 case EbtSampler2DArrayShadow: return GL_SAMPLER_2D_ARRAY_SHADOW;
4106 default: UNREACHABLE();
4112 GLenum OutputHLSL::glVariablePrecision(const TType &type)
4114 if (type.getBasicType() == EbtFloat)
4116 switch (type.getPrecision())
4118 case EbpHigh: return GL_HIGH_FLOAT;
4119 case EbpMedium: return GL_MEDIUM_FLOAT;
4120 case EbpLow: return GL_LOW_FLOAT;
4122 // Should be defined as the default precision by the parser
4123 default: UNREACHABLE();
4126 else if (type.getBasicType() == EbtInt || type.getBasicType() == EbtUInt)
4128 switch (type.getPrecision())
4130 case EbpHigh: return GL_HIGH_INT;
4131 case EbpMedium: return GL_MEDIUM_INT;
4132 case EbpLow: return GL_LOW_INT;
4134 // Should be defined as the default precision by the parser
4135 default: UNREACHABLE();
4139 // Other types (boolean, sampler) don't have a precision
4143 bool OutputHLSL::isVaryingOut(TQualifier qualifier)
4148 case EvqInvariantVaryingOut:
4151 case EvqCentroidOut:
4161 bool OutputHLSL::isVaryingIn(TQualifier qualifier)
4166 case EvqInvariantVaryingIn:
4179 bool OutputHLSL::isVarying(TQualifier qualifier)
4181 return isVaryingIn(qualifier) || isVaryingOut(qualifier);