Core Language (GLSL) - OpenGL Wiki - Khronos Group
文章推薦指數: 80 %
Core Language (GLSL) ... Shader stages: ... The OpenGL Shading Language is a C-style language, so it covers most of the features you would expect ...
CoreLanguage(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
TheOpenGLShadingLanguageisaC-stylelanguage,soitcoversmostofthefeaturesyouwouldexpectwithsuchalanguage.Controlstructures(for-loops,if-elsestatements,etc)existinGLSL,includingtheswitchstatement.Thissectionwillnotcovertheentirelanguageindetail;theGLSLspecificationcanhandlethat.ThisWikipagewillnotethedifferencesbetweenGLSLandC.
Contents
1Compilationsettings
1.1Version
1.1.1OpenGLandGLSLversions
1.1.2Extensions
2Preprocessordirectives
2.1#linedirective
2.2Standardmacros
3Reservednames
4Types
5Qualifiers
6Expressions
6.1Constantexpression
6.1.1Integralconstantexpression
6.2Dynamicallyuniformexpression
6.2.1Invocationgroup
6.2.2Uses
6.2.3Examples
7Functions
7.1Recursion
7.2Parameters
8Controlflow
Compilationsettings
TheOpenGLShadingLanguagerequirescertaininformationtobepresentedearlyinashaderobject'scompilation.Inacommand-line-basedcompiler,thesewouldbecommand-linecompileroptions.GLSL'scompilationmodelinsteadrequiresthemtobepartofthelanguage.
Theseshouldbeinthefirstlinesofthefirststringassociatedwithashaderobject.Ifyouwanttogloballyapplythese,thenyoushouldputtheminastringthatisfirstinthearrayofstringspassedtotheshaderobjectwithglShaderSource,ortoglCreateShaderProgram.
Version
TheOpenGLShadingLanguagehasgonethroughanumberofrevisions,someofthemquitesubstantial.AspartoftheOpenGLSpecification,eachversionofOpenGLisrequiredtosupportspecificversionsofGLSL;itmayoptionallysupportmore.
TospecifywhichversionofGLSLshouldbeusedtocompile/linkashader,usethisdirective:
#version150
Thiswouldtellthecompilertocompileforversion1.50,orerrorifthatversionisnotavailable.
Theversionnumbercanbefollowedbytheprofilename.Thiscanbecoreorcompatibility.Ifaprofilenameisnotspecified,thedefaultiscore.
The#versiondirectivemustappearbeforeanythingelseinashader,saveforwhitespaceandcomments.Ifa#versiondirectivedoesnotappearatthetop,thenitassumes1.10,whichisalmostcertainlynotwhatyouwant.
OpenGLandGLSLversions
EveryOpenGLversionsince2.0hasbeenreleasedwithacorrespondingGLSLversion.However,theGLSLversionnumberswerenotalwaysinsyncwiththeGLversion.Hereisatable:
OpenGLVersion
GLSLVersion
2.0
1.10
2.1
1.20
3.0
1.30
3.1
1.40
3.2
1.50
ForallversionsofOpenGL3.3andabove,thecorrespondingGLSLversionmatchestheOpenGLversion.SoGL4.1usesGLSL4.10.
Extensions
ManyOpenGLExtensionsmodifyGLSL'sbehaviorandfunctionalityaswell.UnlikeregularOpenGL,whereextensionsareimplicitlyalwaystherewhetheryouuseitornot,GLSLextensionsmustexplicitlybespecifiedintheparticularshaderstringbeingcompiled.
Similartothe#versiondirective,theusercanactivatespecificextensionswiththe"#extension"directive.Youshouldputthesedefinitionsbeforeanyotherlanguagefeatures,butaftertheversiondeclaration.Thesyntaxisasfollows:
#extensionextension_name :behavior
Theextension_namecanalsobethestringall.Thismeansitworksforallextensions.Theavailablebehaviorsare:
enable:Causesthenamedextensiontowork;iftheimplementationdoesnotsupporttheextension,itonlygivesawarning.Failsifusedwithall.
require:Causesthenamedextensiontowork;iftheimplementationdoesnotsupporttheextension,itfails.Italsofailsifusedwithall.
warn:Causesthenamedextensiontowork;however,usingtheextensionwillemitwarnings.Ifusedwithall,thentheuseofanyextensionswillemitwarnings.
disable:Preventsthenamedextensionfromworkingatall.Thus,anyuseofitwillbeseenasundefinedsyntaxandcauseanerror.Ifusedwithall,thenthispreventsanyextensionsfromworking.
Preprocessordirectives
Allofthekeywordsbeginningwith#arepreprocessordirectives,muchlikewithC,although#lineisdifferent.GLSLprovidesmostofthestandardCsetofpreprocessordirectives(#define,#if,etc),inadditiontotheoneslistedabove.Themostnotableomissionis#include.
Macroexpansiondoesnotworkon#versionand#extensiondirectives.
#linedirective
The#linedirectiveallowsyoutochangethecurrent__FILE__and__LINE__values,andisdifferentfromC.Ithastheforms:
#lineline
#linelinesource-string-number
Thelineafterthe#linedirectiveinthesourcewillbesettothegivenlinenumber.Forexample,ifyouhave"#line4"ononelineand"error"onthenext,then"error"willbeonline4ifitisanerror.The#linedirectivedoesnotsupportsourcefilesasinC.
Standardmacros
GLSLdefinesanumberofmacros.__FILE__isnotafilename;itisadecimalintegerrepresentingwhichstringinthelistofstringsgiventotheshader.__LINE__isthelinenumber.__VERSION__isadecimalintegerrepresentingtheGLSLversionbeingcompiled.Iftheversionis3.30,then__VERSION__willbe"330"(asaninteger).
ThemacroGL_core_profileisalwaysdefinedtobe"1".ThemacroGL_compatibility_profileisonlydefinedtobe"1"iftheversionforthisshaderwassettobecompatibility.
Reservednames
GLSLreservesanynamebeginningwith"gl_";attemptstodefinevariablesorfunctionsthatbeginwiththisstringwillresultinanerror.Also,GLSLhasanumberofkeywords,whichcannotbeusedasidentifiersinanycontext.
Types
Mainarticle:DataType(GLSL)
TheGLSLdefinesanumberoftypes.SomeofthemarefamiliartoC/C++users,whileothersarequitedifferent.
Qualifiers
Mainarticle:TypeQualifier(GLSL)
Variablesdeclaredatglobalandlocalscopecanhaveanumberofqualifiersassociatedwiththem.Mostoftheseareuniquetoshadinglanguages.
Expressions
GLSLhassomeuniqueexpressiondefinitions.
Constantexpression
Constantexpressionsareexpressionsthatcanbeevaluatedatcompiletime.ConstantexpressionsinGLSLareexpressionsthatconsistof:
Aliteralvalue.
Aconst-qualifiedvariable(notafunctionparameter)withanexplicitinitializer,butonlyiftheinitializerisitselfoneofthefollowing:
Aconstantexpression.
AnInitializerList,whosecomponentsarethemselvesconstantexpressions.Initializerlistsarenotexpressionsthemselves.
Theresultofthelength()functionofanarray,butonlyifthearrayhasanexplicitsize(who'ssizemustbeaconstantexpression).
Theresultofmostoperators,solongasalltheoperandsarethemselvesconstantexpressions.Theoperatorsnotonthislistareanyassignmentoperators(+=andsoforth),andthecommaoperator.
Theresultofaconstructorforatype,butonlyifalloftheargumentstotheconstructorarethemselvesconstantexpressions.
Thereturnvalueofanybuilt-infunction,butonlyifalloftheargumentstothefunctionarethemselvesconstantexpressions.OpaqueTypesareneverconstantexpressions.NotethatthefunctionsdFdx,dFdy,fwidth,andtheirCoarseandFinevariationswillreturn0,whengivenaconstantexpressionasanargument.
Integralconstantexpression
Theseareconstantexpressionsthatresultinaninteger,signedorunsigned.
Dynamicallyuniformexpression
DynamicallyUniformExpression
Coreinversion
4.6
Coresinceversion
4.0
AdynamicallyuniformexpressionisaGLSLexpressioninwhichallinvocationsofthatshaderwithinaparticularsetofinvocationswillhavethesamevalue.
OnlyGLSL4.00andabovemakesadistinctionaboutdynamicallyuniformexpressions.Anyrestrictionsyouseethatrequirea"dynamicallyuniformexpression"will,inolderGLSLversionsrequirea"constantexpression".
AnexpressioninaGLSLshaderissaidtobedynamicallyuniformif,andonlyif,everyshaderinvocationwithinthesameinvocationgroupwillhavethesamevalue,inthesameorder.Whetheranexpressionisdynamicallyuniformdependsonthevaluesprovided;itcannotalwaysbeapriorideterminedfromashader'scode.
Someexpressionsarealwaysdynamicallyuniform,bytherulesofthelanguage.Theseinclude:
Constantexpressions
Uniformvalues
Anyexpression,whichdoesnotinvolveauser-definedfunctioncall,ImageLoadStoreorSSBOoperations,who'sinputvaluesarealldynamicallyuniform
Thegl_DrawIDinputtotheVertexShader
Otherexpressionsmayormaynotbedynamicallyuniform.Forexample,ashaderstageinputvaluewillusuallynotbedynamicallyuniform.However,ifeveryshaderintherenderingcommandisgiventheexactsameinputvalue,thenitwillbedynamicallyuniform.Itisthevalueoftheexpressionwhichmustbeuniform;everyshaderinvocationmustgetthesamevalue,evenifthatsamevalueisbeingreadfromdifferentmemorylocation.
gl_InstanceIDisanexample.Ifyourenderonlyasingleinstance,thengl_InstanceIDwillbedynamicallyuniformforthatrenderingcommand.However,ifyourendermultipleinstancesinthesamecommand,itwillnot.ThesamegoesforInstancedArrayinputvalues.
Mostimportantofall,ifyouexecutealoopovervalues,wheretheinitializingexpression,offset,andtestconditionallusedynamicallyuniformexpressions,thentheloopcounteritselfwillbedynamicallyuniform.
Whileaccessingtexturesisguaranteedtobedynamicallyuniformifthetexturecoordinatesaredynamicallyuniform,accessingimagevariablesorAtomicCountersisnotnecessarilyso.Thesearemodifiablememory,soeachinvocationmaynotgetthesamevalue.Iftheimagevariableisread-only,thenaccessingitisdynamicallyuniformiftheimagecoordinatesandsofortharedynamicallyuniform.
Invocationgroup
Dynamicallyuniformexpressionsarebasedonshaderinvocations"withinthesameinvocationgroup."Thedefinitionof"invocationgroup"dependsontheshaderstageinquestion.ForComputeShaders,thescopeisallinvocationswithinaworkgroup.ForshaderslaunchedthroughRenderingCommands,thisgetsmorecomplex.
Renderingscopeextendstoallinvocationsofallshaderstagescreatedtoserviceasingledrawingcommand.Thismeansthat,forFragmentShaders,twodistinctprimitivesinarenderingcommandareconsideredpartofthesamescope.Thismeansthatgl_PrimitiveIDisnotdynamicallyuniform(unlessyourenderonlyoneprimitive).Thisisalsowhygl_InstanceIDisonlydynamicallyuniformwhenrenderingasingleinstance;instancedrenderingisconsideredasingledrawingcommand.
However,therearedrawingcommandsthatcreatemultiplescopes.TheMultidrawRenderingcommands,includingtheindirectversions,haveseparatescopesfortheirseparatedrawingsub-commands.Sowhiledoinginstancedrenderinginadrawcommandplacesallinstancesinasinglescope,renderingmultipletimeswithamultidrawcommandwithabaseinstancecreatesmultiplescopes,oneperinternaldraw.
Note:TheaboveinformationinthissectionisbasedonGLSL4.60.Assuch,thismaynotbeentirelycorrectforearlierversions;theydefinedtheideaof"dynamicallyuniform",butdidn'treallygointoexplicitdetails.However,sincetheyarebasedmainlyonthehardwareratherthanthecompiler,andthisdefinitionisreallyaboutthebehaviorofthehardware,itisnotunreasonabletoassumethattheyapplytoolderGLSLversionsaswell.
Uses
ThereareplaceswhereGLSLrequirestheexpressiontobedynamicallyuniform.Allofthefollowingmustuseadynamicallyuniformexpression:
Thearrayindexforarraysofopaquetypes.
Theindextobuffer-backedinterfaceblockarrays.
InComputeShaders,theexpressionsleadingtotheexecutionofabarrier()call.Soifthereisalooporaconditionalstatementorsomesuch,alloftheseconditionsmustbedynamicallyuniformexpressions,sothateverycomputeshaderinvocationencounterseverybarrier()statementinthesamesequenceandthesamenumberoftimes.
Examples
V·E
Thisexamplecodeshowswhatareandarenotdynamicallyuniformexpressions.
invec3fromPrevious;
inuvec2fromRange;
constintfoo=5;
constuvec2range=uvec2(2,5);
uniformvec2pairs;
uniformsampler2dtex;
voidmain()
{
foo;//constantexpressionsaredynamicallyuniform.
uintvalue=21;//'value'isdynamicallyuniform.
value=range.x;//stilldynamicallyuniform.
value=range.y+fromRange.y;//notdynamicallyuniform;currentcontentscomefromanon-dynamicallyuniformsource.
value=4;//dynamicallyuniformagain.
if(fromPrevious.y<3.14)
value=12;
value;//NOTdynamicallyuniform.Currentcontentsdependon'fromPrevious',aninputvariable.
floatnumber=abs(pairs.x);//'number'isdynamicallyuniform.
number=sin(pairs.y);//stilldynamicallyuniform.
number=cos(fromPrevious.x);//notdynamicallyuniform.
vec4colors=texture(tex,pairs.xy);//dynamicallyuniform,eventhoughitcomesfromatexture.
//Itusesthesametexturecoordinate,thusgettingthesametexeleverytime.
colors=texture(tex,fromPrevious.xy);//notdynamicallyuniform.
for(inti=range.x;i
延伸文章資訊
- 1GLSL - 维基百科,自由的百科全书
GLSL - OpenGL Shading Language 也稱作GLslang,是一個以C語言為基礎的高階著色語言。它是由OpenGL ARB 所建立,提供開發者對繪圖管線更多的直接控制,而...
- 2GLSL着色器- 游戏开发环境 - MDN Web Docs
使用GLSL的着色器(shader), GLSL是一门特殊的有着类似于C语言的语法, 在图形管道(graphic pipeline)中直接可执行的OpenGL着色语言.
- 3Core Language (GLSL) - OpenGL Wiki - Khronos Group
Core Language (GLSL) ... Shader stages: ... The OpenGL Shading Language is a C-style language, so...
- 4Day11 [OpenGL] Shader - iT 邦幫忙
GLSL. GLSL(OpenGL Shading Language Language)是OpenGL 的Shader 語言,它長得有點像C語言,一個Shader 通常長這樣:
- 5OpenGL Shading Language - Khronos Group
OpenGL Shading Language ... Shader stages: ... The OpenGL Shading Language (GLSL) is the principa...