Built-in Variable (GLSL) - OpenGL Wiki - Khronos Group
文章推薦指數: 80 %
Fragment Shader · Compute Shader · Other shading languages. The OpenGL Shading Language defines a number of special variables for the various ...
Built-inVariable(GLSL)
FromOpenGLWiki
Jumptonavigation
Jumptosearch
GLSL
OpenGLShadingLanguage
Shader
Objects
Compilation
Introspection
Thecorelanguage
Variabletypes
Typequalifiers
Layoutqualifiers
Uniformvariables
Samplervariables
Imagevariables
Built-invariables
Interfaceblocks
Uniformblocks
Shaderstorageblocks
SPIR-V
Shaderstages:
VertexShader
Tessellation
GeometryShader
FragmentShader
ComputeShader
Othershadinglanguages
TheOpenGLShadingLanguagedefinesanumberofspecialvariablesforthevariousshaderstages.Thesebuilt-invariables(orbuilt-invariables)havespecialproperties.Theyareusuallyforcommunicatingwithcertainfixed-functionality.Byconvention,allpredefinedvariablesstartwith"gl_";nouser-definedvariablesmaystartwiththis.
Note:ThispageonlydescribesthecoreOpenGLshadinglanguagepre-definedvariables.Anyvariablesthatarefromthecompatibilityprofilesarenotlistedhere.
Contents
1Vertexshaderinputs
2Vertexshaderoutputs
3Tessellationcontrolshaderinputs
4Tessellationcontrolshaderoutputs
5Tessellationevaluationshaderinputs
6Tessellationevaluationshaderoutputs
7Geometryshaderinputs
8Geometryshaderoutputs
9Fragmentshaderinputs
10Fragmentshaderoutputs
11Computeshaderinputs
12Computeshaderothervariables
13Shaderuniforms
14Constants
Vertexshaderinputs
V·E
VertexShadershavethefollowingbuilt-ininputvariables.
inintgl_VertexID;
inintgl_InstanceID;
inintgl_DrawID;//RequiresGLSL4.60orARB_shader_draw_parameters
inintgl_BaseVertex;//RequiresGLSL4.60orARB_shader_draw_parameters
inintgl_BaseInstance;//RequiresGLSL4.60orARB_shader_draw_parameters
gl_VertexID
theindexofthevertexcurrentlybeingprocessed.Whenusingnon-indexedrendering,itistheeffectiveindexofthecurrentvertex(thenumberofverticesprocessed+thefirstvalue).Forindexedrendering,itistheindexusedtofetchthisvertexfromthebuffer.
Note:gl_VertexIDwillhavethebaseVertexparameteraddedtotheindex,iftherewassuchaparameterintherenderingcommand.
gl_InstanceID
theindexofthecurrentinstancewhendoingsomeformofinstancedrendering.Theinstancecountalwaysstartsat0,evenwhenusingbaseinstancecalls.Whennotusinginstancedrendering,thisvaluewillbe0.
Warning:ThisvaluedoesnotfollowthebaseInstanceprovidedbysomeinstancedrenderingfunctions.gl_InstanceIDalwaysfallsonthehalf-openrange[0,instancecount).IfyouhaveGLSL4.60,youmayusegl_BaseInstancetocomputetheproperinstanceindex.
gl_DrawID
theindexofthedrawingcommandwithinmulti-drawrenderingcommands(includingindirectmulti-drawcommands).ThefirstdrawcommandhasanIDof0,increasingbyoneastherendererpassesthroughdrawingcommands.
ThisvaluewillalwaysbeaDynamicallyUniformExpression.
gl_BaseVertex
thevalueofthebaseVertexparameteroftherenderingcommand.Iftherenderingcommanddidnotincludethatparameter,thevalueofthisinputwillbe0.
gl_BaseInstance
thevalueofthebaseInstanceparameteroftheinstancedrenderingcommand.Iftherenderingcommanddidnotincludethisparameter,thevalueofthisinputwillbe0.
Vertexshaderoutputs
V·E
VertexShadershavethefollowingpredefinedoutputs.
outgl_PerVertex
{
vec4gl_Position;
floatgl_PointSize;
floatgl_ClipDistance[];
};
gl_PerVertexdefinesaninterfaceblockforoutputs.Theblockisdefinedwithoutaninstancename,sothatprefixingthenamesisnotrequired.
ThesevariablesonlytakeonthemeaningsbelowifthisshaderisthelastactiveVertexProcessingstage,andifrasterizationisstillactive(ie:GL_RASTERIZER_DISCARDisnotenabled).ThetextbelowexplainshowtheVertexPost-Processingsystemusesthevariables.Thesevariablesmaynotberedeclaredwithinterpolationqualifiers.
gl_Position
theclip-spaceoutputpositionofthecurrentvertex.
gl_PointSize
thepixelwidth/heightofthepointbeingrasterized.Itonlyhasameaningwhenrenderingpointprimitives.ItwillbeclampedtotheGL_POINT_SIZE_RANGE.
gl_ClipDistance
allowstheshadertosetthedistancefromthevertextoeachuser-definedclippinghalf-space.Anon-negativedistancemeansthatthevertexisinside/behindtheclipplane,andanegativedistancemeansitisoutside/infrontoftheclipplane.Eachelementinthearrayisoneclipplane.Inordertousethisvariable,theusermustmanuallyredeclareitwithanexplicitsize.WithGLSL4.10orARB_separate_shader_objects,thewholegl_PerVertexblockneedstoberedeclared.Otherwisejustthegl_ClipDistancebuilt-inneedstoberedeclared.
Tessellationcontrolshaderinputs
V·E
TessellationControlShadersprovidethefollowingbuilt-ininputvariables:
inintgl_PatchVerticesIn;
inintgl_PrimitiveID;
inintgl_InvocationID;
gl_PatchVerticesIn
thenumberofverticesintheinputpatch.
gl_PrimitiveID
theindexofthecurrentpatchwithinthisrenderingcommand.
gl_InvocationID
theindexoftheTCSinvocationwithinthispatch.ATCSinvocationwritestoper-vertexoutputvariablesbyusingthistoindexthem.
TheTCSalsotakesthebuilt-invariablesoutputbythevertexshader:
ingl_PerVertex
{
vec4gl_Position;
floatgl_PointSize;
floatgl_ClipDistance[];
}gl_in[gl_MaxPatchVertices];
Notethatjustbecausegl_inisdefinedtohavegl_MaxPatchVerticesentriesdoesnotmeanthatyoucanaccessbeyondgl_PatchVerticesInandgetreasonablevalues.Thesevariableshaveonlythemeaningthevertexshaderthatpassedthemgavethem.
Tessellationcontrolshaderoutputs
V·E
TessellationControlShadershavethefollowingbuilt-inpatchoutputvariables:
patchoutfloatgl_TessLevelOuter[4];
patchoutfloatgl_TessLevelInner[2];
Thesedefinetheouterandinnertessellationlevelsusedbythetessellationprimitivegenerator.Theydefinehowmuchtessellationtoapplytothepatch.Theirexactmeaningdependsonthetypeofpatch(andothersettings)definedintheTessellationEvaluationShader.
Note:Ifanyoftheouterlevelsusedbytheabstractpatchtypeis0ornegative(orNaN),thenthepatchwillbediscardedbythegenerator,andnoTESinvocationsforthispatchwillresult.
Aswithanyotherpatchvariable,multipleTCSinvocationsforthesamepatchcanwritetothesametessellationlevelvariable,solongastheyareallcomputingandwritingtheexactsamevalue.
TCS'salsoprovidethefollowingoptionalper-vertexoutputvariables:
outgl_PerVertex
{
vec4gl_Position;
floatgl_PointSize;
floatgl_ClipDistance[];
}gl_out[];
TheuseofanyoftheseinaTCSiscompletelyoptional.Indeed,theirsemanticswillgenerallybeofnopracticalvaluetotheTCS.Theyhavethesamegeneralmeaningasforvertexshaders,butsinceaTCSmustalwaysbefollowedbyanevaluationshader,theTCSneverhastowritetoanyofthem.
Tessellationevaluationshaderinputs
V·E
TessellationEvaluationShadershavethefollowingbuilt-ininputs.
invec3gl_TessCoord;
inintgl_PatchVerticesIn;
inintgl_PrimitiveID;
gl_TessCoord
thelocationwithinthetessellatedabstractpatchforthisparticularvertex.EveryinputparameterotherthanthisonewillbeidenticalforallTESinvocationswithinapatch.
Whichcomponentsofthisvec3thathavevalidvaluesdependsontheabstractpatchtype.Forisolinesandquads,onlytheXYcomponentshavevalidvalues.Fortriangles,allthreecomponentshavevalidvalues.Allvalidvaluesarenormalizedfloats(ontherange[0,1]).
gl_PatchVerticesIn
thevertexcountforthepatchbeingprocessed.ThisiseithertheoutputvertexcountspecifiedbytheTCS,orthepatchvertexsizespecifiedbyglPatchParameterifnoTCSisactive.Attemptstoindexper-vertexinputsbyavaluegreaterthanorequaltogl_PatchVerticesInresultsinundefinedbehavior.
gl_PrimitiveID
theindexofthecurrentpatchintheseriesofpatchesbeingprocessedforthisdrawcall.Primitiverestart,ifused,hasnoeffectontheprimitiveID.
Note:Thetessellationprimitivegeneratorwillcullpatchesthathaveazeroforoneoftheactiveoutertessellationlevels.Theintentofthespecificationseemstobethatgl_PrimitiveIDwillstillbeincrementedforculledpatches.SotheprimitiveIDfortheTESisequivalenttotheIDfortheTCSinvocationsthatgeneratedthatpatch.Butthisisnotentirelyclearfromthespecitself.
TheTESalsohasaccesstothetessellationlevelsprovidedforthepatchbytheTCSorbyOpenGL:
patchinfloatgl_TessLevelOuter[4];
patchinfloatgl_TessLevelInner[2];
Onlytheouterandinnerlevelsactuallyusedbytheabstractpatcharevalid.Forexample,ifthisTESusesisolines,onlygl_TessLevelOuter[0]andgl_TessLevelOuter[1]willhavevalidvalues.
TheTESalsotakesthebuilt-inper-vertexvariablesoutputbytheTCS:
ingl_PerVertex
{
vec4gl_Position;
floatgl_PointSize;
floatgl_ClipDistance[];
}gl_in[gl_MaxPatchVertices];
Notethatjustbecausegl_inisdefinedtohavegl_MaxPatchVerticesentriesdoesnotmeanthatyoucanaccessbeyondgl_PatchVerticesInandgetreasonablevalues.
Tessellationevaluationshaderoutputs
V·E
TessellationEvaluationShadershavethefollowingbuilt-inoutputs.
outgl_PerVertex{
vec4gl_Position;
floatgl_PointSize;
floatgl_ClipDistance[];
};
gl_PerVertexdefinesaninterfaceblockforoutputs.Theblockisdefinedwithoutaninstancename,sothatprefixingthenamesisnotrequired.
ThesevariablesonlytakeonthemeaningsbelowifthisshaderisthelastactiveVertexProcessingstage,andifrasterizationisstillactive(ie:GL_RASTERIZER_DISCARDisnotenabled).ThetextbelowexplainshowtheVertexPost-Processingsystemusesthevariables.Thesevariablesmaynotberedeclaredwithinterpolationqualifiers.
gl_Position
theclip-spaceoutputpositionofthecurrentvertex.
gl_PointSize
thepixelwidth/heightofthepointbeingrasterized.Itonlyhasameaningwhenrenderingpointprimitives,whichinaTESrequiresusingthepoint_modeinputlayoutqualifier.
gl_ClipDistance
allowstheshadertosetthedistancefromthevertextoeachUser-DefinedClipPlane.Apositivedistancemeansthatthevertexisinside/behindtheclipplane,andanegativedistancemeansitisoutside/infrontoftheclipplane.Eachelementinthearrayisoneclipplane.Inordertousethisvariable,theusermustmanuallyredeclareitwithanexplicitsize.
Geometryshaderinputs
V·E
GeometryShadersprovidethefollowingbuilt-ininputvariables:
ingl_PerVertex
{
vec4gl_Position;
floatgl_PointSize;
floatgl_ClipDistance[];
}gl_in[];
Thesevariableshaveonlythemeaningthepriorshaderstage(s)thatpassedthemgavethem.
TherearesomeGSinputvaluesthatarebasedonprimitives,notvertices.Thesearenotaggregatedintoarrays.Theseare:
inintgl_PrimitiveIDIn;
inintgl_InvocationID;//RequiresGLSL4.0orARB_gpu_shader5
gl_PrimitiveIDIn
thecurrentinputprimitive'sID,basedonthenumberofprimitivesprocessedbytheGSsincethecurrentdrawingcommandstarted.
gl_InvocationID
thecurrentinstance,asdefinedwheninstancinggeometryshaders.
Geometryshaderoutputs
V·E
GeometryShadershavethefollowingbuilt-inoutputs.
outgl_PerVertex
{
vec4gl_Position;
floatgl_PointSize;
floatgl_ClipDistance[];
};
gl_PerVertexdefinesaninterfaceblockforoutputs.Theblockisdefinedwithoutaninstancename,sothatprefixingthenamesisnotrequired.
TheGSisthefinalVertexProcessingstage.Therefore,unlessrasterizationisbeingturnedoff,youmustwritetosomeofthesevalues.Theseoutputsarealwaysassociatedwithstream0.Soifyou'reemittingverticestoadifferentstream,youdon'thavetowritetothem.
gl_Position
theclip-spaceoutputpositionofthecurrentvertex.Thisvaluemustbewrittenifyouareemittingavertextostream0,unlessrasterizationisoff.
gl_PointSize
thepixelwidth/heightofthepointbeingrasterized.Itisonlynecessarytowritetothiswhenoutputtingpointprimitives.
gl_ClipDistance
allowstheshadertosetthedistancefromthevertextoeachUser-DefinedClipPlane.Apositivedistancemeansthatthevertexisinside/behindtheclipplane,andanegativedistancemeansitisoutside/infrontoftheclipplane.Inordertousethisvariable,theusermustmanuallyredeclareit(andthereforetheinterfaceblock)withanexplicitsize.
Certainpredefinedoutputshavespecialmeaningandsemantics.
outintgl_PrimitiveID;
TheprimitiveIDwillbepassedtothefragmentshader.TheprimitiveIDforaparticularline/trianglewillbetakenfromtheprovokingvertexofthatline/triangle,somakesurethatyouarewritingthecorrectvaluefortherightprovokingvertex.
Themeaningforthisvalueiswhateveryouwantittobe.However,ifyouwanttomatchthestandardOpenGLmeaning(ie:whattheFragmentShaderwouldgetifnoGSwereused),youmustdothisforeachvertexbeforeemittingit:
gl_PrimitiveID=gl_PrimitiveIDIn;
ThisnaturallyassumesthatthenumberofprimitivesoutputbytheGSequalsthenumberofprimitivesreceivedbytheGS.
V·E
LayeredrenderingintheGSworksviatwospecialoutputvariables:
outintgl_Layer;
outintgl_ViewportIndex;//RequiresGL4.1orARB_viewport_array.
Thegl_Layeroutputdefineswhichlayerinthelayeredimagetheprimitivegoesto.Eachvertexintheprimitivemustgetthesamelayerindex.Notethatwhenrenderingtocubemaparrays,thegl_Layervaluerepresentslayer-faces(thefaceswithinalayer),notthelayersofcubemaps.
gl_ViewportIndex,whichrequiresGL4.1orARB_viewport_array,specifieswhichviewportindextousewiththisprimitive.
Note:ARB_viewport_array,whiletechnicallya4.1feature,iswidelyavailableon3.3hardware,frombothNVIDIAandAMD.
Fragmentshaderinputs
V·E
FragmentShadershavethefollowingbuilt-ininputvariables.
invec4gl_FragCoord;
inboolgl_FrontFacing;
invec2gl_PointCoord;
gl_FragCoord
Thelocationofthefragmentinwindowspace.TheX,YandZcomponentsarethewindow-spacepositionofthefragment.TheZvaluewillbewrittentothedepthbufferifgl_FragDepthisnotwrittentobythisshaderstage.TheWcomponentofgl_FragCoordis1/Wclip,whereWclipistheinterpolatedWcomponentoftheclip-spacevertexpositionoutputtogl_PositionfromthelastVertexProcessingstage.
Thespaceofgl_FragCoordcanbemodifiedbyredeclaringgl_FragCoordwithspecialinputlayoutqualifiers:
layout(origin_upper_left)invec4gl_FragCoord;
Thismeansthattheoriginforgl_FragCoord'swindow-spacewillbetheupper-leftofthescreen,ratherthantheusuallower-left.
layout(pixel_center_integer)invec4gl_FragCoord;
OpenGLwindowspaceisdefinedsuchthatpixelcentersareonhalf-integerboundaries.Sothecenterofthelower-leftpixelis(0.5,0.5).Usingpixel_center_integeradjustgl_FragCoordsuchthatwholeintegervaluesrepresentpixelcenters.
BothoftheseexisttobecompatiblewithD3D'swindowspace.Unlessyouneedyourshaderstohavethiscompatibility,youareadvisednottousethesefeatures.
gl_FrontFacing
Thisisfalseifthefragmentwasgeneratedbytheback-faceoftheprimitive;itistrueinallothercases(includingPrimitivesthathavenobackface).
gl_PointCoord
Thelocationwithinapointprimitivethatdefinesthepositionofthefragmentrelativetothesideofthepoint.Pointsareeffectivelyrasterizedaswindow-spacesquaresofacertainpixelsize.Sincepointsaredefinedbyasinglevertex,theonlywaytotellwhereinthatsquareaparticularfragmentisiswithgl_PointCoord.
Thevaluesofgl_PointCoord'scoordinatesrangefrom[0,1].OpenGLusesaupper-leftoriginforpoint-coordinatesbydefault,so(0,0)istheupper-left.However,theorigincanbeswitchedtoabottom-leftoriginbycallingglPointParameteri(GL_POINT_SPRITE_COORD_ORIGIN,GL_LOWER_LEFT);
OpenGL4.0andabovedefineadditionalsystem-generatedinputvalues:
inintgl_SampleID;
invec2gl_SamplePosition;
inintgl_SampleMaskIn[];
gl_SampleID
Thisisanintegeridentifierforthecurrentsamplethatthisfragmentisrasterizedfor.
Warning:Anyuseofthisvariableatallwillforcethisshadertobeevaluatedper-sample.Sincemuchofthepointofmultisamplingistoavoidthat,youshoulduseitonlywhenyoumust.
gl_SamplePosition
Thisisthelocationofthecurrentsampleforthefragmentwithinthepixel'sarea,withvaluesontherange[0,1].Theoriginisthebottom-leftofthepixelarea.
Warning:Anyuseofthisvariableatallwillforcethisshadertobeevaluatedper-sample.Sincemuchofthepointofmultisamplingistoavoidthat,youshoulduseitonlywhenyoumust.
gl_SampleMaskIn
Whenusingmultisampling,thisvariablecontainsabitfieldforthesamplemaskofthefragmentbeinggenerated.ThearrayisaslongasneededtofillinthenumberofsamplessupportedbytheGLimplementation.
SomeFragmentshaderbuilt-ininputswilltakevaluesspecifiedbyOpenGL,butthesevaluescanbeoverriddenbyusercontrol.
infloatgl_ClipDistance[];
inintgl_PrimitiveID;
gl_ClipDistance
Thisarraycontainstheinterpolatedclippingplanehalf-spaces,asoutputforverticesfromthelastVertexProcessingstage.
gl_PrimitiveID
Thisvalueistheindexofthecurrentprimitivebeingrenderedbythisdrawingcommand.ThisincludesanyTessellationappliedtothemesh,soeachindividualprimitivewillhaveauniqueindex.
However,ifaGeometryShaderisactive,thenthegl_PrimitiveIDisexactlyandonlywhattheGSprovidedasoutput.Normally,gl_PrimitiveIDisguaranteedtobeunique,soiftwoFSinvocationshavethesameprimitiveID,theycomefromthesameprimitive.ButifaGSisactiveandoutputsnon-uniquevalues,thendifferentfragmentshaderinvocationsfordifferentprimitiveswillgetthesamevalue.IftheGSdidnotoutputavalueforgl_PrimitiveID,thenthefragmentshadergetsanundefinedvalue.
Warning:Theabovediscussionofgl_PrimitiveIDisbasedonaparticularreadingoftheOpenGL4.6specification.However,thespecificationitselfissomewhatinconsistentwiththisview,suggestingthattheprimitiveIDmayonlygetincrementedbasedondatafedtothesystem,notdatageneratedby,forexample,thetessellator.AndtheVulkanspecificationseemstoconcurwiththisinterpretation,andatleastoneimplementationisknowntoagreewiththataswell.Untilthereissomeclarificationontheissue,youshouldconsidertheabovetobequestionable.
GL4.3providesthefollowingadditionalinputs:
inintgl_Layer;
inintgl_ViewportIndex;
gl_Layer
Thisiseither0orthelayernumberforthisprimitiveoutputbytheGeometryShader.
gl_ViewportIndex
Thisiseither0ortheviewportindexforthisprimitiveoutputbytheGeometryShader.
Fragmentshaderoutputs
V·E
FragmentShadershavethefollowingbuilt-inoutputvariables.
outfloatgl_FragDepth;
gl_FragDepth
Thisoutputisthefragment'sdepth.Iftheshaderdoesnotstaticallywritethisvalue,thenitwilltakethevalueofgl_FragCoord.z.
To"staticallywrite"toavariablemeansthatyouwritetoitanywhereintheprogram.Evenifthewritingcodeistechnicallyunreachableforsomereason,ifthereisagl_FragDepth=...expressionanywhereintheshader,thenitisstaticallywritten.
Warning:Ifthefragmentshaderstaticallywritestogl_FragDepth,thenitistheresponsibilityoftheshadertostaticallywritetothevalueinallcircumstances.Nomatterwhatbranchesmayormaynotbetaken,theshadermustensurethatthevalueiswritten.So,ifyouconditionallywritetoitinoneplace,youshouldatleastmakesurethatthereisasinglenon-conditionalwritesometimebeforethat.
GLSL4.20orARB_conservative_depthallowstheusertospecifythatmodificationstogl_FragDepth(relativetothegl_FragCoord.zvalueitwouldhaveotherwisehad)willhappenincertainways.ThisallowstheimplementationthefreedomtonotturnoffEarlyDepthTestsincertainsituations.
Thisisdonebyre-declaringgl_FragDepthwithaspeciallayoutqualifier:
layout(depth_
延伸文章資訊
- 1認識著色器
getElementById('glCanvas')); installProgram(gl, shaderSourceById('vertex-shader'), shaderSourceBy...
- 2Built-in Variable (GLSL) - OpenGL Wiki - Khronos Group
Fragment Shader · Compute Shader · Other shading languages. The OpenGL Shading Language defines a...
- 3Intro to GLSL - Cornell CS
Vertex shader controls vertex transformation ... "cs4620/gl/Grid.frag", // Path to fragment shade...
- 4高级GLSL
其中两个我们已经打过交道了: gl_Position 和 gl_FragCoord ,前一个是顶点着色器的 ... 好几次了,因为 gl_FragCoord 向量的z元素和特定的fragment...
- 5Geometry Shader - LearnOpenGL
Between the vertex and the fragment shader there is an optional shader stage ... Each time we cal...